エージェント開発キットを使用したクイックスタート

Vertex AI Agent Engine Sessions と Memory Bank を使用するように Agent Development Kit(ADK)エージェントを構成すると、エージェントは自動的にメモリーとセッションの読み取りと書き込みを行います。

REST API を使用したクイックスタートについては、REST API のクイックスタートをご覧ください。

このチュートリアルでは、ADK で Vertex AI Agent Engine Sessions と Memory Bank を使用してセッションと長期記憶を作成して使用する方法について説明します。

  1. Vertex AI Agent Engine のセッションとメモリバンクにアクセスするには、Vertex AI Agent Engine インスタンスを作成します。

  2. ローカル ADK エージェントとランナーを作成します

  3. エージェントとやり取りして、セッション間でアクセス可能な長期記憶を動的に生成します。

  4. クリーンアップします。

始める前に

このチュートリアルで説明する手順を完了するには、まずプロジェクトと環境を設定する必要があります。

プロジェクトを設定する

  1. Sign in to your Google Cloud account. If you're new to Google Cloud, create an account to evaluate how our products perform in real-world scenarios. New customers also get $300 in free credits to run, test, and deploy workloads.
  2. In the Google Cloud console, on the project selector page, select or create a Google Cloud project.

    Go to project selector

  3. Make sure that billing is enabled for your Google Cloud project.

  4. Enable the Vertex AI API.

    Enable the API

  5. In the Google Cloud console, on the project selector page, select or create a Google Cloud project.

    Go to project selector

  6. Make sure that billing is enabled for your Google Cloud project.

  7. Enable the Vertex AI API.

    Enable the API

  8. プロジェクトを選択した場合は、そのプロジェクトに対する Vertex AI ユーザーroles/aiplatform.user)IAM ロールがあることを確認します。
  9. Vertex AI に対する認証

    ローカル開発環境でこのページの Python サンプルを使用するには、gcloud CLI をインストールして初期化し、ユーザー認証情報を使用してアプリケーションのデフォルト認証情報を設定します。

    1. Install the Google Cloud CLI.

    2. If you're using an external identity provider (IdP), you must first sign in to the gcloud CLI with your federated identity.

    3. To initialize the gcloud CLI, run the following command:

      gcloud init
    4. If you're using a local shell, then create local authentication credentials for your user account:

      gcloud auth application-default login

      You don't need to do this if you're using Cloud Shell.

      If an authentication error is returned, and you are using an external identity provider (IdP), confirm that you have signed in to the gcloud CLI with your federated identity.

    詳細については、 Google Cloud 認証ドキュメントのローカル開発環境の ADC の設定をご覧ください。

    ライブラリをインポートする

    Agent Development Kit と Vertex AI SDK をインストールします。

    pip install google-adk>=1.5.0
    pip install google-cloud-aiplatform>=1.100.0

    環境変数を設定する

    ADK を使用するには、環境変数を設定します。

    import os
    
    os.environ["GOOGLE_GENAI_USE_VERTEXAI"] = "TRUE"
    os.environ["GOOGLE_CLOUD_PROJECT"] = "PROJECT_ID"
    os.environ["GOOGLE_CLOUD_LOCATION"] = "LOCATION"
    

    次のように置き換えます。

    • PROJECT_ID: プロジェクト ID。
    • LOCATION: リージョン。Vertex AI Agent Engine Memory Bank では us-central1 のみがサポートされています。

    Vertex AI Agent Engine インスタンスを作成する

    Vertex AI Agent Engine セッションと Vertex AI Agent Engine Memory Bank にアクセスするには、まず Vertex AI Agent Engine インスタンスを作成する必要があります。セッションとメモリバンクの使用を開始するためにコードをデプロイする必要はありません。コードなしでデプロイする場合、Vertex AI Agent Engine インスタンスの作成には数秒かかります。

    import vertexai
    
    client = vertexai.Client(
        project="PROJECT_ID",
        location="LOCATION",
    )
    
    agent_engine = client.agent_engines.create()
    

    ADK エージェントを作成する

    1. ADK エージェントを開発する際は、メモリ サービスがいつ使用されるか、プロンプトにどのようにメモリが含まれるかを制御する Memory ツールを含めます。このエージェントの例では、PreloadMemoryTool を使用しています。これは、各ターンの開始時に常にメモリを取得し、システム指示にメモリを含めます。

      from google import adk
      
      agent = adk.Agent(
          model="gemini-2.0-flash",
          name='stateful_agent',
          instruction="""You are a Vehicle Voice Agent, designed to assist users with information and in-vehicle actions.
      
      1.  **Direct Action:** If a user requests a specific vehicle function (e.g., "turn on the AC"), execute it immediately using the corresponding tool. You don't have the outcome of the actual tool execution, so provide a hypothetical tool execution outcome.
      2.  **Information Retrieval:** Respond concisely to general information requests with your own knowledge (e.g., restaurant recommendation).
      3.  **Clarity:** When necessary, try to seek clarification to better understand the user's needs and preference before taking an action.
      4.  **Brevity:** Limit responses to under 30 words.
      """,
          tools=[adk.tools.preload_memory_tool.PreloadMemoryTool()]
      )
      
    2. ADK ランナーが思い出の取得に使用する VertexAiMemoryBankService メモリ サービスを作成します。

      from google.adk.memory import VertexAiMemoryBankService
      
      agent_engine_id = agent_engine.api_resource.name.split("/")[-1]
      
      memory_service = VertexAiMemoryBankService(
          project="PROJECT_ID",
          location="LOCATION",
          agent_engine_id=agent_engine_id
      )
      
    3. エージェント、ツール、コールバックの実行をオーケストレートする ADK ランナーを作成します。

      from google.adk.sessions import VertexAiSessionService
      from google.genai import types
      
      # You can use any ADK session service.
      session_service = VertexAiSessionService(
          project="PROJECT_ID",
          location="LOCATION",
          agent_engine_id=agent_engine_id
      )
      
      app_name="APP_NAME"
      runner = adk.Runner(
          agent=agent,
          app_name=app_name,
          session_service=session_service,
          memory_service=memory_service
      )
      
      def call_agent(query, session, user_id):
        content = types.Content(role='user', parts=[types.Part(text=query)])
        events = runner.run(user_id=user_id, session_id=session, new_message=content)
      
        for event in events:
            if event.is_final_response():
                final_response = event.content.parts[0].text
                print("Agent Response: ", final_response)
      

      次のように置き換えます。

      • APP_NAME: ADK アプリの名前。

    エージェントを操作する

    エージェントを定義し、セッションとメモリバンクを設定したら、エージェントとやり取りできます。

    1. 最初のセッションを作成します。ユーザーとの最初のセッションでは利用可能なメモリがないため、エージェントはユーザーの好みの温度などのユーザー設定を認識していません。

      session = await session_service.create_session(
          app_name=app_name,
          user_id="USER_ID"
      )
      
      call_agent(
          "Can you update the temperature to my preferred temperature?",
          session.id,
          "USER_ID"
      )
      
      # Agent response: "What is your preferred temperature?"
      call_agent("I like it at 71 degrees", session.id, "USER_ID")
      # Agent Response:  Setting the temperature to 71 degrees Fahrenheit.
      # Temperature successfully changed.
      

      次のように置き換えます。

      • USER_ID: ユーザーの識別子。このセッションから生成されたメモリーは、この不透明な識別子でキー設定されます。生成された思い出のスコープは {"user_id": "USER_ID"} として保存されます。
    2. 現在のセッションの思い出を生成します。Memory Bank が会話から思い出を抽出すると、それらはスコープ {"user_id": USER_ID, "app_name": APP_NAME} に保存されます。

      session = await session_service.get_session(
          app_name=app_name,
          user_id="USER_ID",
          session_id=session.id
      )
      await memory_service.add_session_to_memory(session)
      
    3. 2 つ目のセッションを作成します。PreloadMemoryTool を使用した場合、エージェントは各ターンの開始時にメモリを取得して、ユーザーが以前にエージェントに伝えた設定にアクセスします。

      session = await session_service.create_session(
          app_name=app_name,
          user_id="USER_ID"
      )
      
      call_agent("Fix the temperature!", session.id, "USER_ID")
      # Agent Response:  Setting temperature to 71 degrees.  Is that correct?
      

    クリーンアップ

    このプロジェクトで使用しているすべてのリソースをクリーンアップするには、クイックスタートで使用した Google Cloud プロジェクトを削除します。

    それ以外の場合は、このチュートリアルで作成した個々のリソースを次のように削除できます。

    1. 次のコードサンプルを使用して Vertex AI Agent Engine インスタンスを削除します。これにより、その Vertex AI Agent Engine に属するセッションまたはメモリも削除されます。

      agent_engine.delete(force=True)
      
    2. ローカルで作成したファイルを削除します。

    次のステップ