Sub topic 3
Trimming and Managing Conversation History
Assume you can call a language model through an API and understand prompts and tokens. A model sees only the context sent with the current request. Conversation history is useful evidence, but every old message competes with current instructions, documents, and the output budget.
Trim History Before It Crowds the Window
Keep messages that affect the current task. Remove greetings, repeated explanations, resolved branches, and stale requirements. A practical policy is:
- Keep the latest messages verbatim.
- Preserve decisions, constraints, and unresolved questions.
- Remove details that can be retrieved again.
- Reserve tokens for the model's answer.
def trim_history(history, keep_last):
"""Keep the newest messages; history is oldest first."""
if keep_last < 0:
raise ValueError("keep_last must be non-negative")
return history[-keep_last:] if keep_last else []Trimming can lose important facts. Mark durable facts separately before deleting their source messages.
Compact Long Sessions
Compaction replaces older messages with a shorter summary. The summary should preserve decisions, user preferences, open tasks, failures, and important identifiers. It should not preserve every conversational detail.
def compact(history, keep_last, summarize):
split = max(0, len(history) - keep_last)
older, recent = history[:split], history[split:]
if not older:
return history
summary = summarize(older)
return ["Earlier summary: " + summary] + recentA common error is summarizing without checking the result. Require structured summaries or test that the summary still answers key questions.
Memory Outside the Window
External memory is stored information that is loaded only when needed. Use a database, files, or a search index for durable facts and past decisions. Store provenance and timestamps so stale notes can be rejected.
Separate Work with Subagents
A subagent is a model call with its own context. Use one for an isolated task, such as investigating an error or summarizing documents. Pass it a focused request and return only its result. Isolation reduces distraction, but it can hide assumptions from the main task.
Cache Stable Prompt Prefixes
Place rarely changing content first: system rules, tool descriptions, and stable schemas. Put retrieved documents, recent history, and the question afterward. This makes the prefix identical across calls and can reduce latency or cost when the provider supports prompt caching.
Measure the Change
Compare context strategies on a fixed test set. Track answer correctness, required facts retained, token use, latency, and failure types. Change one policy at a time. A shorter prompt is not an improvement if it loses evidence needed for correct answers.
Exercise
When should you compact history instead of simply deleting it?
Show answer
Compact it when older decisions or unresolved facts may still matter, but the full wording is no longer needed.