次の方法で共有


手順 4: メモリと永続化

ユーザー設定、過去の対話、または外部の知識を記憶できるように、エージェントにコンテキストを追加します。

カスタム ChatHistoryProviderを使用してメモリを設定します。

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

var endpoint = Environment.GetEnvironmentVariable("AZURE_OPENAI_ENDPOINT")
    ?? throw new InvalidOperationException("Set AZURE_OPENAI_ENDPOINT");
var deploymentName = Environment.GetEnvironmentVariable("AZURE_OPENAI_DEPLOYMENT_NAME") ?? "gpt-4o-mini";

AIAgent agent = new AzureOpenAIClient(new Uri(endpoint), new AzureCliCredential())
    .GetChatClient(deploymentName)
    .AsAIAgent(instructions: "You are a friendly assistant. Keep your answers brief.", name: "MemoryAgent");

セッションを使用して、実行間でコンテキストを保持します。

AgentSession session = await agent.CreateSessionAsync();

Console.WriteLine(await agent.RunAsync("Hello! What's the square root of 9?", session));
Console.WriteLine(await agent.RunAsync("My name is Alice", session));
Console.WriteLine(await agent.RunAsync("What is my name?", session));

ヒント

完全な実行可能ファイルについては、 完全なサンプル を参照してください。

すべてのエージェント呼び出しに追加のコンテキストを挿入するコンテキスト プロバイダーを定義します。

class UserNameProvider(BaseContextProvider):
    """A simple context provider that remembers the user's name."""

    def __init__(self) -> None:
        super().__init__(source_id="user-name-provider")
        self.user_name: str | None = None

    async def before_run(
        self,
        *,
        agent: Any,
        session: AgentSession,
        context: SessionContext,
        state: dict[str, Any],
    ) -> None:
        """Called before each agent invocation — add extra instructions."""
        if self.user_name:
            context.instructions.append(f"The user's name is {self.user_name}. Always address them by name.")
        else:
            context.instructions.append("You don't know the user's name yet. Ask for it politely.")

    async def after_run(
        self,
        *,
        agent: Any,
        session: AgentSession,
        context: SessionContext,
        state: dict[str, Any],
    ) -> None:
        """Called after each agent invocation — extract information."""
        for msg in context.input_messages:
            text = msg.text if hasattr(msg, "text") else ""
            if isinstance(text, str) and "my name is" in text.lower():
                # Simple extraction — production code should use structured extraction
                self.user_name = text.lower().split("my name is")[-1].strip().split()[0].capitalize()

コンテキスト プロバイダーを使用してエージェントを作成します。

credential = AzureCliCredential()
client = AzureOpenAIResponsesClient(
    project_endpoint=os.environ["AZURE_AI_PROJECT_ENDPOINT"],
    deployment_name=os.environ["AZURE_OPENAI_RESPONSES_DEPLOYMENT_NAME"],
    credential=credential,
)

memory = UserNameProvider()

agent = client.as_agent(
    name="MemoryAgent",
    instructions="You are a friendly assistant.",
    context_providers=[memory],
)

Python では、永続化/メモリは履歴プロバイダーによって処理されます。 BaseHistoryProviderBaseContextProviderであり、InMemoryHistoryProviderは組み込みのローカル実装です。 RawAgent は、特定のケース (たとえば、コンテキスト プロバイダーが構成されておらず、サービス側のストレージ インジケーターがないセッションを使用する場合) に InMemoryHistoryProvider("memory") を自動的に追加する場合がありますが、これはすべてのシナリオで保証されるわけではありません。 常にローカル永続化が必要な場合は、 InMemoryHistoryProvider を明示的に追加します。 また、複数のストアを同じ呼び出しに再生しないように、1 つの履歴プロバイダーのみが load_messages=Trueしていることを確認します。

また、context_providersを使用して、store_context_messages=Trueの最後に別の履歴プロバイダーを追加することで、監査ストアを追加することもできます。

from agent_framework import InMemoryHistoryProvider

memory_store = InMemoryHistoryProvider("memory", load_messages=True)
audit_store = InMemoryHistoryProvider(
    "audit",
    load_messages=False,
    store_context_messages=True,  # include context added by other providers
)

agent = client.as_agent(
    name="MemoryAgent",
    instructions="You are a friendly assistant.",
    context_providers=[memory, memory_store, audit_store],  # audit store last
)

それを実行します。エージェントはコンテキストにアクセスできるようになりました。

session = agent.create_session()

# The provider doesn't know the user yet — it will ask for a name
result = await agent.run("Hello! What's the square root of 9?", session=session)
print(f"Agent: {result}\n")

# Now provide the name — the provider extracts and stores it
result = await agent.run("My name is Alice", session=session)
print(f"Agent: {result}\n")

# Subsequent calls are personalized
result = await agent.run("What is 2 + 2?", session=session)
print(f"Agent: {result}\n")

print(f"[Memory] Stored user name: {memory.user_name}")

ヒント

完全な実行可能ファイルについては、 完全なサンプル を参照してください。

次のステップ

より深く進む: