This prompt is for production engineers and API developers who need to recover a JSON payload that was cut off mid-stream by a model's token limit. The job-to-be-done is not to generate new content, but to salvage a partial, structurally invalid JSON response by identifying the exact truncation point, estimating the missing closing structure, and producing a valid, parseable JSON object that preserves as much of the original data as possible. The ideal user is an SRE or backend engineer who has already received a finish_reason: 'length' or similar signal from the model API and has a raw, truncated string that fails JSON.parse.
Prompt
Token Limit Truncation Recovery Prompt for JSON Payloads

When to Use This Prompt
Define the job, reader, and constraints for the Token Limit Truncation Recovery Prompt.
This prompt should be used when the truncated payload is a single, complete JSON object or array that was cut off before its closing brackets. It works best when you can provide the original prompt or task context so the recovery model can infer the intended schema. Do not use this prompt for streaming fragments that arrive in arbitrary chunks—use the Streaming Fragment Assembly Prompt instead. Do not use it when the payload is so severely truncated that no key structural elements remain; in that case, the correct action is to re-request with a higher max_tokens setting or to split the original task into smaller requests.
The prompt requires three inputs: the [TRUNCATED_PAYLOAD] string, the [ORIGINAL_TASK] that generated it, and an optional [EXPECTED_SCHEMA] to guide structural recovery. The output should be a valid JSON object with a recovery_metadata field that marks the truncation point and flags any estimated or reconstructed sections. Before shipping this into a production pipeline, you must validate the output with a strict JSON parser, diff the recovered payload against the original truncated string to ensure no data was hallucinated, and implement a circuit breaker that escalates to a human or re-requests the original task if the recovery confidence is below your threshold.
Use Case Fit
Where the Token Limit Truncation Recovery Prompt delivers value and where it introduces unacceptable risk. This playbook is designed for production engineers who must recover partial JSON payloads, not for general content generation.
Good Fit: Streaming API Interruption
Use when: A streaming response from a model API is cut off mid-JSON due to a max_tokens limit or a connection interruption, and you have a partial payload. Guardrail: Always log the raw truncated fragment before repair for auditability. The prompt should only close or flag the payload, never invent missing business data.
Bad Fit: Inventing Missing Critical Data
Avoid when: The truncated section contains required financial amounts, legal clauses, or personally identifiable information (PII). Risk: The model may hallucinate plausible but incorrect values to close the JSON structure. Guardrail: For high-risk fields, the prompt must be instructed to return null or a TRUNCATION_ERROR flag instead of synthesizing content.
Required Inputs: Schema Awareness
Use when: You can provide the expected JSON Schema or a valid example of the complete structure alongside the truncated payload. Guardrail: Without a schema, the model cannot reliably distinguish between a missing closing brace and a missing array of objects. The prompt must take [EXPECTED_SCHEMA] as a required variable to estimate structural depth.
Operational Risk: Silent Data Corruption
Risk: A repair that produces technically valid JSON but semantically incorrect data (e.g., closing an array early, dropping a final record). Guardrail: Implement a post-repair validation step that checks record counts, array lengths, and checksums against the pre-truncation state if available. Flag any payload for human review if structural estimates were used.
Good Fit: Continuation Request Preparation
Use when: The truncation point is cleanly identified, and the system can request the next chunk of data from the model. Guardrail: The prompt should output a structured continuation_context object containing the exact cut-off point and the last valid key path, enabling a follow-up API call to resume generation without duplication.
Bad Fit: Non-Deterministic Payloads
Avoid when: The JSON payload contains non-deterministic fields like generated UUIDs, timestamps, or creative text that cannot be safely continued or closed. Risk: A continuation request will generate a conflicting or duplicate value. Guardrail: For non-deterministic payloads, the only safe repair is to close the structure and mark the entire record for regeneration, not continuation.
Copy-Ready Prompt Template
A reusable prompt for recovering JSON payloads that were truncated by model token limits, with placeholders for the partial output, expected schema, and recovery strategy.
This prompt template is designed to be copied directly into your application's recovery layer. It takes a partial JSON payload that was cut off by a token limit, identifies the structural break point, and either closes the payload safely or prepares a continuation request. The template uses square-bracket placeholders that you must replace with runtime values before sending the prompt to the model.
textYou are a JSON repair specialist. Your task is to recover a JSON payload that was truncated due to a token limit. ## INPUT Partial JSON payload (truncated): ```json [PARTIAL_JSON_PAYLOAD]
EXPECTED SCHEMA
[EXPECTED_SCHEMA]
RECOVERY STRATEGY
[RECOVERY_STRATEGY]
INSTRUCTIONS
- Parse the partial JSON payload and identify the exact truncation point.
- Determine the structural context at the truncation point:
- Is it inside a string value?
- Is it inside an array or object?
- What keys, brackets, or braces are unclosed?
- Based on [RECOVERY_STRATEGY]:
- If strategy is "safe_close": Close all open structures (arrays, objects) and truncate the incomplete final value. Add a
_truncated: trueflag at the root level. Do not hallucinate missing data. - If strategy is "continuation_request": Output a continuation prompt that includes the last complete structural element and requests the model to continue generating from that point.
- If strategy is "best_effort_fill": For the final incomplete value, provide a reasonable default based on [EXPECTED_SCHEMA] and mark it with
_estimated: true.
- If strategy is "safe_close": Close all open structures (arrays, objects) and truncate the incomplete final value. Add a
- Output the repaired JSON payload inside a ```json code block.
- After the code block, provide a brief truncation report including:
- Truncation point (character position or field path)
- Structural context at break
- Recovery action taken
- Completeness estimate (percentage of expected fields present)
CONSTRAINTS
- Do not invent data for missing fields beyond what [RECOVERY_STRATEGY] allows.
- Preserve all valid data from the partial payload exactly as provided.
- If the payload is too damaged to recover, output:
{"error": "unrecoverable_truncation", "details": "..."} - If [RECOVERY_STRATEGY] is "continuation_request", output the continuation prompt, not a closed payload.
OUTPUT FORMAT
json{ "repaired_payload": { ... }, "truncation_report": { "truncation_point": "...", "structural_context": "...", "recovery_action": "...", "completeness_estimate": "..." } }
To adapt this template, replace the three required placeholders: [PARTIAL_JSON_PAYLOAD] with the raw truncated output from your model, [EXPECTED_SCHEMA] with your target JSON Schema or a natural-language description of the expected structure, and [RECOVERY_STRATEGY] with one of the three supported strategies: safe_close, continuation_request, or best_effort_fill. The safe_close strategy is appropriate for user-facing responses where partial data is acceptable. Use continuation_request when you need the complete payload and can afford a second model call. Reserve best_effort_fill for internal pipelines where estimated values are better than missing records, but always flag estimated fields for downstream review.
Before deploying this prompt, validate that your application can parse the output JSON block and extract the repaired_payload field. Add a parse retry loop: if the model's response itself is malformed, retry once with a simplified instruction. Log every truncation recovery event with the completeness estimate so you can monitor whether your token limits need adjustment. For high-stakes payloads—financial records, clinical data, or legal documents—route best_effort_fill outputs to a human review queue and never auto-commit estimated values to a system of record.
Prompt Variables
Required inputs for the Token Limit Truncation Recovery Prompt. Each variable must be populated before the prompt is assembled and sent. Validation checks prevent silent failures when the model receives incomplete context.
| Placeholder | Purpose | Example | Validation Notes |
|---|---|---|---|
[TRUNCATED_PAYLOAD] | The incomplete JSON string cut off by the token limit. Must include everything up to the truncation point. | {"users":[{"id":1,"name":"Alice","email":"alice@example.com"},{"id":2,"na | Parse check: must be a non-empty string. Length check: should be shorter than [MAX_OUTPUT_TOKENS] to confirm truncation occurred. Null not allowed. |
[EXPECTED_SCHEMA] | The target JSON Schema or a plain-text description of the expected structure, required fields, and nesting depth. | {"type":"object","required":["users"],"properties":{"users":{"type":"array","items":{"type":"object","required":["id","name","email"]}}}} | Schema check: if JSON Schema provided, validate it parses correctly. If plain text, confirm it mentions required fields. Null not allowed. |
[TRUNCATION_DIRECTION] | Indicates whether the payload was truncated at the end of the stream or mid-structure. Accepted values: 'end', 'mid-structure', 'unknown'. | mid-structure | Enum check: must be one of 'end', 'mid-structure', 'unknown'. Default to 'unknown' if the caller cannot determine. Null allowed only if [RECOVERY_STRATEGY] is 'flag_only'. |
[RECOVERY_STRATEGY] | Specifies the repair approach. 'close_safely' attempts to close open brackets and return a valid partial payload. 'flag_for_continuation' returns the truncation point and a continuation prompt. 'best_effort' attempts close_safely and falls back to flagging. | close_safely | Enum check: must be one of 'close_safely', 'flag_for_continuation', 'best_effort'. Default to 'best_effort' if unset. Null not allowed. |
[MAX_OUTPUT_TOKENS] | The token limit that caused the truncation. Used to estimate how much structure was lost and to size the continuation request. | 4096 | Type check: must be a positive integer. Range check: should match the model's documented output limit. Used for heuristic estimation, not enforcement. Null allowed if unknown. |
[CONTINUATION_CONTEXT] | Optional preceding context if this payload is part of a multi-turn or streaming sequence. Helps the model understand what came before the truncation. | Previous response completed user records 1-50. This payload starts at record 51. | Null allowed. If provided, must be a non-empty string. Length check: keep under 500 tokens to avoid crowding the repair instruction. |
[FAILURE_MODE_HINT] | Optional hint about the likely failure cause: 'token_limit', 'stream_interruption', 'model_early_stop', or 'unknown'. Guides the repair heuristic. | token_limit | Enum check: must be one of 'token_limit', 'stream_interruption', 'model_early_stop', 'unknown'. Null allowed. If null, the prompt treats the cause as unknown. |
Implementation Harness Notes
How to wire the Token Limit Truncation Recovery Prompt into a production application with validation, retries, and continuation logic.
The Token Limit Truncation Recovery Prompt is not a standalone fix; it is a component inside a larger recovery harness. The application layer must detect truncation before invoking the prompt, manage continuation state, and validate that the repaired output is structurally sound. The most reliable detection heuristic is to attempt JSON.parse() on the raw model response. If parsing fails with an unexpected end-of-input error near the final characters, the payload is likely truncated. A secondary signal is comparing the response's finish_reason to length or max_tokens in the API response object. Both checks should gate invocation of this prompt to avoid wasting tokens on non-truncated payloads.
Once truncation is detected, the harness should construct the prompt with three required inputs: the [TRUNCATED_PAYLOAD] (the raw string from the model), the [EXPECTED_SCHEMA] (a JSON Schema or TypeScript interface describing the target structure), and the [CONTEXT_HINT] (the last known complete field or array element before truncation, extracted from the partial parse). The prompt returns a repaired JSON object. The harness must then validate this output against the expected schema using a library like ajv or zod. If validation passes, the payload proceeds downstream. If it fails, the harness should not blindly retry the same prompt. Instead, it should attempt a continuation request: send the truncated payload back to the model with a continue instruction and a higher max_tokens setting, then feed the concatenated result through the repair prompt once more. Log every attempt with the original response ID, truncation point, repair latency, and validation result for observability.
For high-throughput systems, implement a circuit breaker. If the repair prompt fails three consecutive times for the same payload, stop retrying and escalate to a dead-letter queue for human review. Do not silently drop truncated payloads—they often contain partial user-facing content or database records. Model choice matters here: prefer models with strong code-completion capabilities (such as gpt-4o or claude-3.5-sonnet) for structural repair, as they are better at inferring bracket closure and field completion than smaller models. Avoid using this prompt on payloads under 100 tokens; the overhead of the repair call exceeds the cost of re-generating the entire response with a higher token limit. Finally, instrument the harness to track the rate of truncation events by model and prompt version—rising truncation rates signal that your primary generation prompts need higher max_tokens settings or output compression.
Expected Output Contract
Fields, format, and validation rules for the token limit truncation recovery prompt output. Use this contract to validate the model's response before passing it to downstream systems or continuation logic.
| Field or Element | Type or Format | Required | Validation Rule |
|---|---|---|---|
truncation_detected | boolean | Must be true if input ends mid-structure; false only if payload is complete. Parse check: strict boolean, not string. | |
truncation_point | object | Contains line_number (integer) and character_offset (integer). Both must be positive integers. Schema check: required keys present. | |
completeness_estimate | number | Float between 0.0 and 1.0 representing estimated payload completeness. Range check: 0.0 <= value <= 1.0. | |
recovery_action | string | Must be one of: close_payload, flag_for_continuation, or request_continuation. Enum check: exact match required. | |
repaired_payload | string | Required when recovery_action is close_payload. Must be valid parseable JSON. Parse check: JSON.parse succeeds. Null allowed for other actions. | |
missing_structure_estimate | array | List of strings describing estimated missing keys, closing brackets, or array elements. Required when recovery_action is flag_for_continuation. Schema check: array of non-empty strings. | |
continuation_context | string | Required when recovery_action is request_continuation. Contains the last complete structural element before truncation. Must not exceed 500 characters. Length check enforced. | |
confidence_score | number | Float between 0.0 and 1.0 indicating confidence in the repair or diagnosis. Range check: 0.0 <= value <= 1.0. Values below 0.5 should trigger human review. |
Common Failure Modes
Token limit truncation breaks JSON payloads silently. These are the most common failure patterns and how to guard against them before they corrupt your data pipeline.
Mid-Structure Truncation
What to watch: The model output stops mid-key, mid-value, or mid-array, leaving unclosed brackets and braces. Parsers reject the entire payload. Guardrail: Run a structural completeness check before parsing—count open vs. closed brackets, braces, and quotes. If mismatched, route to the repair prompt instead of the parser.
Silent Field Loss at Tail
What to watch: The last few fields in an array or object are simply missing because the token budget ran out. No error is thrown if the JSON is technically valid but incomplete. Guardrail: Compare the output record count or required field presence against the expected schema. Flag any object missing required fields even if the JSON parses cleanly.
Continuation Context Collapse
What to watch: When requesting continuation of a truncated payload, the model loses context of the original structure and invents fields, reorders keys, or changes nesting. Guardrail: Always pass the partial payload and the expected schema into the continuation request. Use a strict repair prompt that forbids new field creation and validates against the original structure.
Streaming Chunk Boundary Corruption
What to watch: In streaming responses, truncation can occur mid-chunk, splitting a JSON token across two chunks. Reassembly produces garbled keys or values. Guardrail: Buffer chunks until you can parse a complete JSON structure. Use a streaming JSON parser that detects incomplete tokens and waits for the next chunk before attempting parse.
False Completion Signal
What to watch: The model emits a closing brace or bracket prematurely when it hits the token limit, producing valid JSON that is semantically incomplete. The parser succeeds but the data is wrong. Guardrail: Validate semantic completeness—check that array lengths match expected counts, required fields are present, and terminal nodes have non-null values where required. Never trust parse success alone.
Repair Loop Exhaustion
What to watch: A truncated payload enters a repair loop, but each repair attempt consumes more tokens and produces a new truncation. The system burns budget without resolution. Guardrail: Set a maximum repair attempt count (2-3 retries). After exhaustion, flag the record for human review or async batch repair. Log the truncation point and remaining token budget for diagnosis.
Evaluation Rubric
Criteria for evaluating the quality of a recovered JSON payload before it is passed to a downstream system. Use this rubric to gate the output of the Token Limit Truncation Recovery Prompt.
| Criterion | Pass Standard | Failure Signal | Test Method |
|---|---|---|---|
Structural Validity | Output is valid, parseable JSON with no trailing commas, unclosed brackets, or syntax errors. | JSON.parse() throws an error. | Automated parse check. Run the output through a standard JSON parser for the target language. |
Truncation Point Identification | The | The | Unit test with a set of pre-truncated payloads at known breakpoints. Assert the identified index matches the known breakpoint. |
Missing Structure Estimation | The | The estimated structure, when appended to the original payload, does not produce a valid JSON object. | Append the |
Safe Closure Strategy | When | The | Diff the keys in the recovered payload against the keys in the valid portion of the original payload. No new semantic keys should appear. |
Continuation Request Flagging | When | The | Assert that |
Completeness Score Accuracy | The | A payload missing only a closing bracket scores 0.1, or a payload missing 90% of its structure scores 0.9. | Validate the score is a float in the range [0.0, 1.0]. Spot-check with human evaluation on a sample of 10 cases to ensure the score correlates with actual structural loss. |
No Hallucinated Content | The recovered payload contains no invented data, summaries, or placeholder values like '...' or 'truncated' as string values. | The output contains any explanatory text or placeholder strings inside the final | Automated scan of all string values in |
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 single model call and manual inspection. Focus on the truncation detection heuristic and safe closure logic. Skip the continuation-request path initially—just close the payload or flag it. Test with deliberately truncated JSON samples at known cut points.
Prompt modification
- Remove the continuation-request branch and keep only the safe-closure path
- Simplify the output schema to
{ "repaired_json": [OUTPUT], "truncation_point": "[PATH]", "repair_action": "closed" } - Use a smaller model for cost testing; accept that deep nesting recovery may be weaker
Watch for
- Missing schema checks against expected structure
- Overly aggressive bracket insertion that creates valid JSON with wrong semantics
- No logging of truncation frequency or repair success rate

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