This prompt is for agent infrastructure developers who need to prevent context window overflow when tool responses are too large to fit safely into the remaining token budget. It acts as a pre-insertion gate: given a raw tool output, a maximum token limit, and a priority-ordered list of fields to preserve, the prompt returns a budget-compliant payload with explicit truncation decisions. Use this when tool outputs are unpredictable in size, when multiple tool calls compete for context space, or when you need auditable truncation decisions rather than silent drops.
Prompt
Tool Output Context Window Budget Check Prompt

When to Use This Prompt
Identify the right scenarios for deploying a context window budget check on tool outputs and recognize when alternative approaches are required.
The ideal user is building a production agent loop where a model may call several tools in sequence, and each tool's response must be inserted into the context before the next reasoning step. Without a budget check, a single oversized response from a database query, API call, or file read can silently push critical instructions, earlier results, or conversation history out of the context window. This prompt solves that by making truncation an explicit, logged decision with field-level priority rather than relying on the model's implicit summarization or the platform's silent mid-window truncation. It is designed for structured outputs—JSON, XML, tabular data, or key-value records—where preserving specific fields matters more than maintaining prose fluency.
Do not use this prompt as a general summarizer for long-form text, articles, or conversational transcripts. It is not designed for semantic compression of prose and will produce poor results if asked to 'summarize' a narrative document while preserving its argument structure. For those cases, use a dedicated summarization prompt with instruction-level control over length, style, and fact density. Similarly, if your tool outputs are consistently small and predictable, a static truncation rule in application code is simpler, faster, and cheaper than an LLM call. Reserve this prompt for situations where the size variance is high, the field priority is non-obvious, or you need an audit trail of what was kept and what was dropped. When deploying in regulated or high-stakes domains, always log the full original output alongside the truncated version and require human review of the truncation decisions before they become part of a permanent record.
Use Case Fit
Where the Tool Output Context Window Budget Check Prompt works and where it introduces unacceptable risk.
Good Fit: High-Volume API Responses
Use when: tool outputs from REST APIs, database queries, or log searches routinely exceed 10k tokens and risk pushing critical instructions out of the context window. Guardrail: apply budget check before the output re-enters the agent's reasoning loop, not after context overflow has already occurred.
Good Fit: Multi-Tool Agent Pipelines
Use when: an agent chains 3+ tool calls and each response consumes unpredictable context. Guardrail: enforce a cumulative budget across the entire turn, not per-tool, and reserve at least 20% of the context window for system instructions and conversation history.
Bad Fit: Real-Time Streaming Responses
Avoid when: the tool produces a streaming response where truncation mid-stream would break a downstream parser or user experience. Guardrail: use chunk-level budget enforcement with explicit continuation markers instead of whole-output truncation.
Bad Fit: Single Small-Tool Calls
Avoid when: tool outputs are consistently under 2k tokens and the overhead of budget estimation exceeds the risk. Guardrail: implement a lightweight token counter that skips the full budget prompt when output size is below a configured threshold.
Required Input: Token Budget Configuration
Risk: without explicit budget parameters, the prompt either over-truncates and loses critical data or under-truncates and fails to prevent overflow. Guardrail: always supply [MAX_OUTPUT_TOKENS], [RESERVED_INSTRUCTION_TOKENS], and [PRIORITY_FIELD_LIST] as structured inputs before invoking the budget check.
Operational Risk: Silent Critical Field Loss
Risk: the budget prompt drops a field that a downstream tool or human reviewer requires, causing a cascading failure with no obvious root cause. Guardrail: always return a [TRUNCATION_LOG] with explicit dropped-field names and require agent confirmation before proceeding when priority fields are removed.
Copy-Ready Prompt Template
A reusable prompt that inspects a tool's raw output, estimates its token cost, and produces a budget-aware summary or truncation plan before the output re-enters the agent's context window.
This prompt acts as a context-window gatekeeper. It receives the raw output from a tool call, a defined token budget, and a priority-ordered list of fields or sections that must be preserved. The model is instructed to measure the output size, decide whether truncation or summarization is required, and return a structured payload containing the processed content, size estimates, and an explicit record of what was kept, compressed, or dropped. Use this template before tool outputs are appended to the agent's message history to prevent silent context overflow, mid-turn amnesia, and runaway token costs.
textYou are a context-window budget controller for an AI agent system. Your job is to inspect the output of a tool call and ensure it fits within a strict token budget before the output is added to the agent's ongoing context. ## INPUT [TOOL_OUTPUT] ## PARAMETERS - **Token Budget:** [MAX_TOKENS] - **Priority Fields (ordered):** [PRIORITY_FIELDS] - **Truncation Strategy:** [TRUNCATION_STRATEGY] // Options: "summarize", "drop-low-priority", "head-only" - **Output Schema:** [OUTPUT_SCHEMA] ## INSTRUCTIONS 1. Estimate the token count of the raw [TOOL_OUTPUT]. Use a conservative estimate: roughly 1 token per 4 characters for English text, or use the provided tokenizer estimate if available. 2. If the estimated token count is less than or equal to [MAX_TOKENS], return the output unchanged with `truncation_applied: false`. 3. If the estimated token count exceeds [MAX_TOKENS], apply the [TRUNCATION_STRATEGY]: - **summarize:** Compress the content while preserving all information in [PRIORITY_FIELDS]. Summarize or drop non-priority content. - **drop-low-priority:** Keep [PRIORITY_FIELDS] intact and drop all other fields or sections entirely. - **head-only:** Keep only the first portion of the output that fits within [MAX_TOKENS], preserving [PRIORITY_FIELDS] if they appear in that portion. 4. After processing, re-estimate the token count of the final output. 5. Return a JSON object conforming to [OUTPUT_SCHEMA] that includes the processed content, size estimates, and a clear record of what was kept, compressed, or removed. ## CONSTRAINTS - Never fabricate data to fill gaps created by truncation. - If a priority field cannot be preserved within the budget, flag it in `missing_critical_fields`. - Preserve the original meaning of priority fields; do not alter factual claims. - If the entire output must be dropped, return an empty content field with `truncation_applied: true` and a clear explanation. ## OUTPUT_SCHEMA Return ONLY valid JSON matching this structure: { "original_token_estimate": number, "final_token_estimate": number, "truncation_applied": boolean, "strategy_used": "none" | "summarize" | "drop-low-priority" | "head-only", "content": "string or structured object containing the processed output", "preserved_fields": ["field1", "field2"], "dropped_fields": ["field3"], "summarized_fields": ["field4"], "missing_critical_fields": ["field5"], "truncation_notes": "Explanation of decisions made" }
To adapt this template, replace the square-bracket placeholders with values from your agent harness. [TOOL_OUTPUT] should be the raw string or JSON response from the tool. [MAX_TOKENS] is the remaining context budget you've allocated for this tool's output—calculate this dynamically based on the current context window usage. [PRIORITY_FIELDS] is an ordered list of field names or section headers that must survive truncation; this list should be derived from your downstream task requirements. [TRUNCATION_STRATEGY] can be set statically per tool or chosen dynamically based on the output type. [OUTPUT_SCHEMA] can be tightened further for your specific needs, but the provided schema includes the essential fields for observability and debugging. Wire this prompt into your agent loop immediately after a tool returns and before the output is appended to the message list. Log the truncation_notes and missing_critical_fields fields so you can detect when important information is being lost to budget constraints.
Before deploying, test this prompt against tool outputs of varying sizes: outputs that fit comfortably, outputs that exceed the budget by a small margin, and outputs that are 10x the budget. Verify that priority fields survive in all cases where they are present. Check that missing_critical_fields is populated when a priority field cannot be preserved. If you observe hallucinated content filling gaps, add stronger language to the CONSTRAINTS section. If the token estimates are consistently off, consider passing a token count from your application layer instead of relying on the model's estimate. For high-stakes domains where information loss could cause harm, route outputs flagged with missing_critical_fields to a human review queue or trigger a fallback workflow that fetches the data through a narrower, more targeted tool call.
Prompt Variables
Required inputs for the Tool Output Context Window Budget Check Prompt. Each placeholder must be populated before the prompt is assembled and sent to the model.
| Placeholder | Purpose | Example | Validation Notes |
|---|---|---|---|
[TOOL_OUTPUT] | The raw, complete response body from the tool invocation that needs to be budget-checked. | {"results": [...500 items...], "metadata": {...}} | Must be a non-null string or serialized JSON object. Validate parseability before passing to the prompt. Empty string is allowed but will produce a zero-token budget result. |
[MAX_TOKEN_BUDGET] | The hard ceiling on tokens allowed for the sanitized output before it re-enters the agent's main context window. | 8000 | Must be a positive integer. Validate range: 100-128000. Reject non-numeric or negative values. If null, default to 4096 and log a warning. |
[PRIORITY_FIELDS] | An ordered list of JSONPath or dot-notation field selectors that must be preserved in full, even if truncation is required elsewhere. | ["$.results[].id", "$.results[].score", "$.metadata.query"] | Must be a valid JSON array of strings. Validate each path against the [TOOL_OUTPUT] schema. Empty array is allowed and means no field has special priority. |
[TRUNCATION_STRATEGY] | The method the model should prefer when reducing content: 'head', 'tail', 'summarize', or 'priority-only'. | summarize | Must be one of the enumerated string values. Reject unknown strategies. If null, default to 'summarize' and note in the decision log. |
[OUTPUT_FORMAT] | The expected structure for the budget-check response, typically a JSON schema definition. | {"type": "object", "properties": {"truncated_output": {...}, "original_token_count": {...}}} | Must be a valid JSON Schema object. Validate with a schema validator before injection. Reject if schema is not parseable JSON. |
[MODEL_CONTEXT_LIMIT] | The total context window size of the target model, used to contextualize the budget warning severity. | 128000 | Must be a positive integer. Validate against known model limits. If null, default to 128000 and flag as unverified. Used to calculate budget utilization percentage. |
[CRITICALITY_LEVEL] | A label indicating the risk tolerance for information loss: 'low', 'medium', 'high', or 'critical'. | high | Must be one of the enumerated string values. Controls the strictness of preservation checks. 'critical' requires human approval before any truncation. |
Implementation Harness Notes
How to wire the context window budget check into an agent middleware layer with validation, retries, and observability.
The Tool Output Context Window Budget Check Prompt is designed to sit as a middleware gate between tool execution and the agent's main reasoning loop. After a tool returns its raw output, this prompt intercepts the payload before it enters the agent's context window. The harness must calculate the current context window utilization, estimate the incoming payload size, and invoke the budget check prompt only when the combined size threatens to exceed the model's context limit or a predefined safety threshold (e.g., 80% of the context window). This gate prevents silent truncation by the model provider, which often drops middle or end content without warning, and avoids the latency and cost of processing oversized payloads in the reasoning step.
A production implementation requires three integration points: a pre-check calculator, the prompt execution layer, and a post-processing validator. The pre-check calculator uses the model's tokenizer (or a conservative character-count heuristic for cross-model compatibility) to measure current context size and the incoming tool output size. If current_tokens + incoming_tokens > [BUDGET_THRESHOLD], the harness invokes the budget check prompt with the full tool output, the remaining budget, and the priority field map. The prompt returns a truncated or summarized payload. The post-processing validator then confirms that all [CRITICAL_FIELDS] are present in the output, that the total size is under budget, and that the truncation metadata (e.g., fields_retained, fields_dropped, truncation_ratio) is well-formed. If validation fails, the harness should retry once with a stricter budget constraint before escalating to a human operator or logging the failure for offline analysis.
Observability is critical because silent information loss is the primary failure mode. Log the pre-check token counts, the prompt's truncation decisions, the post-validation result, and any dropped critical fields as structured trace spans. Set up an eval harness that replays known tool outputs with varying budget constraints and measures critical field preservation rate and information loss rate against a ground-truth summary. Run this eval on every prompt or model version change. For high-stakes domains (healthcare, finance, legal), route any output where truncation_ratio > 0.3 or where critical fields were dropped to a human review queue before the agent continues. Avoid wiring this prompt directly into the agent's reasoning step without the pre-check gate—invoking it on every tool call wastes latency and tokens on payloads that already fit comfortably within budget.
Expected Output Contract
Fields, format, and validation rules for the truncated or summarized output produced by the Tool Output Context Window Budget Check Prompt. Use this contract to validate the agent's response before it re-enters the main context.
| Field or Element | Type or Format | Required | Validation Rule |
|---|---|---|---|
original_size_tokens | integer | Must be a positive integer. Parse check: value must match the estimated token count of the raw tool output before processing. | |
truncated_size_tokens | integer | Must be a non-negative integer. Parse check: value must be less than or equal to original_size_tokens. If no truncation occurred, must equal original_size_tokens. | |
budget_remaining_tokens | integer | Must be a non-negative integer. Parse check: value must equal the target context budget minus truncated_size_tokens. Schema check: cannot exceed the provided [MAX_OUTPUT_TOKENS]. | |
truncation_applied | boolean | Must be true if truncated_size_tokens is less than original_size_tokens, otherwise false. Schema check: must be consistent with the size fields. | |
preserved_fields | array of strings | Must contain the list of top-level field names retained from the original output. Validation rule: every entry must exist in the original tool output schema. If empty, the entire output was summarized rather than field-filtered. | |
removed_fields | array of strings | Must contain the list of top-level field names excluded from the original output. Validation rule: the union of preserved_fields and removed_fields must equal the complete set of original top-level keys. No field may appear in both arrays. | |
summary_or_truncated_output | string or object | Must contain the processed content. If truncation_applied is true and preserved_fields is not empty, this should be a JSON object with only the preserved fields. If summarization was used, this should be a string. Schema check: must not exceed [MAX_OUTPUT_TOKENS] when tokenized. | |
critical_field_retention_check | object | Must contain a boolean 'all_present' and an array 'missing_critical'. Validation rule: 'missing_critical' must be empty if [CRITICAL_FIELDS] was provided and all were retained. If any critical field is missing, 'all_present' must be false. Approval required if 'all_present' is false. |
Common Failure Modes
Context window budget checks fail silently when truncation logic, priority rules, or size estimation are left implicit. These cards cover the most common production failure modes and the guardrails that prevent them.
Silent Critical Field Truncation
What to watch: The prompt truncates a large tool output but removes a required field (e.g., an API error code, a database primary key, or a security flag) that downstream logic depends on. The agent proceeds with incomplete data and no error surfaces. Guardrail: Define a critical_fields list in the prompt schema and require the model to confirm each critical field is preserved before returning the truncated output. Add a critical_fields_preserved: boolean field to the output schema and fail closed when false.
Token Estimation Drift
What to watch: The model estimates its own output token count incorrectly, especially with non-English text, code blocks, or dense JSON. The budget check passes but the actual output exceeds the window, causing mid-response truncation by the model provider. Guardrail: Use a deterministic tokenizer (e.g., tiktoken) in the application layer to pre-compute the tool output size before the prompt runs. Pass the pre-computed token count as an input field so the model doesn't need to estimate.
Priority Inversion Under Pressure
What to watch: When the tool output is very large, the model keeps low-priority fields (verbose descriptions, debug logs) while dropping high-priority fields (status codes, identifiers, timestamps) because priority rules are ambiguous. Guardrail: Provide an explicit priority-ordered field list in the prompt with clear tie-breaking rules. Use a numbered priority schema (1 = must keep, 2 = keep if space, 3 = drop first) rather than prose descriptions of importance.
Summary Hallucination Replacing Real Data
What to watch: The model summarizes a truncated section instead of preserving the original fields, introducing plausible but incorrect values. A truncated error message becomes a generic "error occurred" summary that hides the actual failure mode. Guardrail: Require the model to mark each output field with a source tag: preserved (original value kept), truncated (original value shortened), or summarized (model-generated summary). Route summarized fields for human review or additional validation before downstream consumption.
Repeated Truncation Across Multi-Step Tool Calls
What to watch: An agent calls the same tool repeatedly, and each response is independently truncated. Cumulative information loss across steps causes the agent to miss patterns, correlations, or error trends that span multiple responses. Guardrail: Track truncation events in agent session state. When truncation occurs more than N times for the same tool in a session, escalate to a human operator or switch to a higher-context-window model variant. Include a truncation_count field in the session metadata.
Budget Check Bypass on Streaming Responses
What to watch: The tool returns a streaming response, and the budget check prompt only evaluates the first chunk or a partial buffer. The full response exceeds the window but the check passes because it never saw the complete output. Guardrail: Buffer streaming tool responses completely before running the budget check, or implement chunk-level budget tracking with a running token counter. If buffering isn't possible, set a conservative per-chunk budget and abort the stream when cumulative tokens exceed the threshold.
Evaluation Rubric
Use this rubric to evaluate the Tool Output Context Window Budget Check Prompt before production deployment. Each criterion targets a specific failure mode in budget estimation, truncation, or critical field preservation. Run these tests against a golden dataset of tool outputs with known sizes and priority annotations.
| Criterion | Pass Standard | Failure Signal | Test Method |
|---|---|---|---|
Size Estimation Accuracy | Estimated token count is within ±15% of actual token count for outputs under 32K tokens | Estimation error exceeds 15% on 3 or more samples in the test set, or systematic under-estimation leads to context overflow | Run prompt against 20 tool outputs of varying sizes (1K-32K tokens). Compare estimated tokens to tiktoken or equivalent tokenizer count. Calculate mean absolute percentage error. |
Critical Field Preservation | All fields marked with priority=critical in [OUTPUT_SCHEMA] appear in full in the truncated output | Any critical field is truncated, summarized, or omitted when the original output contained valid data for that field | Prepare 15 tool outputs where 3-5 fields are marked critical. Verify presence and completeness of each critical field in the truncated output using exact string match or structural comparison. |
Truncation Decision Correctness | Outputs under [BUDGET_LIMIT] are returned unmodified. Outputs over limit are truncated with a truncation notice | An output under budget is unnecessarily truncated, or an output over budget is returned without truncation or notice | Test with 10 outputs below budget and 10 above. Check for presence of truncation notice only on above-budget outputs. Verify below-budget outputs match original byte-for-byte. |
Summary Quality for Truncated Content | Summary of truncated portions preserves key entities, values, and relationships from removed sections | Summary omits a named entity, numeric value, or relationship present in the truncated portion that would change downstream agent decisions | For 10 truncated outputs, extract entities and key-value pairs from the removed portion. Verify each appears in the summary or is explicitly marked as omitted with reason. |
Budget Reporting Completeness | Response includes original_size, truncated_size, tokens_saved, and fields_retained fields with accurate values | Any required budget field is missing, null when it should have a value, or contains an inaccurate count | Parse JSON response from 20 test runs. Validate schema conformance for all budget fields. Cross-check original_size against tokenizer. Verify tokens_saved = original_size - truncated_size. |
Handling of Nested and Large Arrays | Large arrays are intelligently truncated with count of omitted items and preserved first/last N items as specified | Array is silently truncated without item count, or critical array elements are dropped while empty elements are retained | Test with outputs containing arrays of 100+ items. Verify truncation notice includes omitted_count. Check that first 3 and last 3 items are preserved when [RETENTION_STRATEGY] specifies edge preservation. |
Null and Empty Field Handling | Null or empty fields do not consume budget priority over populated fields. They are dropped first when budget is tight | Populated fields are dropped while null or empty fields are retained in the truncated output | Create test outputs with 40% null fields and budget at 60% of full size. Verify all retained fields contain data. Check that dropped fields are predominantly null or empty. |
Malformed or Non-JSON Input Resilience | Prompt returns a valid budget report with error flag when tool output is not parseable JSON | Prompt crashes, returns invalid JSON, or silently passes through malformed content without flagging the issue | Feed 5 malformed inputs: truncated JSON, plain text, binary-like strings, empty string, and deeply nested objects exceeding depth limits. Verify response is valid JSON with error field set to true and original_size estimated. |
Enabling Efficiency, Speed & Accuracy
Intelligent Analysis, Decision & Execution
We build AI systems for teams that need search across company data, workflow automation across tools, or AI features inside products and internal software.
Talk to Us
Search across company data
Give teams answers from docs, tickets, runbooks, and product data with sources and permissions.
Useful when people spend too long searching or get different answers from different systems.

Automate internal workflows
Use AI to route work, draft outputs, trigger actions, and keep approvals and logs in place.
Useful when repetitive work moves across multiple tools and teams.

Add AI to products and internal tools
Build assistants, guided actions, or decision support into the software your team or customers already use.
Useful when AI needs to be part of the product, not a separate tool.
Adapt This Prompt
How to adapt
Start with the base prompt and a simple truncation rule: if the tool output exceeds [MAX_TOKENS], keep the first [KEEP_FIRST_N] tokens and append a summary of the remainder. Use a lightweight token estimator (e.g., character count / 4) instead of a precise tokenizer.
code[SYSTEM] You are a context budget guard. When a tool response exceeds [MAX_TOKENS] estimated tokens: 1. Retain the first [KEEP_FIRST_N] tokens verbatim. 2. Summarize the remainder in ≤ [SUMMARY_MAX] tokens. 3. Return: { "truncated": true, "kept_tokens": [N], "summary": "[SUMMARY]", "original_estimate": [ESTIMATE] }
Watch for
- Character-based token estimates that drift 30-50% from actual token counts
- Critical fields in the truncated tail getting lost in the summary
- No priority-based field retention—everything after the cutoff is treated equally

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.
Partnered with leading AI, data, and software stack.
How We Work
Custom AI workflows for your Business
One-fit-all AI don't work for modern businesses. At Inferensys, we aim to understand your business & custom requirements; which we use to define most efficient agentic workflows, the data, and the tools for your business.
01
Review the use case
We understand the task, the users, and where AI can actually help.
Read more02
Pick the right approach
We define what needs search, automation, or product integration.
Read more03
Build the first useful version
We implement the part that proves the value first.
Read more04
Improve from there
We add the checks and visibility needed to keep it useful.
Read moreThe first call is a practical review of your use case and the right next step.
Talk to Us