本教程演示了如何直接向 Vertex AI Agent Engine 会话和内存库发出 REST API 调用,以创建和使用会话和长期记忆。如果您不希望代理框架为您协调调用,或者您想将会话和内存银行与代理开发套件 (ADK) 以外的代理框架集成,请使用 REST API。
如需使用 ADK 的快速入门,请参阅代理开发套件快速入门。
本教程使用以下步骤:
- 创建 Vertex AI Agent Engine 实例,以访问 Vertex AI Agent Engine 会话和内存银行。
- 使用以下选项创建回忆:
- 使用 Vertex AI Agent Engine 内存库生成记忆:将会话和事件写入 Vertex AI Agent Engine 会话,作为 Vertex AI Agent Engine 内存库生成记忆的来源。
- 直接上传回忆:如果您想完全控制要保留的信息,可以自行撰写回忆,也可以让 Google 助理撰写回忆。
- 检索回忆。
- 清理.
准备工作
如需完成本教程中演示的步骤,您必须先设置项目和环境。
设置项目
- 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.
-
Make sure 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.
-
Make sure that billing is enabled for your Google Cloud project.
-
Enable the Vertex AI API.
- 如果您选择了项目,请确保您拥有该项目的 Vertex AI User (
roles/aiplatform.user
) IAM 角色。 -
Install the Google Cloud CLI.
-
If you're using an external identity provider (IdP), you must first sign in to the gcloud CLI with your federated identity.
-
To initialize the gcloud CLI, run the following command:
gcloud init
-
If you're using a local shell, then create local authentication credentials for your user account:
gcloud auth application-default login
You don't need to do this if you're using Cloud Shell.
If an authentication error is returned, and you are using an external identity provider (IdP), confirm that you have signed in to the gcloud CLI with your federated identity.
- PROJECT_ID:您的项目 ID。
- LOCATION:您的区域。 Vertex AI Agent Engine 内存银行和会话仅支持
us-central1
。 - MODEL_NAME:用于生成回忆的 LLM 模型。您可以使用任何 Gemini 或 Model Garden 模型。
- EMBEDDING_MODEL_NAME:(可选)用于为特定用户查找类似回忆的嵌入模型。您可以使用任何支持嵌入 API 的模型,只要该模型支持向量长度为 768 作为输出维度即可。
创建包含不透明用户 ID 的会话。除非您在生成回忆时明确提供镜,否则此会话生成的所有回忆都会自动按镜
{"user_id": "USER_ID"}
键控。from google.cloud import aiplatform_v1beta1 sessions_client = aiplatform_v1beta1.SessionServiceClient( client_options={ "api_endpoint": "https://LOCATION-aiplatform.googleapis.com" }, transport="rest") session_lro = sessions_client.create_session( parent=AGENT_ENGINE_NAME, session={"user_id": "USER_ID"} ) session_id = session_lro.operation.name.split("/")[-3]
替换以下内容:
LOCATION:您的区域。 Vertex AI Agent Engine 内存银行和会话仅支持
us-central1
。AGENT_ENGINE_NAME:您创建的 Vertex AI Agent Engine 实例或现有 Vertex AI Agent Engine 实例的名称。该名称应采用以下格式:
projects/{your project}/locations/{your location}/reasoningEngine/{your reasoning engine}
。USER_ID:用户的标识符。除非您在生成回忆时明确提供镜,否则此会话生成的所有回忆都会自动按镜
{"user_id": "USER_ID"}
键控。
迭代地将事件上传到会话。事件可以包括用户、客服人员和工具之间的任何互动。有序事件列表代表会话的对话历史记录。系统会将此对话记录用作为该特定用户生成回忆的素材资源。
event = aiplatform_v1beta1.SessionEvent( author="user", # Required by Sessions. invocation_id="1", # Required by Sessions. timestamp=datetime.now().strftime('%Y-%m-%dT%H:%M:%SZ'), # Required by Sessions. content = aiplatform_v1beta1.Content( role="user", parts=[aiplatform_v1beta1.Part(text="Hello")] ) ) client.append_event(name=f"{agent_engine_name}/sessions/{session_id}", event=event)
如需根据对话记录生成回忆,请为会话触发回忆生成请求:
credentials, _ = google.auth.default() auth_req = google.auth.transport.requests.Request() credentials.refresh(auth_req) url = "https://LOCATION-aiplatform.googleapis.com/v1beta1/AGENT_ENGINE_NAME" response = requests.post( url=f"{url}/memories:generate", headers={ "Content-Type": "application/json; charset=utf-8", "Authorization": f"Bearer {credentials.token}", }, json={ "vertex_session_source": { "session": f"{agent_engine_name}/sessions/{session_id}" }, # Optional when using Agent Engine Sessions. Defaults to {"user_id": session.user_id}. "scope": SCOPE } )
- (可选)SCOPE:一个字典,表示生成的回忆的范围。例如
{"session_id": "MY_SESSION"}
。只有具有相同作用域的内存才会被考虑合并。如果未提供,则系统会使用{"user_id": session.user_id}
。 使用以下代码示例删除 Vertex AI Agent Engine 实例,这也会删除与 Vertex AI Agent Engine 实例关联的所有会话或记忆。
credentials, _ = google.auth.default() auth_req = google.auth.transport.requests.Request() credentials.refresh(auth_req) url = "https://LOCATION-aiplatform.googleapis.com/v1beta1/AGENT_ENGINE_NAME" response = requests.delete( url=url, json={"force": True}, headers={ "Content-Type": "application/json; charset=utf-8", "Authorization": f"Bearer {credentials.token}" } )
删除本地创建的所有文件。
向 Vertex AI 进行身份验证
如需在本地开发环境中使用本页面上的 Python 示例,请安装并初始化 gcloud CLI,然后使用您的用户凭据设置应用默认凭据。
Google Cloud
创建 Vertex AI Agent Engine 实例
如需访问 Vertex AI Agent Engine 会话和 Vertex AI Agent Engine 内存银行,您首先需要创建一个 Vertex AI Agent Engine 实例。您无需部署代理即可开始使用会话和内存银行。如果未部署智能体,创建 Vertex AI Agent Engine 实例应该需要几秒钟。
如果您希望 Vertex AI Agent Engine 内存银行使用大语言模型 (LLM) 为您生成回忆,请提供 memoryBankConfig.generationConfig
,并添加您希望内存银行用于生成回忆的模型。您项目的 Vertex AI Reasoning Engine Service Agent 必须具有 aiplatform.endpoints.predict
权限才能使用该模型。
import requests
import google.auth
import google.auth.transport.requests
credentials, _ = google.auth.default()
auth_req = google.auth.transport.requests.Request()
credentials.refresh(auth_req)
url = "https://LOCATION-aiplatform.googleapis.com/v1beta1/projects/PROJECT_ID/locations/LOCATION/reasoningEngines"
response = requests.post(
url=url,
json={
"contextSpec": {
"memoryBankConfig": {
"generationConfig": {
"model": f"projects/PROJECT_ID/locations/LOCATION/publishers/google/models/MODEL_NAME"
},
"similaritySearchConfig": {
"embeddingModel": f"projects/PROJECT_ID/locations/LOCATION/publishers/google/models/EMBEDDING_MODEL_NAME"
}
}
}
},
headers={
"Content-Type": "application/json; charset=utf-8",
"Authorization": f"Bearer {credentials.token}"
}
)
split_name = response.json()["name"].split("/")
agent_engine_name = "/".join(split_name[:-2])
替换以下内容:
从 Vertex AI Agent Engine 会话生成回忆
设置 Vertex AI Agent Engine 会话和内存银行后,您可以创建会话并将事件附加到其中。系统会根据用户与代理的对话生成记忆,以便在日后用户互动时使用。如需了解详情,请参阅生成和检索回忆。
替换以下内容:
上传回忆
除了使用原始对话生成回忆之外,您还可以使用 CreateMemory
直接上传回忆。您可以直接提供应存储的用户相关事实,而无需 Memory Bank 从您的内容中提取信息。我们建议您以第一人称(例如 I am a software engineer
)撰写有关用户的事实。
credentials, _ = google.auth.default()
auth_req = google.auth.transport.requests.Request()
credentials.refresh(auth_req)
url = "https://LOCATION-aiplatform.googleapis.com/v1beta1/AGENT_ENGINE_NAME"
response = requests.post(
url=f"{url}/memories",
headers={
"Content-Type": "application/json; charset=utf-8",
"Authorization": f"Bearer {credentials.token}",
},
json={
"fact": "This is a fact",
"scope": {"user_id": "USER_ID"}
}
)
检索和使用回忆
您可以为用户检索回忆,并将其包含在系统说明中,以便 LLM 访问您的个性化情境。
如需了解基于镜区的回忆检索方法,请参阅“提取回忆”文档。
response = requests.post(
url=f"{url}/memories:retrieve",
headers={
"Content-Type": "application/json; charset=utf-8",
"Authorization": f"Bearer {credentials.token}",
},
json={
"scope": {"user_id": "USER_ID"}
}
)
您可以使用 jinja
将结构化记忆转换为问题:
from jinja2 import Template
template = Template("""
<MEMORIES>
Here is some information about the user:
{% for memory in data.memories %}* {{ memory.fact }}
{% endfor %}</MEMORIES>
""")
prompt = template.render(data=response.json())
"""
Output:
<MEMORIES>
Here is some information about the user:
* This is a fact
</MEMORIES>
"""
清理
如需清理此项目中使用的所有资源,您可以删除用于本快速入门的 Google Cloud 项目。
否则,您可以逐个删除在本教程中创建的资源,如下所示: