擷取回憶

本頁面說明如何使用範圍為基礎的回憶擷取功能,從 Memory Bank 擷取回憶。如要瞭解設定、產生及使用 Memory Bank 的完整工作流程,請參閱「使用 REST API 快速入門」一文。

範圍式記憶體擷取

您可以使用 RetrieveMemories 擷取特定範圍的回憶。系統只會傳回與擷取要求範圍完全相同 (不受順序影響) 的回憶錄。舉例來說,您可以使用 {"user_id": "123"} 擷取特定使用者範圍內的所有回憶集錦。如果沒有任何回憶集錦,表示 Memory Bank 沒有提供範圍內的任何回憶集錦。

記憶體的範圍是在記憶體產生或建立時定義,且無法變更。

您可以使用 RetrieveMemories 針對特定範圍執行下列作業:

如果特定範圍內有許多回憶,你可以提供相似搜尋參數,讓相似搜尋功能只擷取最相似的回憶。執行相似搜尋時,回憶銀行只會考慮與要求範圍完全相同的回憶集錦。相似度搜尋會比較記憶中的事實與要求的搜尋查詢之間的嵌入向量。

系統會將傳回的回憶依相似程度排序 (最短的歐氏距離) 到最不相似 (最長的歐氏距離):

import requests

url = "https://LOCATION-aiplatform.googleapis.com/v1beta1/AGENT_ENGINE_NAME"

response = requests.post(
  url=f"{url}/memories:retrieve",
  headers={
    "Content-Type": "application/json; charset=utf-8",
    "Authorization": f"Bearer {token[0]}",
  },
  json={
    "similarity_search_params": {
      "search_query": "QUERY",
      # Optional. Defaults to 3.
      "top_k": 3
    },
    "scope": SCOPE
  }
)

"""
Returns:

{
  "retrieved_memories": [
    {
      "memory": {
        "name":
        "projects/.../locations/.../reasoningEngines/.../memories/...",
        ...
        "fact": "This is a fact."
      },
      "distance": 0.5
    },
    {
      "memory": {
        "name": "projects/.../locations/.../reasoningEngines/.../memories/...",
        ...
        "fact": "This is another fact."
      },
      "distance": 0.75
    }
  ]
}
"""

更改下列內容:

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

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

  • QUERY:要執行相似度搜尋的查詢。舉例來說,您可以將對話的最後一個使用者回合做為查詢。

  • SCOPE:字典,代表相似度搜尋的範圍。系統只會考量與要求範圍相同的回憶集。

擷取所有回憶

如果未提供相似度搜尋參數,RetrieveMemories 會傳回所有包含指定範圍的回憶,不論與目前對話的相似度為何。

import requests

url = "https://LOCATION-aiplatform.googleapis.com/v1beta1/AGENT_ENGINE_NAME"

response = requests.post(
  url=f"{url}/memories:retrieve",
  headers={
    "Content-Type": "application/json; charset=utf-8",
    "Authorization": f"Bearer {token[0]}",
  },
  json={
    "scope": SCOPE,
    # Optional. By default, a page size of 100 will be used.
    "simple_retrieval_params": {
      "page_size": 3
    }
  }
)

"""
Returns:

{
  "retrieved_memories": [
    {
      "memory": {
        "name":
        "projects/.../locations/.../reasoningEngines/.../memories/...",
        ...
        "fact": "This is a fact."
      }
    },
    {
      "memory": {
        "name": "projects/.../locations/.../reasoningEngines/.../memories/...",
        ...
        "fact": "This is another fact."
      }
    }
  ]
}
"""

更改下列內容:

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

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

  • SCOPE:代表擷取範圍的字典。系統只會傳回與要求範圍相同的回憶集錦。