快速開始使用 REST API

本教學課程將示範如何直接對 Vertex AI Agent Engine 工作階段和記憶庫發出 REST API 呼叫,以建立及使用工作階段和長期記憶。如果您不想讓代理程式架構為您協調呼叫,或是想將工作階段和 Memory Bank 與代理程式開發套件 (ADK) 以外的代理程式架構整合,請使用 REST API。

如需使用 ADK 的快速入門指南,請參閱「使用代理程式開發套件快速入門」。

本教學課程會使用下列步驟:

  1. 建立 Vertex AI Agent Engine 執行個體,以便存取 Vertex AI Agent Engine 工作階段和記憶體庫。
  2. 使用下列選項建立回憶集錦:
  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」。

    建立 Vertex AI Agent Engine 執行個體

    如要存取 Vertex AI Agent Engine 工作階段和 Vertex AI Agent Engine 記憶體庫,您必須先建立 Vertex AI Agent Engine 執行個體。您不必部署代理程式,即可開始使用會話和記憶庫。在沒有代理部署的情況下,建立 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 做為輸出維度即可。

    從 Vertex AI Agent Engine 工作階段產生回憶

    設定 Vertex AI Agent Engine 工作階段和記憶庫後,您可以建立工作階段,並附加事件。系統會根據使用者與服務專員的對話內容產生記憶,並將這些事實儲存為記憶,以利日後的使用者互動。詳情請參閱「產生及擷取回憶集錦」。

    1. 建立使用不透明使用者 ID 的工作階段。除非您在產生回憶集錦時明確提供範圍,否則系統會自動使用範圍 {"user_id": "USER_ID"} 為這個工作階段產生的所有回憶集錦建立索引。

      from google.cloud import aiplatform_v1beta1
      
      sessions_client = aiplatform_v1beta1.SessionServiceClient(
        client_options={
          "api_endpoint": "https://LOCATION-aiplatform.googleapis.com"
        },
        transport="rest")
      
      session_lro = sessions_client.create_session(
        parent=AGENT_ENGINE_NAME,
        session={"user_id": "USER_ID"}
      )
      session_id = session_lro.operation.name.split("/")[-3]
      

      更改下列內容:

      • LOCATION:您的區域。Vertex AI Agent Engine 的 Memory Bank 和工作階段僅支援 us-central1

      • AGENT_ENGINE_NAME:您建立的 Vertex AI Agent Engine 執行個體名稱,或現有的 Vertex AI Agent Engine 執行個體名稱。名稱的格式應為 projects/{your project}/locations/{your location}/reasoningEngine/{your reasoning engine}

      • USER_ID:使用者 ID。除非您在產生回憶集錦時明確提供範圍,否則系統會自動使用範圍 {"user_id": "USER_ID"} 為這個工作階段產生的所有回憶集錦建立索引。

    2. 將事件重複上傳至工作階段。事件可以是使用者、服務專員和工具之間的任何互動。排序後的事件清單代表工作階段的對話記錄。系統會使用這份對話記錄,為該使用者產生回憶。

      event = aiplatform_v1beta1.SessionEvent(
          author="user",  # Required by Sessions.
          invocation_id="1",  # Required by Sessions.
          timestamp=datetime.now().strftime('%Y-%m-%dT%H:%M:%SZ'),  # Required by Sessions.
          content = aiplatform_v1beta1.Content(
              role="user",
              parts=[aiplatform_v1beta1.Part(text="Hello")]
          )
      )
      
      client.append_event(name=f"{agent_engine_name}/sessions/{session_id}", event=event)
      
    3. 如要根據對話記錄產生回憶集錦,請為工作階段觸發回憶集錦產生要求:

      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.post(
        url=f"{url}/memories:generate",
        headers={
          "Content-Type": "application/json; charset=utf-8",
          "Authorization": f"Bearer {credentials.token}",
        },
        json={
          "vertex_session_source": {
            "session": f"{agent_engine_name}/sessions/{session_id}"
          },
          # Optional when using Agent Engine Sessions. Defaults to {"user_id": session.user_id}.
          "scope": SCOPE
        }
      )
      

    更改下列內容:

    • (選用) SCOPE:字典,代表產生回憶的範圍。例如,{"session_id": "MY_SESSION"}。系統只會合併相同範圍的回憶集錦。如果未提供,系統會使用 {"user_id": session.user_id}

    上傳回憶

    除了使用原始對話產生回憶集錦,您也可以直接使用 CreateMemory 上傳回憶集錦。您可以直接提供應儲存的使用者事實,而非讓 Memory Bank 從內容中擷取資訊。建議您以第一人稱 (例如 I am a software engineer) 寫出使用者相關事實。

    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.post(
      url=f"{url}/memories",
      headers={
        "Content-Type": "application/json; charset=utf-8",
        "Authorization": f"Bearer {credentials.token}",
      },
      json={
        "fact": "This is a fact",
        "scope": {"user_id": "USER_ID"}
      }
    )
    

    擷取及使用回憶

    您可以為使用者擷取回憶,並將這些內容納入系統指示,讓大型語言模型存取您的個人化內容。

    如要瞭解以範圍為基礎的回憶擷取方法,請參閱「擷取回憶」說明文件。

    response = requests.post(
      url=f"{url}/memories:retrieve",
      headers={
        "Content-Type": "application/json; charset=utf-8",
        "Authorization": f"Bearer {credentials.token}",
      },
      json={
        "scope": {"user_id": "USER_ID"}
      }
    )
    

    您可以使用 jinja 將結構化回憶轉換為提示:

    
    from jinja2 import Template
    
    template = Template("""
    <MEMORIES>
    Here is some information about the user:
    {% for memory in data.memories %}* {{ memory.fact }}
    {% endfor %}</MEMORIES>
    """)
    
    prompt = template.render(data=response.json())
    
    """
    Output:
    
    <MEMORIES>
    Here is some information about the user:
    * This is a fact
    </MEMORIES>
    """
    
    

    清除所用資源

    如要清除此專案中使用的所有資源,您可以刪除用於入門導覽的 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. 刪除任何在本機建立的檔案。

    後續步驟