设置记忆库

如需使用 Agent Platform 记忆库,您必须先创建并配置记忆库实例。此实例用于管理您的记忆,并且可以与各种运行时中的代理集成。

本文档介绍了如何设置项目、安装所需的库,以及如何使用自定义配置(例如主题和 TTL)创建或更新实例。 Google Cloud

开始使用

在使用记忆库之前,您必须设置环境。

设置 Google Cloud 项目

每个项目都可以通过项目编号和项目 ID 这两种方式来识别。PROJECT_NUMBER 由系统在您创建项目时自动创建,PROJECT_ID 则是由您或项目创建者创建的。如需设置项目,请执行以下操作:

  1. 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 the resourcemanager.projects.create permission. Learn how to grant roles.

    Go to project selector

  2. Verify that billing is enabled for your Google Cloud project.

  3. Enable the Agent Platform API.

    Roles required to enable APIs

    To enable APIs, you need the serviceusage.services.enable permission. 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.

    Enable the API

获取所需的角色

如需获得使用记忆库所需的权限,请让您的管理员为您授予项目的以下 IAM 角色:

如需详细了解如何授予角色,请参阅管理对项目、文件夹和组织的访问权限

您也可以通过自定义 角色或其他预定义 角色来获取所需的权限。

如果您要从部署在 Google Kubernetes Engine (GKE) 或 Cloud Run 上的代理向记忆库发出请求,请确保您的服务帐号具有必要的权限。The Reasoning Engine Service Agent 已经拥有读取和写入记忆所需的权限,因此来自 Agent Runtime 的出站 请求应该已经拥有访问 记忆库的权限。

安装库

本部分假定您已设置 Python 开发 环境,或者正在使用具有 Python 开发环境的运行时(例如 Colaboratory)。

安装 Agent Platform SDK:

pip install google-cloud-aiplatform>=1.111.0

身份验证

按照向 Vertex AI 进行身份验证中的说明操作。

设置 Agent Platform SDK 客户端

运行以下代码以设置 Agent Platform SDK 客户端:

Agent Platform SDK

import vertexai

client = vertexai.Client(
  project="PROJECT_ID",
  location="LOCATION",
)

其中

多区域和全球端点

记忆库支持多区域和全球端点:

  • 对于全球实例,请将位置设置为 global
  • 对于多区域实例,请将位置设置为 useu

创建或更新记忆库实例

如需开始使用记忆库,您首先需要一个记忆库实例。如果您还没有实例,可以使用默认配置和您选择的显示名称创建一个实例。

# create the resource
memory_bank = client.agent_engines.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.api_resource.name)

如果您想自定义新的或现有 记忆库实例的行为配置,请参阅配置记忆库实例。例如,您可以指定记忆库认为哪些信息有意义并应持久保存。

获得记忆库实例后,您可以使用该实例的名称来读取或写入记忆。例如:

# Generate memories using your Memory Bank instance.
client.agent_engines.memories.generate(
  # `name` should have the format `projects/.../locations/.../reasoningEngines/...`.
  name=memory_bank.api_resource.name,
  ...
)

与 Agent Runtime 搭配使用

虽然记忆库可以在任何运行时中使用,但您也可以将记忆库与 Agent Runtime 搭配使用,以从已部署的代理读取和写入记忆。

如需在 Agent Runtime 上部署具有内置记忆库的代理, 请先为 Agent Runtime设置环境。然后,准备将 代理部署到 集成记忆的 Agent Runtime。已部署的代理应根据需要调用读取和写入记忆。

AdkApp

如果您使用的是 Agent Platform 智能体开发套件 (ADK) 模板,则智能体在部署到 Agent Runtime 时默认使用 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 Runtime.
runtime = 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 Runtime to add or modify the Runtime.
runtime = client.agent_engines.update(
      name=runtime.api_resource.name,
      agent=adk_app,
      config={
            "staging_bucket": "STAGING_BUCKET",
            "requirements": ["google-cloud-aiplatform[agent_engines,adk]"],
            # Optional.
            **context_spec
      }
)

替换以下内容:

  • STAGING_BUCKET:用于 暂存 Agent Runtime 的 Cloud Storage 存储桶。

如需详细了解如何将记忆库与 ADK 搭配使用,请参阅 ADK 快速入门

自定义代理

您可以将记忆库与部署在 Agent Runtime 上的custom agent搭配使用。在这种情况下,您的代理应编排 对记忆库的调用,以触发 记忆 生成记忆检索 调用。

部署到 Agent Runtime 的应用可以读取环境变量 GOOGLE_CLOUD_PROJECTGOOGLE_CLOUD_LOCATIONGOOGLE_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.generateaiplatform.memories.retrieve 就足够了。

在所有其他运行时中使用

如果您想在 Cloud Run 或 Colab 等其他环境中使用记忆库,请创建记忆库。如果您未提供配置,系统会使用用于管理记忆生成和检索的默认设置来创建记忆库。

memory_bank = client.agent_engines.create()

如果您之前使用过记忆库,则创建新的记忆库实例应该只需要几秒钟。如果您是首次使用记忆库,则可能需要更长时间(1-2 分钟)。

如果您想配置行为,请提供记忆库 配置

创建

memory_bank = client.agent_engines.create(
  config={
    "context_spec": {
      "memory_bank_config": ...
    }
  }
)

更新

如果您想更改记忆库 配置,可以更新您的 记忆库实例。

memory_bank = client.agent_engines.update(
  # You can access the name using `memory_bank.api_resource.name` for an AgentEngine object.
  name="MEMORY_BANK_NAME",
  config={
    "context_spec": {
      "memory_bank_config": ...
    }
  }
)

替换以下内容:

  • MEMORY_BANK_NAME:记忆库的名称。 它应采用 projects/.../locations/.../reasoningEngines/... 格式。请参阅记忆库 支持的区域。

您可以在任何有权读取和写入记忆的环境中使用记忆库。例如,如需将记忆库与 Cloud Run 搭配使用,请向 Cloud Run 服务 身份授予读取和写入 记忆的权限。所需的权限取决于您的代理应能够执行哪些操作。如果您只希望代理检索和生成 记忆, aiplatform.memories.generateaiplatform.memories.retrieve 就足够了。

配置记忆库实例

您可以配置记忆库,自定义记忆的生成和管理方式。如果您未提供配置,记忆库将针对每种类型的配置使用默认设置。

您可以为实例配置以下记忆库设置:

  • 自定义配置:用于配置如何 从源数据中提取记忆并与现有 记忆整合。
  • 相似度搜索配置:指定 记忆库用于相似度搜索的嵌入模型。 默认值为 text-embedding-005
  • 生成配置:配置记忆库用于记忆生成的 LLM 。默认值为 gemini-3.5-flash
  • TTL 配置:配置如何为创建或更新的记忆自动设置 TTL。默认值为无 TTL。

以下示例展示了默认记忆库:

字典

memory_bank_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"
  },
  "customization_configs": [
    {
      # Extract user information, preferences, key conversation details,
      # and information that the user explicitly asked to be remembered.
      "memory_topics": [
        {"managed_memory_topic": "USER_PERSONAL_INFO"},
        {"managed_memory_topic": "USER_PREFERENCES"},
        {"managed_memory_topic": "KEY_CONVERSATION_DETAILS"},
        {"managed_memory_topic": "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 vertexai.types import MemoryBankCustomizationConfig as CustomizationConfig
from vertexai.types import MemoryBankCustomizationConfigConsolidationConfig as ConsolidationConfig
from vertexai.types import MemoryBankCustomizationConfigMemoryTopic as MemoryTopic
from vertexai.types import MemoryBankCustomizationConfigMemoryTopicManagedMemoryTopic as ManagedMemoryTopic
from vertexai.types import ManagedTopicEnum
from vertexai.types import ReasoningEngineContextSpecMemoryBankConfig as MemoryBankConfig
from vertexai.types import ReasoningEngineContextSpecMemoryBankConfigGenerationConfig as GenerationConfig
from vertexai.types import ReasoningEngineContextSpecMemoryBankConfigSimilaritySearchConfig as SimilaritySearchConfig
from vertexai.types import ReasoningEngineContextSpecMemoryBankConfigTtlConfig as TtlConfig

memory_bank_config = MemoryBankConfig(
  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"
  ),
  customization_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
)

您可以在创建或更新实例时调整记忆库配置。以下示例演示了如何使用特定的记忆库配置创建或更新实例。

client.agent_engines.create(
      ...,
      config={
            "context_spec": {
                  "memory_bank_config": memory_bank_config
            }
      }
)

# Alternatively, update an existing Memory Bank instance's config.
memory_bank = client.agent_engines.update(
      name=memory_bank.api_resource.name,
      config={
          "context_spec": {
                "memory_bank_config": memory_bank_config
          }
      }
)

自然语言记忆自定义配置

如需自定义记忆库提取自然语言记忆的方式,请在设置实例时配置提取行为。使用以下选项自定义行为:

  • 配置记忆主题:定义记忆库应视为有意义并持久保存的信息类型。记忆库只会持久保存符合这些记忆主题之一的信息。
  • 提供少样本示例:演示将记忆提取到记忆库的预期 行为。
  • 配置记忆视角:配置 记忆应以第一人称(默认)还是第三人称生成。
  • 配置整合:配置记忆库在整合每个候选记忆时考虑的 记忆修订版本数量 。

您可以分两步自定义记忆库的提取行为:告知和展示。记忆主题用于告知记忆库要保留哪些信息。 少样本用于向记忆库展示哪些类型的信息应生成特定记忆, 帮助记忆库了解您希望它理解的模式、细微差别和措辞。

您可以选择为不同的范围级别配置不同的行为。例如,对于会话级记忆有意义的主题可能对于用户级记忆(跨多个会话)没有意义。如需为特定部分记忆配置行为,请设置自定义配置的范围键。只有包含这些范围键的 GenerateMemories 请求才会使用该配置。您还可以通过省略 scope_key 字段来配置默认行为(应用于所有范围键集)。如果请求的范围键未与其他任何自定义配置的范围键完全匹配,则此配置将应用于该请求。

例如,user_level_config 仅适用于完全使用范围键 user_idGenerateMemories 请求(即 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": [...]
}

memory_bank_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_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."""
      )
    )
    

    使用自定义主题时,建议同时提供少样本示例,以展示应如何从对话中提取记忆。

通过自定义,您可以任意组合使用记忆主题。例如,您可以使用部分可用的托管式记忆主题:

字典

customization_config = {
  "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

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 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

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."""
          )
    )
  ]
)

少样本示例

通过少样本示例,您可以向记忆库展示预期的记忆提取行为。例如,您可以提供示例输入对话以及预期从该对话中提取的记忆。

我们建议始终使用包含自定义主题的少样本,以便记忆库了解预期行为。使用托管式主题时,由于记忆库会为每个主题定义示例,因此您可以选择不提供少样本。通过提供空的 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=[]
)

记忆视角

默认情况下,记忆以第一人称生成(例如“我使用记忆库进行记忆管理。”)。您可以使用 enable_third_person_memories 参数将记忆库配置为以第三人称生成(例如“用户使用记忆库进行记忆管理。”)。

字典

customization_config = {
  "enable_third_person_memories": True
}

基于类

from vertexai.types import MemoryBankCustomizationConfig as CustomizationConfig

customization_config = CustomizationConfig(
    enable_third_person_memories=True
)

整合自定义

整合期间,记忆库 会确定如何将新获取的信息整合到现有记忆 集中。记忆库会评估是添加新记忆、使用其他上下文更新现有记忆,还是删除过时的记忆。

为了确保记忆的质量和可靠性,记忆库可以选择分析记忆的历史记录,以区分长期趋势和一次性异常值。

默认情况下,记忆库仅将新信息与候选记忆("记忆修订版本")的最新快照进行比较。如需增加此分析的深度,请配置 revisions_per_candidate_count 参数。此参数定义了记忆库在整合期间考虑的每个“候选记忆”(正在评估更新的特定记录)的先前修订版本数量。

字典

customization_config = {
  "consolidation_customization": {
    "revisions_per_candidate_count": 10
  }
}

基于类

from vertexai.types import MemoryBankCustomizationConfig as CustomizationConfig
from vertexai.types import MemoryBankCustomizationConfigConsolidationConfig as ConsolidationConfig

customization_config = CustomizationConfig(
    consolidation_customization=ConsolidationConfig(
      revisions_per_candidate_count=10
    )
)

增加 revisions_per_candidate_count 会考虑注入信息的重复性,从而生成更一致且可靠的记忆。 但是,更高的计数会增加整合过程中的令牌消耗量。

相似度搜索配置

相似度搜索配置用于控制您的实例在相似度搜索中使用的嵌入模型。相似度搜索用于确定 哪些记忆应作为 整合的候选对象,以及 用于基于相似度搜索的记忆 检索。 如果未提供此配置,记忆库将使用 text-embedding-005 作为默认模型。

如果您预计用户对话会使用非英语语言,请使用支持多种语言的 模型(例如 gemini-embedding-2gemini-embedding-001text-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"
    )
)

替换以下内容:

  • EMBEDDING_MODEL:用于 相似度搜索的 Google 文本嵌入模型,格式为 projects/{project}/locations/{location}/publishers/google/models/{model}

生成配置

生成配置用于控制使用哪个 LLM 来生成 记忆,包括 提取记忆以及将新记忆与现有记忆整合。

自 2026 年 6 月 29 日起,记忆库将使用 gemini-3.5-flash 作为默认模型。在此日期之前创建的实例使用 gemini-2.5-flash

对于使用默认模型的新记忆库实例:

  • us 多区域或 us-* 单区域(例如 us-central1)中的记忆库实例使用多区域 us Gemini 3.5 端点。
  • eu 多区域或 eu-* 单区域(例如 europe-west2)中的记忆库实例使用多区域 eu Gemini 3.5 端点。
  • 所有其他记忆库区域都使用全球 Gemini 3.5 端点。

对于在 2026 年 6 月 29 日之前使用默认模型创建的记忆库实例,记忆库将针对没有区域性 Gemini 2.5 端点的区域使用 global Gemini 端点。

字典

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"
  )
)

替换以下内容:

  • LLM_MODEL:用于提取和 整合记忆的 Google LLM 模型,格式为 projects/{project}/locations/{location}/publishers/google/models/{model}

存留时间 (TTL) 配置

TTL 配置用于控制记忆库应如何动态设置记忆的过期时间。过期后,记忆将无法检索,并会被删除。

如果未提供配置,系统不会为创建或更新的记忆动态设置到期时间,因此除非手动设置记忆的到期时间,否则记忆不会过期。

您可以通过以下两种方式配置 TTL:

  • 默认 TTL:TTL 将应用于创建或 更新记忆的所有操作,包括 UpdateMemoryCreateMemoryGenerateMemories

    字典

    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 的时长(以秒为单位)。对于更新后的记忆,新计算的到期时间(当前时间 + TTL)将覆盖记忆之前的到期时间。
  • 精细(按操作)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 创建的记忆的 TTL 时长(以秒为单位)。
    • GENERATE_CREATED_TTL:使用 GenerateMemories 创建的记忆的 TTL 时长(以秒为单位)。
    • GENERATE_UPDATED_TTL:使用 GenerateMemories 更新的记忆的 TTL 时长(以秒为单位)。新计算出的到期时间(当前时间 + TTL)将覆盖记忆之前的到期时间。

后续步骤

快速入门

开始使用记忆库 API 来管理长期记忆。

快速入门

开始使用智能体开发套件 (ADK)。