Series 3 - Bài 5: Summarization Strategy
Summarization không phải lossy compression — là information distillation. Bài này phân tích các strategy nén conversation history mà vẫn giữ được signal quan trọng.
Khi conversation history lớn hơn budget cho phép, bạn phải chọn: cắt bỏ hay nén.
Cắt bỏ (sliding window) đơn giản nhưng brutal — mọi thứ trước window đều mất. Nén (summarization) phức tạp hơn nhưng preserve signal quan trọng.
Sự khác biệt nằm ở luận điểm này: agent không cần nhớ chi tiết từng turn, nhưng cần nhớ những gì đã được quyết định và tại sao.
Thông tin nào quan trọng trong conversation
Trước khi nói về cách nén, cần biết nén gì:
High-value information (KEEP):
Quyết định đã được đưa ra
"Dùng Strategy pattern thay vì if/else"
"Không dùng singleton vì thread safety"
Files đã được modified
"loan.service.ts đã được refactor tại turn 5"
Bugs đã được phát hiện
"processLoan có race condition khi amount=0"
User preferences/constraints
"User muốn không thêm dependency mới"
Task completion status
"Unit tests đã pass, integration tests pending"
Low-value information (SAFE TO DROP):
Chi tiết tool results đã được processed
Full content của file đã đọc và đã dùng
Intermediate reasoning steps
LLM nghĩ gì trước khi quyết định
Repetitive context
"Reading file..." → result → "Based on the file..."
Failed attempts
Những approach đã thử và không work
(Trừ khi cần nhớ để không thử lại)
Strategy 1: Rolling Summary
Đây là strategy phổ biến nhất. Sau mỗi N turns, compress turns cũ thành summary:
Rolling Summary Flow:
Turns 1-10:
[Turn 1] User: Refactor processLoan
[Turn 2] Agent: read_file → [4,500 tokens]
[Turn 3] Agent: Analysis complete, here's the plan
[Turn 4] Agent: write_file → success
[Turn 5] Agent: run_command → tests pass
...
After turn 10, generate summary:
Prompt to LLM:
"Summarize this conversation, focusing on:
1. Decisions made and rationale
2. Files modified and how
3. Current task status
4. Pending items
Be concise — target 300 tokens."
Summary output (~300 tokens):
"Completed refactor of processLoan in loan.service.ts.
Applied Strategy pattern for payment types. All unit
tests pass (47 tests). Integration test for edge case
amount=0 is still pending — user noted this can wait.
Next: address payment.service.ts validation."
Turns 11+:
[Summary] ← 300 tokens thay vì 10 turns x 1,500 tokens
[Turn 11] User: Now fix payment.service.ts
...
Saving: 15,000 tokens → 300 tokens. Ratio 50:1.
Cost: 1 thêm LLM call để generate summary.
Strategy 2: Structured Summary
Thay vì free-form text, summary có structure:
[SUMMARY]
Task progress:
✓ processLoan refactored (loan.service.ts:45-89)
✓ Unit tests pass (47/47)
⏳ Integration test for amount=0 edge case
⏳ payment.service.ts validation (next task)
Decisions made:
- Strategy pattern for payment type handling
- No new dependencies (user constraint)
- Validation logic in separate LoanValidator class
Files modified:
- src/loan/loan.service.ts (refactored processLoan)
- src/loan/loan.service.spec.ts (added 3 test cases)
User preferences:
- Don't add new npm dependencies
- Run tests after each significant change
Structured summary dễ parse hơn cho LLM, nhưng cần template và prompt engineering cẩn thận hơn.
Strategy 3: Tiered History
Thay vì summarize tất cả, giữ full detail cho turns gần nhất:
Tiered History:
[Summary: turns 1-10] ← 300 tokens
[Summary: turns 11-20] ← 300 tokens
[Full: turns 21-25] ← 7,500 tokens (recent, full detail)
[Current: turn 26] ← in progress
Logic:
Turns > 20 cũ: summarized
Turns 1-5 cũ: full detail
Current turn: full detail
Giống như human memory — gần đây nhớ rõ, xa hơn nhớ highlights.
Strategy 4: Decision Log
Song song với conversation, maintain một decision log riêng biệt:
Decision Log (maintained separately):
Turn 3: Decided to use Strategy pattern
Reason: Loan types will expand, if/else won't scale
Impact: Needs LoanStrategy interface
Turn 7: Decided NOT to extract LoanValidator now
Reason: Out of scope, user said keep minimal
Impact: Validation stays in service for now
Turn 12: Test for amount=0 deferred
Reason: Integration test infra not ready
Impact: Technical debt, need follow-up
Khi summarize history, decision log là nguồn chính — không cần re-derive từ conversation.
Decision log được inject ngay sau system prompt, trước conversation history.
When to Trigger Summarization
Trigger conditions:
Token-based: history > 60% of allocated budget
→ Summarize oldest 50% of history
Turn-based: every 15 turns
→ Summarize turns 1 to (current - 5)
→ Keep 5 most recent full
Task-boundary: user explicitly changes topic
"Ok, now let's work on payments"
→ Good time to summarize loan-related turns
→ Start fresh context for payment work
Quality Check: Summary Completeness
Làm sao biết summary đủ tốt? Checklist:
Summary completeness check:
[ ] Tất cả files đã modified được mention
[ ] Decisions có rationale
[ ] Pending items được list rõ
[ ] User constraints được preserve
[ ] Current status rõ ràng (what's done, what's next)
[ ] Không có contradictions với current user message
Trade-off: LLM-generated vs Rule-based Summary
LLM-generated summary:
+ Flexible, handle nhiều contexts
+ Capture nuance
- Tốn thêm LLM call (latency + cost)
- Output không deterministic
- Có thể hallucinate details
Rule-based summary:
Extract structured fields: files modified, commands run
Template-based: fill in slots
+ Fast, cheap, deterministic
- Chỉ capture structured data
- Miss unstructured decisions và reasoning
Hybrid approach:
Rule-based extract structured data (files, test results)
LLM fill in reasoning và decisions
→ Tốt nhất cả hai
Kết luận
- Summarization là information distillation, không phải lossy compression — cần preserve signal.
- High-value: decisions, file changes, user constraints, task status. Low-value: full tool results, intermediate reasoning.
- Rolling summary: compress N cũ turns thành summary sau mỗi threshold.
- Structured summary tốt hơn free-form cho consistency và parseability.
- Decision log maintain riêng biệt là pattern mạnh — không cần re-derive từ conversation.
- Trigger summarization proactively (token hoặc turn-based), không phải khi đã overflow.
- Hybrid approach: rule-based cho structured data, LLM cho reasoning.