compaction.py 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323
  1. """
  2. Context 压缩 — 两级压缩策略
  3. Level 1: GoalTree 过滤(确定性,零成本)
  4. - 跳过 completed/abandoned goals 的消息(信息已在 GoalTree summary 中)
  5. - 始终保留:system prompt、第一条 user message、当前 focus goal 的消息
  6. Level 2: LLM 总结(仅在 Level 1 后仍超限时触发)
  7. - 在消息列表末尾追加压缩 prompt → 主模型回复 → summary 存为新消息
  8. - summary 的 parent_sequence 跳过被压缩的范围
  9. 压缩不修改存储:原始消息永远保留在 messages/,通过 parent_sequence 树结构实现跳过。
  10. """
  11. import logging
  12. from dataclasses import dataclass
  13. from typing import List, Dict, Any, Optional, Set
  14. from .goal_models import GoalTree
  15. from .models import Message
  16. from agent.core.prompts import (
  17. COMPRESSION_EVAL_PROMPT_TEMPLATE,
  18. REFLECT_PROMPT,
  19. build_compression_eval_prompt,
  20. )
  21. logger = logging.getLogger(__name__)
  22. # ===== 模型 Context Window(tokens)=====
  23. MODEL_CONTEXT_WINDOWS: Dict[str, int] = {
  24. # Anthropic Claude
  25. "claude-sonnet-4": 200_000,
  26. "claude-opus-4": 200_000,
  27. "claude-3-5-sonnet": 200_000,
  28. "claude-3-5-haiku": 200_000,
  29. "claude-3-opus": 200_000,
  30. "claude-3-sonnet": 200_000,
  31. "claude-3-haiku": 200_000,
  32. # OpenAI
  33. "gpt-4o": 128_000,
  34. "gpt-4o-mini": 128_000,
  35. "gpt-4-turbo": 128_000,
  36. "gpt-4": 8_192,
  37. "o1": 200_000,
  38. "o3-mini": 200_000,
  39. # Google Gemini
  40. "gemini-2.5-pro": 1_000_000,
  41. "gemini-2.5-flash": 1_000_000,
  42. "gemini-2.0-flash": 1_000_000,
  43. "gemini-1.5-pro": 2_000_000,
  44. "gemini-1.5-flash": 1_000_000,
  45. # DeepSeek
  46. "deepseek-chat": 64_000,
  47. "deepseek-r1": 64_000,
  48. }
  49. DEFAULT_CONTEXT_WINDOW = 200_000
  50. def get_context_window(model: str) -> int:
  51. """
  52. 根据模型名称获取 context window 大小。
  53. 支持带 provider 前缀的模型名(如 "anthropic/claude-sonnet-4.5")和
  54. 带版本后缀的名称(如 "claude-3-5-sonnet-20241022")。
  55. """
  56. # 去掉 provider 前缀
  57. name = model.split("/")[-1].lower()
  58. # 精确匹配
  59. if name in MODEL_CONTEXT_WINDOWS:
  60. return MODEL_CONTEXT_WINDOWS[name]
  61. # 前缀匹配(处理版本后缀)
  62. for key, window in MODEL_CONTEXT_WINDOWS.items():
  63. if name.startswith(key):
  64. return window
  65. return DEFAULT_CONTEXT_WINDOW
  66. # ===== 配置 =====
  67. @dataclass
  68. class CompressionConfig:
  69. """压缩配置"""
  70. max_tokens: int = 0 # 最大 token 数(0 = 自动:context_window * 0.5)
  71. threshold_ratio: float = 0.5 # 触发压缩的阈值 = context_window 的比例
  72. keep_recent_messages: int = 10 # Level 1 中始终保留最近 N 条消息
  73. max_messages: int = 50 # 最大消息数(超过此数量触发压缩,0 = 禁用)
  74. def get_max_tokens(self, model: str) -> int:
  75. """获取实际的 max_tokens(如果为 0 则自动计算)"""
  76. if self.max_tokens > 0:
  77. return self.max_tokens
  78. window = get_context_window(model)
  79. return int(window * self.threshold_ratio)
  80. # ===== Level 1: GoalTree 过滤 =====
  81. def filter_by_goal_status(
  82. messages: List[Message],
  83. goal_tree: Optional[GoalTree],
  84. ) -> List[Message]:
  85. """
  86. Level 1 过滤:跳过 completed/abandoned goals 的消息
  87. 始终保留:
  88. - goal_id 为 None 的消息(system prompt、初始 user message)
  89. - 当前 focus goal 及其祖先链上的消息
  90. - in_progress 和 pending goals 的消息
  91. 跳过:
  92. - completed 且不在焦点路径上的 goals 的消息
  93. - abandoned goals 的消息
  94. Args:
  95. messages: 主路径上的有序消息列表
  96. goal_tree: GoalTree 实例
  97. Returns:
  98. 过滤后的消息列表
  99. """
  100. if not goal_tree or not goal_tree.goals:
  101. return messages
  102. # 构建焦点路径(当前焦点 + 父链 + 直接子节点)
  103. focus_path = _get_focus_path(goal_tree)
  104. # 构建需要跳过的 goal IDs
  105. skip_goal_ids: Set[str] = set()
  106. for goal in goal_tree.goals:
  107. if goal.id in focus_path:
  108. continue # 焦点路径上的 goal 始终保留
  109. if goal.status in ("completed", "abandoned"):
  110. skip_goal_ids.add(goal.id)
  111. # 过滤消息
  112. result = []
  113. for msg in messages:
  114. if msg.goal_id is None:
  115. result.append(msg) # 无 goal 的消息始终保留
  116. elif msg.goal_id not in skip_goal_ids:
  117. result.append(msg) # 不在跳过列表中的消息保留
  118. return result
  119. def _get_focus_path(goal_tree: GoalTree) -> Set[str]:
  120. """
  121. 获取焦点路径上需要保留消息的 goal IDs
  122. 保留:焦点自身 + 父链 + 未完成的直接子节点
  123. 不保留:已完成/已放弃的直接子节点(信息已在 goal.summary 中)
  124. """
  125. focus_ids: Set[str] = set()
  126. if not goal_tree.current_id:
  127. return focus_ids
  128. # 焦点自身
  129. focus_ids.add(goal_tree.current_id)
  130. # 父链
  131. goal = goal_tree.find(goal_tree.current_id)
  132. while goal and goal.parent_id:
  133. focus_ids.add(goal.parent_id)
  134. goal = goal_tree.find(goal.parent_id)
  135. # 直接子节点:仅保留未完成的(completed/abandoned 的信息已在 summary 中)
  136. children = goal_tree.get_children(goal_tree.current_id)
  137. for child in children:
  138. if child.status not in ("completed", "abandoned"):
  139. focus_ids.add(child.id)
  140. return focus_ids
  141. # ===== Token 估算 =====
  142. def estimate_tokens(messages: List[Dict[str, Any]]) -> int:
  143. """
  144. 估算消息列表的 token 数量
  145. 对 CJK 字符和 ASCII 字符使用不同的估算系数:
  146. - ASCII/Latin 字符:~4 字符 ≈ 1 token
  147. - CJK 字符(中日韩):~1 字符 ≈ 1.5 tokens(BPE tokenizer 特性)
  148. """
  149. total_tokens = 0
  150. for msg in messages:
  151. content = msg.get("content", "")
  152. if isinstance(content, str):
  153. total_tokens += _estimate_text_tokens(content)
  154. elif isinstance(content, list):
  155. for part in content:
  156. if isinstance(part, dict):
  157. if part.get("type") == "text":
  158. total_tokens += _estimate_text_tokens(part.get("text", ""))
  159. elif part.get("type") in ("image_url", "image"):
  160. total_tokens += _estimate_image_tokens(part)
  161. # tool_calls
  162. tool_calls = msg.get("tool_calls")
  163. if tool_calls and isinstance(tool_calls, list):
  164. for tc in tool_calls:
  165. if isinstance(tc, dict):
  166. func = tc.get("function", {})
  167. total_tokens += len(func.get("name", "")) // 4
  168. args = func.get("arguments", "")
  169. if isinstance(args, str):
  170. total_tokens += _estimate_text_tokens(args)
  171. return total_tokens
  172. def _estimate_text_tokens(text: str) -> int:
  173. """
  174. 估算文本的 token 数,区分 CJK 和 ASCII 字符。
  175. CJK 字符在 BPE tokenizer 中通常占 1.5-2 tokens,
  176. ASCII 字符约 4 个对应 1 token。
  177. """
  178. if not text:
  179. return 0
  180. cjk_chars = 0
  181. other_chars = 0
  182. for ch in text:
  183. if _is_cjk(ch):
  184. cjk_chars += 1
  185. else:
  186. other_chars += 1
  187. # CJK: 1 char ≈ 1.5 tokens; ASCII: 4 chars ≈ 1 token
  188. return int(cjk_chars * 1.5) + other_chars // 4
  189. def _estimate_image_tokens(block: Dict[str, Any]) -> int:
  190. """
  191. 估算图片块的 token 消耗。
  192. Anthropic 计算方式:tokens = (width * height) / 750
  193. 优先从 _image_meta 读取真实尺寸,其次从 base64 数据量粗估,最小 1600 tokens。
  194. """
  195. MIN_IMAGE_TOKENS = 1600
  196. # 优先使用 _image_meta 中的真实尺寸
  197. meta = block.get("_image_meta")
  198. if meta and meta.get("width") and meta.get("height"):
  199. tokens = (meta["width"] * meta["height"]) // 750
  200. return max(MIN_IMAGE_TOKENS, tokens)
  201. # 回退:从 base64 数据长度粗估
  202. b64_data = ""
  203. if block.get("type") == "image":
  204. source = block.get("source", {})
  205. if source.get("type") == "base64":
  206. b64_data = source.get("data", "")
  207. elif block.get("type") == "image_url":
  208. url_obj = block.get("image_url", {})
  209. url = url_obj.get("url", "") if isinstance(url_obj, dict) else str(url_obj)
  210. if url.startswith("data:"):
  211. _, _, b64_data = url.partition(",")
  212. if b64_data:
  213. # base64 编码后大小约为原始字节的 4/3
  214. raw_bytes = len(b64_data) * 3 // 4
  215. # 粗估:假设 JPEG 压缩率 ~10:1,像素数 ≈ raw_bytes * 10 / 3 (RGB)
  216. estimated_pixels = raw_bytes * 10 // 3
  217. estimated_tokens = estimated_pixels // 750
  218. return max(MIN_IMAGE_TOKENS, estimated_tokens)
  219. return MIN_IMAGE_TOKENS
  220. def _is_cjk(ch: str) -> bool:
  221. """判断字符是否为 CJK(中日韩)字符"""
  222. cp = ord(ch)
  223. return (
  224. 0x2E80 <= cp <= 0x9FFF # CJK 基本区 + 部首 + 笔画 + 兼容
  225. or 0xF900 <= cp <= 0xFAFF # CJK 兼容表意文字
  226. or 0xFE30 <= cp <= 0xFE4F # CJK 兼容形式
  227. or 0x20000 <= cp <= 0x2FA1F # CJK 扩展 B-F + 兼容补充
  228. or 0x3000 <= cp <= 0x303F # CJK 标点符号
  229. or 0xFF00 <= cp <= 0xFFEF # 全角字符
  230. )
  231. def estimate_tokens_from_messages(messages: List[Message]) -> int:
  232. """从 Message 对象列表估算 token 数"""
  233. return estimate_tokens([msg.to_llm_dict() for msg in messages])
  234. def needs_level2_compression(
  235. token_count: int,
  236. config: CompressionConfig,
  237. model: str = "",
  238. ) -> bool:
  239. """判断是否需要触发 Level 2 压缩"""
  240. limit = config.get_max_tokens(model) if model else config.max_tokens
  241. return token_count > limit
  242. # ===== Level 2: 压缩 Prompt =====
  243. # 注意:这些 prompt 已迁移到 agent.core.prompts
  244. # COMPRESSION_EVAL_PROMPT 和 REFLECT_PROMPT 现在从 prompts.py 导入
  245. def build_compression_prompt(goal_tree: Optional[GoalTree]) -> str:
  246. """构建 Level 2 压缩 prompt"""
  247. goal_prompt = ""
  248. if goal_tree:
  249. goal_prompt = goal_tree.to_prompt(include_summary=True)
  250. return build_compression_eval_prompt(
  251. goal_tree_prompt=goal_prompt,
  252. )
  253. def build_reflect_prompt() -> str:
  254. """构建反思 prompt"""
  255. return REFLECT_PROMPT