Agent Platform メモリーバンクは、Agent Development Kit(ADK)で構築したエージェントに、セッション間で長期記憶を提供します。このクイックスタートでは、1 つのセッションでユーザーの好みの温度を学習し、次のセッションでその好みを呼び出すエージェントを実行します。
このクイックスタートでは、次の手順について説明します。
- 環境をセットアップする。
- Memory Bank インスタンスを作成します。
- メモリ対応の ADK エージェントをローカルで実行する。
- エージェントが新しいセッションで設定を記憶していることを確認します。
ADK を使用せずに Memory Bank を直接呼び出すには、Memory Bank API のクイックスタートをご覧ください。他のメモリツール、コールバック、ランタイムを選択するには、ADK で Memory Bank を使用するをご覧ください。
始める前に
- Google Cloud アカウントにログインします。 Google Cloudを初めて使用する場合は、アカウントを作成して、実際のシナリオで Google プロダクトのパフォーマンスを評価してください。新規のお客様には、ワークロードの実行、テスト、デプロイができる無料クレジット $300 分を差し上げます。
-
In the Google Cloud console, on the project selector page, select or create a Google Cloud project.
Roles required to select or create a project
- Select a project: Selecting a project doesn't require a specific IAM role—you can select any project that you've been granted a role on.
-
Create a project: To create a project, you need the Project Creator role
(
roles/resourcemanager.projectCreator), which contains theresourcemanager.projects.createpermission. Learn how to grant roles.
-
If you're using an existing project for this guide, verify that you have the permissions required to complete this guide. If you created a new project, then you already have the required permissions.
-
Verify that billing is enabled for your Google Cloud project.
Enable the Agent Platform API, if it is not already enabled.
Roles required to enable APIs
To enable APIs, you need the
serviceusage.services.enablepermission. If you created the project, then you likely already have this permission through the Owner role (roles/owner). Otherwise, you can get this permission through the Service Usage Admin role (roles/serviceusage.serviceUsageAdmin). Learn how to grant roles.-
In the Google Cloud console, on the project selector page, select or create a Google Cloud project.
Roles required to select or create a project
- Select a project: Selecting a project doesn't require a specific IAM role—you can select any project that you've been granted a role on.
-
Create a project: To create a project, you need the Project Creator role
(
roles/resourcemanager.projectCreator), which contains theresourcemanager.projects.createpermission. Learn how to grant roles.
-
If you're using an existing project for this guide, verify that you have the permissions required to complete this guide. If you created a new project, then you already have the required permissions.
-
Verify that billing is enabled for your Google Cloud project.
Enable the Agent Platform API, if it is not already enabled.
Roles required to enable APIs
To enable APIs, you need the
serviceusage.services.enablepermission. If you created the project, then you likely already have this permission through the Owner role (roles/owner). Otherwise, you can get this permission through the Service Usage Admin role (roles/serviceusage.serviceUsageAdmin). Learn how to grant roles.- Python 開発環境を設定します。
-
ローカルシェルを使用している場合は、ユーザー アカウントのローカル認証情報を作成します。
gcloud auth application-default login
Cloud Shell を使用している場合は、この操作を行う必要はありません。
認証エラーが返され、外部 ID プロバイダ(IdP)を使用している場合は、フェデレーション ID を使用して gcloud CLI にログインしていることを確認します。
必要なロール
Memory Bank インスタンスの作成、メモリの生成と取得に必要な権限を取得するには、プロジェクトに対する次の IAM ロールを付与するよう管理者に依頼してください。
- メモリーバンク インスタンスを作成または更新する: Agent Platform ユーザー(`roles/aiplatform.user`)
- 記憶の読み取り、書き込み、生成: メモリーバンク ユーザー(`roles/aiplatform.memoryUser`)
ロールの付与については、プロジェクト、フォルダ、組織へのアクセス権の管理をご覧ください。
必要な権限は、カスタムロールや他の事前定義ロールから取得することもできます。
環境の設定
ターミナルで、ADK と Agent Platform SDK をインストールします。
pip install --upgrade "google-adk[gcp]" "google-cloud-agentplatform>=2.0.1"このクイックスタートのスクリプトが読み取る環境変数を設定します。
export GOOGLE_GENAI_USE_ENTERPRISE=TRUE export GOOGLE_CLOUD_PROJECT=PROJECT_ID export GOOGLE_CLOUD_LOCATION=globalPROJECT_ID は、実際の Google Cloud プロジェクト ID に置き換えます。
このクイックスタートでは、グローバル エンドポイントを使用します。代わりにリージョンまたはマルチリージョンのロケーションを使用するには、
globalをサポートされているロケーションのいずれかに置き換えます。顧客管理の暗号鍵(CMEK)が必要な場合は、リージョンまたはマルチリージョンのロケーションを使用します。CMEK はグローバル エンドポイントでは使用できません。スクリプトがこれらの変数を読み取れるように、このクイックスタートの残りの部分を同じターミナル セッションとディレクトリで実行します。
Memory Bank インスタンスを作成する
次のコードを含むファイルを
create_memory_bank.pyという名前で作成します。import os import agentplatform client = agentplatform.Client( project=os.environ["GOOGLE_CLOUD_PROJECT"], location=os.environ["GOOGLE_CLOUD_LOCATION"], ) memory_bank = client.memory_banks.create( config={"display_name": "Memory Bank quickstart"} ) # Print only the instance ID, for example 1234567890. print(memory_bank.name.split("/")[-1])スクリプトを実行し、インスタンス ID を
MEMORY_BANK_ID環境変数に保存します。export MEMORY_BANK_ID=$(python create_memory_bank.py)これが最初の Memory Bank インスタンスの場合、作成に 1 ~ 2 分かかることがあります。
変数にインスタンス ID が含まれていることを確認します。
echo $MEMORY_BANK_ID出力は
1234567890などの ID です。出力が空の場合、または401エラーまたは403エラーが返された場合は、必要なロールを確認してgcloud auth application-default loginを実行します。新しいglobalインスタンスが最初の使用時に一時的な403エラーを返す場合は、30 秒待ってからスクリプトを再度実行します。
メモリ対応エージェントを実行する
このセクションのスクリプトは、同じユーザーに対して 2 つのセッションを実行します。最初のセッションで、ユーザーは温度の好みを指定します。2 番目のセッションでは、エージェントは Memory Bank からその設定を呼び出します。
次の手順を行います。
memory_agentという名前のディレクトリを作成します。mkdir memory_agent次のコードを含む
memory_agent/agent.pyという名前のファイルを作成します。このコードは、環境を設定するとMemory Bank インスタンスを作成するで設定した変数から、プロジェクト、ロケーション、インスタンス ID を読み取ります。コードを編集する必要はありません。import asyncio import os import agentplatform from google import adk from google.adk.agents.callback_context import CallbackContext from google.adk.memory import VertexAiMemoryBankService from google.adk.sessions import InMemorySessionService from google.adk.tools.preload_memory_tool import PreloadMemoryTool from google.genai import types PROJECT_ID = os.environ["GOOGLE_CLOUD_PROJECT"] LOCATION = os.environ["GOOGLE_CLOUD_LOCATION"] MEMORY_BANK_ID = os.environ["MEMORY_BANK_ID"] # Memory Bank scopes memories to this app name and user ID. APP_NAME = "memory_agent" USER_ID = "quickstart_user" async def generate_memories_callback( callback_context: CallbackContext, ) -> None: # Send the latest turn to Memory Bank and wait until memory generation # finishes, so that the next session can retrieve the new memory. await callback_context.add_events_to_memory( events=callback_context.session.events[-5:], custom_metadata={"wait_for_completion": True}, ) return None root_agent = adk.Agent( model="gemini-3.5-flash", name="memory_agent", instruction=( "You are a vehicle voice agent that controls in-vehicle settings. " "Use what you know about the user's preferences. " "If you don't know the user's preferred temperature, ask for it. " "Limit responses to under 30 words." ), tools=[PreloadMemoryTool()], after_agent_callback=generate_memories_callback, ) memory_service = VertexAiMemoryBankService( project=PROJECT_ID, location=LOCATION, agent_engine_id=MEMORY_BANK_ID, ) session_service = InMemorySessionService() runner = adk.Runner( agent=root_agent, app_name=APP_NAME, session_service=session_service, memory_service=memory_service, ) async def send_message(session_id: str, text: str) -> None: print(f"User: {text}") message = types.Content(role="user", parts=[types.Part(text=text)]) async for event in runner.run_async( user_id=USER_ID, session_id=session_id, new_message=message ): if event.is_final_response() and event.content: print(f"Agent: {event.content.parts[0].text}") async def main() -> None: print("--- Session 1: share a preference ---") session = await session_service.create_session( app_name=APP_NAME, user_id=USER_ID ) await send_message(session.id, "Can you fix the temperature?") await send_message(session.id, "I'm comfortable at 71 degrees.") print("--- Session 2: recall the preference ---") session = await session_service.create_session( app_name=APP_NAME, user_id=USER_ID ) await send_message(session.id, "Fix the temperature.") print("--- Memories stored in Memory Bank ---") client = agentplatform.Client(project=PROJECT_ID, location=LOCATION) memory_bank_name = ( f"projects/{PROJECT_ID}/locations/{LOCATION}" f"/reasoningEngines/{MEMORY_BANK_ID}" ) results = client.memory_banks.memories.retrieve( name=memory_bank_name, scope={"app_name": APP_NAME, "user_id": USER_ID}, ) for retrieved_memory in results.page: print(f"* {retrieved_memory.memory.fact}") if __name__ == "__main__": asyncio.run(main())スクリプトを実行します。
python memory_agent/agent.pyコールバックは、各ターンの後にメモリ生成が完了するまで待機するため、2 回目のセッションが開始されるときにメモリを使用できます。
エージェントが記憶していることを確認する
スクリプトが終了すると、両方の会話と保存されたメモリがターミナルに出力されます。その出力を次の例と比較して、エージェントが新しいセッションで設定を記憶していることを確認します。
最初のセッションでは、エージェントはユーザーのメモリを保持していないため、温度を尋ねます。
--- Session 1: share a preference ---
User: Can you fix the temperature?
Agent: Sure. What temperature would you like?
User: I'm comfortable at 71 degrees.
Agent: Okay, I've set the temperature to 71 degrees.
2 回目のセッションでは、エージェントは Memory Bank からメモリを取得し、質問することなく温度を 71 度に設定します。保存されたメモリは出力の最後に表示されます。
--- Session 2: recall the preference ---
User: Fix the temperature.
Agent: Okay, I've set the temperature to 71 degrees, as you prefer.
--- Memories stored in Memory Bank ---
* I like the temperature to be 71 degrees.
エージェントの回答とメモリの文言は、エージェントと Memory Bank が使用するモデルによって異なります。
省略可: ADK Web でエージェントとチャットする
ADK Web は、開発中にエージェントをテストするためのブラウザベースのインターフェースです。
同じターミナル セッションで、
memory_agentディレクトリを含むディレクトリから次のコマンドを実行します。adk web --memory_service_uri=agentengine://$MEMORY_BANK_ID memory_agentブラウザで
http://localhost:8000?userId=quickstart_userを開きます。userIdクエリ パラメータがスクリプトのユーザー ID と一致するため、エージェントはスクリプトが作成したメモリを取得できます。メッセージ
Fix the temperature.を送信し、エージェントが質問せずに温度を 71 度に設定することを確認します。エージェントは、メモリ対応エージェントを実行するでスクリプトが保存した設定を使用します。ADK Web を停止するには、ターミナルで Ctrl+C キーを押します。
クリーンアップ
このページで使用したリソースについて、 Google Cloud アカウントに課金されないようにするには、 Google Cloudプロジェクトを削除します。それ以外の場合は、個々のリソースを削除します。
次のコードを含むファイルを
clean_up.pyという名前で作成します。import os import agentplatform project = os.environ["GOOGLE_CLOUD_PROJECT"] location = os.environ["GOOGLE_CLOUD_LOCATION"] memory_bank_id = os.environ["MEMORY_BANK_ID"] client = agentplatform.Client(project=project, location=location) client.memory_banks.delete( name=f"projects/{project}/locations/{location}/reasoningEngines/{memory_bank_id}", force=True, )スクリプトを実行して、Memory Bank インスタンスを削除します。
python clean_up.py作成したローカル ファイルを削除します。
rm -r memory_agent create_memory_bank.py clean_up.py