Azure Cosmos DB

Azure Cosmos DBでは、Agent Framework で 2 つの異なるコンテキスト プロバイダー パターンがサポートされています。 正確なトランスクリプトが必要か、長期的な知識を抽出するかに基づいて、プロバイダーを選択します。

Pattern Provider Behavior
会話履歴 CosmosChatHistoryProvider(.NET) またはCosmosHistoryProvider(Python) 再起動後または別のアプリケーション インスタンスでセッションを再開できるように、完全なメッセージを保持します。
長期記憶 CosmosMemoryContextProvider (パイソン) 事実、手続き的知識、エピソード記憶、および要約を抽出し、後続の実行時に関連する記憶を取得します。

会話履歴を保持する

パッケージをインストールする

dotnet add package Microsoft.Agents.AI.CosmosNoSql --prerelease

Cosmos DB チャット履歴の構成

マネージド ID 拡張機能を使用して、CosmosChatHistoryProviderにChatClientAgentOptionsをアタッチします。

using Azure.Identity;
using Microsoft.Agents.AI;

var options = new ChatClientAgentOptions
{
    ChatOptions = new() { Instructions = "You are a helpful assistant." }
}.WithCosmosDBChatHistoryProviderUsingManagedIdentity(
    accountEndpoint: Environment.GetEnvironmentVariable("AZURE_COSMOS_ENDPOINT")!,
    databaseId: Environment.GetEnvironmentVariable("AZURE_COSMOS_DATABASE_NAME")!,
    containerId: Environment.GetEnvironmentVariable("AZURE_COSMOS_CONTAINER_NAME")!,
    tokenCredential: new DefaultAzureCredential());

AIAgent agent = chatClient.AsAIAgent(options);

既定の状態初期化子は、会話 ID を作成します。 アプリケーションで明示的な会話、テナント、ユーザー ルーティングが必要な場合は、 CosmosChatHistoryProvider.State 初期化子を指定します。 テナント ID とユーザー ID が存在する場合、プロバイダーは階層パーティション キーを使用します。

Warning

DefaultAzureCredential は開発に便利です。 運用環境では、 ManagedIdentityCredentialなどの特定の資格情報を使用します。

パッケージをインストールする

pip install agent-framework-azure-cosmos --pre

CosmosHistoryProvider のコンフィギュレーション

Python プロバイダーは、Azure資格情報またはアカウント キーを受け入れます。 パーティション キーとして session_id を使用します。 同じアカウント、データベース、コンテナー、空でない session_id、および空でない source_id を使用するプロバイダー インスタンスは、同じ永続化された履歴にアクセスします。 source_idは、パーティション内の履歴をフィルター処理します。 これらの識別子は、保存された履歴を選択します。認証や承認の境界ではありません。 認証された承認されたアプリケーション コンテキストにバインドし、分離が必要な場合は個別の信頼された名前空間を使用します。

# 1. Create an Azure credential and a CosmosHistoryProvider for agent context
async with (
    AzureCliCredential() as credential,
    CosmosHistoryProvider(
        endpoint=cosmos_endpoint,
        database_name=cosmos_database_name,
        container_name=cosmos_container_name,
        credential=cosmos_key or credential,
    ) as history_provider,
    # 2. Create an agent that uses Cosmos for persisted conversation history.
    Agent(
        client=FoundryChatClient(
            project_endpoint=project_endpoint,
            model=model,
            credential=credential,
        ),
        name="CosmosHistoryAgent",
        instructions="You are a helpful assistant that remembers prior turns.",
        context_providers=[history_provider],
        default_options={"store": False},
    ) as agent,
):
    # 3. Create a session (session_id is used as the partition key).
    session = agent.create_session()

    # 4. Run a multi-turn conversation; history is persisted by CosmosHistoryProvider.
    response1 = await agent.run("My name is Ada and I enjoy distributed systems.", session=session)
    print(f"Assistant: {response1.text}")

    response2 = await agent.run("What do you remember about me?", session=session)
    print(f"Assistant: {response2.text}")
    print(f"Container: {history_provider.container_name}")

後でクライアントが同じセッション識別子を回復する必要がある場合は、シリアル化された AgentSession を信頼されたアプリケーション ストレージに保持します。

Note

Go SDK には、他の SDK に示されている専用の Cosmos DB 会話履歴プロバイダーは含まれません。 厳密な会話の永続化のために agent.HistoryProvider を実装します。 Go Cosmos DB ベクター ストア コネクタは、別の目的、つまりベクター検索と取得を果たします。

長期的なセマンティック メモリを追加する

Note

Azure Cosmos DBの長期メモリ プロバイダーは現在、Pythonで使用できます。 .NET アプリケーションで正確なトランスクリプトの永続化が必要な場合は、上記の会話履歴プロバイダーを使用します。

前提条件

  • Azure Cosmos DB アカウントとデータベース。
  • チャットと埋め込みモデルのデプロイを含むMicrosoft Foundry プロジェクト。
  • Azure ID による両方のリソースへのアクセス

パッケージをインストールする

pip install agent-framework-azure-cosmos-memory agent-framework-foundry --pre

メモリ プロバイダーを構成する

同じ Foundry プロジェクトで、チャット モデル、埋め込み、メモリ抽出モデルを提供できます。 context_providers経由でプロバイダーをアタッチします。


def _foundry_project_endpoint() -> str:
    """Read the preferred project endpoint variable with legacy compatibility."""
    return os.environ.get("FOUNDRY_PROJECT_ENDPOINT") or os.environ["FOUNDRY_ENDPOINT"]


def _build_agent(provider: CosmosMemoryContextProvider, credential: DefaultAzureCredential) -> Agent:
    """Build an agent that uses the memory provider and the same Foundry endpoint for chat."""
    return Agent(
        client=FoundryChatClient(
            project_endpoint=_foundry_project_endpoint(),
            model=os.getenv("CHAT_MODEL", "gpt-4o-mini"),
            credential=credential,
        ),
        name="Memory Assistant",
        instructions="You are a helpful assistant with long-term memory about the user.",
        context_providers=[provider],
    )


async def user_scoped_memory() -> None:
    """Memory scoped to a stable user id, so it persists across sessions and threads."""
    credential = DefaultAzureCredential()
    provider = CosmosMemoryContextProvider(
        cosmos_endpoint=os.environ["COSMOS_ENDPOINT"],
        foundry_endpoint=_foundry_project_endpoint(),
        embedding_model=os.getenv("EMBEDDING_MODEL", "text-embedding-3-large"),
        chat_model=os.getenv("CHAT_MODEL", "gpt-4o-mini"),
        credential=credential,
    )
    agent = _build_agent(provider, credential)

    async with provider:
        session = agent.create_session()
        # Provider state is scoped by source id; set a stable user id there so memory
        # persists across sessions rather than being limited to this one.
        session.state.setdefault(provider.source_id, {})["user_id"] = "alice"
        first = await agent.run("I love hiking and I'm allergic to peanuts.", session=session)
        print("Assistant:", first.text)

        # A brand-new session for the same user still recalls the earlier facts.
        new_session = agent.create_session()

安定した user_id により、セッションとスレッド間でメモリを使用できます。 プロバイダー所有の状態名前空間 ( session.state[provider.source_id]["user_id"]) の下に格納します。 他のプロバイダーやアプリケーションのフィールドと競合する可能性があるため、フラットなセッション状態には格納しないでください。 ユーザー ID がない場合、プロバイダーはメモリの適用範囲を現在のセッション ID に限定します。

メモリ処理

メモリ抽出は、ターンごとにバックグラウンドで実行されます。 非同期コンテキスト マネージャーとしてプロバイダーを使用するか、シャットダウン前に flush() を呼び出して、クライアントが閉じる前に保留中の抽出が完了します。

プロバイダーでは、カスタム抽出プロンプト、プロセッサの周期、信頼度のしきい値、メモリの種類、取得の制限もサポートされています。 memory_typesで事実、手順、エピソードを選択します。 エージェント メモリ ツールキット 0.3.0b2 以降では、ファクトと選択したエピソードは、ランク付けされた top_k 結果の制限を共有します。 選択したプロシージャは現在のタスク用に別個にコンパイルされ、その上限にはカウントされません。 サポートされている以前のバージョンのツールキットでは、一般的な取得動作が保持されます。 top_kを正の整数に設定し、0.0を1.0からmin_confidenceまでの値(両端を含む)に設定します。 無効な値を指定すると、プロバイダーの作成時に ValueError が発生します。

Go は、azureprovider.NewCosmosDBを介して NoSQL 用 Cosmos DB ベクター ストアを提供します。 既存の azcosmos.Client とデータベースを使用し、コレクションは vectordata を通じて公開された状態です。

コネクタでは、生成された埋め込み、ベクター検索、フルテキスト/ベクター ハイブリッド検索がサポートされます。 アカウントで必要な検索機能が有効になっている必要があります。 ランク付けされたクエリでは、構成されているすべてのパーティション キー プロパティに対して等値フィルターが必要です。クロスパーティションランク付けは、このコネクタではサポートされていません。

Cosmos DB Go サンプルには、AZURE_COSMOS_ENDPOINT、AZURE_COSMOS_DATABASE、FOUNDRY_PROJECT_ENDPOINT、およびFOUNDRY_EMBEDDING_MODELが必要です。 3,072 次元スキーマを使用し、既存のデータベース内に一意の名前を持つ一時コンテナーを作成および削除します。

このコネクタは、C# の例に示されている専用の長期メモリ プロバイダーではありません。 アプリケーション管理の取得では、コネクタのパーティション フィルターとアプリケーションのアクセス制御を保持して、テキスト検索 RAG を使用してコレクション検索を構成します。 使用可能な Go ストアについては、 ベクター ストアの統合 を参照してください。

実稼働に関する考慮事項

  • 認証されたアプリケーション ID からユーザー、テナント、およびセッション識別子を派生させます。
  • テナントの分離を強制しながらトラフィックを分散するパーティション キーを選択します。
  • 承認されたリージョンに Cosmos DB とモデル リソースを保持し、最小特権 RBAC を適用します。
  • トランスクリプトと抽出されたメモリの両方に対して、有効期間、バックアップ、保持、削除のポリシーを構成します。
  • 永続化の前に機密性の高いコンテンツをフィルター処理または編集し、抽出されたメモリを承認の決定に直接使用しないでください。

次のステップ

より深く進む: