0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

GeminiとReactで簡単なAI質問アプリを作る

Last updated at Posted at 2025-03-30

GeminiとReactで簡単なAI質問アプリを作る

質問に対してAIが回答してくれるアプリを作ります。

Gemini API Keyの用意

googleのアカウントを所有していることが前提になるので、アカウントがなければ作って下さい。
このサイトを参考に、APIキーを取得します
https://monomonotech.jp/kurage/memo/m240725_get_gemini_api_key.html

ライブラリのインストール

GeminiのAPI キーを取り扱うためのライブラリをReactプロジェクトにインストールします。
"@google/generative-ai"というライブライを使います。
https://www.npmjs.com/package/@google/generative-ai

インストールは、下記のコマンドで実行します。

npm install @google/generative-ai

完成コード

以下が完成したコードです。
APIキーは外部に漏れないよう、env環境変数で取り扱うことを強く推奨します。

App.ts
import React, { useEffect, useState } from 'react'; // useEffectとuseStateを追加
import logo from './logo.svg';
import './App.css';

function App() {
  const [resultText, setResultText] = useState(""); // 結果を格納するstate
  const[question,setQuestion] = useState<string|undefined>();

  //モデルをイニシャライズ
  const { GoogleGenerativeAI } = require("@google/generative-ai");
  const genAI = new GoogleGenerativeAI(process.env.REACT_APP_API_KEY); // 環境変数からAPIキーを取得
  const model = genAI.getGenerativeModel({ model: "gemini-1.5-flash" });


  const generateResponse = async ({prompt}:{prompt:string|undefined}) => {
    
    try {
      const result = await model.generateContent(prompt);
      const response = await result.response;
      const answer = response.text();
      setResultText(answer); // 結果をstateに設定
    } catch (error) {
      console.error("エラーが発生しました:", error);
      setResultText("エラーが発生しました。");
    }
  };

  return (
    <div className="App">
      <header className='header'>
        Gemini + React 質問アプリ
      </header>
      <main className="App-header">

        <div>
          <p>
            {resultText ? resultText : "Geminiからの応答を待っています..."}
          </p>

          <textarea 
            name="question" 
            onChange={(e:any) => setQuestion(e.target.value)}
          >
          </textarea>     

          <button onClick={() => generateResponse({prompt:question})}>
            質問
          </button>   

        </div>

      </main>
    </div>
  );
}

export default App;

簡単ではありますが、以上です。
応用すれば、色々作れそうですね。

0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?