通过


存储

存储控制会话历史记录的存储位置、加载会话历史记录的数量,以及会话恢复的可靠性。

内置存储模式

代理框架支持两种常规存储模式:

模式 存储的内容 典型用途
本地会话状态 通过AgentSession.state获取完整聊天记录(例如通过 InMemoryHistoryProvider 不需要服务器端会话持久性的服务
服务托管存储 服务中的聊天状态; AgentSession.service_session_id 指向它 具有本机持久会话支持的服务

内存中聊天历史记录存储

当提供程序不需要服务器端聊天历史记录时,Agent Framework 会在会话中本地保留历史记录,并在每次运行时发送相关消息。

AIAgent agent = new OpenAIClient("<your_api_key>")
    .GetChatClient(modelName)
    .AsAIAgent(instructions: "You are a helpful assistant.", name: "Assistant");

AgentSession session = await agent.CreateSessionAsync();
Console.WriteLine(await agent.RunAsync("Tell me a joke about a pirate.", session));

// Works when in-memory storage is active.
IList<ChatMessage>? messages = session.GetService<IList<ChatMessage>>();
from agent_framework import InMemoryHistoryProvider
from agent_framework.openai import OpenAIChatClient

agent = OpenAIChatClient().as_agent(
    name="StorageAgent",
    instructions="You are a helpful assistant.",
    context_providers=[InMemoryHistoryProvider("memory", load_messages=True)],
)

session = agent.create_session()
await agent.run("Remember that I like Italian food.", session=session)

减少内存中历史记录大小

如果历史记录对于模型限制太大,请应用化简器。

AIAgent agent = new OpenAIClient("<your_api_key>")
    .GetChatClient(modelName)
    .AsAIAgent(new ChatClientAgentOptions
    {
        Name = "Assistant",
        ChatOptions = new() { Instructions = "You are a helpful assistant." },
        ChatHistoryProviderFactory = (ctx, ct) => new ValueTask<ChatHistoryProvider>(
            new InMemoryChatHistoryProvider(
                new MessageCountingChatReducer(20),
                ctx.SerializedState,
                ctx.JsonSerializerOptions,
                InMemoryChatHistoryProvider.ChatReducerTriggerEvent.AfterMessageAdded))
    });

注释

化简器配置适用于内存中历史记录提供程序。 对于由服务管理的历史记录,简化行为是提供方/服务特定的。

服务托管存储

当服务管理会话历史记录时,会话将存储远程聊天标识符。

AIAgent agent = new OpenAIClient("<your_api_key>")
    .GetOpenAIResponseClient(modelName)
    .AsAIAgent(instructions: "You are a helpful assistant.", name: "Assistant");

AgentSession session = await agent.CreateSessionAsync();
Console.WriteLine(await agent.RunAsync("Tell me a joke about a pirate.", session));
# Rehydrate when the service already has the conversation state.
session = agent.get_session(service_session_id="<service-conversation-id>")
response = await agent.run("Continue this conversation.", session=session)

第三方存储模式

对于基于数据库/Redis/blob 的历史记录,请实现自定义历史记录提供程序。

关键指南:

  • 将消息存储在会话范围的密钥下。
  • 在模型上下文限制内保留返回的历史记录。
  • session.state中保存提供程序特定的标识符。
  • 在 Python 中,只有一个历史记录提供程序应使用 load_messages=True
from agent_framework.openai import OpenAIChatClient

history = DatabaseHistoryProvider(db_client)
agent = OpenAIChatClient().as_agent(
    name="StorageAgent",
    instructions="You are a helpful assistant.",
    context_providers=[history],
)

session = agent.create_session()
await agent.run("Store this conversation.", session=session)

在重启后保持会话持续

保留完整 AgentSession消息,而不仅仅是消息文本。

JsonElement serialized = agent.SerializeSession(session);
// Store serialized payload in durable storage.
AgentSession resumed = await agent.DeserializeSessionAsync(serialized);
serialized = session.to_dict()
# Store serialized payload in durable storage.
resumed = AgentSession.from_dict(serialized)

重要

视为 AgentSession 不透明状态对象,并使用创建该对象的同一代理/提供程序配置还原它。

小窍门

使用附加的审计/评估历史记录提供程序(load_messages=Falsestore_context_messages=True)以捕获丰富的上下文及输入/输出,而不影响主要历史记录的加载。

后续步骤