Inferensys

Prompt

Dynamic Context Truncation Prompt for Agents

A practical prompt playbook for compressing accumulated agent context by truncating verbose tool outputs, collapsing redundant observations, and retaining action-critical details before the next agent step.
Developer demonstrating multi-agent tool use, agent tool selection interface on laptop, casual tech demo moment.
PROMPT PLAYBOOK

When to Use This Prompt

Define the job, ideal user, required inputs, and hard constraints for the Dynamic Context Truncation Prompt.

This prompt is designed for agent builders whose systems accumulate verbose tool outputs, redundant observations, and repetitive sub-task results that rapidly exhaust the context window. The primary job-to-be-done is compressing agent context in-flight—collapsing noisy tool responses, removing duplicate observations, and retaining only the details required for the next action or decision—without breaking the agent's ability to complete its task. The ideal user is a production AI engineer or technical decision maker who has already instrumented their agent loop with tool-call logging and needs a deterministic, prompt-driven compression step before the next model call to control cost, latency, and reliability at scale.

Use this prompt when your agent's context budget is dominated by raw tool outputs rather than conversation history. It is most effective in single-agent loops where the model receives a sequence of Observation blocks from tools like web browsers, code executors, API calls, or database queries. You should have access to the raw tool output, the action that produced it, and the agent's current task or goal. The prompt works best when you can batch multiple observations into a single compression pass, rather than compressing one observation at a time, because cross-observation redundancy is the primary target. Do not use this prompt for compressing multi-turn user-assistant dialogue; use a conversation summarization or turn pruning prompt instead. Do not use it when tool outputs are already terse and information-dense with no redundancy—the compression step adds latency without benefit.

Before implementing this prompt, ensure you have a validation harness that can compare the agent's task completion rate and error rate with and without compression. The prompt is lossy by design: it will drop details that appear redundant at compression time but may become relevant later. Always log both the raw and compressed context for debugging. If the agent operates in a high-risk domain—such as healthcare, finance, or safety-critical infrastructure—require human review of the compression logic or implement a conservative mode that flags rather than drops uncertain content. Start by applying this prompt when the accumulated tool outputs exceed 50% of your remaining context budget, and measure whether task completion holds steady as you tune the aggressiveness of compression.

PRACTICAL GUARDRAILS

Use Case Fit

Where the Dynamic Context Truncation Prompt delivers value and where it introduces unacceptable risk.

01

Strong Fit: Verbose Agent Tool Loops

Use when: Your agent accumulates large, semi-structured tool outputs (API responses, search results, file reads) across multiple steps, and you need to reclaim context budget before the next reasoning step. Avoid when: Tool outputs are already minimal or the truncation prompt costs more tokens than it saves on average.

02

Poor Fit: Single-Turn or Stateless Workflows

Avoid when: The system processes one request at a time with no accumulated history. The truncation overhead adds latency and cost without any budget reclamation benefit. Guardrail: Gate the truncation call behind a minimum context-length threshold before invoking.

03

Required Inputs: Structured Observations

Risk: The truncation prompt fails silently if it receives unstructured or poorly delimited tool outputs. Guardrail: Require that all tool outputs passed to the truncation prompt include a tool_name, timestamp, and output field. Validate this schema in the application layer before calling the truncation prompt.

04

Operational Risk: Loss of Action-Critical Detail

Risk: The model may collapse a tool output containing a unique ID, error code, or file path that is essential for the next agent action. Guardrail: Implement a post-truncation validation step that checks for the presence of known critical fields (e.g., IDs, status codes) before the agent acts on the compressed context.

05

Operational Risk: Compounding Errors in Multi-Step Tasks

Risk: A small truncation error in step 3 causes a wrong action in step 4, which generates more bad context, leading to a failure cascade. Guardrail: Track task_completion_rate and error_rate after truncation. If the error rate increases beyond a threshold, fall back to using the full, uncompressed context for the remainder of the task.

06

When to Use Code Instead

Avoid when: The truncation logic is purely mechanical, such as keeping only the last N characters of each tool output or removing duplicate status lines. Guardrail: Use deterministic string manipulation or jq filters for simple, rule-based compression. Reserve the LLM-based prompt for semantic summarization and redundancy collapse that requires reasoning.

PROMPT PLAYBOOK

Copy-Ready Prompt Template

A reusable prompt with square-bracket placeholders that compresses verbose agent context by truncating tool outputs, collapsing redundant observations, and retaining action-critical details.

This prompt template is designed to be inserted into an agent's execution loop when the accumulated context—tool outputs, sub-task results, and observations—threatens to exceed the context window budget. It instructs the model to act as a context compressor, producing a dense, structured summary that preserves the information necessary for the agent to continue its task without error. The template uses square-bracket placeholders so you can wire in the specific agent state, tool definitions, and output schema required by your harness.

text
You are an agent context compressor. Your task is to reduce the token footprint of the provided agent context while preserving all information required for successful task completion.

## INPUT
[AGENT_CONTEXT]

## COMPRESSION RULES
1. **Truncate Verbose Tool Outputs:** For each tool output, retain only the fields and values listed in [RETAINED_FIELDS]. Remove all other content. If a tool output is a natural language response, summarize it into a single sentence capturing the actionable result.
2. **Collapse Redundant Observations:** If multiple observations or tool results convey the same fact, keep only the most recent or most authoritative instance. Note the deduplication in a brief `[DEDUP: reason]` tag.
3. **Retain Action-Critical Details:** Preserve verbatim any information that matches the patterns in [CRITICAL_PATTERNS]. This includes error codes, IDs, URLs, specific user corrections, and decision outcomes.
4. **Summarize Sub-Task Results:** For each completed sub-task in [SUB_TASKS], replace the full execution trace with a single-line summary: `[SUB_TASK_ID]: [OUTCOME]`. Include any unresolved items.
5. **Preserve Unresolved Items:** List all unanswered questions, pending actions, and unfulfilled commitments from [UNRESOLVED_ITEMS] in a dedicated section at the end of your output.

## OUTPUT FORMAT
Output a valid JSON object conforming to this schema:
{
  "compressed_context": "string containing the full compressed agent context",
  "token_estimate": "integer estimated token count of compressed_context",
  "removed_items": [
    {
      "item_id": "string",
      "reason": "truncated | redundant | summarized | low_signal"
    }
  ],
  "unresolved_items": ["string list of pending questions or actions"]
}

## CONSTRAINTS
- Do not introduce new facts or hallucinate details not present in the input.
- If compression would remove information matching [CRITICAL_PATTERNS], do not remove it.
- If the input is already under [TOKEN_BUDGET] tokens, return it unchanged with a token_estimate and an empty removed_items list.

To adapt this template, start by defining the [RETAINED_FIELDS] for each tool your agent uses. For a web-browsing agent, you might retain only url, status_code, and page_title from a full page fetch. Next, populate [CRITICAL_PATTERNS] with regex-like descriptions of high-signal data: error codes, confirmation numbers, or user corrections. Wire [SUB_TASKS] and [UNRESOLVED_ITEMS] from your agent's internal state tracker. Set [TOKEN_BUDGET] to a value below your model's context limit, leaving headroom for the system prompt and future turns. Before deploying, run this prompt against a golden dataset of agent traces and validate that the compressed_context leads to identical task completion rates as the uncompressed baseline. If your agent operates in a high-risk domain, route outputs where removed_items contains items matching [CRITICAL_PATTERNS] to a human reviewer before the agent continues.

IMPLEMENTATION TABLE

Prompt Variables

Required inputs for the Dynamic Context Truncation Prompt. Each placeholder must be populated before the prompt is assembled and sent to the model. Missing or malformed inputs are the most common cause of truncation errors in production.

PlaceholderPurposeExampleValidation Notes

[AGENT_CONTEXT]

Full accumulated agent context including tool outputs, sub-task results, observations, and action history that has exceeded the target budget

{"turn_1": {"tool": "search", "output": "..."}, "turn_2": {...}}

Must be valid JSON string. Length must exceed [TARGET_TOKEN_BUDGET] by at least 20% or truncation is unnecessary. Parse check before prompt assembly.

[TARGET_TOKEN_BUDGET]

Maximum token count the compressed context must fit within, typically 60-80% of model context window to leave room for system prompt and future turns

6000

Must be positive integer. Should be validated against model context window: [TARGET_TOKEN_BUDGET] < (model_context_limit - system_prompt_tokens - reserved_output_tokens). Reject if budget leaves less than 500 tokens for future turns.

[TASK_DESCRIPTION]

Current agent task or goal that determines which details are action-critical and must survive truncation

Book a flight from SFO to JFK for March 15 with window seat preference

Must be non-empty string. Task description is used to score retention priority. If null or empty, truncation will be generic and may drop task-critical details. Schema check: required field.

[RETENTION_PRIORITIES]

Ordered list of context categories to prioritize during truncation: tool_outputs, observations, action_history, user_preferences, errors, confirmations

["errors", "user_preferences", "action_history", "confirmations", "observations", "tool_outputs"]

Must be valid JSON array of strings from allowed enum. Invalid category names cause retention misprioritization. Enum check against allowed values. Empty array defaults to generic priority ordering.

[COMPRESSION_STRATEGY]

Strategy selection: collapse_redundant, truncate_verbose, summarize_observations, or hybrid. Controls how compression is applied before truncation

hybrid

Must be one of: collapse_redundant, truncate_verbose, summarize_observations, hybrid. Enum check required. Invalid strategy causes fallback to truncate-only behavior which may lose structured data. Default to hybrid if not specified.

[OBSERVATION_SCHEMA]

JSON schema defining required fields in observations that must survive compression. Fields not in schema may be truncated

{"required": ["status", "result", "error"], "optional": ["duration", "retry_count"]}

Must be valid JSON schema object. Schema is used to preserve required fields during observation summarization. Parse check: valid JSON. Schema validation: required and optional must be arrays of strings. Null allowed if no schema preservation is needed.

[MAX_REDUNDANT_COLLAPSE]

Maximum number of redundant observations or confirmations to collapse into a single entry before retaining as distinct

3

Must be positive integer or null. Values below 2 disable collapse. Values above 10 risk over-collapsing distinct observations. Range check: 2-10 recommended. Null disables redundant collapse entirely.

[ERROR_RETENTION_RULE]

Rule for retaining error context: retain_all, retain_first, retain_last, retain_unique. Controls how multiple errors from same tool are handled

retain_unique

Must be one of: retain_all, retain_first, retain_last, retain_unique. Enum check required. retain_all may waste budget on repeated identical errors. retain_unique is default for production. Invalid rule defaults to retain_all which is safest but most expensive.

PROMPT PLAYBOOK

Implementation Harness Notes

How to wire the Dynamic Context Truncation Prompt into an agent loop with validation, retries, and observability.

This prompt is designed to be called as a pre-processing step inside an agent's main execution loop, immediately before the primary reasoning or action model is invoked. The harness should intercept the agent's working memory—a structured object containing the system prompt, recent conversation turns, and accumulated tool outputs—and pass it to the truncation prompt when a token budget threshold is exceeded. The output is a compressed, structured representation of the agent's context that replaces the verbose working memory for the subsequent call to the primary model. This is not a one-time setup; it is a recurring budget-reclamation subroutine that fires whenever the estimated token count of the agent's state crosses a configured limit, such as 80% of the model's context window.

The implementation must treat the truncation prompt as a deterministic state transformation with a strict input and output contract. The input should be a JSON object with fields for system_instructions, conversation_turns (an ordered list of objects with role, content, and turn_id), and tool_outputs (a list of objects with tool_name, output, and call_id). The prompt's output must be parsed and validated against a schema that includes compressed_context (a string for the model's next system message), retained_turn_ids (a list of IDs preserved verbatim), and discard_log (a list of removed items with a reason for each). If the output fails schema validation, the harness should retry once with the validation error injected into the prompt's [CONSTRAINTS] field. If the retry also fails, the system must fall back to a safe but expensive behavior, such as sending the full, untruncated context and logging an alert, rather than proceeding with a malformed compression.

To make this workflow observable, the harness must emit structured logs and metrics at each invocation. Log the pre_truncation_token_count, post_truncation_token_count, compression_ratio, and the full discard_log. This data is critical for debugging agent failures: if a task fails after truncation, you can query the discard log to see if a critical observation was removed. Instrument a counter metric for truncation_attempts and truncation_failures (both schema validation failures and downstream task failures attributed to truncation). For high-stakes agent workflows, consider a shadow mode where the truncated context is used for the primary model, but a parallel, async call is made with the full context to a cheaper evaluator model. The evaluator can judge if the compressed context led to a materially different or worse action, creating a continuous feedback loop for tuning the truncation prompt's instructions without degrading the live user experience.

IMPLEMENTATION TABLE

Expected Output Contract

The prompt must return a valid JSON object conforming to this schema. Use this contract to validate the model response before the truncated context is passed to the next agent step.

Field or ElementType or FormatRequiredValidation Rule

truncation_plan

object

Top-level object must parse as valid JSON. Schema check: contains required keys 'retained_context', 'removed_blocks', 'compression_summary'.

retained_context

array of objects

Each object must have 'id' (string), 'content' (string), 'retention_reason' (enum: ACTION_CRITICAL | STATE_DEFINING | UNRESOLVED | RECENT_OBSERVATION). Array must not be empty.

removed_blocks

array of objects

Each object must have 'id' (string), 'original_length_tokens' (integer), 'removal_reason' (enum: REDUNDANT | VERBOSE | STALE | LOW_SIGNAL). 'id' values must not appear in retained_context.

compression_summary

object

Must contain 'original_token_estimate' (integer), 'retained_token_estimate' (integer), 'compression_ratio' (float between 0.0 and 1.0). 'compression_ratio' must equal retained_token_estimate / original_token_estimate.

action_critical_preserved

array of strings

List of action-critical detail types preserved (e.g., 'tool_call_parameters', 'error_messages', 'user_constraints'). Must not be empty. If no action-critical content existed, use ['NONE_IDENTIFIED'].

truncation_notes

string or null

If present, must be a non-empty string explaining edge cases or ambiguity in truncation decisions. Null allowed. No markdown or special characters.

confidence_score

float

Model's self-assessed confidence in truncation correctness. Must be between 0.0 and 1.0 inclusive. If below 0.7, truncation_notes must be non-null with explanation.

PRACTICAL GUARDRAILS

Common Failure Modes

Dynamic context truncation fails silently in production. These are the most common failure modes when compressing agent tool outputs and observations, along with practical guardrails to prevent them.

01

Action-Critical Detail Loss

What to watch: The truncation prompt removes IDs, status codes, error messages, or parameter values that downstream tool calls require. The agent then calls tools with hallucinated or stale arguments. Guardrail: Require the truncation prompt to preserve all structured identifiers, error codes, and numeric values in a reserved preserved_fields block before compressing narrative text.

02

Observation Collapse Across Distinct Steps

What to watch: The prompt merges observations from different sub-tasks into a single summary, losing the causal chain of which action produced which result. The agent then repeats completed steps or skips pending ones. Guardrail: Instruct the truncation prompt to maintain step-level grouping with explicit step_id labels and never collapse observations across different action boundaries.

03

Error Signal Suppression

What to watch: Tool failure messages, partial results, and retry indicators are treated as low-signal verbose output and removed during compression. The agent proceeds as if all steps succeeded. Guardrail: Add a hard constraint that any output containing error keywords, non-2xx status codes, or partial-result flags must be retained verbatim regardless of token budget.

04

Budget Overshoot on Re-expansion

What to watch: The truncation prompt produces compressed output that, when combined with the next round of fresh tool outputs, still exceeds the context budget. The system enters a compression loop with no net budget reduction. Guardrail: Include a target token ceiling in the truncation prompt and validate output length before re-injection. If the ceiling is breached, escalate to a more aggressive summarization tier.

05

Temporal Ordering Inversion

What to watch: The prompt reorders observations by perceived importance rather than chronological sequence. The agent then reasons about state transitions in the wrong order and produces incorrect conclusions. Guardrail: Require the truncation prompt to preserve strict temporal ordering with monotonic observation_index fields, even when prioritizing content for retention.

06

Silent Schema Drift After Truncation

What to watch: The compressed output changes field names, types, or nesting structure compared to the original tool output schema. Downstream parsing logic fails with schema mismatch errors that are hard to attribute to truncation. Guardrail: Validate compressed output against the original tool output schema after truncation. Reject and retry with stricter schema-preservation instructions if validation fails.

IMPLEMENTATION TABLE

Evaluation Rubric

Use this rubric to evaluate the quality of the dynamic context truncation prompt before deploying it into a production agent loop. Each criterion targets a specific failure mode that can degrade task completion or increase error rates after truncation.

CriterionPass StandardFailure SignalTest Method

Action-Critical Detail Preservation

All tool outputs containing actionable parameters (e.g., IDs, status codes, exact values) retain those fields in the compressed output.

A downstream action fails or uses a null/incorrect parameter because it was stripped during truncation.

Run 20 agent traces with truncation enabled. Compare action arguments pre- and post-truncation. Pass if 0 argument mismatches occur.

Redundant Observation Collapse

Repeated observations from consecutive tool calls with identical status are collapsed into a single entry with a repeat count.

The compressed context contains verbatim copies of the same observation, wasting budget without adding information.

Feed a synthetic agent trace with 5 identical consecutive observations. Assert the compressed output contains exactly 1 entry for that observation.

Schema Preservation

Compressed tool outputs maintain the original JSON schema structure with only verbose fields removed or summarized.

A downstream parser fails because a required field was deleted or its type changed (e.g., string became null).

Validate compressed outputs against the expected tool response JSON schema. Pass if schema validation succeeds for 50 consecutive truncations.

Token Budget Compliance

The compressed context is under the target token budget specified in [TARGET_TOKEN_BUDGET] for 95% of requests.

The truncation prompt consistently outputs context that exceeds the budget, forcing an application-layer hard truncation.

Run 100 truncation requests. Assert that 95 or more outputs have a token count <= [TARGET_TOKEN_BUDGET].

Task Completion Rate Parity

The agent's task completion rate with truncated context is within 5 percentage points of the rate with full context.

Task completion drops significantly (e.g., >10%) after enabling truncation, indicating critical information loss.

Run a standard agent eval suite of 50 tasks with full context and 50 with truncated context. Compare completion rates. Pass if the difference is <= 5%.

Error Introduction Rate

The truncation process itself introduces no new errors (e.g., hallucinated summaries, incorrect collapse).

The agent makes a mistake that is directly traceable to a fabrication in the compressed context, not present in the original tool output.

Run 50 traces. For any agent error, manually verify if the error source exists in the original tool output. Pass if 0 errors are traced to a truncation fabrication.

Verbose Field Removal

Long, unstructured text fields (e.g., full page HTML, verbose logs) are replaced with a concise summary or removed entirely.

The compressed context still contains large blocks of raw, low-signal text that consume significant budget.

Inspect 10 compressed outputs. Assert that no single field exceeds 200 tokens unless it is flagged as action-critical by the prompt.

ADAPTATION OPTIONS

Adapt This Prompt

How to adapt

Add strict output schema validation, retry logic with backoff, structured logging of compression decisions, and a pre-deployment eval harness. Wire the compressor as a middleware step before the main agent loop.

code
You are an agent context compressor operating in a production pipeline. Given the accumulated [AGENT_CONTEXT], compress it to fit within [MAX_TOKENS] tokens.

Rules:
- Preserve action-critical details: IDs, status codes, error messages, file paths, and user-facing data.
- Collapse redundant observations into a single representative entry with a count of occurrences.
- Truncate verbose tool outputs to essential fields defined in [FIELD_PRESERVATION_SCHEMA].
- Retain all unresolved items and pending actions with their original timestamps.
- Flag any items where compression confidence is below [CONFIDENCE_THRESHOLD] for human review.

Output strictly according to [OUTPUT_SCHEMA]. If validation fails, retry up to [MAX_RETRIES] times with the validation errors included.

Watch for

  • Silent format drift in compressed output over model version upgrades
  • Missing human review flag for low-confidence compressions
  • Token estimation inaccuracies causing budget overshoot
  • Compression latency adding unacceptable delay to agent loop
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.