如要使用 Agent Platform Memory Bank,請先建立並設定 Memory Bank 執行個體。這個執行個體會管理記憶,並可與不同執行階段的代理整合。
本文說明如何設定 Google Cloud 專案、安裝必要程式庫,以及建立或更新執行個體,並套用主題和存留時間等自訂設定。
開始使用
使用 Memory Bank 前,請先設定環境。
設定 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 提出要求,請確認服務帳戶具備讀取、寫入或生成記憶的必要權限。推論引擎服務代理已具備讀取、寫入和生成記憶所需的權限,因此 Agent Runtime 的傳出要求應已具備 Memory Bank 的存取權限。
安裝程式庫
本節假設您已設定 Python 開發環境,或使用具備 Python 開發環境的執行階段 (例如 Colaboratory)。
安裝 Agent Platform SDK:
pip install google-cloud-agentplatform>=2.0.1驗證
請按照「向 Gemini Enterprise Agent Platform 驗證」一節的說明操作。
設定 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 環境。接著,準備將代理部署至 Agent Runtime,並整合記憶體。部署的代理應視需要呼叫讀取和寫入記憶。
AdkApp
如果您使用 Agent Platform Agent Development Kit (ADK) 範本,代理部署至 Agent Runtime 時,預設會使用 VertexAiMemoryBankService。也就是說,ADK 記憶體工具會從 Memory Bank 讀取記憶。
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:用於暫存 Agent Runtime 的 Cloud Storage bucket。
如要進一步瞭解如何搭配使用 Memory Bank 與 ADK,請參閱「ADK 快速入門導覽課程」。
自訂代理
Memory Bank 可與部署在 Agent Runtime 的自訂代理搭配使用。在這種情況下,代理應對 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 執行個體應該只需要幾秒鐘。如果是第一次使用記憶庫,可能需要較長時間 (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:記憶庫名稱。格式應為
projects/.../locations/.../reasoningEngines/...。請參閱 Memory Bank 支援的區域。
只要環境有權讀寫記憶,就能使用記憶庫。舉例來說,如要搭配 Cloud Run 使用記憶庫,請授予 Cloud Run 服務身分讀取及寫入記憶的權限。所需權限取決於代理應能執行的作業。如果只想讓代理擷取及生成記憶,aiplatform.memories.generate 和 aiplatform.memories.retrieve 就足夠了。
設定 Memory Bank 執行個體
您可以設定記憶庫,自訂記憶的生成和管理方式。如未提供設定,Memory Bank 會使用每種設定的預設值。
您可以為執行個體調整下列記憶體庫設定:
- 自訂設定 (
unstructured_memory_configs):設定如何從來源資料擷取記憶,並與現有記憶合併。 - 相似度搜尋設定:指定 Memory Bank 用於相似度搜尋的嵌入模型。預設值為
text-embedding-005。 - 生成設定:設定 Memory Bank 用於生成記憶的大型語言模型。預設值為
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_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」,記憶庫就會生成「我主要使用 Python」這類記憶。
- 使用者資訊 (
自訂主題:設定記憶庫執行個體時,由您定義標籤和操作說明。這些資訊會用於 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 瞭解預期行為。使用代管主題時,少量樣本為選用,因為記憶庫會為每個主題定義範例。提供空白的 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 參數。這個參數定義了記憶庫在整合期間,會考量每筆「候選記憶」(正在評估是否更新的特定記錄) 的多少個先前修訂版本。
字典
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) 的記憶庫執行個體,會使用多區域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:使用