如要使用 Agent Platform Memory Bank,請先建立及設定 Memory Bank 執行個體。這個執行個體會管理記憶內容,並可與各種執行階段的代理程式整合。
本文說明如何設定 Google Cloud 專案、安裝必要程式庫,以及建立或更新執行個體,並使用主題和 TTL 等自訂設定。
開始使用
使用記憶庫前,必須先設定環境。
設定 Google Cloud 專案
每項專案都可用專案編號或專案 ID 來識別。PROJECT_NUMBER 是系統在您建立專案時自動產生,而 PROJECT_ID 則是由您或專案建立者所建立。如何設定專案:
- 登入 Google Cloud 帳戶。如果您未曾使用過 Google Cloud,歡迎 建立帳戶,親自體驗實際使用我們產品的成效。新客戶還能獲得價值 $300 美元的免費抵免額,用於執行、測試及部署工作負載。
-
In the Google Cloud console, on the project selector page, select or create a Google Cloud project.
Roles required to select or create a project
- Select a project: Selecting a project doesn't require a specific IAM role—you can select any project that you've been granted a role on.
-
Create a project: To create a project, you need the Project Creator role
(
roles/resourcemanager.projectCreator), which contains theresourcemanager.projects.createpermission. Learn how to grant roles.
-
Verify that billing is enabled for your Google Cloud project.
Enable the Agent Platform API, if it is not already enabled.
Roles required to enable APIs
To enable APIs, you need the
serviceusage.services.enablepermission. If you created the project, then you likely already have this permission through the Owner role (roles/owner). Otherwise, you can get this permission through the Service Usage Admin role (roles/serviceusage.serviceUsageAdmin). Learn how to grant roles.-
In the Google Cloud console, on the project selector page, select or create a Google Cloud project.
Roles required to select or create a project
- Select a project: Selecting a project doesn't require a specific IAM role—you can select any project that you've been granted a role on.
-
Create a project: To create a project, you need the Project Creator role
(
roles/resourcemanager.projectCreator), which contains theresourcemanager.projects.createpermission. Learn how to grant roles.
-
Verify that billing is enabled for your Google Cloud project.
Enable the Agent Platform API, if it is not already enabled.
Roles required to enable APIs
To enable APIs, you need the
serviceusage.services.enablepermission. If you created the project, then you likely already have this permission through the Owner role (roles/owner). Otherwise, you can get this permission through the Service Usage Admin role (roles/serviceusage.serviceUsageAdmin). Learn how to grant roles.
取得必要權限
如要取得使用 Memory Bank 所需的權限,請要求管理員在專案中授予您下列 IAM 角色:
-
建立或更新 Memory Bank 執行個體:
Agent Platform 使用者 (
roles/aiplatform.user) -
讀取、寫入或生成記憶:Memory Bank 使用者 (
roles/aiplatform.memoryUser)
如要進一步瞭解如何授予角色,請參閱「管理專案、資料夾和組織的存取權」。
如果您要從部署在 Google Kubernetes Engine (GKE) 或 Cloud Run 的代理程式,對 Memory Bank 提出要求,請確認服務帳戶具備讀取、寫入或生成記憶內容的必要權限。推理引擎服務代理已具備讀取、寫入及生成記憶內容的必要權限,因此代理程式執行階段的外送要求應已具備存取記憶體庫的權限。
安裝程式庫
本節假設您已設定 Python 開發環境,或使用具備 Python 開發環境的執行階段 (例如 Colaboratory)。
安裝 Agent Platform SDK:
pip install google-cloud-agentplatform>=2.0.1驗證
請按照「向 Vertex AI 進行驗證」一文中的指示操作。
設定 Agent Platform SDK 用戶端
執行下列程式碼,設定 Agent Platform SDK 用戶端:
Agent Platform SDK
import agentplatform
client = agentplatform.Client(
project="PROJECT_ID",
location="LOCATION",
)
其中
多區域和全域端點
Memory Bank 支援多區域和全域端點:
- 如果是全域執行個體,請將位置設為
global。 - 如果是多區域執行個體,請將位置設為
us或eu。
建立或更新 Memory Bank 執行個體
如要開始使用 Memory Bank,您必須先建立 Memory Bank 執行個體。如果還沒有執行個體,可以透過預設設定建立一個,並選擇顯示名稱。
# create the resource
memory_bank = client.memory_banks.create(
config={
"display_name": "My Memory Bank",
}
)
# Optionally, print out the Memory Bank resource name. You will need the
# resource name to interact with your Memory Bank instance later on.
print(memory_bank.name)
如要自訂新/現有 Memory Bank 執行個體的行為設定,請參閱「設定 Memory Bank 執行個體」。舉例來說,您可以指定要讓 Memory Bank 記住哪些資訊。
建立 Memory Bank 執行個體後,您可以使用執行個體名稱讀取或寫入記憶內容。例如:
# Generate memories using your Memory Bank instance.
client.memory_banks.memories.generate(
# `name` should have the format `projects/.../locations/.../reasoningEngines/...`.
name=memory_bank.name,
...
)
與 Agent Runtime 搭配使用
雖然記憶體庫可用於任何執行階段,但您也可以搭配代理程式執行階段使用記憶體庫,從已部署的代理程式讀取及寫入記憶體。
如要使用內建的 Memory Bank 在 Agent Runtime 部署代理,請先設定 Agent Runtime 環境。接著,準備將代理程式部署至 Agent Runtime,並整合記憶體。部署的代理應視需要呼叫,讀取及寫入記憶。
AdkApp
如果您使用 Agent Platform Agent Development Kit (ADK) 範本,代理在部署至 Agent Runtime 時,預設會使用 VertexAiMemoryBankService。也就是說,ADK 記憶體工具會從記憶庫讀取記憶。
from google.adk.agents import Agent
from agentplatform.frameworks import AdkApp
# Develop an agent using the ADK template.
agent = Agent(...)
adk_app = AdkApp(
agent=adk_agent,
...
)
# Deploy the agent to Agent Runtime.
runtime = client.runtimes.create(
agent=adk_app,
config={
"staging_bucket": "STAGING_BUCKET",
"requirements": ["google-cloud-agentplatform[runtimes,adk]"],
# Optional.
**context_spec
}
)
# Update an existing Agent Runtime to add or modify the Runtime.
runtime = client.runtimes.update(
name=runtime.api_resource.name,
agent=adk_app,
config={
"staging_bucket": "STAGING_BUCKET",
"requirements": ["google-cloud-agentplatform[runtimes,adk]"],
# Optional.
**context_spec
}
)
更改下列內容:
- STAGING_BUCKET:用於暫存代理程式執行階段的 Cloud Storage bucket。
如要進一步瞭解如何搭配使用 Memory Bank 與 ADK,請參閱「ADK 快速入門導覽課程」。
自訂代理
您可以在 Agent Runtime 上部署自訂代理程式,並搭配 Memory Bank 使用。在這種情況下,代理程式應協調對 Memory Bank 的呼叫,以觸發記憶體生成和記憶體擷取呼叫。
部署至 Agent Runtime 的應用程式可以讀取環境變數 GOOGLE_CLOUD_PROJECT、GOOGLE_CLOUD_LOCATION、GOOGLE_CLOUD_AGENT_ENGINE_ID,從環境推論 Agent Runtime 名稱:
project = os.environ.get("GOOGLE_CLOUD_PROJECT")
location = os.environ.get("GOOGLE_CLOUD_LOCATION")
agent_engine_id = os.environ.get("GOOGLE_CLOUD_AGENT_ENGINE_ID")
agent_engine_name = f"projects/{project}/locations/{location}/reasoningEngines/{agent_engine_id}"
如果代理在 Agent Runtime 使用預設服務代理,則已具備讀取及寫入記憶的權限。如果您使用客戶服務帳戶,則須授予服務帳戶讀取和寫入記憶體的權限。所需權限取決於代理程式應能執行的作業。如果只想讓代理擷取及生成記憶,aiplatform.memories.generate 和 aiplatform.memories.retrieve 就足夠。
在所有其他執行階段中使用
如要在 Cloud Run 或 Colab 等其他環境使用 Memory Bank,請建立 Memory Bank。如未提供設定,系統會使用預設設定建立 Memory Bank,用於管理記憶生成和擷取。
memory_bank = client.memory_banks.create()
如果您先前使用過 Memory Bank,建立新的 Memory Bank 執行個體應該只需要幾秒鐘。如果是第一次使用 Memory Bank,可能需要較長時間 (1 到 2 分鐘)。
如要設定行為,請提供 Memory Bank 設定:
建立
memory_bank = client.memory_banks.create(
managed_semantic_memory_config={
"generation_config": ...,
"unstructured_memory_configs": [...],
"structured_memory_configs": [...],
"similarity_search_config": ...,
"ttl_config": ...,
"disable_memory_revisions": False,
}
)
更新
如要變更 Memory Bank 設定,可以更新 Memory Bank 執行個體。
memory_bank = client.runtimes.update(
# You can access the name using `memory_bank.name` for a MemoryBank object.
name="MEMORY_BANK_NAME",
config={
"context_spec": {
"memory_bank_config": {
"generation_config": ...,
"customization_configs": [...],
"structured_memory_configs": [...],
"similarity_search_config": ...,
"ttl_config": ...,
"disable_memory_revisions": False,
}
}
}
)
更改下列內容:
- MEMORY_BANK_NAME:Memory Bank 的名稱。格式應為
projects/.../locations/.../reasoningEngines/...。請參閱 Memory Bank 支援的區域。
只要環境有權讀取及寫入記憶,您就能使用記憶庫。舉例來說,如要搭配 Cloud Run 使用記憶庫,請授予 Cloud Run 服務身分讀取及寫入記憶的權限。所需權限取決於代理應能執行的作業。如果只想讓代理擷取及生成記憶,aiplatform.memories.generate 和 aiplatform.memories.retrieve 就足夠。
設定 Memory Bank 執行個體
你可以設定 Memory Bank,自訂記憶的生成和管理方式。如未提供設定,Memory Bank 會使用各類型設定的預設設定。
您可以為執行個體設定下列記憶體庫:
- 自訂設定 (
unstructured_memory_configs):設定如何從來源資料擷取記憶,並與現有記憶合併。 - 相似度搜尋設定:指定記憶庫用於相似度搜尋的嵌入模型。預設為
text-embedding-005。 - 生成設定:設定 Memory Bank 用於記憶生成的 LLM。預設值為
gemini-3.5-flash。 - 存留時間設定:設定如何為建立或更新的記憶內容自動設定存留時間。預設為沒有存留時間。
以下範例顯示預設記憶庫:
字典
managed_semantic_memory_config = {
"generation_config": {
# `gemini-3.5-flash` will be used to extract and consolidate memories.
"model": "projects/{PROJECT}/locations/{LOCATION}/publishers/google/models/gemini-3.5-flash"
},
"similarity_search_config": {
# `text-embedding-005` will be used for similarity search, including
# during consolidation. Consolidation uses similarity search to find
# candidate memories that may be updated with new information.
"embedding_model": "projects/{PROJECT}/locations/{LOCATION}/publishers/google/models/text-embedding-005"
},
"ttl_config": {
# Default TTL for memory revisions is 365 days.
"memory_revision_default_ttl": f"{365 * 24 * 60 * 60}s"
},
"unstructured_memory_configs": [
{
# Extract user information, preferences, key conversation details,
# and information that the user explicitly asked to be remembered.
"memory_topics": [
{"managed_memory_topic": {"managed_topic_enum": "USER_PERSONAL_INFO"}},
{"managed_memory_topic": {"managed_topic_enum": "USER_PREFERENCES"}},
{"managed_memory_topic": {"managed_topic_enum": "KEY_CONVERSATION_DETAILS"}},
{"managed_memory_topic": {"managed_topic_enum": "EXPLICIT_INSTRUCTIONS"}}
],
"consolidation_config": {
# Only use the latest memory revision of each candidate memory during
# consolidation.
"revisions_per_candidate_count": 1
},
# Only use the pre-defined set of examples.
"generate_memories_examples": [],
# Generate memories in the first person.
"enable_third_person_memories": False
}
],
# Memory revisions will be persisted. This can be overridden on a request-level.
"disable_memory_revisions": False
}
以類別為基礎
from agentplatform.types import ManagedSemanticMemoryConfig
from agentplatform.types import ManagedSemanticMemoryConfigGenerationConfig as GenerationConfig
from agentplatform.types import ManagedSemanticMemoryConfigSimilaritySearchConfig as SimilaritySearchConfig
from agentplatform.types import ManagedSemanticMemoryConfigTtlConfig as TtlConfig
from agentplatform.types import ManagedTopicEnum
from agentplatform.types import MemoryBankCustomizationConfig as CustomizationConfig
from agentplatform.types import MemoryBankCustomizationConfigConsolidationConfig as ConsolidationConfig
from agentplatform.types import MemoryBankCustomizationConfigMemoryTopic as MemoryTopic
from agentplatform.types import MemoryBankCustomizationConfigMemoryTopicManagedMemoryTopic as ManagedMemoryTopic
managed_semantic_memory_config = ManagedSemanticMemoryConfig(
generation_config=GenerationConfig(
# `gemini-3.5-flash` will be used to extract and consolidate memories.
# Note: The global endpoint will be used for regions that don't have a
# regional endpoint available.
model="projects/{PROJECT}/locations/{LOCATION}/publishers/google/models/gemini-3.5-flash"
),
similarity_search_config=SimilaritySearchConfig(
# `text-embedding-005` will be used for similarity search, including
# during consolidation. Consolidation uses similarity search to find
# candidate memories that may be updated with new information.
embedding_model="projects/{PROJECT}/locations/{LOCATION}/publishers/google/models/text-embedding-005"
),
ttl_config=TtlConfig(
# Default TTL for memory revisions is 365 days.
memory_revision_default_ttl=f"{365 * 24 * 60 * 60}s"
),
unstructured_memory_configs=[
CustomizationConfig(
# Extract personal information, preferences, key conversation details,
# and information that the user explicitly asked to be remembered.
memory_topics=[
MemoryTopic(
managed_memory_topic=ManagedMemoryTopic(
managed_topic_enum=ManagedTopicEnum.USER_PERSONAL_INFO)),
MemoryTopic(
managed_memory_topic=ManagedMemoryTopic(
managed_topic_enum=ManagedTopicEnum.USER_PREFERENCES)),
MemoryTopic(
managed_memory_topic=ManagedMemoryTopic(
managed_topic_enum=ManagedTopicEnum.KEY_CONVERSATION_DETAILS)),
MemoryTopic(
managed_memory_topic=ManagedMemoryTopic(
managed_topic_enum=ManagedTopicEnum.EXPLICIT_INSTRUCTIONS))
],
# Only use the pre-defined set of examples.
generate_memories_examples=[],
consolidation_config=ConsolidationConfig(
# Only use the latest memory revision of each candidate memory during
# consolidation.
revisions_per_candidate_count=1
),
# Generate memories in the first person.
enable_third_person_memories=False,
)
],
# Memory revisions will be persisted. This can be overridden on a request-level.
disable_memory_revisions=False
)
您可以在建立或更新執行個體時,調整 Memory Bank 設定。以下範例說明如何建立具有特定記憶體庫設定的執行個體。
memory_bank = client.memory_banks.create(
managed_semantic_memory_config=managed_semantic_memory_config
)
自然語言記憶自訂設定
如要自訂 Memory Bank 擷取自然語言記憶的方式,請在設定執行個體時設定擷取行為。請使用下列選項自訂行為:
- 設定記憶主題:定義 Memory Bank 應視為有意義並保留的資訊類型。只有符合其中一個記憶主題的資訊,才會由 Memory Bank 保留。
- 提供少量樣本:向 Memory Bank 示範記憶擷取的預期行為。
- 設定回憶視角:設定回憶應以第一人稱 (預設) 或第三人稱生成。
- 設定合併:設定 Memory Bank 在合併每個記憶體候選項目時,要考量多少記憶修訂版本。
- 套用自訂設定:使用
unstructured_memory_configs將自訂設定套用至執行個體。
自訂 Memory Bank 的擷取行為時,可以分為兩個步驟:指示和示範。記憶主題會指示 Memory Bank 要保留哪些資訊。少量樣本可顯示 Memory Bank 應從哪種資訊產生特定記憶內容,協助系統學習您希望瞭解的模式、細微差異和措辭。
您可以視需要為不同範圍層級設定不同行為。舉例來說,對工作階段層級記憶有意義的主題,可能對使用者層級記憶 (跨多個工作階段) 沒有意義。如要設定特定回憶集錦子集的行為,請設定自訂設定的範圍索引鍵。只有包含這些範圍金鑰的 GenerateMemories 要求,才會使用該設定。您也可以省略 scope_key 欄位,設定預設行為 (套用至所有範圍金鑰組合)。這項設定會套用至所有要求,但如果要求有設定,且與其他自訂設定的範圍金鑰完全比對,則不適用。
舉例來說,user_level_config 只會套用至完全使用範圍鍵 user_id 的 GenerateMemories 要求 (即 scope={"user_id":
"123"},沒有其他鍵)。default_config 則會套用至其他要求:
字典
user_level_config = {
"scope_keys": ["user_id"],
"memory_topics": [...],
"generate_memories_examples": [...]
}
default_config = {
"memory_topics": [...],
"generate_memories_examples": [...]
}
managed_semantic_memory_config = {
"unstructured_memory_configs": [
user_level_config,
default_config
]
}
以類別為基礎
from agentplatform.types import ManagedSemanticMemoryConfig
from agentplatform.types import MemoryBankCustomizationConfig as CustomizationConfig
user_level_config = CustomizationConfig(
scope_keys=["user_id"],
memory_topics=[...],
generate_memories_examples=[...]
)
default_config = CustomizationConfig(
memory_topics=[...],
generate_memories_examples=[...]
)
managed_semantic_memory_config = ManagedSemanticMemoryConfig(
unstructured_memory_configs=[
user_level_config,
default_config,
]
)
設定記憶主題
「記憶主題」會識別 Memory Bank 認為有意義的資訊,因此應保留為生成的記憶。Memory Bank 支援兩種記憶主題:
受管理主題:標籤和指示由 Memory Bank 定義。您只需要提供代管主題的名稱。例如,假設使用者要求系統 將文字從英文翻譯成法文
字典
memory_topic = { "managed_memory_topic": { "managed_topic_enum": "USER_PERSONAL_INFO" } }以類別為基礎
from agentplatform.types import ManagedTopicEnum from agentplatform.types import MemoryBankCustomizationConfigMemoryTopic as MemoryTopic from agentplatform.types import MemoryBankCustomizationConfigMemoryTopicManagedMemoryTopic as ManagedMemoryTopic memory_topic = MemoryTopic( managed_memory_topic=ManagedMemoryTopic( managed_topic_enum=ManagedTopicEnum.USER_PERSONAL_INFO ) )記憶庫支援下列受管理主題:
- 使用者資訊 (
USER_PERSONAL_INFO):使用者的重要資訊,例如姓名、關係、興趣和重要日期。例如「我在 Google 工作」或「我的結婚紀念日是 12 月 31 日」。 - 使用者偏好 (
USER_PREFERENCES):使用者明確表達或隱約透露的好惡、偏好風格或模式。例如「我喜歡中間座位」。 - 重要對話事件和工作結果 (
KEY_CONVERSATION_DETAILS):對話中的重要進展或結論。例如:「我預訂了 JFK 和 SFO 之間的來回機票。我會在 2025 年 6 月 1 日出發,2025 年 6 月 7 日回國。」 - 明確的記住 / 忘記指令 (
EXPLICIT_INSTRUCTIONS):使用者明確要求代理記住或忘記的資訊。舉例來說,如果使用者說「記住我主要使用 Python」,Memory Bank 就會生成「我主要使用 Python」這類記憶。
- 使用者資訊 (
自訂主題:設定 Memory Bank 執行個體時,您可以定義標籤和指令。這些資訊會用於 Memory Bank 擷取步驟的提示。例如,假設使用者要求系統 將文字從英文翻譯成法文
字典
memory_topic = { "custom_memory_topic": { "label": "business_feedback", "description": """Specific user feedback about their experience at the coffee shop. This includes opinions on drinks, food, pastries, ambiance, staff friendliness, service speed, cleanliness, and any suggestions for improvement.""" } }以課程為準
from agentplatform.types import MemoryBankCustomizationConfigMemoryTopic as MemoryTopic from agentplatform.types import MemoryBankCustomizationConfigMemoryTopicCustomMemoryTopic as CustomMemoryTopic memory_topic = MemoryTopic( custom_memory_topic=CustomMemoryTopic( label="business_feedback", description="""Specific user feedback about their experience at the coffee shop. This includes opinions on drinks, food, pastries, ambiance, staff friendliness, service speed, cleanliness, and any suggestions for improvement.""" ) )使用自訂主題時,建議一併提供少量樣本,說明如何從對話中擷取記憶內容。
自訂功能可讓你任意搭配使用記憶體主題。舉例來說,您可以使用可用受管理記憶體主題的子集:
字典
customization_config = {
"memory_topics": [
{ "managed_memory_topic": { "managed_topic_enum": "USER_PERSONAL_INFO" } },
{ "managed_memory_topic": { "managed_topic_enum": "USER_PREFERENCES" } }
]
}
以課程為準
from agentplatform.types import ManagedTopicEnum
from agentplatform.types import MemoryBankCustomizationConfig as CustomizationConfig
from agentplatform.types import MemoryBankCustomizationConfigMemoryTopic as MemoryTopic
from agentplatform.types import MemoryBankCustomizationConfigMemoryTopicManagedMemoryTopic as ManagedMemoryTopic
customization_config = CustomizationConfig(
memory_topics=[
MemoryTopic(
managed_memory_topic=ManagedMemoryTopic(
managed_topic_enum=ManagedTopicEnum.USER_PERSONAL_INFO)
),
MemoryTopic(
managed_memory_topic=ManagedMemoryTopic(
managed_topic_enum=ManagedTopicEnum.USER_PREFERENCES)
),
]
)
您也可以結合使用代管和自訂主題 (或只使用自訂主題):
字典
customization_config = {
"memory_topics": [
{ "managed_memory_topic": { "managed_topic_enum": "USER_PERSONAL_INFO" } },
{
"custom_memory_topic": {
"label": "business_feedback",
"description": """Specific user feedback about their experience at
the coffee shop. This includes opinions on drinks, food, pastries, ambiance,
staff friendliness, service speed, cleanliness, and any suggestions for
improvement."""
}
}
]
}
以課程為準
from agentplatform.types import ManagedTopicEnum
from agentplatform.types import MemoryBankCustomizationConfig as CustomizationConfig
from agentplatform.types import MemoryBankCustomizationConfigMemoryTopic as MemoryTopic
from agentplatform.types import MemoryBankCustomizationConfigMemoryTopicCustomMemoryTopic as CustomMemoryTopic
from agentplatform.types import MemoryBankCustomizationConfigMemoryTopicManagedMemoryTopic as ManagedMemoryTopic
customization_config = CustomizationConfig(
memory_topics=[
MemoryTopic(
managed_memory_topic=ManagedMemoryTopic(
managed_topic_enum=ManagedTopicEnum.USER_PERSONAL_INFO)
),
MemoryTopic(
custom_memory_topic=CustomMemoryTopic(
label="business_feedback",
description="""Specific user feedback about their experience at
the coffee shop. This includes opinions on drinks, food, pastries, ambiance,
staff friendliness, service speed, cleanliness, and any suggestions for
improvement."""
)
)
]
)
少量樣本
少量樣本可向記憶庫示範預期的記憶擷取行為。例如,您可以提供輸入對話範例,以及預期從該對話中擷取的記憶。
建議您一律搭配自訂主題使用少量樣本,讓 Memory Bank 瞭解預期行為。使用受管理主題時,由於 Memory Bank 會為每個主題定義範例,因此您可以選擇不提供少量樣本。提供空白的 generated_memories 清單,示範不應產生回憶內容的對話。
舉例來說,您可以提供少量樣本,示範如何從顧客訊息中擷取對商家的意見回饋:
字典
example = {
"conversationSource": {
"events": [
{
"content": {
"role": "model",
"parts": [{ "text": "Welcome back to The Daily Grind! We'd love to hear your feedback on your visit." }] }
},
{
"content": {
"role": "user",
"parts": [{ "text": "Hey. The drip coffee was a bit lukewarm today, which was a bummer. Also, the music was way too loud, I could barely hear my friend." }] }
}
]
},
"generatedMemories": [
{
"fact": "The user reported that the drip coffee was lukewarm."
},
{
"fact": "The user felt the music in the shop was too loud."
}
]
}
以類別為基礎
from google.genai.types import Content, Part
from agentplatform.types import MemoryBankCustomizationConfigGenerateMemoriesExample as GenerateMemoriesExample
from agentplatform.types import MemoryBankCustomizationConfigGenerateMemoriesExampleConversationSource as ConversationSource
from agentplatform.types import MemoryBankCustomizationConfigGenerateMemoriesExampleConversationSourceEvent as ConversationSourceEvent
from agentplatform.types import MemoryBankCustomizationConfigGenerateMemoriesExampleGeneratedMemory as ExampleGeneratedMemory
example = GenerateMemoriesExample(
conversation_source=ConversationSource(
events=[
ConversationSourceEvent(
content=Content(
role="model",
parts=[Part(text="Welcome back to The Daily Grind! We'd love to hear your feedback on your visit.")]
)
),
ConversationSourceEvent(
content=Content(
role="user",
parts=[Part(text= "Hey. The drip coffee was a bit lukewarm today, which was a bummer. Also, the music was way too loud, I could barely hear my friend.")]
)
)
]
),
generated_memories=[
ExampleGeneratedMemory(
fact="The user reported that the drip coffee was lukewarm."
),
ExampleGeneratedMemory(
fact="The user felt the music in the shop was too loud."
)
]
)
您也可以提供不應產生任何記憶的對話範例,方法是為預期輸出內容提供空白清單 (generated_memories):
字典
example = {
"conversationSource": {
"events": [
{
"content": {
"role": "model",
"parts": [{ "text": "Good morning! What can I get for you at The Daily Grind?" }] }
},
{
"content": {
"role": "user",
"parts": [{ "text": "Thanks for the coffee." }] }
}
]
},
"generatedMemories": []
}
以課程為準
from google.genai.types import Content, Part
from agentplatform.types import MemoryBankCustomizationConfigGenerateMemoriesExample as GenerateMemoriesExample
from agentplatform.types import MemoryBankCustomizationConfigGenerateMemoriesExampleConversationSource as ConversationSource
from agentplatform.types import MemoryBankCustomizationConfigGenerateMemoriesExampleConversationSourceEvent as ConversationSourceEvent
example = GenerateMemoriesExample(
conversation_source=ConversationSource(
events=[
ConversationSourceEvent(
content=Content(
role="model",
parts=[Part(text="Welcome back to The Daily Grind! We'd love to hear your feedback on your visit.")]
)
),
ConversationSourceEvent(
content=Content(
role="user",
parts=[Part(text= "Thanks for the coffee!")]
)
)
]
),
generated_memories=[]
)
記憶體觀點
根據預設,個人化記憶會以第一人稱生成 (例如「我使用 Memory Bank 管理記憶。」)。您可以使用 enable_third_person_memories 參數,設定 Memory Bank 以第三人稱生成內容 (例如「使用者使用 Memory Bank 進行記憶體管理」)。
字典
customization_config = {
"enable_third_person_memories": True
}
以類別為基礎
from agentplatform.types import MemoryBankCustomizationConfig as CustomizationConfig
customization_config = CustomizationConfig(
enable_third_person_memories=True
)
自訂整合
在整合期間,Memory Bank 會決定如何將新取得的資訊整合至現有的記憶體集。Memory Bank 會評估是否要新增記憶、使用額外脈絡資訊更新現有記憶,或刪除過時記憶。
為確保 Memory Bank 提供高品質的佐證回憶,系統可選擇分析記憶體記錄,區分長期趨勢和一次性離群值。
根據預設,記憶庫只會將新資訊與候選記憶的最新快照 (「記憶修訂版本」) 進行比較。如要提高分析深度,請設定 revisions_per_candidate_count 參數。這個參數會定義「候選記憶」(即正在評估是否要更新的特定記錄) Memory Bank 在合併期間會考量的先前修訂版本數量。
字典
customization_config = {
"consolidation_config": {
"revisions_per_candidate_count": 10
}
}
以類別為基礎
from agentplatform.types import MemoryBankCustomizationConfig as CustomizationConfig
from agentplatform.types import MemoryBankCustomizationConfigConsolidationConfig as ConsolidationConfig
customization_config = CustomizationConfig(
consolidation_config=ConsolidationConfig(
revisions_per_candidate_count=10
)
)
增加 revisions_per_candidate_count 可讓記憶體更一致且經過驗證,因為這會考量擷取資訊的重複性。不過,如果數量較多,整合程序中的符記用量也會增加。
套用自訂設定
如要將自訂設定套用至記憶庫執行個體,請在 managed_semantic_memory_config 的 unstructured_memory_configs 清單中提供這些設定:
字典
managed_semantic_memory_config = {
"unstructured_memory_configs": [customization_config],
# Include other configurations (similarity search, generation, TTL)...
}
以類別為基礎
from agentplatform.types import ManagedSemanticMemoryConfig
managed_semantic_memory_config = ManagedSemanticMemoryConfig(
unstructured_memory_configs=[customization_config],
# Include other configurations (similarity search, generation, TTL)...
)
相似度搜尋設定
相似度搜尋設定可控管執行個體用於相似度搜尋的嵌入模型。相似度搜尋可用於找出哪些記憶應列為整合候選項目,以及用於以相似度搜尋為基礎的記憶檢索。如未提供這項設定,Memory Bank 會使用 text-embedding-005 做為預設模型。
如果預期使用者會以非英文對話,請使用支援多種語言的模型,例如 gemini-embedding-2、gemini-embedding-001 或 text-multilingual-embedding-002,以提升檢索品質。
字典
similarity_search_config = {
"embedding_model": "EMBEDDING_MODEL",
}
以課程為準
from agentplatform.types import ManagedSemanticMemoryConfigSimilaritySearchConfig as SimilaritySearchConfig
similarity_search_config = SimilaritySearchConfig(
embedding_model="EMBEDDING_MODEL"
)
更改下列內容:
- EMBEDDING_MODEL:用於相似度搜尋的 Google 文字嵌入模型,格式為
projects/{project}/locations/{location}/publishers/google/models/{model}。
生成設定
生成設定可控管要使用哪個 LLM 生成記憶,包括擷取記憶,以及將新記憶與現有記憶整合。
2026 年 6 月 29 日起,記憶庫會使用 gemini-3.5-flash 做為預設模型。該日期前建立的執行個體會使用 gemini-2.5-flash。
如要使用預設模型建立新的 Memory Bank 執行個體:
us多區域或us-*單一區域 (例如 us-central1) 的 Memory Bank 執行個體會使用多區域usGemini 3.5 端點。eu多區域或eu-*單一區域 (例如 europe-west2) 的 Memory Bank 執行個體會使用多區域euGemini 3.5 端點。- 所有其他 Memory Bank 區域則使用全域 Gemini 3.5 端點。
如果記憶庫執行個體是在 2026 年 6 月 29 日前建立,且使用預設模型,則在沒有區域 Gemini 2.5 端點的區域,記憶庫會使用 global Gemini 端點。
字典
generation_config = {
"model": "LLM_MODEL",
}
以課程為準
from agentplatform.types import ManagedSemanticMemoryConfigGenerationConfig as GenerationConfig
generation_config = GenerationConfig(
model="LLM_MODEL"
)
更改下列內容:
- LLM_MODEL:用於擷取及整合記憶的 Google LLM 模型,格式為
projects/{project}/locations/{location}/publishers/google/models/{model}。
存留時間 (TTL) 設定
TTL 設定可控管 Memory Bank 如何動態設定記憶的到期時間。到期後,記憶體將無法擷取,並會遭到刪除。
如未提供設定,系統不會為建立或更新的記憶動態設定到期時間,因此除非手動設定到期時間,否則記憶不會過期。
TTL 設定有兩種方式:
預設存留時間:存留時間會套用至所有建立或更新記憶的作業,包括
UpdateMemory、CreateMemory和GenerateMemories。字典
ttl_config = { "default_ttl": f"TTLs" }以課程為準
from agentplatform.types import ManagedSemanticMemoryConfigTtlConfig as TtlConfig ttl_config = TtlConfig( default_ttl=f"TTLs" )更改下列內容:
- TTL:存留時間的長度 (以秒為單位)。如果是更新後的記憶,新計算的到期時間 (目前時間 + 存留時間) 會覆寫記憶先前的到期時間。
精細 (依作業) 存留時間:根據建立或更新記憶的作業計算存留時間。如果未針對特定作業設定,作業就不會更新記憶體的到期時間。
字典
ttl_config = { "granular_ttl": { "create_ttl": f"CREATE_TTLs", "generate_created_ttl": f"GENERATE_CREATED_TTLs", "generate_updated_ttl": f"GENERATE_UPDATED_TTLs" } }以課程為準
from agentplatform.types import ManagedSemanticMemoryConfigTtlConfig as TtlConfig from agentplatform.types import ManagedSemanticMemoryConfigTtlConfigGranularTtlConfig as GranularTtlConfig ttl_config = TtlConfig( granular_ttl_config=GranularTtlConfig( create_ttl=f"CREATE_TTLs", generate_created_ttl=f"GENERATE_CREATED_TTLs", generate_updated_ttl=f"GENERATE_UPDATED_TTLs", ) )更改下列內容:
- CREATE_TTL:使用
CreateMemory建立的記憶存留時間 (以秒為單位)。 - GENERATE_CREATED_TTL:使用
GenerateMemories建立的回憶,其存留時間 (以秒為單位)。 - GENERATE_UPDATED_TTL:使用
GenerateMemories更新的記憶存留時間 (以秒為單位)。新計算的到期時間 (目前時間 + 存留時間) 會覆寫記憶體先前的到期時間。
- CREATE_TTL:使用