Inferensys

Prompt

Output Truncation Recovery Prompt

A practical prompt playbook for using Output Truncation Recovery Prompt in production AI workflows.
Developer doing prompt engineering on laptop, prompt variations visible on screen, casual coding session.
PROMPT PLAYBOOK

When to Use This Prompt

Defines the production scenarios where truncation recovery is the right tool and when a full retry or human review is safer.

This playbook is for production engineers who receive an LLM response that has been cut off mid-structure by a max_tokens limit. The core job-to-be-done is to recover a valid, machine-readable payload from a partial output—such as a truncated JSON object, an unfinished code block, or a sentence broken mid-clause—without discarding the valuable computation already performed. The ideal user is an integration engineer or backend developer who owns a pipeline where a retry is either too expensive in terms of latency and cost, or where the partial output contains non-deterministic reasoning that would be lost on regeneration.

Use this prompt when the truncation point is close enough to the end of the structure that the model can infer a safe completion. For example, a JSON response missing only a closing brace and the final field value is a strong candidate. A code block missing its last line of a function is another. The prompt works by providing the model with the truncated text and explicit instructions to close the structure without inventing new substantive content. It is most effective when combined with a structural validator in your application harness: the repair is attempted, the result is parsed, and if it fails validation, the system falls back to a full retry or escalation. This pattern is particularly useful in streaming scenarios where you must flush an incomplete chunk to the client before the connection closes.

Do not use this prompt when the truncation point is so early that the model cannot reasonably infer the missing structure—for instance, if only the opening brace of a complex nested object has been emitted. In regulated domains such as healthcare or finance, where exactness is non-negotiable, a truncated output should trigger a full regeneration with a higher token limit or human review rather than an inferred completion. Similarly, if the partial output contains factual claims that are cut off, the repair prompt may hallucinate a plausible but incorrect ending. Always weigh the cost of a retry against the risk of a malformed or subtly incorrect completion reaching a downstream system. The next section provides the prompt template you can adapt and embed directly into your recovery harness.

PRACTICAL GUARDRAILS

Use Case Fit

Where this prompt works and where it does not. Use these cards to decide if the Output Truncation Recovery Prompt is the right tool for your production context.

01

Good Fit: Mid-Structure Cutoffs

Use when: The model output is truncated mid-JSON, mid-XML, or mid-code-block due to max_tokens limits. Guardrail: The prompt is designed to close open brackets, quotes, and fences. Always validate the repaired output against the original schema before ingestion.

02

Bad Fit: Semantic Incompleteness

Avoid when: The output is structurally complete but logically unfinished (e.g., a summary that stops mid-argument). Guardrail: This prompt repairs syntax, not semantics. Use a separate completeness evaluation step to detect and flag logically truncated content for a full regeneration.

03

Required Input: Partial Output Context

Use when: You can provide the raw, truncated string and the intended output format (JSON schema, XML DTD, or language identifier). Guardrail: The prompt's accuracy depends on the model recognizing the structural pattern. For highly nested or uncommon formats, include a complete example of the expected structure in the system prompt.

04

Operational Risk: Hallucinated Completion

Risk: The model may invent data to fill the repaired structure, especially for truncated lists or objects near the cutoff point. Guardrail: Always mark repaired sections with an explicit [AUTO-CLOSED] or similar marker. Downstream systems must treat auto-closed fields as potentially unreliable and trigger a human review or re-extraction.

05

Operational Risk: Cost Amplification

Risk: A naive retry loop can double token costs if every truncated output triggers a full regeneration instead of a targeted repair. Guardrail: Use this repair prompt only when the partial output is valuable and regeneration is expensive. Implement a cost gate: if prompt_tokens + completion_tokens exceeds a threshold, prefer a fresh, shorter request.

06

Bad Fit: Streaming Chunk Assembly

Avoid when: You are processing a real-time stream of delta chunks and the final message is not yet assembled. Guardrail: This prompt requires the full, static, truncated text block as input. For streaming, buffer chunks and apply the repair logic only after the stream ends or a timeout is reached, not on each intermediate delta.

PROMPT PLAYBOOK

Copy-Ready Prompt Template

A reusable few-shot prompt that teaches the model to recover from output truncation by safely closing structures and marking incomplete content.

This template provides a complete prompt for recovering from output truncation caused by max_token limits. It uses few-shot examples to demonstrate two distinct recovery strategies: safe structural closing (completing JSON objects, code blocks, or markdown fences) and explicit truncation markers (inserting [... truncated ...] tokens when safe completion is impossible). The prompt is designed to be dropped into a post-processing or retry pipeline where the partial output and the original generation context are available.

text
You are an output repair assistant. Your job is to take a partially generated response that was cut off due to token limits and produce a clean, usable version.

You have two repair strategies:
1. **Safe structural closing**: If the output is truncated mid-structure (JSON object, code block, markdown fence, XML tag, or list), close the structure correctly without inventing new content. Add only the minimal closing tokens needed.
2. **Explicit truncation marker**: If the output is truncated mid-sentence or mid-thought where structural closing is impossible, insert the marker `[... output truncated ...]` at the cutoff point and preserve all existing content exactly.

Rules:
- Never invent facts, values, or conclusions that were not present in the partial output.
- Never complete a sentence or thought that was cut off mid-expression.
- Preserve all existing content verbatim up to the truncation point.
- If the partial output ends inside a string value, close the string and the containing structure.
- If the partial output ends inside a code block, close the fence and any containing structure.
- If the partial output is plain text with no open structures, insert the truncation marker at the cutoff.

[EXAMPLES]

[INPUT]
Partial output: {"name": "Alice", "address": {"street": "123 Main St", "city": "Spring
Original prompt: Generate a JSON object with user details.
[/INPUT]

[OUTPUT]
{"name": "Alice", "address": {"street": "123 Main St", "city": "Spring[... output truncated ...]"}}
[/OUTPUT]

---

[INPUT]
Partial output: ```python
def calculate_total(items):
    total = 0
    for item in items:
        total += item["p
Original prompt: Write a Python function to calculate totals.
[/INPUT]

[OUTPUT]
```python
def calculate_total(items):
    total = 0
    for item in items:
        total += item["p[... output truncated ...]

[/OUTPUT]


[INPUT] Partial output: The three main factors to consider are: 1) cost efficiency, 2) scalability, and 3) maintainability. Cost efficiency involves analyzing Original prompt: Explain key factors for system design. [/INPUT]

[OUTPUT] The three main factors to consider are: 1) cost efficiency, 2) scalability, and 3) maintainability. Cost efficiency involves analyzing[... output truncated ...] [/OUTPUT]


[INPUT] Partial output: {"results": [{"id": 1, "score": 0.95}, {"id": 2, "score": 0. Original prompt: Generate a JSON array of scored results. [/INPUT]

[OUTPUT] {"results": [{"id": 1, "score": 0.95}, {"id": 2, "score": 0.[... output truncated ...]}]} [/OUTPUT]


Now repair the following partial output:

[INPUT] Partial output: [PARTIAL_OUTPUT] Original prompt: [ORIGINAL_PROMPT] [/INPUT]

[OUTPUT]

Adaptation guidance: Replace [PARTIAL_OUTPUT] with the truncated model response and [ORIGINAL_PROMPT] with the prompt that produced it. The [EXAMPLES] section can be extended with domain-specific truncation patterns relevant to your output format. For JSON-heavy workloads, add examples showing nested object closing, array completion, and string-escape preservation. For code generation, add examples covering multiple language syntaxes. The truncation marker [... output truncated ...] should be replaced with a token that your downstream parsers recognize and handle gracefully—consider using a unique sentinel like <<<TRUNC>>> if the default marker conflicts with your content domain.

What to do next: Test this prompt against a golden dataset of 20–30 real truncation cases from your production logs. Measure two metrics: structural validity (does the repaired output parse correctly?) and content preservation (is all original content present verbatim?). Watch for the failure mode where the model attempts to complete a truncated sentence instead of inserting the marker—this is the most common hallucination pattern. If you observe this, add a counterexample showing the correct marker insertion for that specific case. For high-stakes workflows where hallucinated completions could cause downstream errors, route outputs containing the truncation marker to a human review queue rather than silently consuming them.

IMPLEMENTATION TABLE

Prompt Variables

Required inputs for the Output Truncation Recovery Prompt. Each placeholder must be populated before the prompt is assembled and sent. Validation notes describe how to programmatically verify the input before execution.

PlaceholderPurposeExampleValidation Notes

[TRUNCATED_OUTPUT]

The partial, malformed model output that was cut off mid-generation due to token limits

{"users": [{"id": 1, "name": "Alice", "email": "alice@

Must be a non-empty string. Validate that the output ends mid-token, mid-field, or mid-structure rather than at a clean boundary. Check for trailing unclosed brackets, quotes, or code blocks.

[OUTPUT_FORMAT]

The intended complete format of the output (JSON schema, XML DTD, markdown structure, code language)

JSON object with array of user records containing id, name, email, role fields

Must be a non-empty string describing the target format. If a formal schema exists, validate that the schema itself is parseable and complete. For code, specify the language explicitly.

[TRUNCATION_POINT]

The exact character or token position where truncation occurred, or a description of what was being generated

Mid-email field value after 'alice@' with closing quote and bracket missing

Must be a non-empty string. Can be derived programmatically from the stop_reason or finish_reason in the API response. Validate that the described point matches the actual end of [TRUNCATED_OUTPUT].

[COMPLETION_STRATEGY]

The preferred recovery approach: structural-close, safe-truncate, mark-incomplete, or best-effort

structural-close

Must be one of the allowed enum values: structural-close, safe-truncate, mark-incomplete, best-effort. Validate against the closed set before prompt assembly. Default to structural-close if not specified.

[MAX_COMPLETION_TOKENS]

The token budget allocated for the recovery completion itself

256

Must be a positive integer. Validate that this value plus the token count of [TRUNCATED_OUTPUT] does not exceed the model's context limit. Set a reasonable default (128-512) based on output complexity.

[CONTEXT_HINTS]

Optional preceding context or the original prompt that produced the truncated output, used to ground the completion

Extract all users from the database export and return as JSON array

Can be null or empty string. If provided, validate that it does not contain sensitive or PII data that should not be re-sent. Keep under 500 tokens to avoid consuming recovery budget.

[HALLUCINATION_CONSTRAINT]

Explicit instruction weight for avoiding invented content during completion

Do not invent new fields, values, or records. Only close existing structures.

Must be a non-empty string. Default to a standard anti-hallucination constraint if not provided. Validate that the constraint is clear and actionable, not vague like 'be accurate'.

PROMPT PLAYBOOK

Implementation Harness Notes

How to wire the Output Truncation Recovery Prompt into a production application with validation, retries, and safe completion guards.

The Output Truncation Recovery Prompt is designed to be called as a post-processing repair step immediately after the primary model response is cut off by max_tokens or a context window limit. It should not be used as a standalone generation prompt. Instead, integrate it into your inference pipeline as a conditional recovery path: when the primary response ends without a valid closing token (e.g., unclosed JSON bracket, dangling sentence, incomplete code block), pass the partial output and the original generation context to this prompt for safe structural closure. The prompt's few-shot examples teach the model to distinguish between completable patterns (closing a known structure) and uncompletable patterns (mid-thought reasoning where any completion would be hallucination).

Harness integration steps: (1) Detect truncation by checking for parse failures, missing end delimiters, or token-count proximity to max_tokens. (2) Extract the last N tokens of the partial output (typically 200-500 tokens) plus the original [SYSTEM_INSTRUCTION] and [USER_QUERY] to provide full context. (3) Call the recovery prompt with these inputs and a strict [OUTPUT_SCHEMA] that requires either a completed_output field or an explicit truncation_marker with a completion_confidence score. (4) Validate the repaired output against the original expected schema before accepting it. (5) If completion_confidence is below your threshold (we recommend 0.7 for structured data, 0.5 for prose), discard the repair and either increase max_tokens on retry or return the partial output with an explicit truncation warning to the user. Model choice: Use the same model that produced the original output to avoid distribution mismatch. For cost-sensitive pipelines, a smaller model can handle structural closing (JSON, XML) while prose completion benefits from the original model's capabilities.

Failure modes to monitor: The most dangerous failure is the model hallucinating a plausible ending that contradicts the user's intent or the source evidence. Log every recovery attempt with the original partial output, the completed output, and the confidence score. Implement a human review queue for high-risk domains (legal, medical, financial) where any completion confidence below 0.9 triggers manual inspection. For code generation, never execute repaired code without syntax validation and a sandboxed test run. What to avoid: Do not use this prompt as a general-purpose output extender—it is specifically tuned for recovery from token-limit truncation, not for expanding short answers or adding detail. Do not chain multiple recovery calls; if the first repair fails validation, escalate to a higher token budget or human review rather than retrying the repair prompt.

IMPLEMENTATION TABLE

Expected Output Contract

Defines the fields, format, and validation rules for the output of the Output Truncation Recovery Prompt. Use this contract to programmatically validate the model's completion before accepting it into your application.

Field or ElementType or FormatRequiredValidation Rule

completion

String

Must be a non-empty string that logically continues from the provided [PARTIAL_OUTPUT]. A null or empty string is a failure signal.

truncation_marker

String

If present, must exactly match the [TRUNCATION_MARKER] value provided in the prompt input. Validate with a strict string equality check.

completion_strategy

String

Must be one of the allowed enum values: 'structural_close', 'safe_stop', 'explicit_marker'. Any other value fails schema validation.

confidence_score

Number

If present, must be a float between 0.0 and 1.0 inclusive. A score below the [CONFIDENCE_THRESHOLD] should trigger a retry or human review.

hallucination_warning

Boolean

If true, the output must be flagged for human review. The presence of this field with a true value overrides any automated acceptance logic.

closed_structures

Array of Strings

If completion_strategy is 'structural_close', this field is required. Each string must be a valid closing token sequence (e.g., '}]', '</xml>', '```'). Validate by checking for balanced open/close pairs against [PARTIAL_OUTPUT].

rationale

String

A brief explanation of the chosen strategy. If present, its length must not exceed 200 characters to prevent verbose justifications from consuming the output token budget.

PRACTICAL GUARDRAILS

Common Failure Modes

Output truncation breaks structured data, mid-sentence cutoffs, and incomplete code blocks. These cards cover what fails first and how to recover safely without introducing hallucinated completions.

01

Mid-JSON Structural Collapse

What to watch: Truncation cuts JSON mid-object, leaving unclosed braces, partial key-value pairs, or dangling arrays. Downstream parsers reject the entire payload. Guardrail: Implement a structural closer that parses the partial JSON, identifies the last valid complete path, and safely closes remaining brackets. Add an explicit "truncated": true marker before closing to signal incompleteness to consumers.

02

Mid-Sentence Semantic Hallucination

What to watch: When truncation occurs mid-sentence, naive completion strategies invent plausible endings that contradict the model's intended output or source evidence. Guardrail: Never auto-complete mid-sentence text. Instead, append a [TRUNCATED] token at the exact cutoff point and return the partial output with a finish_reason: "length" flag. Let downstream logic decide whether to request continuation or accept the fragment.

03

Unclosed Code Block Corruption

What to watch: Truncation inside fenced code blocks leaves unclosed triple backticks, causing markdown parsers to swallow subsequent content or misrender the entire response. Guardrail: Scan for unclosed fences in the truncated output. If detected, close the fence immediately after the last complete line and add a comment marker like # -- output truncated -- inside the code block before the closing fence.

04

Continuation Prompt Context Loss

What to watch: When requesting continuation with a follow-up prompt, the model loses the original context window and may contradict earlier output, repeat content, or shift tone. Guardrail: Include the last 2-3 complete sentences or the last valid structural boundary from the truncated output as a prefix in the continuation prompt. Explicitly instruct: 'Continue exactly from this point. Do not repeat or summarize prior content.'

05

Token Budget Exhaustion Without Warning

What to watch: The model hits max_tokens silently, and the application layer assumes the output is complete. This produces partial records that pass initial validation but contain missing fields or incomplete reasoning. Guardrail: Always check finish_reason in the API response. If finish_reason === "length", flag the output as incomplete before any downstream processing. Log truncation events with the output length and token budget for monitoring.

06

Partial Tool Call Argument Corruption

What to watch: Truncation inside a function call argument JSON breaks the tool invocation entirely, causing the agent to fail silently or retry with corrupted state. Guardrail: Validate tool call arguments against the function schema before execution. If the arguments JSON is malformed due to truncation, discard the partial call, log the failure with the raw truncated payload, and either request a continuation or fall back to a safe default action with human escalation.

IMPLEMENTATION TABLE

Evaluation Rubric

Criteria for evaluating the safety and correctness of an output truncation recovery prompt. Use this rubric to test whether the model completes partial outputs without introducing hallucinated content or breaking structural integrity.

CriterionPass StandardFailure SignalTest Method

Structural Closure

Output closes all open JSON brackets, XML tags, or code blocks without introducing new data.

Output leaves a bracket, tag, or fence unclosed; or adds a new, unsupported key.

Parse the completed output with a strict parser. Check for trailing commas or unclosed delimiters.

Content Hallucination

The model adds no new factual claims, values, or list items beyond what is inferable from the partial output.

The completed output contains a new name, number, or sentence not present in the truncated prefix.

Diff the truncated input against the completed output. Flag any added noun phrases or numeric values.

Truncation Marker Insertion

An explicit [TRUNCATED] marker is placed at the exact cutoff point before any completion logic.

The marker is missing, placed at the wrong position, or replaced with a generic ellipsis.

Use a regex check for the exact marker string at the boundary between the original prefix and new tokens.

Safe Code Completion

For code blocks, the model closes the block without generating new executable logic or fixing the user's code.

The model adds a new function body, changes a variable, or inserts a comment that alters intent.

AST-diff the completed code against the prefix. Fail if any new statement or expression node is added.

JSON Value Neutrality

For partial JSON values, the model uses null or the placeholder "..." instead of guessing a value.

The model inserts a plausible but ungrounded string, number, or boolean.

Schema-validate the output. Fail if a required field contains a non-null, non-placeholder value not in the prefix.

List Truncation Safety

For a partial list, the model closes the array without adding new elements.

The model adds one or more new list items, even if they look like continuations.

Count the array length in the prefix vs. the completed output. Fail if the count increases.

Sentence Boundary Respect

For mid-sentence text, the model completes only to the nearest word boundary and stops.

The model finishes the sentence or paragraph with invented content.

Token-diff the output. Fail if more than 3 new tokens are added after the last complete word in the prefix.

Refusal on Ambiguity

If the prefix is too ambiguous to close safely, the model returns the prefix unchanged with a warning.

The model attempts a risky structural close or hallucinates a completion.

Provide a prefix ending mid-key. Check that the output is identical to the input plus a refusal note.

ADAPTATION OPTIONS

Adapt This Prompt

How to adapt

Start with the base prompt and a single completion example showing safe structural closing. Use max_tokens limits intentionally to trigger truncation during testing. Keep the prompt simple: show the truncated output, ask the model to complete it, and provide one example of correct recovery.

Prompt snippet

code
You received a truncated output. Complete it safely.

Truncated output:
[TRUNCATED_OUTPUT]

Example recovery:
Input: {"users": [{"id": 1, "name": "Alice"}, {"id": 2
Output: {"users": [{"id": 1, "name": "Alice"}, {"id": 2, "name": "UNKNOWN"}]} // Closed safely with placeholder

Now recover:

Watch for

  • Model hallucinating plausible but incorrect completions
  • No validation of structural correctness after recovery
  • Overly aggressive completion that invents data instead of marking truncation
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.