Logicoya
HOME › オンライン教材 › React & Next.js 超入門 › Lesson 11 Gemini API でプロンプト
11

Gemini API でプロンプト

Gemini APIの利用

カスタムAPIの作成

.env.local の作成

.env.local を作成し、Gemini APIキーを設定します。

# キーの部分は、Google AI Studio で作成したキーを使用してください。
GEMINI_API_KEY=xxxxxxxxx

ルーティングファイル

app/ai/gemini/route.ts を作成し、GETリクエストでレスポンスします。

app/ai/gemini/route.ts
import { NextResponse } from "next/server";

export async function GET() {
    // APIキーの取得
    const API_KEY = process.env.GEMINI_API_KEY;

    const data = { message: API_KEY };
    return NextResponse.json(data);
}

APIキーの確認

http://localhost:3000/api/gemini/ にアクセスし、設定したAPIキーが読み込まれているか確認します。

Generative AI のインストール

Generative AIライブラリをインストールします。

npm i @google/genai

インポート

@google/genai をインポートします。

app/ai/gemini/route.ts
// GoogleGenAIインポート
import { GoogleGenAI } from '@google/genai';

GoogleGenAIインスタンス

APIキーを使って GoogleGenAIインスタンスを生成します。

app/ai/gemini/route.ts
export async function GET(req: NextRequest) {
    const API_KEY = process.env.GEMINI_API_KEY;

    // GoogleGenAIインスタンス生成
    const ai = new GoogleGenAI({ apiKey: API_KEY });
    ...
}

プロンプト生成

Gemini API に送信するプロンプトを生成します。

app/ai/gemini/route.ts
export async function GET() {
    ...
    // プロンプト内容
    const prompt = 'Geminiは何食べたい?';
    const contents = [
        {
            role: 'user',
            parts: [
                {
                    text: prompt,
                },
            ],
        },
    ];
    ...
}

リクエスト & レスポンス

GeminiAPI にプロンプトを送信し、レスポンスからテキストデータを取得します。

項目設定
Modelgemini-2.0-flash
MIME Typetext/plain
レスポンス(テキスト)candidates[0].content.parts[0].text
app/ai/gemini/route.ts
import { GoogleGenAI } from '@google/genai';
import { NextResponse } from 'next/server';

export async function GET() {
    const API_KEY = process.env.GEMINI_API_KEY;

    // GoogleGenAIインスタンス生成
    const ai = new GoogleGenAI({ apiKey: API_KEY });

    // プロンプト内容
    const prompt = 'Geminiは何食べたい?';
    const contents = [
        {
            role: 'user',
            parts: [
                {
                    text: prompt,
                },
            ],
        },
    ];
    // GeminiAPIにリクエスト
    const response = await ai.models.generateContent({
        model: 'gemini-2.0-flash',
        config: { responseMimeType: 'text/plain' },
        contents,
    });
    // レスポンスからテキストを取得
    const text = response.candidates?.[0]?.content?.parts?.[0]?.text || 'No response';

    return NextResponse.json({ message: text });
}

動作確認

http://localhost:3000/api/gemini/ にアクセスし、結果を確認します。

コンポーネント

AIBot コンポーネントを作成し、use client とします。

app/components/AIBot.tsx
"use client"

export default function AIBot() {
    return (
        <div>AIBot</div>
    )
}

フォーム作成

ステート変数 message を定義し、フォームを作成します。

app/components/AIBot.tsx
"use client"

import React, { useState } from 'react'

export default function AIBot() {
    const [message, setMessage] = useState("");

    return (
        <div>
            <h2 className="text-2xl font-bold mb-4">教えて!Gemini!</h2>
            <div className="text-left p-4">
                {message}
            </div>
            <button
                className="px-6 py-3 bg-sky-600 text-white rounded-xl shadow hover:bg-sky-700 cursor-pointer">
                教えて!Gemini!
            </button>
        </div>
    )
}

APIリクエスト

ボタンにクリックイベント sendMessage() を追加し、API /api/gemini へリクエストします。レスポンスされたデータは message に設定します。

app/components/AIBot.tsx
"use client"

import React, { useState } from 'react'
import ReactMarkdown from 'react-markdown';
import remarkGfm from 'remark-gfm';

export default function AIBot() {
    const [message, setMessage] = useState("");

    const sendMessage = async () => {
        // /api/gemini にリクエスト
        const res = await fetch('/api/gemini');
        // JSONデータをパースして、message に設定
        const data = await res.json();
        setMessage(data.message);
    };

    return (
        <div>
            <h2 className="text-2xl font-bold mb-4">教えて!Gemini!</h2>
            <div className="text-left p-4">
                {message}
            </div>
            <button
                onChange={sendMessage}
                className="px-6 py-3 bg-sky-600 text-white rounded-xl shadow hover:bg-sky-700 cursor-pointer">
                教えて!Gemini!
            </button>
        </div>
    )
}

動作確認

ボタンをクリックして、Gemini API のレスポンスがブラウザに表示されるか確認します。

チャットボット

ユーザのテキスト入力に対するプロンプトでチャットボットするように修正します。

フォーム送信処理

ステート追加

AIBot コンポーネントで、プロンプトテキスト入力のステート text を定義します。

app/components/AIBot.ts
const [text, setText] = useState("");

テキストボックス追加

質問用のテキストボックスを追加して text をバインドします。

app/components/AIBot.ts
    return (
        <div className="mx-auto max-w-2xl p-6 bg-white rounded-lg shadow-md space-y-4">
            <h2 className="text-2xl font-bold">教えて!Gemini!</h2>
            {/* テキストボックス */}
            <input type="text"
                value={text}
                onChange={(e) => setText(e.target.value)}
                placeholder="質問を入力してください"
                className="w-full px-3 py-2 border border-gray-400 rounded"
            />

            <div className="text-left p-3 bg-gray-100 rounded shadow text-sm whitespace-pre-wrap">
                {message}
            </div>
            <button
                onChange={sendMessage}
                className="px-6 py-3 bg-sky-600 text-white rounded-xl shadow hover:bg-sky-700 cursor-pointer">
                教えて!Gemini!
            </button>
        </div>
    )

動作確認

APIの修正

app/api/gemini/route.ts のHTTPリクエストをPOSTに変更します。このとき、データを受け取る引数を req: NextRequest とします。

app/api/gemini/route.ts
export async function POST(req: NextRequest) {
    ...
}

データの取得

クライアントからの送信データ(JSONフォーマット)を req.json() で取得します。また、プロンプトもアレンジしておきます。

app/api/gemini/route.ts
export async function POST(req: NextRequest) {
    ...
    // JSONデータを取得してオブジェクトに変換
    const body = await req.json();
    // プロンプト内容
    const prompt = "つぎの質問を単語で答えて\n\n" + body.text;
    ...
}

APIリクエスト

sendMessage() で、APIに POSTリクエストするように修正します。このとき、データはJSONフォーマットで送信します。

app/components/AIBot.ts
    const sendMessage = async () => {
        if (text && confirm('Geminiに聞いてみますか?')) {
            setMessage("Geminiに聞いています...");
            // APIにリクエストを送信
            const res = await fetch('/api/gemini',
                {
                    method: 'POST',
                    body: JSON.stringify({ "text": text }),
                    headers: {
                        'Content-Type': 'application/json',
                    },
                }
            );
            const data = await res.json();
            setMessage(data.message);
        }
    };

動作確認

ローディングの追加

APIのリクエスト中に、操作できないようにローディングを追加します。

Loading コンポーネント作成

app/components/Loading.tsx を作成します。このコンポーネントでは、TailwindCSS の animate-spin でスピナーを表示します。

app/components/Loading.tsx
export default function Loading() {
    return (
        <div className="fixed inset-0 bg-white flex items-center justify-center z-50">
            <div className="rounded-lg p-6 flex flex-col items-center bg-white">
                <div className="w-12 h-12 border-4 border-sky-600 border-t-transparent rounded-full animate-spin mb-4"></div>
                <p className="text-lg text-gray-800">Loading...</p>
            </div>
        </div>
    );
}

Loading コンポーネント読み込み

インポート

AIBot コンポーネントから Loading コンポーネントをインポートします。

app/components/AIBot.tsx
import Loading from '@/app/components/Loading';

ステート変数

ローディング中フラグ isLoading をステートで設定します。

app/components/AIBot.tsx
const [isLoading, setIsLoading] = useState(false);

ローディング実装

sendMessage() でリクエスト前にローディングを開始、レスポンス後にローディングを終了します。

app/components/AIBot.tsx
const sendMessage = async () => {
    setIsLoading(true);
    const res = await fetch('/api/gemini');
    const data = await res.json();
    setIsLoading(false);
    setMessage(data.message);
};

動作確認

Gemini APIにアクセス中は、ローディングが表示されます。