B5记忆压缩

This commit is contained in:
root committed 2026-06-30 10:26:02 +08:00
1 parent 538d887b4e
commit 00fbf7c2a4
2 files changed
+36 -14

No files matched your search

-11
View File
@@ -47,17 +47,6 @@ def _extract_tool_result(message: dict) -> dict:
def _three_points(text: str) -> list[str]:
"""
从工具返回的文本内容中提取最多3个关键要点。
处理逻辑:
1. 按换行符或中文标点(句号、感叹号、问号)分割文本
2. 去除每个片段的空白字符和末尾标点
3. 去重并保留最多3个不同的片段
4. 如果不足3个,用默认提示填充
用于将工具执行结果转换为简洁的3条中文摘要。
"""
parts = [part.strip(" \t\r\n。") for part in re.split(r"\n+|(?<=[。!?!?])", text) if part.strip()]
points = []
for part in parts:
+36 -3
View File
@@ -216,6 +216,37 @@ def _keyword_search_memory(
return docs
def _summarize_messages(messages: list, trace: dict, answer: str, max_chars: int = 600) -> str:
"""Generate a deterministic extractive summary of a conversation."""
parts = []
user_questions = []
tool_calls_made = []
for msg in messages:
role = msg.get("role", "")
content = msg.get("content", "")
if role == "user" and content:
user_questions.append(content[:200])
elif role == "assistant":
tcs = msg.get("tool_calls", [])
for tc in tcs:
tool_calls_made.append(tc.get("name", "unknown"))
if user_questions:
parts.append("用户提问:")
for q in user_questions:
parts.append(f" - {q}")
if tool_calls_made:
tools_unique = list(dict.fromkeys(tool_calls_made))
parts.append(f"调用工具: {', '.join(tools_unique)}")
parts.append(f"LLM 调用 {trace.get('llm_call_count', '?')} 次,"
f"工具回合 {trace.get('tool_rounds_used', '?')} 次")
parts.append(f"最终回答: {answer[:200]}")
text = "\n".join(parts)
return text[:max_chars]
def _safe_conversation_id(conversation_id: str) -> str:
if not isinstance(conversation_id, str) or not re.fullmatch(r"[A-Za-z0-9_.-]+", conversation_id):
raise ValueError("conversation_id may only contain letters, numbers, dot, underscore, and hyphen")
@@ -247,12 +278,14 @@ def save_memory(
target_path = Path(target_dir) / f"{conversation_id}.md"
relative_path = f"{relative_dir}/{conversation_id}.md"
title = f"{save_type.title()} {conversation_id}"
summary = answer[:200]
compressed = _summarize_messages(messages, trace, answer)
markdown = (
f"# {title}\n\n"
f"- memory_id: `{memory_id}`\n"
f"- conversation_id: `{conversation_id}`\n"
f"- created_or_updated_at: `{now}`\n\n"
"## Conversation Summary\n\n"
f"{compressed}\n\n"
"## Final Answer\n\n"
f"{answer}\n\n"
"## Messages\n\n```json\n"
@@ -268,7 +301,7 @@ def save_memory(
"memory_id": memory_id,
"memory_type": save_type,
"title": title,
"summary": summary,
"summary": compressed,
"path": relative_path,
"conversation_id": conversation_id,
"created_at": created_at,
@@ -281,7 +314,7 @@ def save_memory(
"memory_type": save_type,
"conversation_id": conversation_id,
"title": title,
"summary": summary,
"summary": compressed,
"path": relative_path,
"index_path": Path(paths["index"]).name,
"created_at": created_at,