1- from app .core .llm .llm import LLM
1+ from app .core .llm .llm import LLM , simple_chat
22from app .utils .log_util import logger
33
44
@@ -32,8 +32,8 @@ async def run(self, prompt: str, system_prompt: str, sub_title: str) -> str:
3232 self .current_chat_turns = 0 # 重置对话轮次计数器
3333
3434 # 更新对话历史
35- self .append_chat_history ({"role" : "system" , "content" : system_prompt })
36- self .append_chat_history ({"role" : "user" , "content" : prompt })
35+ await self .append_chat_history ({"role" : "system" , "content" : system_prompt })
36+ await self .append_chat_history ({"role" : "user" , "content" : prompt })
3737
3838 # 获取历史消息用于本次对话
3939 response = await self .model .chat (
@@ -50,14 +50,80 @@ async def run(self, prompt: str, system_prompt: str, sub_title: str) -> str:
5050 logger .error (f"Agent执行失败: { str (e )} " )
5151 return error_msg
5252
53- def append_chat_history (self , msg : dict ) -> None :
54- self .clear_memory ()
53+ async def append_chat_history (self , msg : dict ) -> None :
54+ await self .clear_memory ()
5555 self .chat_history .append (msg )
5656
57- def clear_memory (self ):
57+ async def clear_memory (self ):
58+ """当聊天历史超过最大记忆轮次时,使用 simple_chat 进行总结压缩"""
5859 if len (self .chat_history ) <= self .max_memory :
5960 return
60- logger .info (f"{ self .__class__ .__name__ } :清除记忆" )
6161
62- # 使用切片保留第一条和最后两条消息
63- self .chat_history = self .chat_history [:2 ] + self .chat_history [- 5 :]
62+ logger .info (
63+ f"{ self .__class__ .__name__ } :开始清除记忆,当前记录数:{ len (self .chat_history )} "
64+ )
65+
66+ try :
67+ # 保留第一条系统消息
68+ system_msg = (
69+ self .chat_history [0 ]
70+ if self .chat_history and self .chat_history [0 ]["role" ] == "system"
71+ else None
72+ )
73+
74+ # 构造总结提示
75+ summarize_history = []
76+ if system_msg :
77+ summarize_history .append (system_msg )
78+
79+ # 添加要总结的对话内容(跳过第一条系统消息和最后5条消息)
80+ start_idx = 1 if system_msg else 0
81+ end_idx = len (self .chat_history ) - 5
82+
83+ if end_idx > start_idx :
84+ summarize_history .append (
85+ {
86+ "role" : "user" ,
87+ "content" : f"请简洁总结以下对话的关键内容和重要结论,保留重要的上下文信息:\n \n { self ._format_history_for_summary (self .chat_history [start_idx :end_idx ])} " ,
88+ }
89+ )
90+
91+ # 调用 simple_chat 进行总结
92+ summary = await simple_chat (self .model , summarize_history )
93+
94+ # 重构聊天历史:系统消息 + 总结 + 最后5条消息
95+ new_history = []
96+ if system_msg :
97+ new_history .append (system_msg )
98+
99+ new_history .append (
100+ {"role" : "assistant" , "content" : f"[历史对话总结] { summary } " }
101+ )
102+
103+ # 添加最后5条消息
104+ new_history .extend (self .chat_history [- 5 :])
105+
106+ self .chat_history = new_history
107+ logger .info (
108+ f"{ self .__class__ .__name__ } :记忆清除完成,压缩至:{ len (self .chat_history )} 条记录"
109+ )
110+ else :
111+ logger .info (f"{ self .__class__ .__name__ } :无需清除记忆,记录数量合理" )
112+
113+ except Exception as e :
114+ logger .error (f"记忆清除失败,使用简单切片策略: { str (e )} " )
115+ # 如果总结失败,回退到简单的切片策略
116+ self .chat_history = self .chat_history [:2 ] + self .chat_history [- 5 :]
117+
118+ def _format_history_for_summary (self , history : list [dict ]) -> str :
119+ """格式化历史记录用于总结"""
120+ formatted = []
121+ for msg in history :
122+ role = msg ["role" ]
123+ content = (
124+ msg ["content" ][:500 ] + "..."
125+ if len (msg ["content" ]) > 500
126+ else msg ["content" ]
127+ ) # 限制长度
128+ formatted .append (f"{ role } : { content } " )
129+ return "\n " .join (formatted )
0 commit comments