Inferensys

Prompt

Context Window Eviction Strategy Prompt Template

A practical prompt playbook for using Context Window Eviction Strategy Prompt Template in production AI workflows.
Engineer optimizing context window usage on laptop, token usage charts visible, technical work session.
PROMPT PLAYBOOK

When to Use This Prompt

Defines the job, ideal user, and constraints for the Context Window Eviction Strategy Prompt Template.

This prompt template is designed for AI architects and platform engineers building long-running agent workflows where the context window is a hard constraint. The core job-to-be-done is to programmatically decide which information to discard when the token limit is reached, ensuring the agent can continue its task without losing critical state. The ideal user is someone integrating this into an agent harness or orchestration framework, not an end-user chatting with a model. You need a structured history of the agent's actions, observations, and a clearly defined goal to use this effectively.

Do not use this prompt for simple chat history summarization or one-off document truncation. It is specifically for multi-step agent tasks where the cost of evicting the wrong information is a derailed plan or a repeated loop. The prompt requires a pre-computed context inventory—a list of messages, tool outputs, or thoughts—each tagged with metadata like recency, type, and dependencies. Without this structured input, the model cannot make a reliable eviction decision. This is a decision prompt, not a summarization prompt; its output is a list of identifiers to remove, which your application code must then execute.

Before implementing this, ensure your agent harness can capture and serialize the full conversation state into the required [CONTEXT_INVENTORY] format. The prompt is a component in a larger control loop: your system detects an impending overflow, invokes this prompt to get an eviction plan, prunes the context, and then re-injects the remaining history into the next model call. The primary risk is evicting a dependency that a future step requires, so your evaluation must test for task continuity after eviction, not just the validity of the eviction plan itself.

PRACTICAL GUARDRAILS

Use Case Fit

Where the Context Window Eviction Strategy Prompt works, where it fails, and the operational prerequisites for production use.

01

Good Fit: Long-Running Agent Workflows

Use when: An autonomous agent must maintain task continuity across hundreds of turns without losing critical state. Guardrail: The eviction prompt must receive structured context metadata (recency, dependency graph, task relevance scores) rather than raw text to make reliable decisions.

02

Bad Fit: Single-Turn Q&A or Stateless Tasks

Avoid when: The task fits comfortably within the context window or requires no memory of prior interactions. Guardrail: Skip eviction logic entirely and use a simple context assembly prompt. Adding eviction overhead to stateless workflows increases latency and complexity without benefit.

03

Required Input: Structured Context Metadata

What to watch: The eviction prompt cannot make good decisions from raw conversation text alone. Guardrail: Provide each context block with a JSON metadata wrapper containing recency_score, dependency_list, task_relevance, and completion_status. The prompt uses these fields, not guesswork.

04

Required Input: Task Goal and Dependency Graph

What to watch: Without understanding which context blocks are prerequisites for future steps, the eviction prompt may remove essential information. Guardrail: Supply a current task goal statement and a dependency map showing which prior outputs feed into pending steps before invoking eviction.

05

Operational Risk: Evicting Unresolved Decisions

Risk: The prompt may evict context containing open questions, pending approvals, or partially completed subtasks. Guardrail: Tag all context blocks with resolution_status and instruct the prompt to never evict blocks marked unresolved or awaiting_approval unless explicitly escalated.

06

Operational Risk: Silent Task Drift After Eviction

Risk: After eviction, the agent may continue with a subtly different understanding of the task, producing outputs that appear valid but are misaligned. Guardrail: After every eviction, run a lightweight task-recap prompt that restates the current goal, completed steps, and next action. Compare against pre-eviction state before proceeding.

PROMPT PLAYBOOK

Copy-Ready Prompt Template

A reusable prompt template for intelligently evicting context when the window fills, using recency, relevance, and dependency scoring.

This prompt template is designed to be injected into a long-running agent workflow when the context window approaches its limit. Instead of naive truncation—which often discards critical instructions, recent observations, or unresolved dependencies—this prompt instructs the model to analyze the full context, score each element, and produce a compressed continuation context that preserves what matters most. The output is not a final answer but a restructured context payload that can be loaded into a fresh window so the agent can continue without losing state.

text
You are managing a context window that has reached its capacity limit. Your job is to produce a compressed continuation context that fits within [MAX_OUTPUT_TOKENS] tokens while preserving the information most critical for completing the task below.

## TASK
[TASK_DESCRIPTION]

## FULL CONTEXT (TOO LARGE TO CONTINUE)
[FULL_CONTEXT]

## EVICTION RULES
1. Score every context element (messages, tool outputs, observations, instructions) on three dimensions from 1 (low) to 5 (high):
   - RECENCY: How recently was this element added?
   - RELEVANCE: How directly does this element relate to the current task?
   - DEPENDENCY: Do other elements or pending actions depend on this element?
2. Compute a composite score: (RECENCY * [RECENCY_WEIGHT]) + (RELEVANCE * [RELEVANCE_WEIGHT]) + (DEPENDENCY * [DEPENDENCY_WEIGHT]).
3. Preserve ALL elements with a composite score above [PRESERVATION_THRESHOLD].
4. For elements below the threshold, create a one-line summary only if they contain information that might be needed later.
5. Never evict: the original task description, active tool schemas, pending action items, unresolved errors, or user identity and permissions.

## OUTPUT FORMAT
Return a JSON object with this schema:
{
  "preserved_elements": [
    {
      "element_id": "string",
      "content": "string (verbatim preserved content)",
      "composite_score": number,
      "preservation_reason": "string"
    }
  ],
  "summarized_elements": [
    {
      "element_id": "string",
      "summary": "string (one-line summary)",
      "original_score": number
    }
  ],
  "evicted_elements": [
    {
      "element_id": "string",
      "eviction_reason": "string"
    }
  ],
  "continuation_context": "string (assembled context ready for the next window, including preserved content and summaries)",
  "state_checkpoint": {
    "pending_actions": ["string"],
    "unresolved_dependencies": ["string"],
    "critical_state_variables": {"key": "value"}
  }
}

## CONSTRAINTS
- The continuation_context field must be under [MAX_OUTPUT_TOKENS] tokens.
- Preserve exact quotes, numbers, dates, and identifiers without modification.
- If two elements conflict, preserve both and flag the conflict in state_checkpoint.
- If the task cannot be safely compressed below the token limit, set a flag "requires_escalation": true and explain why.

Adaptation guidance: Replace [TASK_DESCRIPTION] with the original task the agent is pursuing. [FULL_CONTEXT] should contain the entire context window contents, typically assembled from message history, tool outputs, and system instructions. Tune [RECENCY_WEIGHT], [RELEVANCE_WEIGHT], and [DEPENDENCY_WEIGHT] based on your domain—for real-time operational agents, recency often dominates; for research agents, relevance and dependency matter more. Set [PRESERVATION_THRESHOLD] between 8 and 12 depending on how aggressively you need to compress. [MAX_OUTPUT_TOKENS] should be your target context window size minus space reserved for the next model response. Before deploying, run this prompt against at least 20 recorded overflow scenarios and verify that the continuation context preserves all elements needed to complete the original task without restarting. For high-risk domains such as healthcare or finance, require human review of the eviction decisions before the agent continues with the compressed context.

IMPLEMENTATION TABLE

Prompt Variables

Required inputs for the context window eviction strategy prompt. Each variable must be populated before the prompt is assembled and sent. Validation notes describe how to confirm the input is well-formed before execution.

PlaceholderPurposeExampleValidation Notes

[FULL_CONTEXT]

The complete context payload currently occupying the window, including all messages, tool outputs, retrieved passages, and system instructions.

{"messages": [...], "tools": [...], "retrieved_docs": [...]}

Must be a valid JSON object with at least one message. Check that total token count exceeds the model's context limit before invoking this prompt.

[TOKEN_LIMIT]

The maximum token capacity of the target model's context window.

128000

Must be a positive integer. Validate against the model's published context window size. Do not use a value larger than the model supports.

[CURRENT_TOKEN_COUNT]

The estimated number of tokens currently consumed by [FULL_CONTEXT].

135200

Must be a positive integer greater than [TOKEN_LIMIT] for this prompt to be relevant. Use the same tokenizer that the target model uses for accurate counting.

[TASK_DESCRIPTION]

A clear statement of the ongoing task the agent is trying to complete, used to score relevance of context elements.

Extract all contract termination clauses and their effective dates from the provided legal documents.

Must be a non-empty string. Should match the original task instruction exactly. Avoid paraphrasing, as this changes relevance scoring behavior.

[RECENCY_WEIGHT]

A float between 0.0 and 1.0 that controls how much recency influences eviction priority. Higher values protect recent context.

0.4

Must be a float in range [0.0, 1.0]. Default to 0.4 if not specified. Values above 0.8 may cause loss of critical early context; values below 0.2 may evict recent clarifications.

[DEPENDENCY_GRAPH]

A mapping of which context elements depend on which other elements, used to prevent evicting a parent while keeping an orphaned child.

{"msg_5": ["msg_2", "msg_3"], "tool_output_1": ["tool_call_1"]}

Must be a valid JSON object with string keys and array-of-string values. Can be null if no dependencies are tracked. Validate that all referenced IDs exist in [FULL_CONTEXT].

[MINIMUM_RETAIN_SET]

A list of context element IDs that must never be evicted, such as the system prompt, safety policies, or the current user request.

["system_prompt", "current_user_message", "safety_policy"]

Must be an array of strings. Each ID must exist in [FULL_CONTEXT]. If empty, the prompt may evict safety-critical instructions. Review this set with the safety and product teams.

[OUTPUT_SCHEMA]

The expected JSON schema for the eviction plan, specifying which elements to remove and why.

{"evictions": [{"id": "string", "reason": "string", "risk": "low|medium|high"}], "retained_summary": "string"}

Must be a valid JSON Schema object. The prompt will return output conforming to this schema. Validate that downstream code can parse this exact structure before deployment.

PROMPT PLAYBOOK

Implementation Harness Notes

How to wire the eviction strategy prompt into a production agent loop with scoring, validation, and fallback logic.

The Context Window Eviction Strategy prompt is not a one-shot call; it is a decision node inside a long-running agent harness. When the context window approaches a configured high-water mark (e.g., 80% of the model's maximum context tokens), the harness must pause the primary task, collect the current context inventory, and invoke this prompt to produce a ranked eviction plan. The harness then executes the plan by removing the lowest-scoring items before resuming the primary task. This section covers the wiring, validation, and failure modes you need to handle before deploying this prompt into a production agent loop.

Harness integration steps: 1) Token monitoring: Use the model's token-counting API or a local tokenizer to track total context tokens after each turn. Define a HIGH_WATERMARK threshold (e.g., 0.8 * model_context_limit). 2) Context inventory construction: When the watermark is breached, build a structured inventory of all context items—system prompt segments, tool results, prior turns, retrieved documents, memory entries—each with a unique item_id, content_summary (first 100 chars), age_in_turns, and source_type. 3) Prompt invocation: Populate the [CONTEXT_INVENTORY] placeholder with this inventory and [TASK_DESCRIPTION] with the current agent goal. Call the model with response_format set to JSON and a strict schema requiring { "eviction_plan": [{"item_id": "...", "score": 0.0-1.0, "reasoning": "..."}] }. 4) Validation gate: Before evicting, validate that the returned item_id values exist in the inventory, scores are within range, and the plan does not evict items tagged as [IMMUTABLE] (e.g., system-level safety instructions). Reject invalid plans and retry with an error message injected into the prompt. 5) Eviction execution: Remove items with scores below a configurable EVICTION_THRESHOLD (start at 0.3), log the eviction event with item IDs and scores, and resume the primary agent loop.

Model choice and latency considerations: This prompt requires strong instruction-following and structured output reliability. Use GPT-4o or Claude 3.5 Sonnet for production; avoid smaller models that may produce malformed JSON or hallucinate item IDs. Expect 1-3 seconds of latency per eviction decision. For high-frequency agent loops, consider batching eviction decisions or using a cheaper model for the scoring pass and a stronger model only when the plan is ambiguous. Retry logic: If the model returns invalid JSON, missing fields, or references to non-existent item IDs, retry up to 2 times with the validation error appended to the prompt. After 2 failed retries, fall back to a deterministic eviction strategy (e.g., evict oldest items first) and log the fallback for review. Logging and observability: Record every eviction event with item_id, score, reasoning, timestamp, and task_id. This log is essential for debugging task continuity failures—if the agent loses critical context, you can trace which eviction decision caused the loss and tune the scoring prompt or threshold.

Testing and evaluation: Before production, build an eval harness that simulates context overflow with known critical items (e.g., a user's name, a key constraint, a tool result needed for the final answer). Run the eviction prompt and verify that critical items receive high scores and survive eviction. Measure task continuity: after eviction, ask the agent a question that requires the retained context and check for correct answers. A failure here means the scoring prompt is undervaluing certain context types—update the [SCORING_CRITERIA] section of the prompt template to weight those types higher. What to avoid: Do not invoke this prompt on every turn; it is expensive and adds latency. Do not evict items without logging; you will lose the ability to debug context-loss bugs. Do not skip the validation gate; a hallucinated item ID can crash your context manager. Finally, always pair this prompt with a checkpoint-and-resume strategy for tasks that cannot tolerate any context loss—eviction is a best-effort optimization, not a guarantee of perfect continuity.

IMPLEMENTATION TABLE

Expected Output Contract

Defines the fields, types, and validation rules for the eviction strategy output. Use this contract to parse the model response and verify correctness before applying the eviction decision.

Field or ElementType or FormatRequiredValidation Rule

eviction_plan

array of objects

Must be a non-empty array. Each element must match the eviction_entry schema.

eviction_entry.context_id

string

Must match a context_id provided in [CONTEXT_BLOCKS]. No fabricated IDs allowed.

eviction_entry.eviction_order

integer

Must be a positive integer starting at 1. No gaps or duplicates in the sequence.

eviction_entry.rationale

string

Must be 1-2 sentences referencing the scoring criteria (recency, relevance, dependency). Cannot be empty or generic.

eviction_entry.dependency_risk

string

Must be one of: 'none', 'low', 'medium', 'high'. 'high' risk blocks must include a mitigation note.

preserved_context_ids

array of strings

Must list all context_ids from [CONTEXT_BLOCKS] not selected for eviction. Union with evicted IDs must equal input set.

task_continuity_assessment

string

Must be one of: 'full', 'partial', 'degraded', 'blocked'. 'blocked' or 'degraded' must trigger an escalation flag.

escalation_required

boolean

Must be true if task_continuity_assessment is 'blocked' or if any dependency_risk is 'high' without mitigation. Otherwise false.

PRACTICAL GUARDRAILS

Common Failure Modes

Context window eviction strategies fail silently when scoring is wrong, dependencies are missed, or the model over-summarizes critical state. These cards cover the most common production failure modes and how to guard against them.

01

Critical Dependency Chain Broken

What to watch: The eviction prompt removes a mid-context instruction or entity that later turns reference. The model continues without error but produces logically incoherent output because a dependency was severed. Guardrail: Require the eviction prompt to output an explicit dependency map before removing content. Validate that no remaining context element references an evicted element by ID or name.

02

Recency Bias Overwrites Relevance

What to watch: The scoring function overweights recency and evicts older but task-critical information such as the original goal, constraints, or user identity. The model continues with recent context only and drifts from the task. Guardrail: Pin non-negotiable elements with a permanent retention flag. Include a task-alignment check after eviction that compares the current plan against the original objective.

03

Over-Compression Loses Entity Fidelity

What to watch: The eviction strategy summarizes a block of context into a dense paragraph that drops specific names, numbers, dates, or IDs. Downstream steps hallucinate replacements or make decisions on degraded information. Guardrail: Require the compression step to preserve a structured fact table with exact values for entities, quantities, and identifiers. Run a fact-retention eval comparing pre- and post-eviction key fields.

04

Eviction Scoring Hallucinates Importance

What to watch: The model assigns high importance scores to verbose but low-value content while evicting concise, high-signal instructions. The scoring rationale looks plausible but is objectively wrong. Guardrail: Use a separate verification prompt that reviews the eviction plan and flags misranked elements. Log the scoring justification for human spot-checking during eval runs.

05

Checkpoint Corruption on Resume

What to watch: The eviction prompt produces a checkpoint summary that is syntactically valid but semantically misaligned with the original state. When a fresh context window resumes from the checkpoint, it inherits subtle errors that compound. Guardrail: Include a state-consistency assertion in the resume prompt that compares the checkpoint against the last known valid state. Abort and escalate if the assertion fails.

06

Infinite Eviction Loop Under Budget Pressure

What to watch: The retry harness triggers eviction, re-attempts the task, still exceeds the token limit, and triggers eviction again without changing strategy. The loop burns compute and eventually escalates with no useful output. Guardrail: Implement a retry budget with progressive strategy changes. After the first eviction fails, switch to aggressive summarization. After the second, escalate to a human or fallback model with a partial result.

IMPLEMENTATION TABLE

Evaluation Rubric

Use this rubric to evaluate the quality of the eviction strategy output before integrating it into a production agent harness. Each criterion targets a specific failure mode common in context window recovery workflows.

CriterionPass StandardFailure SignalTest Method

Eviction Justification

Every removed item includes a specific reason tied to recency, relevance, or dependency score

Generic reasons like 'old' or 'not needed' without reference to the scoring criteria

Parse output for justification strings; assert each contains a scoring dimension keyword

Dependency Integrity

No item is evicted if a retained item explicitly depends on it for task completion

A retained action references a tool output or entity that was evicted without a summary

Build a dependency graph from [TASK_STATE]; assert no broken edges in the eviction plan

Critical State Preservation

All items marked as [CRITICAL] in the input remain in the retained context

A [CRITICAL] item appears in the eviction list or is missing from the retained summary

Diff the [CRITICAL] list against the eviction list; assert intersection is empty

Token Budget Compliance

The retained context plus new input fits within [MAX_TOKENS] with at least 5% buffer

Retained context size exceeds [MAX_TOKENS] minus new input size, causing immediate re-overflow

Tokenize the proposed retained context; assert token count <= [MAX_TOKENS] * 0.95

Task Continuity Score

A downstream agent can resume the task from the retained context without requesting rework

The retained context omits the current step, goal, or last action, forcing the agent to restart

Run a mock continuation prompt with the retained context; assert task step increments correctly

Eviction Order Rationality

Items are evicted in order of lowest composite score first, with ties broken by recency

A high-relevance recent item is evicted before a low-relevance stale item

Sort evicted items by declared scores; assert monotonic non-decreasing order of composite score

Summary Fidelity

Evicted items are summarized with enough detail to reconstruct key facts if needed later

Summary omits named entities, numeric values, or decision outcomes present in the evicted item

Extract entities and numbers from evicted items; assert each appears in the summary or is explicitly marked as non-essential

Output Schema Validity

The output strictly matches the [OUTPUT_SCHEMA] with all required fields populated

Missing required field, extra field, or wrong type in the eviction plan JSON

Validate output against [OUTPUT_SCHEMA] using a JSON Schema validator; assert no errors

ADAPTATION OPTIONS

Adapt This Prompt

How to adapt

Use the base prompt with a simple recency-only heuristic. Replace the scoring rubric with a single instruction: "Evict the oldest messages first, preserving the system prompt and the last [N] turns." Skip dependency scoring and just track turn order.

Watch for

  • Losing critical context from earlier turns that later messages depend on
  • No validation that evicted context wasn't needed for the final output
  • Overly aggressive eviction that breaks multi-step reasoning chains
Prasad Kumkar

About the author

Prasad Kumkar

CEO & MD, Inference Systems

Prasad Kumkar is the CEO & MD of Inference Systems and writes about AI systems architecture, LLM infrastructure, model serving, evaluation, and production deployment. Over 5+ years, he has worked across computer vision models, L5 autonomous vehicle systems, and LLM research, with a focus on taking complex AI ideas into real-world engineering systems.

His work and writing cover AI systems, large language models, AI agents, multimodal systems, autonomous systems, inference optimization, RAG, evaluation, and production AI engineering.