使用 Vertex AI Agent Engine Memory Bank 前,請先設定環境。請注意,雖然 Memory Bank 是 Agent Engine 的一部分,但您不需要將程式碼部署至 Agent Engine 執行階段,即可使用 Memory Bank。
設定您的 Google Cloud 專案
每項專案都可用專案編號或專案 ID 來識別。PROJECT_NUMBER
是系統在您建立專案時自動產生的,而 PROJECT_ID
則是由您或專案建立者所建立。如要設定專案,請按照下列步驟操作:
- 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.
-
In the Google Cloud console, on the project selector page, select or create a Google Cloud project.
-
Verify that billing is enabled for your Google Cloud project.
-
Enable the Vertex AI API.
-
In the Google Cloud console, on the project selector page, select or create a Google Cloud project.
-
Verify that billing is enabled for your Google Cloud project.
-
Enable the Vertex AI API.
如果未使用 Vertex AI 的快速模式,請按照「向 Vertex AI 進行驗證」一文中的操作說明進行驗證。
如果您使用快速模式的 Vertex AI,請在環境中設定 API 金鑰,藉此設定驗證:
os.environ["GOOGLE_API_KEY"] = "API_KEY"
PROJECT_ID
是您的專案 ID。LOCATION
是 Memory Bank 支援的地區之一。建立或更新 Agent Engine 執行個體:建立或更新執行個體時,您可以覆寫 Agent Engine 的預設值,對執行個體進行下列修改:
- AGENT_ENGINE_NAME:Agent Engine 的名稱。格式應為
projects/.../locations/.../reasoningEngines/...
。請參閱支援記憶體庫的區域。 設定記憶體庫生成及管理記憶體的方式。
將代理程式部署至 Agent Engine 執行階段。
agent_engine = client.agent_engines.create( # Optional. Set this argument if you want to deploy to Agent Engine Runtime. agent_engine=..., # Optional. Set this argument if you want to change the Memory Bank configuration. config=... )
如要讀取或寫入記憶內容,您需要 Agent Engine 的名稱:
agent_engine_name = agent_engine.api_resource.name
- AGENT_ENGINE_NAME:Agent Engine 的名稱。格式應為
projects/.../locations/.../reasoningEngines/...
。請參閱支援記憶體庫的區域。 - 自訂設定:設定如何從來源資料擷取回憶集錦。
- 相似度搜尋設定:設定用於相似度搜尋的嵌入模型。預設值為
text-embedding-005
。 - 生成設定:設定用於生成記憶體的 LLM。預設值為
gemini-2.0-flash-001
。 - 存留時間設定:設定系統如何為建立或更新的記憶內容自動設定存留時間。預設為沒有存留時間。
管理主題:標籤和操作說明由記憶體庫定義。您只需要提供受管理主題的名稱。例如,假設使用者要求系統 將文字從英文翻譯成法文
字典
memory_topic = { "managed_memory_topic": { "managed_topic_enum": "USER_PERSONAL_INFO" } }
以類別為準
from vertexai.types import ManagedTopicEnum from vertexai.types import MemoryBankCustomizationConfigMemoryTopic as MemoryTopic from vertexai.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_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 vertexai.types import MemoryBankCustomizationConfigMemoryTopic as MemoryTopic from vertexai.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.""" ) )
使用自訂主題時,建議一併提供少量樣本,示範如何從對話中擷取記憶內容。
- EMBEDDING_MODEL:用於相似性搜尋的 Google 文字嵌入模型,格式為
projects/{project}/locations/{location}/publishers/google/models/{model}
。 - LLM_MODEL:用於擷取和整合記憶內容的 Google LLM 模型,格式為
projects/{project}/locations/{location}/publishers/google/models/{model}
。 預設存留時間:存留時間會套用至所有建立或更新記憶內容的操作,包括
UpdateMemory
、CreateMemory
和GenerateMemories
。字典
memory_bank_config = { "ttl_config": { "default_ttl": f"TTLs" } }
以類別為準
from vertexai.types import ReasoningEngineContextSpecMemoryBankConfig as MemoryBankConfig from vertexai.types import ReasoningEngineContextSpecMemoryBankConfigTtlConfig as TtlConfig memory_bank_config = MemoryBankConfig( ttl_config=TtlConfig( default_ttl=f"TTLs" ) )
更改下列內容:
- TTL:存留時間的長度 (以秒為單位)。如果是更新的記憶體,新計算的到期時間 (現在 + TTL) 會覆寫記憶體先前的到期時間。
精細 (依作業) 存留時間:系統會根據建立或更新記憶體的作業計算存留時間。如果未針對特定作業設定,作業就不會更新記憶體的到期時間。
字典
memory_bank_config = { "ttl_config": { "granular_ttl": { "create_ttl": f"CREATE_TTLs", "generate_created_ttl": f"GENERATE_CREATED_TTLs", "generate_updated_ttl": f"GENERATE_UPDATED_TTLs" } } }
以類別為準
from vertexai.types import ReasoningEngineContextSpecMemoryBankConfig as MemoryBankConfig from vertexai.types import ReasoningEngineContextSpecMemoryBankConfigTtlConfig as TtlConfig from vertexai.types import ReasoningEngineContextSpecMemoryBankConfigTtlConfigGranularTtlConfig as GranularTtlConfig memory_bank_config = MemoryBankConfig( 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:使用
GeneratedMemories
建立的記憶內容存留時間,以秒為單位。 - GENERATE_UPDATED_TTL:使用
GeneratedMemories
更新回憶內容時,TTL 的時間長度 (以秒為單位)。新計算出的到期時間 (目前時間 + TTL) 會覆寫先前的到期時間。
- CREATE_TTL:使用
- STAGING_BUCKET:用於暫存 Agent Engine Runtime 的 Cloud Storage 值區。
取得必要角色
如要取得使用 Vertex AI Agent Engine 所需的權限,請要求管理員為您授予專案的「Vertex AI 使用者」 (roles/aiplatform.user
) IAM 角色。如要進一步瞭解如何授予角色,請參閱「管理專案、資料夾和機構的存取權」。
如果從部署在 Google Kubernetes Engine 或 Cloud Run 的代理程式對 Memory Bank 提出要求,請確認服務帳戶具備必要權限。推理引擎服務代理已具備讀取及寫入記憶體的必要權限,因此來自 Agent Engine Runtime 的輸出要求應已具備存取記憶體庫的權限。
設定環境
本節假設您已設定 Python 開發環境,或是使用具備 Python 開發環境的執行階段 (例如 Colab)。
安裝程式庫
安裝 Vertex AI SDK:
pip install google-cloud-aiplatform>=1.104.0
驗證
驗證說明取決於您是否使用快速模式的 Vertex AI:
設定 Vertex AI SDK 用戶端
執行下列程式碼,設定 Vertex AI SDK 用戶端:
import vertexai
client = vertexai.Client(
project="PROJECT_ID",
location="LOCATION",
)
其中
為記憶體庫設定 Agent Engine 執行個體
如要開始使用 Memory Bank,您必須先建立 Agent Engine 執行個體。
您可以執行下列其中一項操作:
使用現有執行個體
如不需修改現有的 Agent Engine 執行個體,請執行下列指令,為 Memory Bank 設定執行個體:
agent_engine = client.agent_engines.get(name="AGENT_ENGINE_NAME")
更改下列內容:
您可以在任何環境中使用執行個體,包括 Google Kubernetes Engine 和 Cloud Run。如要開始使用,您需要可識別記憶體庫的 Agent Engine 名稱,以及呼叫記憶體庫的足夠權限。
建立或更新執行個體
建立
建立 Agent Engine 執行個體時,系統預設會啟用 Memory Bank。建立沒有執行階段的新 Agent Engine 只需要幾秒鐘。
agent_engine = client.agent_engines.create()
您也可以在建立 Agent Engine 執行個體時覆寫 Agent Engine 的預設值,進行下列修改:
更新
如要更新 Agent Engine,同時保留儲存在執行個體中的記憶內容,可以更新現有的 Agent Engine 執行個體。您可以進行更新,例如變更記憶體庫設定,或將代理程式部署至 Agent Engine Runtime。
agent_engine = client.agent_engines.update(
# If you have an existing AgentEngine, you can access the name using `agent_engine.api_resource.name`.
name="AGENT_ENGINE_NAME",
# Optional. Set this argument if you want to deploy to Agent Engine Runtime.
agent_engine=...,
# Optional. Set this argument if you want to change the Memory Bank configuration.
config=...
)
更改下列內容:
設定記憶體庫
您可以設定記憶體庫,自訂回憶集錦的生成和管理方式。如未提供設定,記憶體庫會針對每種設定類型使用預設設定。
建立或更新 Agent Engine 執行個體時,系統會設定 Memory Bank:
client.agent_engines.create(
...,
config={
"context_spec": {
"memory_bank_config": memory_bank_config
}
}
)
# Alternatively, update an existing Agent Engine's Memory Bank config.
agent_engine = client.agent_engines.update(
name=agent_engine.api_resource.name,
config={
"context_spec": {
"memory_bank_config": memory_bank_config
}
}
)
您可以為執行個體設定下列項目:
自訂設定
如要自訂從來源資料擷取記憶的方式,可以在設定 Agent Engine 執行個體時,設定記憶擷取行為。您可以使用以下兩種方式進行自訂:
您可以視需要為不同範圍層級設定不同行為。舉例來說,對工作階段層級記憶內容有意義的主題,可能對使用者層級記憶內容 (跨多個工作階段) 來說就沒有意義。如要為特定記憶體子集設定行為,請設定自訂設定的範圍鍵。只有包含這些範圍鍵的 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": [...]
}
config = {
"customization_configs": [
user_level_config,
default_config
]
}
以類別為準
from vertexai.types import MemoryBankCustomizationConfig as CustomizationConfig
user_level_config = CustomizationConfig(
scope_keys=["user_id"],
memory_topics=[...],
generate_memories_examples=[...]
)
設定記憶體主題
「記憶主題」會判斷記憶庫中哪些資訊有意義,因此應保留為生成回憶。記憶體庫支援兩種記憶體主題:
自訂功能可讓您任意組合記憶體主題。舉例來說,您可以使用可用受管理記憶體主題的子集:
字典
{
"memory_topics": [
"managed_memory_topic": { "managed_topic_enum": "USER_PERSONAL_INFO" },
"managed_memory_topic": { "managed_topic_enum": "USER_PREFERENCES" }
]
}
以類別為準
from vertexai.types import MemoryBankCustomizationConfig as CustomizationConfig
from vertexai.types import MemoryBankCustomizationConfigMemoryTopic as MemoryTopic
from vertexai.types import MemoryBankCustomizationConfigMemoryTopicManagedMemoryTopic as ManagedMemoryTopic
from vertexai.types import ManagedTopicEnum
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)
),
]
)
您也可以同時使用受管理和自訂主題 (或只使用自訂主題):
字典
{
"memory_topics": [
"managed_memory_topic": { "managed_topic_enum": "USER_PERSONAL_INFO" },
"custom_memory_topic": {
"label": "Jargon",
"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 vertexai.types import MemoryBankCustomizationConfig as CustomizationConfig
from vertexai.types import MemoryBankCustomizationConfigMemoryTopic as MemoryTopic
from vertexai.types import MemoryBankCustomizationConfigMemoryTopicCustomMemoryTopic as CustomMemoryTopic
from vertexai.types import MemoryBankCustomizationConfigMemoryTopicManagedMemoryTopic as ManagedMemoryTopic
from vertexai.types import ManagedTopicEnum
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."""
)
)
]
)
少量樣本
少量樣本範例可向記憶體庫展示預期的記憶體擷取行為。舉例來說,您可以提供輸入對話範例,以及預期從該對話中擷取的記憶內容。
建議您一律搭配自訂主題使用少量樣本,讓記憶庫瞭解預期行為。使用受管理的主題時,由於記憶體庫會為每個主題定義範例,因此您可以選擇不提供少量樣本。提供空白的 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 vertexai.types import MemoryBankCustomizationConfigGenerateMemoriesExample as GenerateMemoriesExample
from vertexai.types import MemoryBankCustomizationConfigGenerateMemoriesExampleConversationSource as ConversationSource
from vertexai.types import MemoryBankCustomizationConfigGenerateMemoriesExampleConversationSourceEvent as ConversationSourceEvent
from vertexai.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 vertexai.types import MemoryBankCustomizationConfigGenerateMemoriesExample as GenerateMemoriesExample
from vertexai.types import MemoryBankCustomizationConfigGenerateMemoriesExampleConversationSource as ConversationSource
from vertexai.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 會使用 text-embedding-005
做為預設模型。
如果預期使用者對話會使用非英文語言,請使用支援多種語言的模型 (例如 gemini-embedding-001
或 text-multilingual-embedding-002
),提升檢索品質。
字典
memory_bank_config = {
"similarity_search_config": {
"embedding_model": "EMBEDDING_MODEL",
}
}
以類別為準
from vertexai.types import ReasoningEngineContextSpecMemoryBankConfig as MemoryBankConfig
from vertexai.types import ReasoningEngineContextSpecMemoryBankConfigSimilaritySearchConfig as SimilaritySearchConfig
memory_bank_config = MemoryBankConfig(
similarity_search_config=SimilaritySearchConfig(
embedding_model="EMBEDDING_MODEL"
)
)
更改下列內容:
生成設定
生成設定會控管用於生成回憶集錦的大型語言模型,包括擷取回憶集錦,以及將新回憶集錦與現有回憶集錦合併。
記憶體庫預設使用 gemini-2.0-flash-001
模型。
字典
memory_bank_config = {
"generation_config": {
"model": "LLM_MODEL",
}
}
以類別為準
from vertexai.types import ReasoningEngineContextSpecMemoryBankConfig as MemoryBankConfig
from vertexai.types import ReasoningEngineContextSpecMemoryBankConfigGenerationConfig as GenerationConfig
memory_bank_config = MemoryBankConfig(
generation_config=GenerationConfig(
model="LLM_MODEL"
)
)
更改下列內容:
存留時間 (TTL) 設定
TTL 設定可控制記憶體銀行應如何動態設定記憶體的到期時間。過期後,系統會刪除回憶集錦,且無法復原。
如果未提供設定,系統就不會為建立或更新的回憶內容動態設定到期時間,因此回憶內容不會過期,除非手動設定到期時間。
TTL 設定有兩種方式:
將具備記憶體的代理程式部署至 Agent Engine
雖然 Memory Bank 可在任何執行階段中使用,但您也可以搭配 Agent Engine Runtime 使用 Memory Bank,從已部署的代理程式讀取及寫入記憶體。
如要在 Vertex AI Agent Engine 執行階段部署具備 Memory Bank 的代理程式,請先設定 Agent Engine 執行階段的環境。接著,準備將代理程式部署至 Agent Engine Runtime,並整合記憶體。部署的代理程式應視需要呼叫讀取和寫入記憶體。
AdkApp
如果您使用 Agent Engine Agent Development Kit 範本,代理程式在部署至 Agent Engine 執行階段時,預設會使用 VertexAiMemoryBankService
。這表示 ADK 記憶體工具會從記憶體庫讀取記憶體。
from google.adk.agents import Agent
from vertexai.preview.reasoning_engines import AdkApp
# Develop an agent using the ADK template.
agent = Agent(...)
adk_app = AdkApp(
agent=adk_agent,
...
)
# Deploy the agent to Agent Engine Runtime.
agent_engine = client.agent_engines.create(
agent_engine=adk_app,
config={
"staging_bucket": "STAGING_BUCKET",
"requirements": ["google-cloud-aiplatform[agent_engines,adk]"],
# Optional.
**context_spec
}
)
# Update an existing Agent Engine to add or modify the Runtime.
agent_engine = client.agent_engines.update(
name=agent_engine.api_resource.name,
agent_engine=adk_app,
config={
"staging_bucket": "STAGING_BUCKET",
"requirements": ["google-cloud-aiplatform[agent_engines,adk]"],
# Optional.
**context_spec
}
)
更改下列內容:
如要進一步瞭解如何搭配 ADK 使用 Memory Bank,請參閱「Agent Development Kit 快速入門」。
自訂代理
您可以在 Agent Engine Runtime 上部署自訂代理,並搭配使用 Memory Bank。在這種情況下,代理程式應協調對 Memory Bank 的呼叫,以觸發記憶體生成和記憶體擷取呼叫。
如要將同一個 Agent Engine 執行個體用於記憶體庫和 Agent Engine 執行階段,可以讀取環境變數 GOOGLE_CLOUD_PROJECT
、GOOGLE_CLOUD_LOCATION
、GOOGLE_CLOUD_AGENT_ENGINE_ID
,從環境推斷 Agent Engine 名稱:
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}"