記憶體設定檔

您可以使用 Memory Bank 生成結構化設定檔,也就是使用 LLM 填入及更新靜態結構定義的資料結構。定義固定結構定義後,代理就能立即存取不斷變化的資訊,且延遲時間極短,不必在工作階段期間執行昂貴的搜尋作業。

如要完成本指南示範的步驟,請先按照「設定 Memory Bank」中的步驟操作。

總覽

在代理中使用結構化設定檔,可確保擷取的資訊 (例如使用者的技術堆疊或偏好設定) 能以一致的格式快速、簡潔地呈現。舉例來說,您可以擷取包含下列內容的設定檔:

MemoryProfile(
    profile={
        "technical_stacks": "ADK, Python",
        "preferred_language": "Python",
        "tone_preference": "Succinct"
    },
    schema_id="user-profile"
)

結構化設定檔經過最佳化,可縮短檢索延遲時間,因為整理資訊的繁重工作已在生成時完成。非常適合用於初始化代理與使用者之間的互動。

瞭解結構化記憶體分析器設定檔

結構化設定檔的生成方式與自然語言記憶相同 (GenerateMemories 和 IngestEvents)。定義結構定義後,Memory Bank 會自動嘗試使用提供的資料來源,生成符合結構定義的設定檔。

使用結構化設定檔時,Memory Bank 會在生成記憶時執行下列作業:

  • 擷取:從資料來源擷取符合結構定義的資訊和情境。系統只會擷取符合結構定義的資訊。你可以使用記憶修訂版本,查看系統擷取的資訊和背景資訊。
  • 整合:更新 (如有必要) 設定檔中的現有欄位。LLM 會根據新擷取的資訊和背景資訊,判斷如何更新現有內容。如果設定檔中沒有該欄位,系統會略過合併作業,直接使用擷取的資訊更新欄位。

系統會根據您將資料擷取至 Memory Bank 時提供的 scope (例如 {"user_id": "123"}) 隔離設定檔。針對每個結構定義和範圍,記憶庫會維護單一設定檔,做為可靠資料來源。產生的設定檔由一或多個 Memory 執行個體組成。每個 Memory 執行個體都代表設定檔中的單一欄位,可用於檢查欄位的中繼資料和修訂版本記錄,例如:

Memory(
     create_time=datetime.datetime(...),
     memory_type=<MemoryType.STRUCTURED_PROFILE: 'STRUCTURED_PROFILE'>,
     name='projects/.../locations/.../reasoningEngines/.../memories/...',
     scope={
       'user_id': '123'
     },
     structured_content=MemoryStructuredContent(
       data={
         'language_preference': 'Java'
       },
       schema_id='user-profile'
     ),
     update_time=datetime.datetime(...),
     expire_time=datetime.datetime(...),
     metadata={...}
)

結構定義

Memory Bank 生成的設定檔會與 Memory Bank 執行個體上定義的結構定義保持一致。您可以定義多個獨立的設定檔結構定義,每個結構定義都必須有專屬 ID。請注意,新增或更新結構定義不會補充先前記憶的設定檔。

控制台

如要在 Google Cloud 控制台的獨立記憶庫執行個體上,新增或編輯設定檔結構定義 (需要aiplatform.reasoningEngines.update才能儲存變更),請按照下列步驟操作:

  1. 前往 Google Cloud 控制台的 Agent Platform「Memory Bank」頁面,然後點選 Memory Bank 執行個體。

    前往記憶庫

  2. 按一下動作列中的「Schemas」(或「Configuration」分頁的「Generation」部分)。

  3. 按一下「Add schema」(新增結構定義),建立具有專屬 ID 的結構定義,或按一下現有結構定義資訊卡標題展開。

  4. 使用「Simple」(簡易) 或「JSON」檢視畫面定義或編輯結構定義欄位,然後按一下「Save」(儲存)。

Agent Platform SDK

您可以使用 pydantic 模型,定義要讓 Memory Bank 擷取及維護的欄位。例如:

from pydantic import BaseModel, Field
from typing import Literal

class UserProfile(BaseModel):
    name: str = Field(
      description="Name of the user.")
    technical_stack: str = Field(
      description="Comma-separated list tools or languages used by the user.")
    primary_goal: str = Field(
      description="The main objective the user is pursuing.")
    expertise_level: str = Field(
      description="Current skill level (e.g., Junior, Senior).")
    job_status: Literal['unemployed', 'part_time', 'full_time', 'student'] = Field(
      description="The job status of the individual")

建立或更新 Memory Bank 執行個體時,請將結構定義上傳至 Memory Bank:

schema_config = {
  "id": "user-profile",
  "memory_schema": UserProfile.model_json_schema()
}

memory_bank = client.memory_banks.create(
    managed_semantic_memory_config={
        "structured_memory_configs": [
            {
                "schema_configs": [schema_config]
            }
        ]
    }
)

根據預設,Memory Bank 會擷取自然語言記憶。如果只想讓 Memory Bank 生成設定檔,可以關閉自然語言記憶生成功能:

memory_bank = client.memory_banks.create(
    managed_semantic_memory_config={
        "structured_memory_configs": [
            {
                "schema_configs": [schema_config]
            }
        ],
        # Optional: Turn off natural language memories.
        "unstructured_memory_configs": [
            {"disable_natural_language_memories": True}
        ]
    }
)

產生設定檔

如要觸發結構化記憶的生成,請將對話記錄 (事件) 提供給 GenerateMemories 或 IngestEvents 方法。與自然語言記憶一樣,Memory Bank 會使用 LLM 從資料來源擷取有意義的資訊,並與現有記憶整合。

範例

以下範例說明如何使用先前定義的結構定義生成記憶設定檔。

在傳送至 Memory Bank 的第一組事件中 (範圍為 {"user_id": "123"}),使用者表示他們使用 ADK 代理:

client.memory_banks.memories.generate(
  name=memory_bank.name,
  scope={"user_id": "123"},
  direct_contents_source={
    "events": [
      {"content": {
        "parts": [{
          "text": "Can you help me build an ADK agent that organizes my daily tasks?"}]}}]
  }
)

Memory Bank 會擷取「ADK」做為結構定義中的 technical_stack 欄位。由於擷取的事件不含其餘結構定義的相關資訊,因此不會填入其他欄位。由於這是這個範圍的最初互動,系統會略過合併,並使用這個初始值初始化設定檔。

result = client.memory_banks.memories.retrieve_profiles(
    name=memory_bank.name,
    scope={"user_id": "123"},
)

"""
Returns:

RetrieveProfilesResponse(
  profiles={
    'user-profile': MemoryProfile(
      profile={
        'technical_stack': 'ADK'
      },
      schema_id='user-profile'
    )
  }
)
"""

在下一組傳送至 Memory Bank 的事件中,使用者表示自己是學生,主要使用 Python 編寫程式碼:

client.memory_banks.memories.generate(
  name=memory_bank.name,
  scope={"user_id": "123"},
  direct_contents_source={
    "events": [
      {"content": {
        "parts": [
          {"text": "Do you have any career recommendations for students that specialize in Python?"}]}}]
  }
)

Memory Bank 會從互動中擷取「Python」和「學生」狀態。technical_stack 片段會合併,並將「Python」附加至現有的「ADK」項目。系統會將「student」列舉填入先前空白的 job_status 欄位,並略過合併步驟。

result = client.memory_banks.memories.retrieve_profiles(
    name=memory_bank.name,
    scope=scope
)

"""
Returns:

RetrieveProfilesResponse(
  profiles={
    'user-profile': MemoryProfile(
      profile={
        'technical_stack': 'ADK, Python',
        'job_status': 'student'
      },
      schema_id='user-profile'
    )
  }
)
"""

擷取設定檔

產生後,您可以使用 RetrieveProfiles 方法擷取特定範圍的整合設定檔。這會傳回對應至結構定義的最新資料。

result = client.memory_banks.memories.retrieve_profiles(
  name=memory_bank.name,
  scope={"user_id": "123"},
)

# Accessing the data
for profile in result.profiles.values():
  print(profile)
  # Output: {'technical_stack': 'ADK, Python', 'job_status': 'student', ...}

設定檔檢查

在幕後,設定檔是由 STRUCTURED_PROFILE 類型的個別記憶組成。結構定義中的每個欄位都會對應至每個範圍的單一記憶體,提供精細的觀測能力。

雖然 RetrieveProfiles 是在正式環境中擷取設定檔的主要方法,但您可以在Google Cloud 控制台或使用 Agent Platform SDK 檢查個別記憶,稽核設定檔的演變:

  • 欄位層級中繼資料:查看及更新設定檔中個別欄位的特定存留時間 (TTL) 和 Memory.metadata。
  • 修訂版本記錄:追蹤欄位的歷程,查看歷來值和觸發每項變更的特定對話內容。

控制台

  1. 在 Google Cloud 控制台,前往「Memory Bank」頁面開啟獨立執行個體,或前往「Deployments」頁面開啟已部署的代理,然後選取「Memories」分頁標籤。

    前往記憶庫

  2. 選取「Structured」(結構化),然後選擇目標範圍內所有鍵的值 (或在「Unstructured」(非結構化) 中套用範圍篩選器,然後按一下「Search structured memories」(搜尋結構化記憶體))。相符的設定檔資料列會顯示「Schema」(結構定義)、「Type」(類型)、「Content」(內容)、「Created」(建立時間)和「Updated」(更新時間)。

  3. 按一下設定檔資料列上的「View」,開啟「Memory details」面板,其中會顯示範圍方塊、結構定義連結、個別「Memory facts」(每個事實都有「View revisions」),以及整合設定檔 JSON。

Agent Platform SDK

使用 RetrieveMemories 擷取含有使用者設定檔片段的記憶。根據預設,RetrieveMemories 只會擷取自然語言記憶,因此請明確要求 STRUCTURED_PROFILE 記憶:

client.memory_banks.memories.retrieve(
  name="...",
  scope={"user_id": "123"},
  config={
    "memory_types": ["STRUCTURED_PROFILE"]
  }
)

"""
Returns:

[RetrieveMemoriesResponseRetrievedMemory(
   memory=Memory(
     create_time=datetime.datetime(...),
     memory_type=<MemoryType.STRUCTURED_PROFILE: 'STRUCTURED_PROFILE'>,
     name='projects/.../locations/.../reasoningEngines/.../memories/...',
     scope={
       'user_id': '123'
     },
     structured_content=MemoryStructuredContent(
       data={
         'technical_stack': 'ADK, Python'
       },
       schema_id='user'
     ),
     update_time=datetime.datetime(...)
   )
 )]
"""

接著,擷取結構化設定檔片段的修訂版本記錄,檢查設定檔欄位隨時間變化的情形,以及每次變更的背景資訊:

for retrieved_memory in list(results):
    list(client.memory_banks.memories.revisions.list(
        name=retrieved_memory.memory.name
    ))

"""
Returns:

[MemoryRevision(
   create_time=datetime.datetime(...),
   expire_time=datetime.datetime(...),
   extracted_memories=[
     IntermediateExtractedMemory(
       context='The user indicated that they have expertise in Python when asking about career options.',
       structured_data={
         'technical_stack': 'Python'
       }
     ),
   ],
   name='projects/.../locations/.../reasoningEngines/.../memories/.../revisions/...',
   structured_data={
     'technical_stack': 'ADK, Python'
   }
 ),
 MemoryRevision(
   create_time=datetime.datetime(...),
   expire_time=datetime.datetime(...),
   extracted_memories=[
     IntermediateExtractedMemory(
       context='The user indicated that they need help building an ADK agent',
       structured_data={
         'technical_stack': 'ADK'
       }
     ),
   ],
   name='projects/.../locations/.../reasoningEngines/.../memories/.../revisions/...',
   structured_data={
     'technical_stack': 'ADK'
   }
 )]
"""