다음을 통해 공유


4단계: 메모리 및 지속성

사용자 기본 설정, 과거 상호 작용 또는 외부 지식을 기억할 수 있도록 에이전트에 컨텍스트를 추가합니다.

기본적으로 에이전트는 시스템 요구 사항에 따라 채팅 기록을 InMemoryChatHistoryProvider에 저장하거나 기본 AI 서비스에 저장합니다.

다음 에이전트는 OpenAI 채팅 완료를 사용하여 서비스 내 채팅 기록 스토리지를 지원하거나 요구하지 않기 때문에 자동으로 InMemoryChatHistoryProvider를 생성하고 사용합니다.

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

사용자 지정 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(new ChatClientAgentOptions()
    {
        ChatOptions = new() { Instructions = "You are a helpful assistant." },
        ChatHistoryProvider = new CustomChatHistoryProvider()
    });

세션을 사용하여 실행 간에 컨텍스트를 공유합니다.

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 UserMemoryProvider(BaseContextProvider):
    """A context provider that remembers user info in session state."""

    DEFAULT_SOURCE_ID = "user_memory"

    def __init__(self):
        super().__init__(self.DEFAULT_SOURCE_ID)

    async def before_run(
        self,
        *,
        agent: Any,
        session: AgentSession | None,
        context: SessionContext,
        state: dict[str, Any],
    ) -> None:
        """Inject personalization instructions based on stored user info."""
        user_name = state.get("user_name")
        if user_name:
            context.extend_instructions(
                self.source_id,
                f"The user's name is {user_name}. Always address them by name.",
            )
        else:
            context.extend_instructions(
                self.source_id,
                "You don't know the user's name yet. Ask for it politely.",
            )

    async def after_run(
        self,
        *,
        agent: Any,
        session: AgentSession | None,
        context: SessionContext,
        state: dict[str, Any],
    ) -> None:
        """Extract and store user info in session state after each call."""
        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():
                state["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,
)

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

실행 - 이제 에이전트가 컨텍스트에 액세스할 수 있습니다.

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 stores it in session state
result = await agent.run("My name is Alice", session=session)
print(f"Agent: {result}\n")

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

# Inspect session state to see what the provider stored
provider_state = session.state.get("user_memory", {})
print(f"[Session State] Stored user name: {provider_state.get('user_name')}")

팁 (조언)

전체 실행 가능한 파일에 대한 전체 샘플을 참조하세요.

비고

Python에서 지속성/메모리는 컨텍스트 및 기록 공급자에 의해 처리됩니다. A BaseHistoryProviderBaseContextProvider이며, InMemoryHistoryProvider는 내장된 로컬 메모리 내 구현입니다. RawAgent 특정 경우에 자동으로 추가할 InMemoryHistoryProvider() 수 있지만(예: 구성된 컨텍스트 공급자가 없고 서비스 쪽 스토리지 표시기가 없는 세션을 사용하는 경우) 모든 시나리오에서 보장되지는 않습니다. 항상 로컬 지속성을 원하는 경우 명시적으로 추가 InMemoryHistoryProvider 합니다. 또한 기록 공급자가 load_messages=True하나만 있는지 확인하므로 여러 저장소를 동일한 호출로 재생하지 않습니다.

목록 끝에 context_providers 다른 기록 공급자를 추가하여 감사 저장소를 추가할 수도 있습니다 store_context_messages=True.

from agent_framework import InMemoryHistoryProvider
from agent_framework.mem0 import Mem0ContextProvider

memory_store = InMemoryHistoryProvider(load_messages=True) # add a history provider for persistence across sessions
agent_memory = Mem0ContextProvider("user-memory", api_key=..., agent_id="my-agent")  # add Mem0 provider for agent memory
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_store, agent_memory, audit_store],  # audit store last
)

다음 단계:

더 자세히 살펴보기: