This prompt is designed for production AI engineers and agent builders who need to reduce the token footprint of verbose tool outputs—such as raw API responses, search engine results pages, or large file reads—before they consume the context window. The core job-to-be-done is budget reclamation: preserving the actionable data, structured fields, and critical identifiers from a tool response while discarding boilerplate, HTML, redundant metadata, and low-signal prose. The ideal user is an engineering lead or developer integrating this compression step into an agent loop, a copilot's tool-call handler, or a RAG pipeline where tool outputs compete with conversation history and system instructions for limited context space.
Prompt
Tool Output Compression for Budget Reclamation Prompt

When to Use This Prompt
Defines the production job, target user, and operational constraints for compressing verbose tool outputs to reclaim context budget in agent and copilot systems.
You should use this prompt when your agent or copilot makes function calls that return payloads exceeding a few hundred tokens, especially when multiple tool calls occur in a single turn. It is particularly effective for compressing REST API responses, web_search results, database query outputs, and file read operations before they are injected into the model's next request. The prompt expects a raw tool output as [INPUT], an optional [OUTPUT_SCHEMA] describing the fields you need to preserve, and a set of [CONSTRAINTS] such as a target token limit or required fields. The output is a compressed, schema-preserving object that retains only essential information. This is not a summarization prompt for natural language understanding; it is a structured data compression step that must not hallucinate values, drop required identifiers, or alter numeric data.
Do not use this prompt when the tool output is already small, when the downstream task requires verbatim source text for citation or compliance, or when the compression step itself would introduce latency that outweighs the budget savings. It is also inappropriate for compressing user messages or system instructions—those require different preservation rules. Before deploying, wire the prompt into a validation harness that checks the compressed output against the original for field completeness, type consistency, and value preservation. For high-risk domains such as finance or healthcare, add a human review step or a secondary verification prompt that compares critical fields before the compressed output enters the agent's context. Start by measuring your current token consumption per tool call, then apply this prompt to outputs exceeding your budget threshold and monitor downstream task completion rates to confirm that compression is not degrading action correctness.
Use Case Fit
Where the Tool Output Compression prompt works, where it fails, and what inputs it assumes before you wire it into an agent loop.
Good Fit: Verbose API Responses
Use when: Tool outputs from search APIs, databases, or internal services return large payloads where only a subset of fields are actionable. Guardrail: Define a strict [OUTPUT_SCHEMA] so the model knows exactly which fields to preserve and which to drop.
Bad Fit: Unstructured Free Text
Avoid when: The tool output is a single block of unstructured prose (e.g., a legal memo or a creative draft) where summarization, not field extraction, is required. Risk: Compression will fragment narrative logic. Guardrail: Route to a dedicated summarization prompt instead.
Required Input: Structured Source + Target Schema
Risk: Without a clear [OUTPUT_SCHEMA], the model may hallucinate fields or drop critical data. Guardrail: Always provide both the raw tool output and a strict JSON schema or enumerated field list defining what to keep. Test with schema validation before the compressed output is used downstream.
Operational Risk: Silent Data Loss
Risk: Numeric values, enums, or nested objects can be subtly altered during compression, corrupting downstream actions. Guardrail: Implement a post-compression validator that checks field types, ranges, and required keys. Log compression diffs for auditability.
Bad Fit: Real-Time Binary Streams
Avoid when: The tool output is a binary stream, image, or audio buffer that cannot be represented as structured text. Risk: The prompt has no access to the raw bytes. Guardrail: Perform budget reclamation at the application layer by truncating or discarding non-textual payloads before they reach the model.
Operational Risk: Budget Overhead of Compression
Risk: For very small tool outputs, the compression instruction itself may consume more tokens than it saves. Guardrail: Implement a token-count gate in the application layer. Only invoke the compression prompt when the tool output exceeds a minimum size threshold.
Copy-Ready Prompt Template
A reusable prompt with square-bracket placeholders for compressing verbose tool outputs into schema-preserving, action-critical summaries.
This prompt template is the core instruction set for reclaiming context budget from verbose tool outputs. It is designed to be inserted into an agent or copilot harness immediately after a tool returns a response and before that response is appended to the conversation history. The prompt instructs the model to act as a lossy compression function: preserve the fields required for downstream decision-making and tool calls, discard explanatory fluff, and output a structured object that matches a predefined schema. Use this template when your agent's context window is dominated by large API payloads, search result pages, or multi-step function returns that contain far more text than actionable signal.
textYou are a tool output compressor for an AI agent system. Your task is to compress the provided tool output into a minimal, schema-preserving summary. You must preserve every field that could affect a downstream decision, tool call, or user-facing answer. You must discard explanatory text, markdown formatting, boilerplate, and any field that is not actionable. [OUTPUT_SCHEMA] [TOOL_OUTPUT] [COMPRESSION_RULES] Return ONLY the compressed output as valid JSON matching the schema above. Do not add commentary, markdown fences, or extra text. If a required field is missing from the tool output, set its value to null. If you are uncertain whether a field is actionable, retain it.
After copying the template, replace the three square-bracket placeholders with concrete values for your integration. [OUTPUT_SCHEMA] should contain a JSON Schema or TypeScript interface describing the exact shape you need downstream. [TOOL_OUTPUT] is the raw string returned by the tool, API, or function. [COMPRESSION_RULES] is where you encode domain-specific retention logic—for example, 'Retain all order IDs, status codes, and error messages. Drop product descriptions, timestamps older than 24 hours, and HTTP headers.' Adapt these rules per tool type. For high-stakes workflows such as financial transactions or clinical data, add a rule requiring the compressor to flag any field it drops that might be safety-relevant, and route those flags to a human reviewer before the compressed output is used downstream.
Prompt Variables
Required and optional inputs for the Tool Output Compression prompt. Each placeholder must be populated before the prompt is assembled and sent to the model. Validation notes describe how to verify the input is well-formed before incurring inference cost.
| Placeholder | Purpose | Example | Validation Notes |
|---|---|---|---|
[TOOL_OUTPUT] | The raw, verbose output from a tool call (API response, search results, function return) that needs compression. | {"results":[{"title":"...","snippet":"...","url":"...","metadata":{...}},...]} | Must be non-empty string or valid JSON. If null or empty, skip compression and return empty result. Parse check: valid JSON if structured output expected. |
[TOOL_NAME] | Identifier for the tool that produced the output, used to select the correct compression schema. | web_search | Must match a key in the compression schema registry. Schema check: verify [TOOL_NAME] exists in SCHEMA_MAP before invoking prompt. |
[COMPRESSION_SCHEMA] | A JSON Schema or field list defining which fields to preserve, rename, or drop. Drives the structure of the compressed output. | {"preserve":["title","url","snippet"],"max_items":5} | Must be valid JSON Schema or field array. Schema check: parse and validate structure. If missing, use default schema for [TOOL_NAME]. Null allowed if default exists. |
[MAX_OUTPUT_TOKENS] | Target maximum token count for the compressed output. The prompt will prioritize information density to fit this budget. | 512 | Must be positive integer. If null or 0, apply default budget from config. Range check: 64–4096 typical. Warn if below 32. |
[PRIORITY_HINT] | Optional natural language hint about what information is most critical to preserve, guiding the compression trade-offs. | Preserve error codes and stack traces; drop verbose descriptions. | Free text, null allowed. If provided, length should not exceed 200 characters to avoid consuming budget. Null check: skip priority guidance if null. |
[DOWNSTREAM_ACTION] | Description of how the compressed output will be used next, helping the model decide what is actionable versus noise. | The compressed output will be passed to a code-fixing agent that needs file paths and error messages. | Free text, null allowed. If provided, keep under 300 characters. Null check: if null, prompt uses generic actionability heuristics. |
[PREVIOUS_COMPRESSED_OUTPUTS] | Array of prior compressed outputs from the same tool in this session, used to deduplicate and avoid repeating information already seen. | [{"title":"Error X in module Y","file":"src/main.py"}] | Must be valid JSON array or null. Parse check: each element must conform to the same compression schema. Null allowed for first invocation. Length check: warn if array exceeds 20 items. |
Implementation Harness Notes
How to wire the Tool Output Compression prompt into an agent loop with pre-compression filtering, post-compression validation, and retry logic.
The Tool Output Compression prompt is not a standalone utility; it is a budget-reclamation step inside an agent execution loop. The harness must intercept verbose tool responses—API payloads, search result blobs, multi-page function returns—before they enter the main context window. The goal is to reduce token consumption while preserving the fields and values that downstream reasoning or tool-calling steps actually need. This means the harness owns three responsibilities: deciding when compression is triggered, validating that the compressed output is still actionable, and recovering when compression drops critical data.
Implement a pre-compression filter that checks the raw tool output size against a configurable threshold (e.g., 2,000 tokens). Outputs below the threshold bypass compression entirely to avoid unnecessary latency. For outputs above the threshold, extract the tool name, the output schema if available, and the downstream task context (e.g., 'the agent needs to decide the next function call' or 'the user needs a summary'). Pass these as [TOOL_NAME], [OUTPUT_SCHEMA], and [DOWNSTREAM_TASK] placeholders into the compression prompt. After compression, run a post-compression validator that checks: (1) the compressed output is valid JSON matching the expected schema, (2) required fields specified in [REQUIRED_FIELDS] are present and non-null, and (3) the compression ratio is within an acceptable range (e.g., 50–90% reduction). If validation fails, log the failure with the tool name, raw output length, compressed output length, and the specific validation error. Then trigger a retry with the same prompt but append the validation error as a [PREVIOUS_FAILURE] constraint.
Retry logic should be bounded. Set a maximum of two retry attempts. If both attempts fail validation, fall back to a safe truncation strategy: take the first N tokens of the raw output (where N is a conservative budget allocation) and attach a warning flag to the context object. The downstream agent or user-facing step can then decide whether to request the full output explicitly. Log all compression events—attempts, ratios, validation results, and fallback triggers—as structured telemetry so the team can tune thresholds, identify brittle tool outputs, and decide when to invest in tool-specific output schemas instead of relying on prompt-based compression. Do not use this prompt for outputs where field-level precision is legally or financially binding without human review of the compressed result.
Expected Output Contract
Defines the exact structure, types, and validation rules for the compressed tool output. Use this contract to parse the model's response and verify it before passing it downstream.
| Field or Element | Type or Format | Required | Validation Rule |
|---|---|---|---|
compressed_output | string | Must be valid stringified JSON. Parse check required. | |
compressed_output.summary | string | Must not be empty or null. Length must be less than [MAX_SUMMARY_LENGTH]. | |
compressed_output.key_actions | array of strings | Each element must be a non-empty string. Array must not be empty if the original output contained actionable data. | |
compressed_output.preserved_fields | object | Must be a valid JSON object. Keys must match the [FIELDS_TO_PRESERVE] list. No extra keys allowed. | |
compressed_output.dropped_fields | array of strings | Must list field names that were removed. Each name must have existed in the original [RAW_TOOL_OUTPUT]. | |
compressed_output.compression_ratio | number | Must be a float between 0.0 and 1.0. Calculated as compressed_size / original_size. | |
compressed_output.confidence | string | Must be one of the allowed enum values: 'high', 'medium', 'low'. Indicates preservation confidence. | |
compressed_output.original_schema_version | string | If present, must match the schema version of [RAW_TOOL_OUTPUT]. Null allowed if original had no version. |
Common Failure Modes
Tool output compression is a high-stakes operation. Removing the wrong field or collapsing a critical value can silently break downstream agent actions. These are the most common failure modes and how to prevent them.
Loss of Actionable Identifiers
What to watch: The compression prompt removes IDs, keys, or slugs that the agent needs for the next tool call, causing a 'not found' or silent null error. Guardrail: Define a required-fields allowlist in [OUTPUT_SCHEMA] and validate that every compressed output retains the exact identifiers present in the raw tool response.
Numeric Precision Truncation
What to watch: Floating-point values like prices, coordinates, or scores are rounded, truncated, or converted to strings, breaking downstream calculations or comparisons. Guardrail: Add a [CONSTRAINTS] block specifying 'Preserve all numeric fields with their original precision and data type. Do not round or abbreviate.'
Array Collapse Losing Order or Duplicates
What to watch: The model summarizes a list of items into prose or deduplicates entries that were intentionally repeated, destroying ranking, sequence, or frequency signals. Guardrail: Instruct the model to 'Retain array structures. Preserve original ordering and duplicate entries unless explicitly instructed to deduplicate.'
Boolean and Null Misrepresentation
What to watch: The model converts false to 'false' (string), drops null fields entirely, or misinterprets null as false, breaking strict schema validation. Guardrail: Post-process compressed JSON with a schema validator. Reject any output where null fields are missing or booleans are stringified.
Error and Status Code Omission
What to watch: The compression prompt treats error messages, HTTP status codes, or warning flags as verbose noise and removes them, causing the agent to proceed as if a failed tool call succeeded. Guardrail: Add a hard rule: 'Always preserve error codes, status fields, and error message text verbatim. These are never safe to compress or summarize.'
Schema Drift Under High Compression Ratio
What to watch: When the target compression ratio is aggressive, the model invents a new, flatter schema instead of preserving the original nested structure, breaking all downstream parsers. Guardrail: Provide the exact target JSON schema in [OUTPUT_SCHEMA] and use a strict validator in the harness. If validation fails, retry with a lower compression ratio.
Evaluation Rubric
Use this rubric to evaluate the quality of compressed tool outputs before deploying the Tool Output Compression for Budget Reclamation Prompt. Each criterion targets a specific failure mode in production.
| Criterion | Pass Standard | Failure Signal | Test Method |
|---|---|---|---|
Information Preservation Rate | All actionable fields from [ORIGINAL_TOOL_OUTPUT] are present in the compressed output with identical values. | A required field like an ID, status code, or URL is missing or altered. | Automated schema diff: compare key-value pairs between original and compressed JSON. Flag any missing required fields. |
Downstream Action Correctness | A downstream agent or function call using the compressed output completes successfully with the same result as using the original. | The agent selects the wrong tool, passes an invalid argument, or fails due to a missing parameter. | Integration test: run a representative agent task with the original output, then with the compressed output. Assert identical final action and status. |
Schema Preservation | The compressed output is valid JSON that conforms to the provided [OUTPUT_SCHEMA] without extra or malformed fields. | The output is not parseable JSON, contains a truncated string, or has a wrong data type for a field. | Schema validation: parse the output and validate against the [OUTPUT_SCHEMA] using a JSON Schema validator. Assert |
Compression Ratio | The compressed output is at least 50% smaller in token count than [ORIGINAL_TOOL_OUTPUT] while meeting the pass standard for Information Preservation. | The output is nearly the same length or trivially reformatted without meaningful reduction. | Token count check: use the model's tokenizer to count tokens for both original and compressed outputs. Calculate ratio. |
Hallucination Absence | No fact, value, or field is present in the compressed output that cannot be directly derived from [ORIGINAL_TOOL_OUTPUT]. | A summary statement, inferred status, or fabricated detail appears that was not in the original data. | Human review on a sample of 50 outputs: flag any assertion not explicitly supported by the source. Target 0% hallucination rate. |
Critical Detail Retention | High-signal fields specified in [CRITICAL_FIELDS] are always retained verbatim, even if they seem redundant. | A critical field like | Targeted unit test: create a test case where only the critical field is needed. Assert the field is present and character-for-character identical. |
Instruction Adherence Under Budget Pressure | When [TARGET_TOKEN_BUDGET] is extremely tight, the output omits low-priority fields gracefully without breaking the schema. | The model returns an error, a refusal, or a malformed truncation instead of a valid, minimal object. | Stress test: set [TARGET_TOKEN_BUDGET] to 20% of the original token count. Assert output is valid JSON and passes schema validation. |
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
Use the base prompt with lighter validation. Start with a single compression pass and a simple schema: {"compressed_output": "[COMPRESSED_TEXT]", "fields_preserved": ["[FIELD_NAMES]"], "compression_ratio": [NUMBER]}. Skip the multi-pass refinement and confidence scoring until you've validated the core compression behavior on 20-30 real tool outputs.
Watch for
- Missing schema checks causing downstream parse failures
- Overly aggressive compression that drops critical identifiers or error codes
- No baseline measurement of information preservation before iterating

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