AI エージェント向け: ドキュメントインデックスは https://www.mongodb.com/ja-jp/docs/llms.txt で利用できます。すべてのページの markdown バージョンは、いずれかの URL パスに .md を追加することで利用できます。

LagGraph とMongoDB AtlasでAIエージェントを構築

MongoDB Atlas をLingGraph と統合して、 AIエージェントを構築できます。このチュートリアルでは、 MongoDBのサンプルデータに関する質問に応答するAIエージェントを構築する方法を説明します。

具体的には、エージェントは統合を使用してエージェント RAGとエージェントメモリを実装します。セマンティック検索と全文検索ツールを使用して、関連情報を検索し、データに関する質問に答えます。また、やり取り履歴と重要なインタラクションを別々のコレクションに保存することで、 MongoDBを使用して短時間と長期のメモリの両方を実装します。

Atlas の サンプル データ セット からの映画データを含むコレクションを使用します。

  • 次のいずれかのMongoDBクラスター タイプ

    • MongoDB バージョン 6.0.11 を実行している Atlas クラスター、7.0.2以降。IP アドレスが Atlas プロジェクトのアクセスリストに含まれていることを確認します。

    • Python と Docker を使用して作成されたローカル Atlas 配置。atlas-local-lib-py (pip install atlas-local-lib-py) をインストールして、ローカル配置をプログラムで作成および管理します。詳細については、atlas-local-lib-py リポジトリを参照してください。

    • 検索とベクトル検索がインストールされた MongoDB Community クラスター。

  • 投票AI APIキー。詳細については、APIキーとPythonクライアントを参照してください。

  • OpenAI APIキー。APIリクエストに使用できるクレジットを持つ OpenAI アカウントが必要です。OpenAI アカウントの登録の詳細については、OpenAI APIウェブサイト を参照してください。

注意

互換性のあるPythonバージョンを使用していることを確認するには、 langgroup-voiceail パッケージの要件を確認してください。

環境を設定するには、以下の手順を完了します。

1

新しいプロジェクトディレクトリを作成し、必要な依存関係をインストールします。

mkdir langgraph-mongodb-ai-agentcd langgraph-mongodb-ai-agentpip install --quiet --upgrade python-dotenv langgraph "langgraph-checkpoint-mongodb>=0.5.0" "langgraph-store-mongodb>=0.3.0" langchain langchain-mongodb langchain-voyageai langchain-openai pymongo

注意

プロジェクトでは、次の構造を使用します。

langgraph-mongodb-ai-agent├── .env├── config.py├── search-tools.py├── memory-tools.py├── agent.py├── main.py
2

プロジェクトに .envファイルを作成し、次の変数を指定します。プレースホルダー値を有効なAPIキーとMongoDBクラスターの接続文字列に置き換えます。

VOYAGE_API_KEY = "<voyage-api-key>"OPENAI_API_KEY = "<openai-api-key>"MONGODB_URI = "<connection-string>"

注意

<connection-string> を Atlas クラスターまたはローカル Atlas 配置の接続文字列に置き換えます。

接続stringには、次の形式を使用する必要があります。

mongodb+srv://<db_username>:<db_password>@<clusterName>.<hostname>.mongodb.net

重要:接続文字列にデータベースユーザーの認証情報が含まれていることを確認します。接続文字列の検索方法の詳細については、クライアント ライブラリ経由でクラスターに接続する を参照してください。

MongoDB をストレージおよび検索用にベクトルデータベースとして構成するには、次の手順を実行します。

1

このチュートリアルでは、サンプルデータセットの 1 つをデータソースとして使用します。サンプルデータを Atlas クラスターにロードする手順をまだ完了していない場合は、完了します。

具体的には、映画のプロットのベクトル埋め込みなど、映画に関するドキュメントを含む embedded_movies データセットを使用します。

注意

独自のデータを使用する場合は、Atlas に vector embeddings を取り込む方法については、LangChain の使用を開始する、またはvector embeddings を手動で作成する方法を参照してください。

2

プロジェクトに config.py という名前のファイルを作成します。このファイルは、 MongoDB をエージェントのベクトルストアとして構成します。また、サンプルデータに対するベクトル検索と全文検索クエリを有効にするためのインデックスも作成します。

プロジェクトに search_tools.pyファイルを作成します。このファイルでは、エージェントがエージェント RAGを実行するために使用する検索ツールを定義します。

注意

特定のタスクを実行するために必要な任意のツールを定義できます。他の検索方法用のツールを定義することもできます。例えば、ハイブリッド検索や親ドキュメント検索などです。

プロジェクトに memory_tools.pyファイルを作成します。このファイルでは、エージェントがセッション全体の重要なインタラクションを保存および取得して、長期メモリを実装するために使用できるツールを定義します。

プロジェクトに agent.pyファイルを作成します。このファイルでは、エージェントのワークフローをオーケストレーションするグラフを構築します。このエージェントは、MongoDB Checkpointer コンポーネントを使用して短期間メモリを実装し、個別の履歴を持つ複数の同時実行通信を可能にします。

エージェントは、次のワークフローを使用してクエリに応答します。

  1. 開始: エージェントはユーザー クエリを受信します。

  2. エージェント ノード : ツールバウンド LM はクエリを分析し、ツールが必要かどうかを判断します。

  3. ツール ノード(必要な場合): 適切な検索またはメモリ ツールを実行します。

  4. 終了 : LM は、 ツール の出力を使用して最終応答を生成します。

Tip

永続性、短期間メモリ、 MongoDBチェックポイントの詳細については、次のリソースを参照してください。

最後に、プロジェクトに「main.py」という名前のファイルを作成します。このファイルはエージェントを実行し、エージェントと交流できるようにします。

プロジェクトを保存し、次のコマンドを実行します。エージェントを実行する際には以下に従います。

  • エージェントはベクトルストアを初期化し、インデックスがまだ存在しない場合はそれを作成します。

  • セッションIDを入力して、新しいセッションを開始することも、既存のセッションを続行することもできます。各セッションは保持され、前のセッションはいつでも再開できます。

  • 映画に関する質問をする。エージェントは、ツールと以前のインタラクションに基づいて応答を生成します。

次の出力は、サンプルインタラクションを示しています。

python main.py
Creating vector search index...Vector search index created successfully!Creating search index...Search index created successfully!Enter a session ID: 123 Ask me about movies! Type 'quit' to exit. Your query: What are some movies that take place in the ocean?🔧 Agent chose to use tool(s): plot_search → Executing plot_search Answer: Here are some movies that take place in the ocean: 1. **20,000 Leagues Under the Sea** - A marine biologist, his daughter, and a mysterious Captain Nemo explore the ocean aboard an incredible submarine.2. **Deep Rising** - A group of armed hijackers board a luxury ocean liner in the South Pacific Ocean, only to fight man-eating, tentacled sea creatures.... (truncated) Your query: What is the plot of the Titanic?🔧 Agent chose to use tool(s): title_search → Executing title_search Answer: The plot of *Titanic* involves the romantic entanglements of two couples aboard the doomed ship's maiden voyage... (truncated) Your query: What movies are like the movie I just mentioned?🔧 Agent chose to use tool(s): plot_search → Executing plot_search Answer: Here are some movies similar to *Titanic*: 1. **The Poseidon Adventure** - A group of passengers struggles to survive when their ocean liner capsizes at sea.2. **Pearl Harbor** - Focused on romance and friendship amidst the backdrop of a historical tragedy, following two best friends and their love lives during wartime.... (truncated) Your query: I don't like sad movies.🔧 Agent chose to use tool(s): save_memory → Executing save_memory Answer: Got it—I'll keep that in mind. Let me know if you'd like recommendations that focus more on uplifting or happy themes! (In different session)Enter a session ID: 456Your query: Recommend me a movie based on what you know about me.🔧 Agent chose to use tool(s): retrieve_memories → Executing retrieve_memories Answer: Based on what I know about you—you don't like sad movies—I'd recommend a fun, uplifting, or action-packed film. Would you be interested in a comedy, adventure, or family-friendly movie? Your query: Sure!🔧 Agent chose to use tool(s): plot_search, plot_search, plot_search → Executing plot_search → Executing plot_search → Executing plot_search Answer: Here are some movie recommendations from various uplifting genres that suit your preferences: ### Comedy:1. **Showtime** (2002): A spoof of buddy cop movies where two very different cops are forced to team up on a new reality-based TV cop show. It's packed with laughs and action!2. **The Big Bus** (1976): A hilarious disaster film parody featuring a nuclear-powered bus going nonstop from New York to Denver, plagued by absurd disasters. ### Adventure:1. **Journey to the Center of the Earth** (2008): A scientist, his nephew, and their mountain guide discover a fantastic and dangerous lost world at the earth's core.2. **Jason and the Argonauts** (1963): One of the most legendary adventures in mythology, brought to life in this epic saga of good versus evil. ### Family-Friendly:1. **The Incredibles** (2004): A family of undercover superheroes is forced into action to save the world while living in quiet suburban life.2. **Mary Poppins** (1964): A magical nanny brings joy and transformation to a cold banker's unhappy family.3. **Chitty Chitty Bang Bang** (1968): A whimsical adventure featuring an inventor, his magical car, and a rescue mission filled with fantasy.