使用 Agent Development Kit 的快速入門

設定代理程式開發套件 (ADK) 代理程式以使用 Vertex AI Agent Engine 工作階段和記憶體銀行後,代理程式就會自動讀取及寫入記憶體和工作階段

如需使用 REST API 的快速入門導覽課程,請參閱「使用 REST API 的快速入門導覽課程」。

本教學課程將示範如何使用 Vertex AI Agent Engine 工作階段和記憶庫,搭配 ADK 建立及使用工作階段和長期記憶:

  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,然後使用您的使用者憑證設定應用程式預設憑證。

  10. Install the Google Cloud CLI.

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

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

    gcloud init
  13. 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.

  14. 詳情請參閱 Google Cloud 驗證說明文件中的「 為本機開發環境設定 ADC」。

    匯入程式庫

    安裝 Agent Development Kit:

    pip install google-adk==1.2.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 的記憶體銀行和工作階段僅支援 us-central1

    建立 Vertex AI Agent Engine 執行個體

    如要存取 Vertex AI Agent Engine 工作階段和 Vertex AI Agent Engine 記憶體庫,您必須先建立 Vertex AI Agent Engine 執行個體。您無需部署任何程式碼,即可開始使用 Sessions 和 Memory Bank。在沒有程式碼部署作業的情況下,建立 Vertex AI Agent Engine 執行個體應只需幾秒鐘的時間。

    如果您希望 Vertex AI Agent Engine 記憶庫使用大型語言模型 (LLM) 為您產生回憶,請提供 memoryBankConfig.generationConfig,並納入您希望記憶庫用來產生回憶的模型。專案的 Vertex AI Reasoning Engine 服務代理必須具備 aiplatform.endpoints.predict 權限,才能使用模型。

    import requests
    
    import google.auth
    import google.auth.transport.requests
    
    credentials, _ = google.auth.default()
    auth_req = google.auth.transport.requests.Request()
    credentials.refresh(auth_req)
    
    url = "https://LOCATION-aiplatform.googleapis.com/v1beta1/projects/PROJECT_ID/locations/LOCATION/reasoningEngines"
    
    response = requests.post(
        url=url,
        json={
            "contextSpec": {
                "memoryBankConfig": {
                    "generationConfig": {
                        "model": f"projects/PROJECT_ID/locations/LOCATION/publishers/google/models/MODEL_NAME"
                    },
                    "similaritySearchConfig": {
                        "embeddingModel": f"projects/PROJECT_ID/locations/LOCATION/publishers/google/models/EMBEDDING_MODEL_NAME"
                    }
                }
            }
        },
        headers={
            "Content-Type": "application/json; charset=utf-8",
            "Authorization": f"Bearer {credentials.token}"
        }
    
    )
    
    split_name = response.json()["name"].split("/")
    agent_engine_name = "/".join(split_name[:-2])
    

    更改下列內容:

    • PROJECT_ID:您的專案 ID。
    • LOCATION:您的區域。Vertex AI Agent Engine 的記憶體銀行和工作階段僅支援 us-central1
    • MODEL_NAME:用於產生回憶的 LLM 模型。您可以使用任何 Gemini 或 Model Garden 模型
    • EMBEDDING_MODEL_NAME:(選用) 用於在特定範圍內找出相似回憶的嵌入模型。您可以使用任何Embeddings API 支援的模型,只要該模型支援向量長度 768 做為輸出維度即可。

    建立 ADK 代理程式

    1. 在 ADK BaseMemoryService 中包裝記憶體銀行,建立以 Vertex AI Agent Engine 記憶體銀行為基礎的記憶體服務。執行程式會呼叫 add_session_to_memory 觸發記憶體產生作業,並呼叫 search_memory 擷取目前範圍的記憶體。

      from datetime import datetime
      import json
      import pprint
      import requests
      
      from google import adk
      from google.adk.memory import BaseMemoryService
      from google.adk.memory import base_memory_service
      from google.adk.memory import memory_entry
      import google.auth
      import google.auth.transport.requests
      from google.genai import types
      
      class AgentEngineMemoryBankService(BaseMemoryService):
        """Memory service for Agent Engine Memory Bank."""
      
        def __init__(self, agent_engine_name):
          self.agent_engine_name = agent_engine_name
          self.url = f"https://us-central1-aiplatform.googleapis.com/v1beta1/{self.agent_engine_name}"
          self.credentials, _ = google.auth.default()
      
        async def add_session_to_memory(self, session: adk.sessions.Session):
          """Adds a session to Agent Engine Memory Bank.
      
          A session can be added multiple times during its lifetime.
      
          Args:
              session: The session to add.
          """
          auth_req = google.auth.transport.requests.Request()
          self.credentials.refresh(auth_req)
      
          response = requests.post(
              url=f"{self.url}/memories:generate",
              headers={
                  "Content-Type": "application/json; charset=utf-8",
                  "Authorization": f"Bearer {self.credentials.token}",
              },
              json={
                  "vertex_session_source": {
                      "session": f"{self.agent_engine_name}/sessions/{session.id}"
                  }
              }
          )
          return response.json()
      
        async def search_memory(
            self, app_name: str, user_id: str, query: str
        ) -> adk.memory.base_memory_service.SearchMemoryResponse:
          """Searches for memories that match the query."""
          auth_req = google.auth.transport.requests.Request()
          self.credentials.refresh(auth_req)
      
          filter = json.dumps(json.dumps({"user_id": user_id}))
      
          response = requests.get(
              url=f"{self.url}/memories?filter=scope={filter}",
              headers={
                  "Content-Type": "application/json; charset=utf-8",
                  "Authorization": f"Bearer {self.credentials.token}",
              },
          )
      
          memory_events = []
          for memory in response.json().get("memories", []):
              memory_events.append(
                  memory_entry.MemoryEntry(
                      author="user",
                      content=types.Content(
                        parts=[types.Part(text=memory.get("fact"))],
                        role="user"),
                      timestamp=memory.get("updateTime")
                  )
              )
      
          return base_memory_service.SearchMemoryResponse(memories=memory_events)
      
    2. 開發 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()]
      )
      
    3. 建立 ADK 執行程式,自動化調度管理虛擬服務專員、工具和回呼。當您將 VertexAiSessionServiceAgentEngineMemoryBankService 類別搭配使用時,執行程式會協調呼叫,以讀取及寫入工作階段和記憶體。

      from google.adk.sessions import VertexAiSessionService
      
      session_service = VertexAiSessionService(
        "PROJECT_ID", "LOCATION")
      
      memory_service = AgentEngineMemoryBankService(
        agent_engine_name="AGENT_ENGINE_NAME")
      
      runner = adk.Runner(
          agent=agent,
          app_name="AGENT_ENGINE_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)
      

      更改下列內容:

      • AGENT_ENGINE_NAME:您建立的 Vertex AI Agent Engine 執行個體名稱,或現有的 Vertex AI Agent Engine 執行個體名稱。名稱的格式應為 projects/PROJECT_ID/locations/LOCATION/reasoningEngines/REASONING_ENGINE_ID

    與服務專員互動

    定義服務機器人並設定工作階段和記憶庫後,您就可以與服務機器人互動。

    1. 建立第一個工作階段。由於在與使用者進行的首次對話中,系統沒有可用的記憶庫,因此對話方不會知道使用者的任何偏好設定,例如偏好的溫度:

      session = await session_service.create_session(
        app_name="AGENT_ENGINE_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:使用者 ID。這個工作階段產生的回憶會以這個不透明 ID 做為索引。產生的回憶集範圍會儲存為 {"user_id": "USER_ID"}

      如要使用工作階段產生回憶,請呼叫 add_session_to_memory

      await memory_service.add_session_to_memory(session)
      
    2. 建立第二個工作階段。如果您使用 PreloadMemoryTool,代理程式會在每個回合開始時擷取回憶,以便存取使用者先前向代理程式傳達的偏好設定。

      session = await session_service.create_session(
        app_name="AGENT_ENGINE_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 的所有工作階段或回憶。

      credentials, _ = google.auth.default()
      auth_req = google.auth.transport.requests.Request()
      credentials.refresh(auth_req)
      
      url = "https://LOCATION-aiplatform.googleapis.com/v1beta1/AGENT_ENGINE_NAME"
      
      response = requests.delete(
          url=url,
          json={"force": True},
          headers={
              "Content-Type": "application/json; charset=utf-8",
              "Authorization": f"Bearer {credentials.token}"
          }
      
      )
      
    2. 刪除任何在本機建立的檔案。

    後續步驟