Inferensys

Prompt

Token Limit Truncation Recovery Prompt for JSON Payloads

A practical prompt playbook for production engineers recovering JSON payloads cut off by model token limits. Identifies the truncation point, estimates missing structure, and either closes the payload safely or flags it for a continuation request.
ML engineer managing model training cluster on laptop, GPU utilization visible, technical deep learning setup.
PROMPT PLAYBOOK

When to Use This Prompt

Define the job, reader, and constraints for the Token Limit Truncation Recovery Prompt.

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.

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.

PRACTICAL GUARDRAILS

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.

01

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.

02

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.

03

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.

04

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.

05

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.

06

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.

PROMPT PLAYBOOK

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.

text
You 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

  1. Parse the partial JSON payload and identify the exact truncation point.
  2. 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?
  3. Based on [RECOVERY_STRATEGY]:
    • If strategy is "safe_close": Close all open structures (arrays, objects) and truncate the incomplete final value. Add a _truncated: true flag 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.
  4. Output the repaired JSON payload inside a ```json code block.
  5. 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.

IMPLEMENTATION TABLE

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.

PlaceholderPurposeExampleValidation Notes

[TRUNCATED_PAYLOAD]

The incomplete JSON string cut off by the token limit. Must include everything up to the truncation point.

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.

PROMPT PLAYBOOK

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.

IMPLEMENTATION TABLE

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 ElementType or FormatRequiredValidation 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.

PRACTICAL GUARDRAILS

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.

01

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.

02

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.

03

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.

04

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.

05

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.

06

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.

IMPLEMENTATION TABLE

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.

CriterionPass StandardFailure SignalTest 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 truncation_point field accurately identifies the exact string index or path where the original payload was cut off.

The truncation_point index is outside the bounds of the [ORIGINAL_TRUNCATED_PAYLOAD] or points to a structurally sound location.

Unit test with a set of pre-truncated payloads at known breakpoints. Assert the identified index matches the known breakpoint.

Missing Structure Estimation

The estimated_missing_structure field provides a plausible, syntactically correct guess for the missing closing brackets, braces, and quotes.

The estimated structure, when appended to the original payload, does not produce a valid JSON object.

Append the estimated_missing_structure to the [ORIGINAL_TRUNCATED_PAYLOAD] at the truncation_point and run a parse test. It must produce a valid, though potentially incomplete, object.

Safe Closure Strategy

When recovery_strategy is 'close', the recovered_payload is a valid JSON object that does not invent new key-value pairs beyond what is needed for structural closure.

The recovered_payload contains keys or values not present in the [ORIGINAL_TRUNCATED_PAYLOAD] before the truncation point.

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 recovery_strategy is 'continue', the continuation_prompt is a non-empty string that clearly requests the next chunk of data.

The continuation_prompt is empty, null, or a generic message that does not reference the specific truncation point.

Assert that continuation_prompt is a string with length > 20 characters and contains a reference to the last complete element from the original payload.

Completeness Score Accuracy

The completeness_score is a float between 0.0 and 1.0 that reasonably reflects the proportion of structural elements recovered.

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 recovered_payload JSON.

Automated scan of all string values in recovered_payload for banned substrings: ['...', 'truncated', 'continued', 'omitted']. A match is an automatic failure.

ADAPTATION OPTIONS

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
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.