微信扫码
添加专属顾问
我要投稿
在多轮对话中,如何高效管理聊天记录避免上下文膨胀?本文通过IChatReducer策略,演示如何自动限制历史长度并观察Agent行为变化。核心内容: 1. 多轮对话中上下文膨胀的问题与IChatReducer解决方案 2. 使用MessageCountingChatReducer实现自动历史记录缩减 3. 验证缩减效果及Agent行为变化分析
在多轮对话场景中,随着聊天次数增加,发送给大语言模型(LLM)的上下文会持续膨胀,带来 Token 成本上升与上下文溢出风险。 Microsoft Agent Framework 将这一问题抽象为 Chat Reduction(聊天记录缩减),并通过 IChatReducer 策略对聊天历史进行统一治理,而不是在业务代码中零散地裁剪或拼接历史消息。
本文基于“客户端本地存储聊天记录(Client-side history)”的典型场景,演示如何使用 MessageCountingChatReducer 自动限制历史长度,防止上下文无限增长,并观察在“历史被遗忘”后 Agent 行为的变化。
Microsoft.Extensions.AI:提供统一的 AI 抽象(ChatMessage、Reducer 等)Azure.AI.OpenAI:用于连接 Azure OpenAI 服务Microsoft.Agents.AI:Agent Framework 核心能力AIAgent agent = new AzureOpenAIClient(
new Uri(endpoint),
new AzureCliCredential())
.GetChatClient(deploymentName)
.CreateAIAgent(new ChatClientAgentOptions
{
ChatOptions = new()
{
Instructions = "你是一位江湖说书人,擅长用幽默、接地气的方式讲笑话和故事。"
},
Name = "Joker",
// 关键点:自定义 ChatMessageStoreFactory
ChatMessageStoreFactory = ctx => new InMemoryChatMessageStore(
new MessageCountingChatReducer(2), // 仅保留最近 2 条 非 System 的 ChatMessage
ctx.SerializedState,
ctx.JsonSerializerOptions)
});
InMemoryChatMessageStoreMessageCountingChatReducer(2)通过多轮连续对话,观察聊天记录在 Reducer 作用下的变化。在每一轮调用 agent.RunAsync(...) 后,读取当前线程中实际保留的聊天历史数量:
AgentThread thread = agent.GetNewThread();
Console.WriteLine(await agent.RunAsync("给我讲一个发生在茶馆里的段子,轻松一点的那种。", thread));
IList<ChatMessage>? chatHistory = thread.GetService<IList<ChatMessage>>();
Console.WriteLine($"\n 聊天有 {chatHistory?.Count} 消息.\n");
// Invoke the agent a few more times.
Console.WriteLine(await agent.RunAsync("现在把这个段子加上一些表情符号,并用说书人的语气再讲一遍。", thread));
Console.WriteLine($"\n 聊天有 {chatHistory?.Count} 消息.\n");
Console.WriteLine(await agent.RunAsync("保持刚才的语气,讲一个关于健忘冒险者的轻松小故事,像是在讲笑话一样。", thread));
Console.WriteLine($"\n 聊天有 {chatHistory?.Count} 消息.\n");
// At this point, the chat history has exceeded the limit and the original message will not exist anymore,
// so asking a follow up question about it will not work as expected.
Console.WriteLine(await agent.RunAsync("接着刚才的氛围,讲一个发生在日常生活里的小乌龙事件,轻松随意一点。", thread));
Console.WriteLine($"\n 聊天有 {chatHistory?.Count} 消息.\n");
MessageCountingChatReducer 开始生效chatHistory.Count 保持在稳定范围内结果一
结果二
结果三
结果四
IChatReducer 只是一个策略接口,可扩展更复杂的上下文治理逻辑:
TokenCountingChatReducer:按 Token 数量而非消息条数进行缩减SummaryChatReducer:将旧消息压缩为摘要,而非直接删除源代码地址
https://github.com/bingbing-gui/aspnetcore-developer/tree/master/src/09-AI-Agent/Agent-Framework/15-ChatReduction
53AI,企业落地大模型首选服务商
产品:场景落地咨询+大模型应用平台+行业解决方案
承诺:免费POC验证,效果达标后再合作。零风险落地应用大模型,已交付160+中大型企业
2026-01-12
Agent Skill 即将统治一切?Claude Code 2.1.3 把斜杠命令"杀"了
2026-01-12
如何用AI表格低门槛手搓一个业务系统?
2026-01-12
Agent Skills入门指南,看这篇就够了 | 保姆级教程
2026-01-12
当技能库超过50个,AI的选择能力会断崖式下跌
2026-01-12
5个让Claude Code效率翻倍的Skill!
2026-01-12
“基模四杰”开年首炸:Chat已死,Agent已来
2026-01-11
Anthropic联创:还不存在真正递归自我改进的AI!曝内部调查结果:AI未必能实现开发效率爆炸式增长;Claude也能修水管,看好分布式预训练
2026-01-11
Claude Skill 快照:给你的 AI 技能迭代加个「后悔药」
2025-10-26
2025-11-19
2025-10-20
2025-11-13
2025-10-18
2025-10-21
2025-10-15
2025-11-03
2025-10-23
2025-10-22
2026-01-12
2026-01-11
2026-01-10
2026-01-10
2026-01-08
2026-01-02
2025-12-31
2025-12-31