将上下文添加到代理,以便它可以记住用户首选项、过去的交互或外部知识。
使用自定义 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 中,持久性/内存由历史记录提供程序处理。 A BaseHistoryProvider 也是一个 BaseContextProvider,InMemoryHistoryProvider 是其内置的本地实现。
RawAgent 可以在特定情况下自动添加 InMemoryHistoryProvider("memory") (例如,在没有配置的上下文提供程序和服务端存储指示器的情况下使用会话时),但这在所有方案中都不能保证。
如果始终需要本地持久性,请显式添加一个 InMemoryHistoryProvider 。 此外,请确保只有一个历史记录提供程序具有 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}")
小窍门
请参阅 完整示例以获取完整可运行文件。
后续步骤
更深入: