This prompt is for AI engineers and platform developers who are building systems where large language models consume tool outputs that can exceed the model's context window. The core job-to-be-done is to produce a prioritized, loss-aware summary of a truncated tool result so the model can still generate a useful response without hallucinating missing information. The ideal user is someone integrating APIs, databases, or search systems where payload sizes are unpredictable and truncation is a runtime reality, not a design choice. Required context includes the raw truncated output, the user's original request, and any known truncation metadata such as byte limits or record counts.
Prompt
Tool Output Truncation Handling Prompt Template

When to Use This Prompt
Define the job, ideal user, and constraints for handling truncated tool outputs before they cause silent information loss in production.
Use this prompt when you cannot guarantee that tool outputs will fit within the model's context budget and you need a structured fallback that explicitly marks what was lost. This is common with log analysis tools, large database result sets, verbose API responses, or document retrieval systems returning hundreds of chunks. Do not use this prompt when you can implement application-layer pagination, streaming, or chunking that avoids truncation entirely. If the tool output is small enough to fit in context, prefer direct summarization without the overhead of truncation-aware instructions. Also avoid this prompt when the truncation point cuts through critical structured data like JSON objects or CSV rows, as the model may not be able to reconstruct partial records reliably.
Before deploying this prompt, instrument your tool-calling layer to detect truncation signals: HTTP 206 responses, truncated flags in API metadata, or context-window overflow events from your model gateway. The prompt works best when it receives explicit truncation metadata alongside the raw output. If your system silently truncates without signaling, the model cannot reliably distinguish between a complete result and a partial one. Pair this prompt with an eval harness that checks for critical information loss by comparing the summary against the full output in pre-production tests. In high-risk domains like healthcare or finance, always route truncated results through human review before the summary reaches end users.
Use Case Fit
Where this prompt works and where it does not. Use these cards to decide if the Tool Output Truncation Handling Prompt Template fits your production scenario.
Good Fit: Large, Unpredictable Tool Outputs
Use when: your tool returns payloads that frequently exceed the model's context window, such as verbose API responses, large log files, or extensive database query results. Guardrail: The prompt is designed to prioritize and summarize, preserving the most salient information first.
Bad Fit: Strict Schema Preservation
Avoid when: you need a byte-for-byte copy of the original tool output or must preserve a strict, nested JSON schema without any transformation. Guardrail: Use a direct passthrough or a structured output extraction prompt instead; this template is for lossy summarization.
Required Input: Raw Truncated Output
What to watch: The prompt requires the raw, truncated tool output and the original user query to function. Without both, it cannot determine what is salient. Guardrail: Always pass the full available output, even if truncated, and the user's original intent as separate, clearly labeled variables.
Operational Risk: Silent Critical Data Loss
What to watch: The summarization process may drop a critical field, error code, or identifier that is essential for the next step in a workflow. Guardrail: Implement an eval check that verifies the presence of known critical keys or patterns in the summary before it is passed to the next tool or user.
Operational Risk: Misleading Completeness
What to watch: The summary may sound so coherent that a user or downstream agent assumes it represents the complete output, missing the fact that data was truncated. Guardrail: The prompt must be configured to explicitly mark what was omitted and state the truncation boundary in the final response.
Bad Fit: Real-Time Streaming Data
Avoid when: you are processing a continuous stream of data where the concept of a single, truncated output doesn't apply. Guardrail: For streaming, use a windowing or incremental processing pattern. This prompt is designed for a single, static, oversized payload.
Copy-Ready Prompt Template
A reusable prompt template for summarizing truncated tool outputs while preserving critical information and marking what was lost.
This prompt template handles the common production scenario where a tool returns more data than the model's context window can accept. Instead of silently dropping information or hallucinating missing details, the prompt instructs the model to produce a prioritized summary that explicitly marks truncation boundaries and flags potentially critical omissions. The template is designed to be dropped into an existing tool-calling pipeline where the application layer has already detected that the raw tool output exceeds the available token budget and has performed initial truncation before passing the remainder to the model.
textYou are processing a truncated tool output. The original result from [TOOL_NAME] exceeded the available context window and was cut to fit. Your job is to produce a useful summary without pretending you saw the full output. ## INPUT [TRUNCATED_TOOL_OUTPUT] ## CONSTRAINTS - Never fabricate data, values, or records that are not present in the truncated output. - Do not imply completeness. If the output was cut mid-record, mid-list, or mid-field, state that explicitly. - Prioritize information by [PRIORITY_CRITERIA] when deciding what to include in the summary. - If the truncation point falls inside a critical section (as defined by [CRITICAL_SECTION_RULES]), flag it as high-severity. ## OUTPUT_SCHEMA Return a JSON object with the following fields: - "summary": string (the prioritized summary of what was retrieved) - "truncation_point": string (description of where the output was cut, e.g., "after record 47 of an estimated 200", "mid-JSON object in the 'items' array") - "missing_information": string[] (list of specific data categories, fields, or record ranges known to be missing) - "critical_omission_risk": "high" | "medium" | "low" (likelihood that truncated content contains decision-critical information) - "recommended_action": string (whether to re-query with narrower parameters, paginate, or proceed with available data) ## EXAMPLES [FEW_SHOT_EXAMPLES] ## RISK_LEVEL [RISK_LEVEL]
Adapt this template by replacing the square-bracket placeholders with your specific tool context. [PRIORITY_CRITERIA] should encode what matters most for your use case—for example, recency, severity, monetary value, or user-specified filters. [CRITICAL_SECTION_RULES] defines which parts of the output are too important to lose mid-stream, such as safety alerts, compliance fields, or primary key columns. [FEW_SHOT_EXAMPLES] should include at least one example where truncation occurred in a high-risk section and one where it occurred in a low-risk section, so the model learns to calibrate the critical_omission_risk field. Set [RISK_LEVEL] to "high" if the tool output contains regulated, financial, clinical, or safety-significant data, and ensure the downstream application routes high-risk summaries for human review before any action is taken.
Prompt Variables
Required inputs for the Tool Output Truncation Handling Prompt Template. Each placeholder must be populated before the prompt is assembled and sent to the model.
| Placeholder | Purpose | Example | Validation Notes |
|---|---|---|---|
[TOOL_OUTPUT] | The raw, truncated tool output that the model must summarize | {"results": [{"id": 1, "name": "Acme Corp"}, {"id": 2, "name": "Beta Inc"}], "truncated": true, "total_results": 2450, "returned_results": 2} | Must be a non-empty string or JSON object. Validate that the input contains a truncation indicator or that the caller has explicitly marked it as truncated before passing to the prompt. |
[TRUNCATION_REASON] | The cause of truncation so the model can explain it to the user | Context window limit exceeded after 128K tokens | Must be one of: context_window, token_limit, pagination_limit, rate_limit, timeout, or user_requested. Reject unknown values. |
[ORIGINAL_QUERY] | The user's original request that triggered the tool call, used to prioritize what to preserve | Find all customers in the West region with active subscriptions and their last purchase date | Must be a non-empty string. If the original query is unavailable, set to null and the prompt will fall back to generic prioritization. |
[PRIORITY_FIELDS] | An ordered list of fields or data categories that matter most for the user's task | ["customer_name", "subscription_status", "last_purchase_date", "annual_revenue"] | Must be a valid JSON array of strings. If empty or null, the model will apply default salience heuristics. Validate that field names match the tool output schema. |
[MAX_OUTPUT_TOKENS] | The token budget for the model's summary response | 2048 | Must be a positive integer. Should be less than the model's max output tokens minus safety margin. Reject values below 256 for this use case. |
[TRUNCATION_MARKER_FIELD] | The exact field name in the tool output that signals truncation occurred | truncated | Must be a string matching a key in the tool output JSON. If the tool output uses a different convention, map it here. Validate presence of this field before calling the prompt. |
[TOTAL_COUNT_FIELD] | The field name indicating how many total results exist before truncation | total_results | Must be a string matching a key in the tool output JSON. Required for the model to accurately report what fraction of results were returned. Validate that the value is a non-negative integer. |
[RETURNED_COUNT_FIELD] | The field name indicating how many results were actually returned | returned_results | Must be a string matching a key in the tool output JSON. Required for the model to state how many records it can see. Validate that the value is less than or equal to [TOTAL_COUNT_FIELD]. |
Implementation Harness Notes
How to wire the truncation handling prompt into a production application with validation, retries, and safety checks.
Integrating the Tool Output Truncation Handling Prompt into a production system requires more than copying the template. The harness must detect truncation before the prompt runs, manage context-window limits, validate the summary output, and decide whether the result is safe to show to a user or feed into a downstream agent. This section covers the application-layer scaffolding that makes the prompt reliable under real load, including pre-processing checks, model selection, output validation, retry logic, and logging for auditability.
Pre-processing and truncation detection. Before the prompt is assembled, the application must determine whether the raw tool output actually exceeds the available context budget. Implement a token-counting step using the target model's tokenizer (e.g., tiktoken for OpenAI models or the Anthropic token-counting API). Compare the tool output token count against the remaining context window after accounting for the system prompt, conversation history, and the truncation-handling prompt template itself. If the output fits comfortably, skip the truncation prompt and pass the full result to the standard summarization path. If it exceeds the budget, inject the raw output into the [FULL_TOOL_OUTPUT] placeholder and set [AVAILABLE_TOKEN_BUDGET] to the remaining capacity. For multi-turn applications, recalculate the budget on each turn, as prior messages consume tokens. Model choice: Prefer models with large context windows (e.g., GPT-4 Turbo, Claude 3 Opus) for the truncation prompt itself, since the prompt must ingest a large output and produce a structured summary. If using a smaller model for cost reasons, apply an aggressive pre-truncation step that keeps only the first N characters and last M characters of the tool output before passing it to the prompt, and log a warning that mid-output data may be lost.
Output validation and schema enforcement. The prompt template requests a JSON output with summary, truncated_sections, preserved_key_facts, and confidence fields. The harness must validate that the model returns parseable JSON matching this schema. Use a strict JSON schema validator (e.g., jsonschema in Python, zod in TypeScript) to check required fields, types, and value ranges. If truncated is true but truncated_sections is empty, flag the response for review. If confidence is below a configurable threshold (e.g., 0.7), route the output to a human reviewer or a secondary model for verification. Retry and fallback logic: If the model returns malformed JSON, retry up to two times with an error message appended to the prompt (e.g., "Your previous response was not valid JSON. Return ONLY the JSON object."). If retries are exhausted, fall back to a simpler truncation strategy: return the first N characters of the tool output with a generic truncation notice, and log the failure for investigation. Never pass a raw, unsummarized tool output to the user if it exceeds the display or context budget.
Logging, observability, and audit. Every truncation event should produce a structured log record containing: the original tool output token count, the available budget, the model used, the generated summary, the confidence score, whether validation passed, and any retry attempts. This log is essential for debugging cases where critical information was lost. For high-risk domains (healthcare, finance, legal), require human review of any truncation summary where confidence < 0.9 or where preserved_key_facts is empty. Wire the truncation prompt into your existing observability stack so that truncation frequency, confidence distributions, and validation failure rates are visible on dashboards. What to avoid: Do not silently truncate tool outputs without logging. Do not assume the model's summary is complete—always cross-check that preserved_key_facts contains the fields your downstream workflow requires. Do not use the truncation prompt as a substitute for proper pagination or result filtering at the tool level; it is a safety net, not a primary data management strategy.
Expected Output Contract
Defines the required fields, types, and validation rules for the structured output produced by the Tool Output Truncation Handling prompt. Use this contract to build a post-processing validator.
| Field or Element | Type or Format | Required | Validation Rule |
|---|---|---|---|
truncation_detected | boolean | Must be true if the input [TOOL_OUTPUT] was truncated, otherwise false. Check against a known truncation flag from the harness. | |
truncation_summary | string | If truncation_detected is true, this field must be a non-empty string explaining what was truncated. If false, it must be an empty string. | |
prioritized_summary | string | Must be a non-empty string. If truncation_detected is true, it must contain only information present in the provided [TOOL_OUTPUT] fragment. No hallucinated details. | |
critical_information_preserved | boolean | Must be true if all items from a pre-defined [CRITICAL_KEYS] list are present in the prioritized_summary. Must be false otherwise. Evaluated by a keyword or embedding check. | |
missing_information_acknowledgement | string | If critical_information_preserved is false, this must be a non-empty string listing the missing critical keys. If true, it must be an empty string. | |
suggested_follow_up | string or null | If the summary is incomplete, this should be a string suggesting a specific, actionable follow-up query or tool call. Must be null if no follow-up is needed. | |
confidence_score | number | A float between 0.0 and 1.0 representing the model's confidence that the prioritized_summary is complete and accurate. Must be >= 0.0 and <= 1.0. |
Common Failure Modes
Tool output truncation breaks summarization by hiding critical information. These failure modes help you detect, prevent, and recover from truncation before it reaches users.
Silent Mid-Field Truncation
What to watch: The context window cuts a tool output in the middle of a critical field, such as a transaction amount, medical value, or legal clause. The model summarizes partial data as if it were complete, producing dangerously wrong conclusions. Guardrail: Add a truncation marker instruction that requires the model to check for incomplete final records and flag them. Validate output with a completeness check that compares expected field count against received fields.
Priority Inversion Under Token Pressure
What to watch: When the context window fills, the model summarizes chronologically rather than by importance, burying the most critical information in the truncated tail. A financial audit summary might omit the largest anomaly because it appeared last in the tool output. Guardrail: Instruct the model to extract and rank key findings before summarization, placing high-priority items first regardless of original order. Use a priority schema that defines what counts as critical per domain.
Truncation Boundary Hallucination
What to watch: The model invents plausible endings for truncated records, such as completing a partial address, guessing a missing diagnosis, or fabricating a conclusion that the full output would have contradicted. Guardrail: Require the model to mark truncated sections with an explicit [TRUNCATED] token and abstain from completing partial records. Add an eval that checks for claims not present in the provided output prefix.
Missing Truncation Disclosure
What to watch: The model produces a confident, fluent summary without indicating that data was truncated, leaving users unaware that their decision rests on incomplete information. Guardrail: Make truncation disclosure a required output field in the schema. If the model cannot confirm completeness, it must emit truncation_status: "partial" with an estimated coverage percentage and a list of missing sections.
Repeated Field Omission Across Pages
What to watch: When paginated results are concatenated, the model drops the same field from every page—such as a timestamp or ID column—because it appears redundant. The summary loses temporal ordering or record identity. Guardrail: Define a required-fields list in the prompt that must survive summarization. Validate output by checking that every required field appears at least once per logical record in the summary.
Context Budget Exhaustion Without Fallback
What to watch: The model runs out of context window before processing all tool outputs and silently drops the remainder, with no fallback strategy for the uncovered data. Guardrail: Implement a pre-flight token budget check. If the combined tool outputs exceed a safe threshold, split into chunks, summarize each independently, and then synthesize a meta-summary. Log a warning when chunking is triggered so operators can tune retrieval limits.
Evaluation Rubric
Use this rubric to test whether the truncation-handling prompt preserves critical information, marks gaps transparently, and avoids hallucination before shipping to production.
| Criterion | Pass Standard | Failure Signal | Test Method |
|---|---|---|---|
Critical information preservation | All key entities, values, and conclusions from the non-truncated portion are present in the summary | A fact present in the provided output prefix is missing from the summary | Diff extracted claims against a manually verified list from the first N tokens of the tool output |
Truncation transparency | Summary explicitly states that output was truncated and identifies what is missing | Summary reads as complete with no mention of truncation or missing data | Scan summary for truncation keywords; assert presence of truncation notice when [TRUNCATED] flag is true |
Hallucination rate | Zero claims unsupported by the provided output prefix | Summary includes a specific value, name, or conclusion not present in the provided output | Extract all factual claims; cross-reference each against the provided tool output prefix using substring or entity match |
Priority ordering | Most salient information appears first; low-priority or boilerplate content is deferred or omitted | A critical finding is buried after verbose metadata or boilerplate | Rank claims by domain-defined priority; assert that top-K priority claims appear in the first half of the summary |
No fabricated completeness | Summary does not imply the full result was seen when it was truncated | Phrases like 'the full report shows' or 'all results indicate' appear when output was truncated | Regex check for completeness-implying phrases; fail if [TRUNCATED] is true and any match is found |
Token budget compliance | Summary stays within the specified [MAX_OUTPUT_TOKENS] limit | Summary exceeds the token budget by more than 5% | Tokenize summary output; assert token count <= [MAX_OUTPUT_TOKENS] * 1.05 |
Truncation boundary handling | Does not invent a conclusion for a sentence or record cut off mid-stream | Summary completes a partial record or sentence that was truncated in the input | Identify the last complete record in the tool output; assert no claims derive from data beyond that boundary |
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 truncation prompt and a simple character-count or token-count cutoff. Use a lightweight [TRUNCATED_OUTPUT] placeholder and ask the model to mark missing sections with [TRUNCATED] tags. Skip formal eval harnesses initially; rely on spot-checking a few large tool outputs.
codeYou received a tool output that was truncated due to length limits. Original output (truncated): [TRUNCATED_OUTPUT] Truncation point: approximately [CUTOFF_POINT] tokens. Summarize the most important information, and mark any claims you cannot verify with [TRUNCATED].
Watch for
- Model inventing content beyond the truncation point without marking it
- No distinction between "summarized from visible content" and "guessed"
- Overly verbose summaries that waste context window on low-signal content

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