Memory Bank を設定する

Agent Platform メモリバンクを使用するには、まずメモリバンク インスタンスを作成して構成する必要があります。このインスタンスはメモリを管理し、さまざまなランタイムでエージェントと統合できます。

このドキュメントでは、 Google Cloud プロジェクトを設定し、必要なライブラリをインストールして、トピックや TTL などのカスタム構成でインスタンスを作成または更新する方法について説明します。

使ってみる

メモリバンク を使用する前に、環境を設定する必要があります。

Google Cloud プロジェクトを設定する

すべてのプロジェクトは、プロジェクト番号またはプロジェクト ID によって識別できます。PROJECT_NUMBER はプロジェクトの作成時に自動的に作成されますが、PROJECT_ID はプロジェクトの作成者が作成します。プロジェクトを設定するには:

  1. Google Cloud アカウントにログインします。 Google Cloudを初めて使用する場合は、 アカウントを作成して、実際のシナリオで Google プロダクトのパフォーマンスを評価してください。新規のお客様には、ワークロードの実行、テスト、デプロイができる無料クレジット $300 分も差し上げます。
  2. 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

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

  4. Enable the Agent Platform API, if it is not already enabled.

    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

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

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

  7. Enable the Agent Platform API, if it is not already enabled.

    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

必要な権限を取得する

Memory Bank の使用に必要な権限を取得するには、プロジェクトに対する次の IAM ロールを付与するよう管理者に依頼してください。

ロールの付与については、プロジェクト、フォルダ、組織へのアクセス権の管理をご覧ください。

必要な権限は、カスタムロールや他の事前定義ロールから取得することもできます。

Google Kubernetes Engine(GKE)または Cloud Run にデプロイされたエージェントから Memory Bank にリクエストを送信する場合は、サービス アカウントに記憶の読み取り、書き込み、生成に必要な権限があることを確認してください。Reasoning Engine サービス エージェントには、記憶の読み取り、書き込み、生成に必要な権限がすでに付与されているため、Agent Runtime からのアウトバウンド リクエストには、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",
)

ここで

マルチリージョン エンドポイントとグローバル エンドポイント

メモリバンクは、マルチリージョン エンドポイントとグローバル エンドポイントをサポートしています。

  • グローバル インスタンスの場合は、ロケーションを global に設定します。
  • マルチリージョン インスタンスの場合は、ロケーションを us または eu に設定します。

メモリバンク インスタンスを作成または更新する

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 ツールは 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 バケット。

ADK でのメモリバンクの使用に関する詳細は、ADK のクイックスタートをご覧ください。

カスタム エージェント

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 = client.memory_banks.create()

メモリバンク を使用したことがある場合は、新しい メモリバンク インスタンスの作成に数秒しかかかりません。Memory Bank を初めて使用する場合は、時間がかかることがあります(1 ~ 2 分)。

動作を構成する場合は、メモリバンクの構成を指定します。

作成

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 = client.memory_banks.update(
  # You can access the name using `memory_bank.name` for a MemoryBank object.
  name="MEMORY_BANK_NAME",
  managed_semantic_memory_config={
    "generation_config": ...,
    "unstructured_memory_configs": [...],
    "structured_memory_configs": [...],
    "similarity_search_config": ...,
    "ttl_config": ...,
    "disable_memory_revisions": False,
  }
)

次のように置き換えます。

Memory Bank は、記憶の読み取りと書き込みの権限を持つ環境で使用できます。たとえば、Cloud Run で Memory Bank を使用するには、記憶の読み取りと書き込みを行う権限を Cloud Run サービス ID に付与します。必要な権限は、エージェントが実行できるオペレーションによって異なります。エージェントが記憶を取得して生成するだけでよい場合は、aiplatform.memories.generate と aiplatform.memories.retrieve で十分です。

メモリバンク インスタンスを構成する

メモリバンクを構成して、記憶の生成と管理の方法をカスタマイズできます。構成を指定しない場合、メモリバンクは各構成タイプのデフォルト設定を使用します。

インスタンスに対して次のメモリバンク設定を構成できます。

  • カスタマイズ構成(unstructured_memory_configs): ソースデータから記憶を抽出し、既存の記憶と統合する方法を構成します。
  • 類似性検索の構成: メモリバンクが類似性検索に使用するエンベディング モデルを指定します。デフォルトは text-embedding-005 です。
  • 生成構成: メモリバンクがメモリーの生成に使用する LLM を構成します。デフォルトは gemini-3.5-flash です。
  • TTL の構成: 作成または更新された記憶の TTL を自動的に設定する方法を構成します。デフォルトでは TTL は設定されません。

次のサンプルは、デフォルトのメモリバンクを示しています。

辞書

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
)

# Alternatively, update an existing Memory Bank instance's config.
memory_bank = client.memory_banks.update(
    name=memory_bank.name,
    managed_semantic_memory_config=managed_semantic_memory_config
)

自然言語メモリーのカスタマイズ構成

Memory Bank が自然言語の記憶を抽出する方法をカスタマイズするには、インスタンスの設定時に抽出動作を構成します。次のオプションを使用して動作をカスタマイズします。

Memory Bank の抽出動作のカスタマイズは、伝える(Telling)と示す(Showing)の 2 つの手順で行います。メモリトピックは、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 は、次の 2 種類の記憶のトピックをサポートしています。

  • 管理対象トピック: ラベルと手順は 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
        )
    )
    

    Memory Bank では、次のマネージド トピックがサポートされています。

    • ユーザー情報(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_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=[]
)

メモリ パースペクティブ

デフォルトでは、メモリは一人称で生成されます(例: 「私はメモリ管理にメモリバンクを使用しています」)。enable_third_person_memories パラメータを使用すると、メモリバンク を構成して三人称で生成できます(例: 「ユーザーはメモリ管理に メモリバンク を使用しています。」)。

辞書

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

類似性検索の構成

類似性検索構成は、類似性検索用にインスタンスで使用されるエンベディング モデルを制御します。類似性検索は、統合の候補となる記憶を特定するためと、類似性検索ベースの記憶取得のために使用されます。この構成が指定されていない場合、メモリバンク はデフォルトのモデルとして 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 を使用します。

デフォルトのモデルを使用する新しいメモリバンク インスタンスの場合:

  • 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 エンドポイントを使用します。

辞書

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 構成には次の 2 つのオプションがあります。

  • デフォルト TTL: 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 の期間(秒単位)。更新された記憶の場合、新たに計算された有効期限(現在 + TTL)によって、記憶の以前の有効期限が上書きされます。
  • 詳細な(オペレーション単位の)TTL: 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 を使用して作成された記憶の TTL の秒単位の期間。
    • GENERATE_CREATED_TTL: GenerateMemories を使用して作成された記憶の TTL の秒単位の期間。
    • GENERATE_UPDATED_TTL: GenerateMemories を使用して更新された記憶の TTL の秒単位の期間。新たに計算された有効期限(現在 + TTL)は、記憶の以前の有効期限を上書きします。

次のステップ

クイックスタート

Memory Bank API を使用して長期記憶の管理を開始します。

クイックスタート

Agent Development Kit(ADK)を使ってみる。