This prompt is for API developers and production engineers who need to detect when a model output was truncated by the max_tokens parameter and request an intelligent continuation. The core job-to-be-done is recovering a complete, valid payload when the model stopped mid-generation due to a hard token limit, without discarding the partial work and restarting from scratch. The ideal user is someone running batch inference, non-streaming completions, or agent tool-call loops where a finish_reason: 'length' signal indicates the output is incomplete. Required context includes the original prompt, the partial output, the output schema or expected format, and the exact truncation point.
Prompt
Token-Limit Cutoff Detection and Recovery Prompt Template

When to Use This Prompt
Determine when a token-limit cutoff recovery prompt is the right tool and when a different repair strategy is required.
Use this prompt when you have a clear truncation signal (API finish_reason equals length or max_tokens), the partial output contains recoverable structure, and the cost of restarting generation exceeds the cost of a continuation request. This is a post-generation repair workflow, not a real-time streaming strategy. Do not use this prompt when the output is malformed for reasons other than token limits—such as schema violations, hallucinated fields, or encoding errors—which require different repair playbooks from the Output Repair and Validation pillar. Do not use this prompt when the partial output is so severely truncated that no meaningful structure remains; in those cases, restarting generation with a higher max_tokens value or chunking the task is more reliable. Avoid this approach in latency-sensitive streaming applications where a continuation request would introduce unacceptable delay.
Before deploying this prompt, verify that your application can reliably detect truncation. The OpenAI and Anthropic APIs both return an explicit finish_reason field. If you are using a local model or proxy that does not surface this signal, you must implement your own truncation detection by checking for unclosed brackets, braces, XML tags, or code blocks in the output. Wire the continuation request to preserve the original system prompt, temperature, and tool definitions to avoid context drift. Always validate the stitched output against the expected schema before accepting it. For high-risk domains such as healthcare or finance, flag stitched outputs for human review rather than silently accepting the repaired payload.
Use Case Fit
Where the Token-Limit Cutoff Detection and Recovery Prompt works, where it fails, and the operational conditions required before you wire it into a production pipeline.
Good Fit: Deterministic Truncation Recovery
Use when: the model output was cut off by a hard max_tokens limit and the partial payload is structurally incomplete (e.g., broken JSON, mid-sentence text, unclosed code block). Guardrail: always pass the original finish_reason and the exact truncation point to the recovery prompt so the model knows why it stopped and where to resume.
Bad Fit: Semantic Drift or Hallucination Repair
Avoid when: the output is complete but factually wrong, hallucinated, or logically inconsistent. This prompt recovers from token cutoffs, not from content quality failures. Guardrail: route to a factuality or hallucination repair prompt instead. Check finish_reason before invoking recovery—only trigger on length or max_tokens.
Required Inputs: Truncation Metadata
Risk: without the original finish_reason, max_tokens limit, and the exact partial output, the recovery prompt cannot distinguish a cutoff from a model that simply stopped early. Guardrail: require a structured input object containing partial_output, finish_reason, original_prompt, and output_schema before the recovery prompt runs.
Operational Risk: Duplicate Content on Resume
Risk: the continuation prompt may repeat the last few tokens of the partial output, causing duplication when the two halves are stitched together. Guardrail: implement a post-stitching deduplication check that compares the boundary tokens and removes overlap before the final payload is delivered downstream.
Operational Risk: Context Window Exhaustion
Risk: if the original prompt plus partial output already fills the context window, the recovery prompt may have no room to generate a continuation. Guardrail: check remaining context budget before invoking recovery. If insufficient, escalate to a summarization-and-continue variant or return the partial output with a truncation flag.
Variant: Streaming Interruption vs. Hard Cutoff
Use when: the truncation happened mid-stream due to a connection drop rather than a max_tokens limit. Guardrail: use the Streaming Interruption Continuation variant instead, which includes chunk-boundary metadata and avoids re-requesting content the client already received. Do not treat a stream break as a token-limit cutoff.
Copy-Ready Prompt Template
A copy-ready prompt for detecting token-limit truncation and requesting a coherent continuation that respects the original task, schema, and partial content.
This prompt template is designed to be used inside a recovery handler when your application detects that a model response was truncated due to hitting the max_tokens limit. Instead of discarding the partial output and starting over—which wastes tokens and can lose valuable reasoning—this prompt instructs the model to analyze the cut-off point and generate only the missing continuation. The template uses square-bracket placeholders that your application must populate with the original request context, the truncated response, and any output schema constraints.
textYou are a recovery assistant. Your only job is to continue a truncated AI response. ## ORIGINAL REQUEST [ORIGINAL_USER_PROMPT] ## SYSTEM INSTRUCTIONS FROM ORIGINAL REQUEST [ORIGINAL_SYSTEM_PROMPT] ## TRUNCATED RESPONSE (CUT OFF BY TOKEN LIMIT) [TRUNCATED_OUTPUT] ## OUTPUT SCHEMA (IF APPLICABLE) [OUTPUT_SCHEMA] ## TASK 1. Identify the exact point where the truncated response was cut off. 2. Determine what content, structure, or reasoning was likely intended to follow. 3. Generate ONLY the missing continuation. Do not repeat any content from the truncated response. 4. If the truncated response ends mid-word, mid-JSON field, or mid-code block, repair that boundary before continuing. 5. Preserve the original tone, format, and output schema exactly. 6. If the truncated response appears complete (false positive), respond with: [COMPLETE_MARKER]. ## CONSTRAINTS - Do not add introductory phrases like "Here is the continuation" or "Continuing from where it left off." - Do not summarize or rephrase the truncated content. - Output only the continuation text, ready to be concatenated directly to the truncated response.
To adapt this template for your application, replace each placeholder with the actual values from the original request. [ORIGINAL_USER_PROMPT] should contain the full user message that triggered the initial generation. [ORIGINAL_SYSTEM_PROMPT] should include the system instructions active during the original call—this is critical for tone and constraint preservation. [TRUNCATED_OUTPUT] is the partial response your application received before the token limit was hit. [OUTPUT_SCHEMA] should contain any JSON schema, XML DTD, or format specification the original output was expected to follow; if none exists, replace this with "No specific output schema required." The [COMPLETE_MARKER] token should be a unique string your application can detect to avoid unnecessary concatenation when the original response was not actually truncated.
Before deploying this prompt into production, wire it into a recovery harness that validates the concatenated output against your original schema and checks for boundary artifacts. Common failure modes include the model repeating the last few tokens of the truncated response (causing duplication at the seam), generating a continuation that drifts from the original output format, or failing to repair a mid-token cut. Your harness should trim overlapping tokens at the concatenation boundary and run the full output through the same validators used for non-truncated responses. For high-risk domains such as healthcare or finance, flag recovered outputs for human review rather than automatically surfacing them to users.
Prompt Variables
Inputs the prompt needs to work reliably. Validate each before sending the recovery request.
| Placeholder | Purpose | Example | Validation Notes |
|---|---|---|---|
[TRUNCATED_OUTPUT] | The partial, cut-off model response that needs completion | {"users": [{"id": 1, "name": "Alice"}, {"id": 2, "na | Must be non-empty string. Check that last 50 tokens show clear truncation signal (unclosed brace, mid-word, missing newline). Reject if output appears intentionally complete. |
[ORIGINAL_TASK] | The full system prompt or instruction that generated the truncated output | Generate a JSON array of user objects with id, name, and email fields from the following text... | Must be non-empty string. Must match the task context that produced [TRUNCATED_OUTPUT]. Mismatch causes context drift in continuation. |
[ORIGINAL_INPUT] | The source data or user query that was provided to the model | User records: 1: Alice Chen, alice@example.com; 2: Bob Smith, bob@example.com; 3: Carol... | Must be non-empty string. Required for the model to infer missing content from source rather than hallucinating. Null allowed only if task had no input. |
[OUTPUT_SCHEMA] | The expected structure, format, or schema the output must conform to | JSON array of objects with fields: id (int), name (string), email (string) | Must be parseable as a schema description. Use for structural repair validation. If absent, model may complete with wrong format. |
[TRUNCATION_POINT] | The exact character or token position where output was cut off | max_tokens=150 reached mid-object at character offset 1423 | Must be a non-negative integer or token count. Used to verify that continuation starts at correct boundary without overlap or gap. Null allowed if exact position unknown. |
[CONTINUATION_START] | The last complete, valid segment before truncation to anchor continuation | {"users": [{"id": 1, "name": "Alice Chen", "email": "alice@example.com"}, | Must be a valid prefix of [TRUNCATED_OUTPUT]. Extract programmatically by walking back from truncation point to last valid delimiter. Ensures seamless stitching. |
[CONSTRAINTS] | Additional rules the continuation must follow | Do not repeat any already-completed records. Preserve exact field names from schema. Return only the completion fragment, not the full output. | Must be a string or null. Include explicit anti-hallucination and anti-duplication rules. Validate that constraints don't contradict [OUTPUT_SCHEMA]. |
Implementation Harness Notes
How to wire the token-limit cutoff detection and recovery prompt into a production application with validation, retries, and observability.
This prompt is designed to sit inside a post-generation recovery loop, not as a standalone utility. After your primary model call returns a finish_reason of length (or equivalent for your provider), you should immediately route the partial output and the original request context into this prompt. The harness must preserve the exact truncation point—do not trim or clean the partial output before passing it, as trailing whitespace, broken tokens, or mid-word cutoffs are the primary signals the recovery prompt uses to detect the boundary. Store the original max_tokens limit, the actual token count consumed, and the finish_reason in your trace metadata before initiating recovery.
Validation gates should run on both the partial input and the completed output. Before calling the recovery prompt, validate that the partial output is non-empty and that the truncation is genuine—a finish_reason of length with tokens remaining in your budget may indicate a different failure mode. After receiving the completed output, run your standard schema validators, parse checks, or content policies against the full result. If the completed output still fails validation, increment a retry counter and re-invoke the recovery prompt with the validator's error message appended to [CONSTRAINTS]. Set a hard retry limit (typically 2–3 attempts) before escalating to a human review queue or logging the partial output as unrecoverable. Log every recovery attempt with the attempt number, token counts, latency, and validation result for later analysis.
Model selection matters here. The recovery prompt works best with models that share the same tokenizer and context window as the original generation model—cross-model recovery can introduce boundary misalignment if tokenization differs. If you must use a different model for recovery, include the original model name in [CONTEXT] and test boundary detection accuracy across model pairs before deploying. For streaming applications, buffer the final chunk and check the stream's termination reason before assembling the partial output; never pass individual streaming chunks to the recovery prompt, as it expects the full partial payload. Wire the recovery prompt into your existing observability stack with a dedicated recovery_attempt span, and set alerts on recovery failure rates exceeding your team's threshold—sustained failures often indicate a prompt design problem upstream, not a recovery logic bug.
Expected Output Contract
Defines the required fields, types, and validation rules for the recovery model's response. Use this contract to parse, validate, and integrate the continuation output into your application harness.
| Field or Element | Type or Format | Required | Validation Rule |
|---|---|---|---|
continuation_text | string | Must be non-empty. Must not duplicate the final 50 characters of [TRUNCATED_OUTPUT]. Check with Levenshtein distance > 0.9 against the tail of the input. | |
confidence_score | number (0.0-1.0) | Must be a float between 0.0 and 1.0. If below 0.7, flag for human review. Parse check: | |
detected_cutoff_point | string | Must be a substring of the last 100 characters of [TRUNCATED_OUTPUT]. If not found, the response is invalid. Perform exact substring match. | |
completion_strategy | enum | Must be one of: 'direct_continuation', 'structural_closure', 'summary_completion'. Reject any other value. Enum check against allowed set. | |
warnings | array of strings | If present, each element must be a non-empty string. Null or empty array is acceptable. Validate with | |
unrecoverable_fields | array of strings | If present, lists field names from [OUTPUT_SCHEMA] that could not be recovered. Each entry must match a known field name. Validate against the provided schema definition. | |
requires_human_review | boolean | Must be |
Common Failure Modes
Token-limit cutoffs break structured outputs, leave partial payloads, and corrupt downstream parsers. Here's what fails first and how to guard against it.
Mid-Object Structural Breakage
What to watch: The model stops inside a JSON object, leaving unclosed braces, dangling commas, or severed string literals. The output is unparseable. Guardrail: Always validate with a strict parser before passing output downstream. Use a repair prompt that receives the partial output and the expected schema, instructing the model to close only the broken structure without inventing new field values.
Silent Field Omission
What to watch: The output parses successfully but required fields from the schema are missing because the model stopped before generating them. Downstream code fails on KeyError or null-pointer access. Guardrail: Post-parse, validate field completeness against the expected schema. If fields are missing, route to a targeted completion prompt that requests only the missing fields, preserving the already-valid partial payload.
Continuation Context Drift
What to watch: When requesting continuation, the model loses the original task constraints, output format, or reasoning chain. The completed output contradicts the partial prefix or switches to a different structure. Guardrail: Include the original system prompt, the partial output, and an explicit instruction to continue in the exact same format and style. Test continuation coherence by comparing key-value counts and structure depth between the partial and completed output.
Duplication at Stitch Boundary
What to watch: The continuation repeats the last few tokens or lines from the partial output, creating duplicate content at the seam. This corrupts lists, repeats paragraphs, or doubles JSON keys. Guardrail: Implement a deduplication check at the boundary. Compare the last N characters of the partial output with the first N characters of the continuation. Trim overlapping segments before concatenation. Log boundary overlap length for monitoring.
False Completion Confidence
What to watch: The model generates a plausible-looking completion that fills missing fields with hallucinated values instead of acknowledging uncertainty. Dates, amounts, and identifiers are especially vulnerable. Guardrail: Instruct the model to use a sentinel value like "__UNKNOWN__" or null for fields it cannot infer from the partial output. Validate that completed fields match the data types and ranges present in the partial payload. Flag completions where inferred values deviate from partial-output patterns.
Infinite Retry Loop on Unrecoverable Truncation
What to watch: The repair prompt fails repeatedly because the partial output is too severely damaged—missing critical context, truncated mid-token, or severed in a way that makes intent ambiguous. The system burns tokens and latency with no path to recovery. Guardrail: Set a maximum retry count (typically 2-3 attempts). After the final failure, log the partial output, surface it to a dead-letter queue for human review, and return a controlled error to the caller. Never loop indefinitely on repair attempts.
Evaluation Rubric
Use this rubric to test the Token-Limit Cutoff Detection and Recovery Prompt before shipping to production. Each criterion targets a specific failure mode observed in truncated output recovery.
| Criterion | Pass Standard | Failure Signal | Test Method |
|---|---|---|---|
Truncation Detection Accuracy | Prompt correctly identifies the last complete token boundary in [TRUNCATED_OUTPUT] without false positives on intentional trailing punctuation. | Prompt flags a complete output as truncated or misses an obvious mid-word cutoff. | Run 20 samples: 10 truncated at known boundaries, 10 complete. Measure precision and recall of truncation flag. |
Continuation Start Point | Continuation begins at the exact character after the last complete token, with no repeated words or missing characters. | Output repeats the last 1-3 words of [TRUNCATED_OUTPUT] or skips content between the cutoff and the continuation. | Diff the last 50 characters of [TRUNCATED_OUTPUT] against the first 50 characters of the continuation. Require zero overlap and zero gap. |
Task Intent Preservation | Continuation respects the original [TASK_DESCRIPTION] and does not change the output type, persona, or goal. | Continuation switches from JSON to prose, changes the subject, or adds disclaimers not present in the original task. | Compare the continuation's format and content type against a reference completion of [TASK_DESCRIPTION]. Require format match. |
Schema Compliance | If [OUTPUT_SCHEMA] is provided, the continuation completes the partial structure into a valid instance of that schema. | Continuation produces malformed JSON, invents new top-level keys, or omits required fields from the schema. | Parse the full reassembled output with the schema validator. Require zero validation errors. |
No Hallucinated Content Beyond Partial Input | Continuation adds only the minimum content needed to complete the truncated unit. It does not invent data, citations, or entities not implied by the partial output. | Continuation adds fabricated names, numbers, URLs, or facts that cannot be inferred from [TRUNCATED_OUTPUT] and [CONTEXT]. | Have a second LLM judge compare the continuation against [TRUNCATED_OUTPUT] and flag any unsupported novel entities. Require zero flags. |
Structural Closure | Continuation properly closes all open brackets, braces, quotes, fences, or tags left incomplete in [TRUNCATED_OUTPUT]. | Reassembled output fails to parse due to unclosed structures introduced or left unclosed by the continuation. | Parse the full reassembled output with the appropriate parser (JSON, XML, Markdown). Require parse success. |
Length and Token Budget Adherence | Continuation does not exceed the available token budget specified in [MAX_COMPLETION_TOKENS] and does not itself get truncated. | Continuation is cut off again, indicating the prompt consumed too many tokens for its own completion. | Check the finish_reason of the continuation API call. Require finish_reason=stop, not length. |
Idempotency and Non-Repetition | Running the prompt twice with the same [TRUNCATED_OUTPUT] produces semantically equivalent continuations without progressive degradation. | Second run appends a second continuation, repeats the first continuation, or adds commentary about the task. | Run the prompt twice. Concatenate [TRUNCATED_OUTPUT] + Continuation1 + Continuation2. Check that Continuation2 is empty or a no-op. |
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 a simple max_tokens check and a single continuation call. Keep the detection heuristic lightweight: if the response doesn't end with a valid closing token (e.g., }, ], </tag>, or a complete sentence), flag it as truncated. Request continuation with the last 100–200 tokens of the partial output as context.
Prompt modification
code[ORIGINAL_PROMPT] If your response was cut off, stop here. The next message will be: "Continue from: [LAST_200_TOKENS_OF_OUTPUT]"
Watch for
- Over-triggering on natural mid-sentence stops that aren't actual truncations
- Continuation that repeats content instead of resuming
- No validation of the final assembled output against the expected schema

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