Inferensys

Prompt

Streaming Output Truncation Detection and Repair Prompt Template

A practical prompt playbook for detecting mid-stream cutoffs from token limits or connection drops and repairing outputs to a valid partial state 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

Identify the right conditions for deploying the streaming truncation detection and repair prompt, and recognize when a different approach is required.

This prompt is designed for API developers and streaming infrastructure engineers who need to recover from mid-stream output cutoffs caused by token limits, connection drops, or model early-stopping. The primary job is to detect incomplete sentences, unclosed structured fields (like JSON braces or XML tags), or truncated code blocks in a partial payload, and then either request a precise continuation or repair the output into a valid partial state that downstream parsers can handle without crashing. Use this when your application consumes streaming LLM responses and you cannot afford to discard partially delivered work—such as in real-time user interfaces, log processors, or agent execution traces where losing context mid-stream creates a broken user experience or corrupts a database record.

The prompt works best when you have access to the raw truncated text and the expected output schema or format contract. For example, if your system expects a complete JSON object with required fields, the prompt can identify that a closing brace is missing and the "summary" field was cut off after 12 characters, then either generate the missing fragment or produce a valid partial object with a "truncated": true flag. It is less effective when the truncation point is ambiguous—such as when a model stops mid-word in a free-text narrative with no structural markers—or when the missing content is semantically critical and cannot be safely inferred. In those cases, requesting a continuation from the original model with the truncated text as context is more reliable than attempting repair.

Do not use this prompt as a substitute for proper token budgeting, max_tokens configuration, or streaming buffer management. If you routinely hit token limits, fix the root cause by reducing context size, implementing prompt compression, or splitting work into smaller chunks. This prompt is a safety net, not a primary strategy. Additionally, avoid using it for outputs where truncation could introduce safety or compliance risks—such as incomplete medical instructions, partial legal clauses, or financial figures—without mandatory human review of the repaired output. For high-stakes domains, flag truncated outputs for escalation rather than attempting automated repair.

PRACTICAL GUARDRAILS

Use Case Fit

Where the Streaming Output Truncation Detection and Repair prompt works, where it breaks, and what you must have in place before relying on it in production.

01

Good Fit: Token Limit Cutoffs

Use when: the model stops mid-sentence or mid-structure because it hit max_tokens. The prompt can detect the truncation point and either request continuation or repair the partial output to a valid state. Guardrail: always log the finish_reason from the API response to confirm the cause before triggering repair.

02

Good Fit: Streaming Connection Drops

Use when: a network interruption or server-side timeout terminates the SSE stream before the complete response arrives. The prompt can reassemble received chunks and identify what's missing. Guardrail: implement a client-side buffer that retains all received chunks with sequence numbers for accurate reassembly before invoking repair.

03

Bad Fit: Semantic Incompleteness Without Structural Break

Avoid when: the output is structurally complete but logically unfinished—the model stopped writing but closed all brackets and ended with a period. Truncation detection looks for structural breaks, not conceptual gaps. Guardrail: pair this prompt with a separate completeness evaluator that checks for logical closure, not just syntax.

04

Required Input: Finish Reason and Raw Chunks

What you need: the API's finish_reason field (e.g., length, stop, content_filter), the raw accumulated output, and the expected output schema or structure. Without the finish reason, you cannot distinguish truncation from intentional stopping. Guardrail: never trigger repair without confirming the stop reason first.

05

Operational Risk: Repair Loop Amplification

Risk: a failed repair triggers another model call, which may also truncate, creating a costly repair loop. Guardrail: cap repair attempts at 2 retries, increase max_tokens on continuation requests, and set a total token budget for the repair workflow. Escalate to human review or graceful degradation after the cap.

06

Bad Fit: Real-Time User-Facing Streams Under 200ms Latency

Avoid when: you need sub-200ms time-to-first-token and cannot afford a secondary repair call before rendering. Detection and repair add latency. Guardrail: for real-time UX, render partial output immediately with a loading indicator, run repair asynchronously, and patch the UI when the corrected output arrives.

PROMPT PLAYBOOK

Copy-Ready Prompt Template

A reusable prompt template with square-bracket placeholders for detecting and repairing truncated streaming outputs.

This template provides a ready-to-use prompt for detecting truncation in streaming LLM outputs and either requesting continuation or repairing the output to a valid partial state. It is designed to be called after a stream has ended unexpectedly—due to token limits, connection drops, or model early-stopping—and the raw output fails completeness checks. The prompt accepts the partial output, the expected schema or structure, and the stream's termination reason, then returns a structured assessment and repair action.

text
You are an output repair agent for a streaming LLM system. Your job is to analyze a partial output that was cut off mid-stream and determine whether it can be repaired to a valid partial state or requires continuation.

## INPUT
- Partial Output: [PARTIAL_OUTPUT]
- Expected Output Schema or Structure Description: [OUTPUT_SCHEMA]
- Stream Termination Reason: [TERMINATION_REASON]
- Maximum Continuation Tokens Available: [MAX_TOKENS]

## TASK
1. Analyze the partial output for truncation indicators:
   - Incomplete sentences or paragraphs
   - Unclosed JSON objects, arrays, or strings
   - Unclosed XML tags or markdown blocks
   - Missing required fields per the expected schema
   - Trailing content that appears cut off mid-token

2. Classify the truncation severity:
   - `repairable`: The output can be closed to a valid partial state without adding new substantive content
   - `continuable`: The output requires additional generation to reach a valid stopping point
   - `unrecoverable`: The output is too corrupted to repair or continue meaningfully

3. If `repairable`, produce the repaired output by:
   - Closing unclosed structures (JSON braces, XML tags, code fences)
   - Truncating incomplete sentences at the last complete sentence boundary
   - Marking missing required fields as `null` with a `_truncated: true` annotation
   - Preserving all valid content without modification

4. If `continuable`, produce a continuation request that:
   - Specifies the exact text to continue from (last 50-100 characters of partial output)
   - Describes what structure or content must be completed
   - Includes any constraints to prevent repetition or hallucination

5. If `unrecoverable`, explain why and recommend fallback behavior.

## OUTPUT FORMAT
Return a JSON object with this exact structure:
{
  "classification": "repairable" | "continuable" | "unrecoverable",
  "truncation_indicators": ["list of specific indicators found"],
  "repair_action": {
    "repaired_output": "<repaired output if repairable, null otherwise>",
    "repairs_applied": ["list of specific repairs made"]
  },
  "continuation_request": {
    "continuation_prompt": "<continuation prompt if continuable, null otherwise>",
    "expected_completion": "<description of what must be completed>"
  },
  "fallback_recommendation": "<recommended fallback if unrecoverable>"
}

## CONSTRAINTS
- Do not invent content to fill gaps unless the classification is `repairable` and the repair is purely structural
- Do not modify any valid content from the partial output
- If continuing, the continuation prompt must include enough context to prevent topic drift
- Mark all repaired or incomplete fields explicitly

To adapt this template, replace the square-bracket placeholders with your runtime values. [PARTIAL_OUTPUT] should contain the raw truncated text exactly as received from the stream. [OUTPUT_SCHEMA] should describe the expected structure—this can be a JSON Schema, a natural language description of required fields, or a reference to your application's output contract. [TERMINATION_REASON] should indicate why the stream ended (e.g., token_limit, connection_closed, model_stopped). [MAX_TOKENS] constrains the continuation budget. For high-risk applications where the repaired output feeds directly into user-facing surfaces or databases, add a human review step before accepting the repair action. Test this prompt against known truncation patterns—mid-sentence cuts, unclosed JSON at various nesting depths, and streams that end exactly at a valid boundary—to ensure the classification logic is reliable before deploying to production.

IMPLEMENTATION TABLE

Prompt Variables

Required inputs for the Streaming Output Truncation Detection and Repair prompt. Each placeholder must be populated before the prompt can reliably detect truncation and attempt repair.

PlaceholderPurposeExampleValidation Notes

[STREAMED_OUTPUT]

The raw, potentially truncated text or structured payload received from the streaming API

{"name": "Acme Corp", "revenue": 1

Must be a non-empty string. Validate that the input is the final received payload, not an intermediate chunk. Null or empty input should abort the repair workflow.

[EXPECTED_SCHEMA]

The target schema or format definition the complete output should conform to

{"type": "object", "required": ["name", "revenue", "founded"]}

Must be a valid JSON Schema, XML Schema, or a structured natural language description of required fields. Schema mismatch with [OUTPUT_TYPE] should trigger a configuration error.

[OUTPUT_TYPE]

The expected format of the complete output

json_object

Must be one of: json_object, json_array, xml, csv, markdown, plain_text. Used to select the appropriate truncation detection heuristic. Invalid values should default to plain_text with a warning.

[TRUNCATION_THRESHOLD]

The minimum number of trailing characters to inspect for truncation signals

50

Must be a positive integer. A value that is too low may miss truncation; a value that is too high may flag false positives on natural endings. Recommended range: 20-200.

[REPAIR_STRATEGY]

The desired action when truncation is detected

complete_or_flag

Must be one of: complete_or_flag, flag_only, attempt_repair. complete_or_flag requests a continuation prompt; attempt_repair tries to close the structure locally; flag_only marks the output without modification.

[CONTINUATION_PROMPT]

The instruction to append when requesting the model to continue a truncated output

Continue exactly from where you stopped. Do not repeat any prior content.

Required if [REPAIR_STRATEGY] is complete_or_flag. Must be a non-empty string. Validate that the continuation prompt does not introduce new instructions that conflict with the original generation context.

[MAX_RETRY_DEPTH]

The maximum number of continuation requests allowed before escalation

3

Must be a positive integer. Prevents infinite repair loops. If exceeded, the workflow must escalate to [FALLBACK_HANDLER] with the best partial output available.

[FALLBACK_HANDLER]

The system or human queue to receive outputs that cannot be repaired

dead_letter_queue_v2

Must be a valid handler identifier. Validate that the handler is registered and reachable. A null value means unrecoverable outputs are silently dropped, which is acceptable only for non-critical, non-audited workflows.

PROMPT PLAYBOOK

Implementation Harness Notes

How to wire truncation detection and repair into a production streaming pipeline with validation, retries, and observability.

The truncation detection and repair prompt is not a standalone utility—it is a recovery step inside a streaming output pipeline. Wire it after your chunk assembly layer and before your schema validator. When the assembled output fails a completeness check (unclosed JSON, truncated sentence, missing required fields), route the partial payload to this prompt along with the original generation context. The prompt returns either a repaired complete output or a structured continuation request that your application can send back to the model provider. Design the harness to distinguish between repairable truncation (the model can infer the missing content from context) and unrecoverable truncation (critical data was lost and must be regenerated).

Implement a truncation detector as a lightweight pre-check before invoking the LLM repair prompt. This detector should run deterministic rules: check for unclosed brackets, braces, or quotes in structured outputs; detect sentence fragments at the end of text outputs; verify that required schema fields are present and non-null. Only invoke the repair prompt when truncation is detected—avoid wasting tokens on complete outputs. The detector should classify truncation severity: minor (trailing punctuation or whitespace), moderate (incomplete final sentence or field), and severe (mid-structure cutoff with missing required data). For severe truncation, prefer requesting a continuation from the model with the original prompt and accumulated context rather than attempting repair. Log the truncation type, severity, and repair decision to your observability stack for later analysis of model behavior and token limit tuning.

Build a retry and fallback circuit around the repair step. If the repair prompt itself fails or returns an invalid output, retry once with explicit error context. If the continuation request to the model provider times out or returns another truncated response, fall back to serving the best available partial output with a truncation flag set in the response metadata. Your application layer should handle this flag gracefully—display a 'response truncated' indicator to users or queue the record for async repair. Set a hard limit on repair attempts (we recommend 2 retries maximum) to avoid latency spikes. For high-throughput systems, consider running truncation repair as an async sidecar process: serve the partial response immediately, then patch the complete response into your data store once repair succeeds.

Choose your model routing carefully. Truncation repair is a low-latency, high-accuracy task that benefits from fast, instruction-following models. Use a smaller, cheaper model for repair (GPT-4o-mini, Claude Haiku, or equivalent) rather than your primary generation model. This keeps repair costs low and latency predictable. However, for domain-specific content where the repair requires deep context understanding, route to the same model class used for generation. Implement a model fallback chain: try the fast repair model first, escalate to a more capable model if the repair output fails validation. Always pass the original generation prompt, the partial output, and the detected truncation point as context—never ask the repair model to guess what was being generated.

Wire validation gates after repair. The repaired output must pass the same schema validation, completeness checks, and safety filters as a normal complete response. If the repair introduces hallucinated content (detected by comparing pre-truncation and post-repair outputs), flag the response for human review rather than serving it automatically. For regulated or high-stakes domains, require human approval on all repaired outputs before they reach end users or downstream systems. Store the pre-repair partial output, the repair prompt, the repaired output, and the validation results in an audit log. This traceability is essential for debugging truncation patterns, tuning token limits, and demonstrating repair quality to stakeholders.

IMPLEMENTATION TABLE

Expected Output Contract

Fields, types, and validation rules for the truncation detection and repair output. Use this contract to parse the model response and decide whether to accept the repaired payload, request continuation, or escalate.

Field or ElementType or FormatRequiredValidation Rule

truncation_detected

boolean

Must be true or false. If true, at least one truncation_site must be present.

truncation_sites

array of objects

true if truncation_detected is true

Each object must contain position, fragment, and severity. Array must not be empty when truncation_detected is true.

truncation_sites[].position

integer

Character or token offset where truncation occurred. Must be >= 0 and less than total input length.

truncation_sites[].fragment

string

The last 20-50 characters before the cut point. Used to verify the model correctly identified the break location.

truncation_sites[].severity

enum: critical, recoverable, cosmetic

critical: unclosed JSON or function call. recoverable: incomplete sentence in prose. cosmetic: trailing whitespace or minor punctuation.

repair_action

enum: repair, request_continuation, accept_as_is, escalate

repair: model fixed the output. request_continuation: model provided a continuation prompt. accept_as_is: output is valid despite truncation. escalate: requires human review.

repaired_output

string or object

true if repair_action is repair

Must parse as valid JSON if original output was structured. Must not contain unclosed brackets, quotes, or code fences. Schema validation against [EXPECTED_SCHEMA] required.

continuation_prompt

string

true if repair_action is request_continuation

Must be a complete, self-contained prompt that can be sent as the next user message to continue generation. Must reference the cut point.

confidence_score

float between 0.0 and 1.0

Model's self-assessed confidence in the repair. Scores below [CONFIDENCE_THRESHOLD] should trigger escalation or human review.

validation_errors

array of strings

List of schema violations or structural issues found during repair. Empty array or null when repair is clean. Each entry must reference a specific field or position.

PRACTICAL GUARDRAILS

Common Failure Modes

Streaming output truncation is one of the most common production failures. Token limits, connection drops, and mid-stream timeouts leave applications with broken JSON, incomplete sentences, and unclosed blocks. These cards cover what breaks first and how to guard against it.

01

Mid-Sentence Cutoff at Token Limit

What to watch: The model hits its max_tokens parameter mid-generation, leaving the final sentence or field value incomplete. This is especially dangerous for structured outputs where a missing closing brace or quote breaks the entire payload. Guardrail: Always check if the finish_reason is 'length' and flag the output for repair. Implement a continuation request that passes the truncated output as context and instructs the model to complete from the cut point without repeating content.

02

Unclosed JSON Structures in Streaming

What to watch: Streaming parsers receive partial JSON chunks that never receive their closing braces, brackets, or quotes because the stream terminated early. Downstream JSON parsers throw fatal errors, halting the entire pipeline. Guardrail: Use a streaming JSON parser that tracks bracket depth and string state. On stream end, check for unclosed structures and either wait for a configurable grace period or invoke a repair prompt that completes the JSON based on schema hints and partial field content.

03

Connection Drop During Chunked Transfer

What to watch: Network instability, load balancer timeouts, or provider outages interrupt the SSE stream mid-response. The application receives a partial payload with no clean termination signal, leaving state ambiguous. Guardrail: Implement idempotent chunk sequence numbers and a client-side timeout. On reconnect, send the last successfully received sequence number and request redelivery from that point. Maintain a local buffer of received chunks to enable gap detection and reassembly without duplication.

04

Truncated Tool Call Arguments

What to watch: In agent workflows, a streaming tool call may deliver the function name but only partial arguments before the stream ends. Executing a tool with incomplete arguments causes runtime errors or, worse, silently incorrect behavior. Guardrail: Validate argument completeness against the tool's JSON Schema before execution. If arguments are incomplete, do not execute the tool. Instead, send a repair prompt with the partial arguments and schema, requesting completion. Gate all tool execution behind a schema validation check.

05

Silent Truncation Without Finish Reason

What to watch: Some providers or proxy layers drop content without setting a proper finish_reason, delivering what appears to be a complete response that is actually missing final content. The output looks valid but is semantically incomplete. Guardrail: Add semantic completeness checks post-stream: verify that the output ends with a terminal token (period, closing tag, final list item), that all opened structures are closed, and that required fields from the expected schema are present. Flag outputs that fail these checks for human review or automated repair.

06

Overlapping Chunk Boundaries on Retry

What to watch: When requesting continuation after a truncation, the model may repeat the last few tokens from the truncated output, creating duplicated content at the seam. This corrupts structured data and creates jarring repetition in text. Guardrail: Before stitching, detect overlap by comparing the tail of the original output with the head of the continuation using token-level or character-level matching. Trim the overlapping portion from the continuation before concatenation. For structured outputs, validate the merged result against the expected schema.

IMPLEMENTATION TABLE

Evaluation Rubric

Criteria for evaluating the quality of a repaired streaming output before it is delivered to the downstream application or user. Use these standards to automate gating in your production harness.

CriterionPass StandardFailure SignalTest Method

Structural Completeness

All JSON objects, arrays, and strings are properly closed. No unclosed brackets, braces, or quotes remain.

Parser throws an error on the repaired output. A bracket-matching check finds an unmatched token.

Parse the repaired string with a strict JSON parser. Run a bracket-pair validator on the raw string.

Schema Compliance

The repaired output validates against the expected [OUTPUT_SCHEMA]. All required fields are present and no extra fields are hallucinated.

Schema validator returns missing required field errors or additional property errors.

Validate the parsed output against the JSON Schema using a standard validator like ajv.

Content Continuity

The repaired text contains no mid-sentence cuts, orphaned words, or abrupt terminations. The final sentence is grammatically complete.

The output ends mid-word or mid-sentence without a closing punctuation mark. A semantic break is detected between the last two tokens.

Check if the final character is a sentence terminator (., !, ?, ", ']). If not, flag for human review.

No Spurious Duplication

The repaired output contains no repeated sentences, paragraphs, or large text blocks that were present in overlapping chunks.

A text similarity check between consecutive sentences or paragraphs exceeds a 0.9 cosine similarity threshold.

Tokenize the output into sentences. Calculate pairwise cosine similarity for adjacent sentences. Flag clusters above the threshold.

Citation Integrity

All in-text citation markers (e.g., [1], [2]) have a corresponding entry in the reference list. No orphaned or mismatched IDs exist.

A regex finds an in-text citation ID that is not present in the extracted reference list.

Extract all citation IDs from the text body and the reference section. Compare the two sets for equality.

Type and Value Correctness

All field values conform to their expected types (string, number, boolean, enum). No type coercion errors like a string 'null' for a null value.

A field defined as an integer contains a float or a string. An enum field contains an unlisted value.

Iterate over every field in the parsed output and check its type and value against the schema definition.

Encoding Sanitization

The output string contains only valid UTF-8 characters. No mojibake, replacement characters (U+FFFD), or mixed encodings are present.

Decoding the byte sequence as UTF-8 fails. The string contains the Unicode replacement character.

Encode the repaired string to UTF-8 bytes and decode it back. Check for errors and the presence of '�'.

Logical Coherence

The assembled output reads as a single, logically flowing document. There are no abrupt topic shifts or contradictory statements between stitched sections.

A human reviewer or an LLM-as-judge identifies a non-sequitur or a direct contradiction between the first and second half of the output.

Use an LLM judge with a coherence rubric to evaluate the text on a 1-5 scale. Fail if the score is below 4.

ADAPTATION OPTIONS

Adapt This Prompt

How to adapt

Start with the base truncation detection prompt and a simple heuristic: check if the last character is a sentence terminator or closing bracket. If not, flag as truncated. Use a lightweight continuation request without schema validation.

code
[SYSTEM]
You are a streaming output validator. Examine the provided text and determine if it was truncated mid-stream. Look for:
- Incomplete sentences at the end
- Unclosed brackets, braces, or quotes
- Trailing partial words

Return JSON: {"truncated": boolean, "truncation_point": string|null, "confidence": float}

[INPUT]
[STREAMED_TEXT]

Watch for

  • False positives on natural trailing ellipses or intentional fragments
  • Missing confidence thresholds leading to unnecessary repair attempts
  • No handling of multi-part structured outputs (JSON, XML) where truncation is structural, not textual
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.