Open2

LangChainでGoogleカスタム検索・連携を試す📝

まさぴょん🐱まさぴょん🐱

LangChain.jsでGeminiを利用してWeb検索機能を実装する

1. 必要なライブラリのインストール

まず、以下のコマンドを使用して必要なライブラリをインストールします。

npm install @langchain/core @langchain/gemini @langchain/serper dotenv
  • @langchain/core: LangChainのコア機能を提供。
  • @langchain/gemini: Geminiモデルとの統合用。
  • @langchain/serper: SerperAPIを利用したWeb検索ツール。
  • dotenv: 環境変数の管理用。

2. APIキーの設定

GeminiとSerperAPIのAPIキーを環境変数として設定します。プロジェクトのルートに.envファイルを作成し、以下のように記述します。

GEMINI_API_KEY=your_gemini_api_key
SERPER_API_KEY=your_serper_api_key

your_gemini_api_keyyour_serper_api_key は各自のAPIキーに置き換えてください。

3. サンプルコード

以下は、LangChain.jsでGeminiとWeb検索機能を組み合わせた完全なサンプルコードです。

// 必要なモジュールをインポート
import { SerperSearch } from '@langchain/serper';
import { Gemini } from '@langchain/gemini';
import { AgentExecutor, createAgent } from '@langchain/core';
import dotenv from 'dotenv';

// 環境変数を読み込み
dotenv.config();

// Web検索ツールを定義
const searchTool = new SerperSearch({
  apiKey: process.env.SERPER_API_KEY,
});

// Geminiモデルを設定
const geminiModel = new Gemini({
  apiKey: process.env.GEMINI_API_KEY,
  model: 'gemini-pro', // 使用するモデル名を指定
});

// エージェントを作成
const agent = createAgent({
  llm: geminiModel,
  tools: [searchTool],
  prompt: `You are a helpful assistant. Use the search tool when you need up-to-date information.`,
});

// エージェントの実行環境を準備
const executor = new AgentExecutor({ agent });

// 質問に対する回答を取得する関数
async function askQuestion(question) {
  const response = await executor.run(question);
  console.log(response);
}

// 実行例
askQuestion('What is the weather like today?');

4. コードの実行方法

  1. 上記のコードをindex.jsなどのファイルに保存します。
  2. 必要なライブラリをインストール後、以下のコマンドで実行します。
node index.js

質問(例: "What is the weather like today?")に対する回答がコンソールに出力されます。

5. 注意点

  • APIキーの管理: APIキーは.envファイルで管理し、コードに直接書き込まないでください。
  • プロンプトの調整: エージェントの動作を改善するには、promptの内容を用途に応じて調整してください。
  • エラーハンドリング: 本番環境では、try-catchを使ったエラーハンドリングを追加することをお勧めします。

このサンプルコードを使えば、LangChain.jsとGeminiを活用してWeb検索機能を簡単に実装できます。
必要に応じてツールや設定をカスタマイズしてください。