将一组消息压缩成摘要。 摘要包含: - 消息统计(几条 user/assistant/tool 消息) - 使用了哪些工具 - 最近的用户请求 - 待完成的工作 - 涉及的关键文件 - 时间线概要 对应源码: compact.rs:113-198
(messages: list[ConversationMessage])
| 165 | # 摘要包含哪些关键信息? |
| 166 | |
| 167 | def summarize_messages(messages: list[ConversationMessage]) -> str: |
| 168 | """ |
| 169 | 将一组消息压缩成摘要。 |
| 170 | |
| 171 | 摘要包含: |
| 172 | - 消息统计(几条 user/assistant/tool 消息) |
| 173 | - 使用了哪些工具 |
| 174 | - 最近的用户请求 |
| 175 | - 待完成的工作 |
| 176 | - 涉及的关键文件 |
| 177 | - 时间线概要 |
| 178 | |
| 179 | 对应源码: compact.rs:113-198 |
| 180 | """ |
| 181 | # 1. 统计各角色的消息数 |
| 182 | user_count = sum(1 for m in messages if m.role == "user") |
| 183 | assistant_count = sum(1 for m in messages if m.role == "assistant") |
| 184 | tool_count = sum(1 for m in messages if m.role == "tool") |
| 185 | |
| 186 | # 2. 收集使用过的工具名 |
| 187 | tool_names = set() |
| 188 | for msg in messages: |
| 189 | for block in msg.blocks: |
| 190 | if isinstance(block, ToolUseBlock): |
| 191 | tool_names.add(block.name) |
| 192 | elif isinstance(block, ToolResultBlock): |
| 193 | tool_names.add(block.tool_name) |
| 194 | |
| 195 | # 3. 收集最近的用户请求 |
| 196 | recent_requests = [] |
| 197 | for msg in reversed(messages): |
| 198 | if msg.role == "user": |
| 199 | for block in msg.blocks: |
| 200 | if isinstance(block, TextBlock) and block.text.strip(): |
| 201 | text = block.text[:160] + "..." if len(block.text) > 160 else block.text |
| 202 | recent_requests.append(text) |
| 203 | if len(recent_requests) >= 3: |
| 204 | break |
| 205 | if len(recent_requests) >= 3: |
| 206 | break |
| 207 | recent_requests.reverse() |
| 208 | |
| 209 | # 4. 检测待完成的工作(含"todo"/"next"等关键词的消息) |
| 210 | pending_work = [] |
| 211 | for msg in reversed(messages): |
| 212 | for block in msg.blocks: |
| 213 | if isinstance(block, TextBlock): |
| 214 | lower = block.text.lower() |
| 215 | if any(kw in lower for kw in ["todo", "next", "pending", "remaining"]): |
| 216 | text = block.text[:160] + "..." if len(block.text) > 160 else block.text |
| 217 | pending_work.append(text) |
| 218 | if len(pending_work) >= 3: |
| 219 | break |
| 220 | pending_work.reverse() |
| 221 | |
| 222 | # 5. 提取关键文件路径 |
| 223 | key_files = set() |
| 224 | for msg in messages: |
no test coverage detected