MongoDB をGoogle ADK と統合して、エージェント検索ツールと永続的なチャット履歴を構成できます。これらは両方ともMongoDBを基盤としています。このチュートリアルでは、MongoDbToolsetクラスを使用して、Google ADKエージェントがペインに関するデータを含むコレクションを検索できるようにします。次に、チュートリアルでは MongoDbSessionServiceクラスの使用が可能になり、エージェントはやり取りの早い段階にアクセスできます。
このチュートリアルでは、次のタスクを実行します。
環境を設定します。
コレクションとベクトル検索インデックスを作成します。
コレクションを検索するエージェントを構築します。
エージェントが以前のオンを記憶するように永続的なセッションを追加します。
ファイルを実行し、出力を検討してください。
バックグラウンド
Google ADK は、 AIエージェントを構築するためのオープンソースのPythonフレームワークです。このチュートリアルでは、次の Google ADK コンポーネントを使用してエージェントを構成し、 MongoDBアクセスを有効にします。
MongoDbToolset: MongoDBデータベースにMongoDB ベクトル検索とハイブリッド検索ツールを提供MongoDbSessionService: MongoDBでエージェントのセッション、イベント、状態を永続化
このチュートリアルでは、MongoDbToolset クラスをAtlas Automated embedded を使用するように構成します。これにより、別の埋め込みモデルや Google 認証情報が必要なく、保存済みドキュメントと検索クエリの両方が埋め込まれます。
前提条件
このチュートリアルを完了するには、次のリソースが必要です。
次のいずれかの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 クラスター。
Gein APIキー。このチュートリアルでは、GeoMon モデルを使用していますが、サポートされている任意のプロバイダーを使用できます。詳細については、Google ADK ドキュメントの「 モデル 」を参照してください。
Python v3.11 以降。
環境を設定する
このセクションでは、必要な依存関係のインストール、環境変数の設定、プロジェクトファイルの作成によって環境を準備します。
環境変数を設定します。
お使いの google-adk-mongodb-project ディレクトリ内で、.env ファイルを作成し、次のコードを追加します。
GOOGLE_API_KEY="<gemini-api-key>"MONGODB_URI="<connection-string>"<connection-string> を Atlas クラスターまたはローカル Atlas 配置の接続文字列に置き換えます。
接続stringには、次の形式を使用する必要があります。
mongodb+srv://<db_username>:<db_password>@<clusterName>.<hostname>.mongodb.net重要:接続文字列にデータベースユーザーの認証情報が含まれていることを確認します。接続文字列の検索方法の詳細については、クライアント ライブラリ経由でクラスターに接続する を参照してください。
接続stringには、次の形式を使用する必要があります。
mongodb://localhost:<port-number>/?directConnection=true詳細については、「接続文字列 」を参照してください。
プロジェクト ファイルを作成する。
google-adk-mongodb-projectディレクトリに、main.py という名前のファイルを作成します。このファイルに次のコードを追加して、環境変数をロード、必要なモジュールをインポートします。
import osimport timeimport asynciofrom dotenv import load_dotenvfrom pymongo import MongoClientfrom pymongo.operations import SearchIndexModelfrom google.adk.agents import Agentfrom google.adk.integrations.mongodb import ( MongoDbToolset, MongoDbToolSettings, MongoDbSessionService,)from google.adk.runners import Runnerfrom google.genai import types
load_dotenv()後の手順では、このファイルにコードを追加してコレクションを作成 し、エージェントを構築して 実行します。
コレクションとインデックスを作成する
このセクションでは、ペインに関するサンプルドキュメントをMongoDBコレクションに挿入し、Atlas 自動埋め込みに必要なMongoDB ベクトル検索インデックスを作成します。
サンプルドキュメントを挿入します。
次のコードを main.pyファイルに追加して、ペインについて説明する 5 つのドキュメントをコレクションに挿入します。 embeddingsフィールドには、Atlas が自動的に埋め込むテキストが保存されます。
collection.insert_many( [ { "title": "Emperor Penguins", "embeddings": "Emperor penguins are the tallest and heaviest of all penguin species, standing up to 4 feet.", }, { "title": "Penguin Habitats", "embeddings": "Penguins are flightless seabirds that live almost exclusively below the equator. Some island-dwellers can be found in warmer climates.", }, { "title": "Penguins of Patagonia", "embeddings": "Patagonia is home to five penguin species: Magellanic, Humboldt, Gentoo, Southern Rockhopper, and King.", }, { "title": "Penguin Diving Depths", "embeddings": "Emperor penguins can dive deeper than any other bird, reaching depths of over 500 meters.", }, { "title": "Penguin Nesting Habits", "embeddings": "Some penguin species mate for life and return to the same nesting site every year.", }, ])Atlas 自動埋め込みインデックスを作成します。
次のコードを main.pyファイルに追加して、embeddingsフィールドにMongoDB ベクトル検索インデックスを作成します。 autoEmbedフィールドタイプは、このフィールドの埋め込みを自動的に生成して保存するように Atlas に指示します。
search_index_model = SearchIndexModel( definition={ "fields": [ { "type": "autoEmbed", "path": "embeddings", "model": "voyage-4", "modality": "text", } ] }, name="autoembed_index", type="vectorSearch",)
collection.create_search_index(model=search_index_model)
# Index build time varies with collection size and cluster typeprint("Waiting for the MongoDB Vector Search index to finish building...")time.sleep(60)
client.close()インデックスのビルドするには約 1 分かかります。構築中、インデックスは最初の同期状態になります。構築が完了したら、コレクション内のデータのクエリを開始できます。
エージェント ツールとセッションの構成
このセクションでは、MongoDbToolsetクラスを使用してコレクションを検索するエージェントを構築します。次に、 MongoDBでエージェントのやり取り履歴を永続化するように MongoDbSessionServiceクラスを構成します。
ツールセットを構成します。
次のコードを main.pyファイルに追加して、MongoDbToolset をデータベースにバインドし、Atlas 自動埋め込みを使用するようにデータベースを構成します。
toolset = MongoDbToolset( connection_string=os.environ["MONGODB_URI"], database_name="google_adk_tutorial", settings=MongoDbToolSettings( use_mongodb_auto_embedding=True, default_embedding_field="embeddings", default_vector_index_name="autoembed_index", ),)use_mongodb_auto_embedding オプションが True に設定されているため、このツールセットは Google 埋め込みモデルを呼び出す代わりに、クエリテキストをプレーンテキストとして Atlas に送信します。
エージェントを定義します。
次のコードを main.pyファイルに追加して、GeoMon モデルとツールセットを使用するエージェントを作成します。
root_agent = Agent( model="gemini-2.5-flash", name="penguin_facts_agent", description="Answers questions about penguins.", instruction=( "Search the penguins collection with your MongoDB" " tools to answer questions about penguins. Remember" " what the user has told you earlier in the" " conversation." ), tools=[toolset],)セッション サービスとドライバーを構成します。
次のコードを main.pyファイルに追加して MongoDbSessionServiceクラスを構成し、それをエージェントとともに Runnerオブジェクトに渡します。
session_service = MongoDbSessionService( connection_string=os.environ["MONGODB_URI"], database_name="google_adk_tutorial",)
runner = Runner( agent=root_agent, app_name="google_adk_tutorial", session_service=session_service,)MongoDbSessionServiceデフォルトでは 、 パラメータをensure_indexes に設定しない限り、False はその使用に推奨されるインデックスを作成します。詳しくは、Google ADK参照の「 インデックス ガイドライン 」を参照してください。
エージェントを2 回の通信で実行します。
次のコードを main.pyファイルに追加してセッションを作成し、そのセッションを通じてエージェントに 2 つのメッセージを送信します。
async def ask(runner, session_id, text): content = types.Content(role="user", parts=[types.Part(text=text)]) async for event in runner.run_async( user_id="tutorial_user", session_id=session_id, new_message=content, ): if event.is_final_response() and event.content: print(f"\n[user]: {text}") print(f"[agent]: {event.content.parts[0].text}")
async def main(): session = await session_service.create_session( app_name="google_adk_tutorial", user_id="tutorial_user", )
await ask( runner, session.id, "How deep can emperor penguins dive?" ) await ask( runner, session.id, "What was the first thing I asked you?" )
asyncio.run(main())どちらの呼び出しでも同じ session_id 値が使用されるため、エージェントが2 番目のメッセージに応答する前に、MongoDbSessionService は 1 回目のタームのイベントを読み込みます。 2 回目の呼び出し用に新しいセッションを作成すると、エージェントには最初の変更のレコードはありません。
ファイルの実行
main.py ファイルを実行するには、google-adk-mongodb-project ディレクトリから次のコマンドを実行します。
python main.pyコマンドが正常に実行されると、出力は次のようになります。
Waiting for the MongoDB Vector Search index to finish building...
[user]: How deep can emperor penguins dive?[agent]: Emperor penguins can dive deeper than any other bird,reaching depths of over 500 meters.
[user]: What was the first thing I asked you?[agent]: The first thing you asked me was about how deep emperorpenguins can dive.次のステップ
MongoDbToolset完全なパラメータとメソッド参照を含む、MongoDbSessionService 、 、MongoDbMemoryService の詳細については、 「 MongoDBと Google ADK の統合 」を参照してください。