多轮对话提示优化:让AI记住上下文
引言 多轮对话是AI助手的核心能力,但也是最容易被忽视的工程细节。一个优秀的对话系统需要记住用户之前说过什么、保持回复风格一致、理解隐含意图。2026年,随着上下文窗口的扩大和对话管理技术的进步,多轮对话体验已经大幅提升。本文将系统介绍多轮对话提示优化技术。 多轮对话的挑战 挑战一:上下文长度限制 即使模型支持128K上下文,也不可能无限保留所有历史。需要智能地管理上下文。 挑战二:指代消解 用户:推荐一部好看的科幻电影。 AI:推荐《盗梦空间》。 用户:它的导演是谁? “它"指的是《盗梦空间》,模型需要正确理解。 挑战三:话题切换 用户:今天天气怎么样? [聊了3轮天气] 用户:对了,帮我查一下航班。 模型需要快速切换话题,不混淆上下文。 挑战四:风格一致性 用户:用严肃的语气回答。 [模型用严肃语气回答了3轮] 用户:现在用幽默的语气。 模型需要切换风格,同时保持对话连贯性。 上下文管理策略 策略一:滑动窗口 保留最近的N轮对话: def sliding_window(history, window_size=10): """ 保留最近window_size轮对话 """ if len(history) <= window_size: return history return history[-window_size:] 优点:简单高效 缺点:可能丢失重要早期信息 策略二:摘要压缩 定期将历史对话压缩为摘要: def compress_history(history): """ 将历史对话压缩为摘要 """ if len(history) < 10: return history # 保留最近3轮 recent = history[-3:] # 压缩早期对话 early = history[:-3] summary_prompt = f"请摘要以下对话:\n{early}" summary = call_llm(summary_prompt) return [{"role": "system", "content": f"对话摘要:{summary}"}] + recent 优点:保留关键信息,减少token消耗 缺点:摘要可能丢失细节 策略三:分层记忆 模拟人类记忆系统: class HierarchicalMemory: def __init__(self): self.working_memory = [] # 最近3-5轮 self.episodic_memory = [] # 重要事件(摘要) self.long_term_memory = [] # 用户偏好、事实 def add_message(self, message): self.working_memory.append(message) # 如果工作记忆过长,压缩到情景记忆 if len(self.working_memory) > 5: summary = self.compress(self.working_memory[:-2]) self.episodic_memory.append(summary) self.working_memory = self.working_memory[-2:] def get_context(self): context = [] context += self.long_term_memory context += self.episodic_memory[-3:] # 最近3个事件 context += self.working_memory return context 策略四:检索增强 从外部记忆库检索相关信息: ...