执行压缩。 算法很简单: 1. 判断是否需要压缩 → 不需要就直接返回 2. 把消息分成两组:旧的(要压缩的)和新的(要保留的) 3. 旧消息 → 生成摘要 4. 新 Session = [摘要消息] + [保留的消息] 对应源码: compact.rs:75-111
(session: Session, config: CompactionConfig)
| 292 | |
| 293 | |
| 294 | def compact_session(session: Session, config: CompactionConfig) -> CompactionResult: |
| 295 | """ |
| 296 | 执行压缩。 |
| 297 | |
| 298 | 算法很简单: |
| 299 | 1. 判断是否需要压缩 → 不需要就直接返回 |
| 300 | 2. 把消息分成两组:旧的(要压缩的)和新的(要保留的) |
| 301 | 3. 旧消息 → 生成摘要 |
| 302 | 4. 新 Session = [摘要消息] + [保留的消息] |
| 303 | |
| 304 | 对应源码: compact.rs:75-111 |
| 305 | """ |
| 306 | if not should_compact(session, config): |
| 307 | return CompactionResult( |
| 308 | summary="", |
| 309 | compacted_session=session, |
| 310 | removed_message_count=0, |
| 311 | ) |
| 312 | |
| 313 | # 分割点:保留最后 N 条消息 |
| 314 | keep_from = max(0, len(session.messages) - config.preserve_recent_messages) |
| 315 | removed_messages = session.messages[:keep_from] |
| 316 | preserved_messages = session.messages[keep_from:] |
| 317 | |
| 318 | # 生成摘要 |
| 319 | summary = summarize_messages(removed_messages) |
| 320 | |
| 321 | # 构造"续接消息"—— 告诉 AI "之前的对话被压缩了,以下是摘要" |
| 322 | continuation = ( |
| 323 | "This session is being continued from a previous conversation " |
| 324 | "that ran out of context. The summary below covers the earlier " |
| 325 | "portion of the conversation.\n\n" |
| 326 | f"{summary}\n\n" |
| 327 | "Recent messages are preserved verbatim.\n" |
| 328 | "Continue the conversation from where it left off without asking " |
| 329 | "the user any further questions." |
| 330 | ) |
| 331 | |
| 332 | # 新的消息列表:[系统摘要] + [保留的消息] |
| 333 | new_messages = [ConversationMessage.system_text(continuation)] |
| 334 | new_messages.extend(preserved_messages) |
| 335 | |
| 336 | return CompactionResult( |
| 337 | summary=summary, |
| 338 | compacted_session=Session(version=session.version, messages=new_messages), |
| 339 | removed_message_count=len(removed_messages), |
| 340 | ) |
| 341 | |
| 342 | |
| 343 | # ============================================================ |
no test coverage detected