This prompt is for integration developers and AI infrastructure engineers who need to recover from a tool call that returned a syntactically or structurally invalid payload. The job-to-be-done is to programmatically normalize, coerce, or reconstruct a valid output from a malformed response so that downstream application logic—such as a JSON parser, a type validator, or a user-facing summary—does not crash or propagate corrupted data. The ideal user is someone who already has a defined expected schema for the tool output and can supply both the malformed payload and the target schema as inputs to the repair prompt.
Prompt
Malformed Tool Response Repair Prompt Template

When to Use This Prompt
Define the job, reader, and constraints for the Malformed Tool Response Repair Prompt Template.
Use this prompt when the tool response is partially intact but fails schema validation, contains type mismatches, has missing required fields, or includes extra garbage text around a valid core. Do not use this prompt when the tool response is completely empty, represents an authentication or authorization failure, or indicates a systemic outage. Those scenarios require different recovery playbooks, such as empty-result interpretation, auth-failure recovery, or circuit-breaker activation. This prompt also assumes that repair is safe: the malformed payload is not adversarial, and the repair operation does not introduce fabricated data that could mislead downstream decisions. If the tool output is used in a regulated domain (healthcare, finance, legal), the repaired output must be flagged for human review before any action is taken.
Before wiring this prompt into a production harness, define a strict repair safety boundary. The prompt should be paired with a post-repair validation step that re-checks the output against the expected schema and a diff tool that logs exactly what was changed. If the repair prompt cannot produce a valid output after one attempt, the system should escalate to a human or fall back to a safe static response rather than retrying indefinitely. The next section provides the copy-ready prompt template you can adapt and embed in your recovery pipeline.
Use Case Fit
Where the Malformed Tool Response Repair Prompt Template works and where it introduces unacceptable risk.
Good Fit: Schema Drift in Internal Services
Use when: An internal microservice returns a response that is structurally valid JSON but violates the expected schema (e.g., missing a newly added field, returning a string instead of a number). Guardrail: Pair the repair prompt with a strict JSON Schema validator. Only attempt repair if the validator can clearly identify the specific violation.
Good Fit: Type Coercion and Normalization
Use when: A tool response contains correct data but in the wrong type, such as a numeric ID wrapped in a string or a date in an inconsistent format. Guardrail: The repair prompt must be instructed to log every coercion it performs so that downstream systems can audit the transformation. Never silently coerce without an audit trail.
Bad Fit: Cryptographic or Financial Integrity
Avoid when: The malformed payload contains cryptographic signatures, financial transaction amounts, or compliance-critical fields where any alteration breaks non-repudiation. Guardrail: If the payload includes a digital signature or a hash, do not repair. Escalate for a fresh, authentic tool call instead.
Bad Fit: Unrecoverable Semantic Garbage
Avoid when: The tool output is not just malformed but semantically nonsensical (e.g., a weather tool returning a recipe). Repairing this hallucinates data. Guardrail: Implement a semantic sanity check before repair. If the topic or entity type is wrong, discard the response and retry the tool call or fall back to a different tool.
Required Input: Strict Expected Schema
Use when: You have a machine-readable, strict expected schema (JSON Schema, Pydantic model, or typed interface) to validate against. Guardrail: The repair prompt must receive both the malformed payload and the exact expected schema. Without the schema, the model will guess the intended structure and introduce drift.
Operational Risk: Masking Systemic Failures
Risk: A repair prompt that succeeds too often can hide a broken upstream tool, leading to data corruption at scale. Guardrail: Always increment a repair_attempt metric and fire an alert if the repair rate exceeds a defined threshold (e.g., >5% of calls). Treat frequent repairs as a P1 upstream bug, not a normal operational cost.
Copy-Ready Prompt Template
A reusable prompt template for normalizing, coercing, or reconstructing a valid tool response from a malformed payload.
This prompt template is the core instruction set for a repair model. It receives a malformed tool response, the expected output schema, and the original tool call context. Its job is to produce a valid, schema-conforming payload without inventing data that wasn't present in the original malformed response. The template uses square-bracket placeholders for all dynamic inputs, making it safe to copy directly into your codebase, prompt management system, or orchestration layer.
codeYou are a strict output repair system. Your only job is to convert a malformed tool response into a valid output that conforms to the expected schema. ## INPUTS - Malformed Tool Response: [MALFORMED_RESPONSE] - Expected Output Schema: [OUTPUT_SCHEMA] - Original Tool Call Arguments: [TOOL_CALL_ARGUMENTS] - Repair Constraints: [REPAIR_CONSTRAINTS] ## REPAIR RULES 1. Extract every recoverable field from the malformed response that matches a field in the expected schema. 2. For missing required fields, use the following strategies in order: - Infer from context in the malformed response if the inference is high-confidence. - Use a safe default if one is defined in the repair constraints. - Set the field to `null` and add an entry to the `repair_metadata.missing_fields` array. 3. For fields with incorrect types, attempt type coercion following these rules: - String to Number: Parse if the string is a valid numeric representation. - Number to String: Convert directly. - String to Boolean: `"true"`, `"yes"`, `"1"` become `true`; `"false"`, `"no"`, `"0"` become `false`. - Object to Array: Wrap in a single-element array if the schema expects an array. - If coercion fails, set the field to `null` and add an entry to `repair_metadata.coercion_failures`. 4. For malformed JSON, attempt structural repair: - Fix unescaped quotes, trailing commas, and missing braces. - If structural repair fails, treat the entire payload as a string and attempt extraction via regex patterns matching the expected field names. 5. Never fabricate data. If a value cannot be recovered, coerced, or defaulted, it must be null. ## OUTPUT FORMAT Return a JSON object with exactly this structure: { "repaired_output": <schema-conforming object>, "repair_metadata": { "repair_attempted": true, "repair_successful": <boolean>, "missing_fields": ["<field_name>", ...], "coercion_failures": [{"field": "<field_name>", "original_type": "<type>", "target_type": "<type>"}, ...], "structural_repair_applied": <boolean>, "confidence": "<high|medium|low>", "unsafe_repair": <boolean> } } ## UNSAFE REPAIR DETECTION Set `unsafe_repair` to `true` and `repair_successful` to `false` if: - More than [MAX_MISSING_RATIO] of required fields are missing. - The malformed response contains no recognizable fields from the expected schema. - Repair would require fabricating values for fields marked as `"no_fabrication"` in the repair constraints. - The malformed response appears to be an error message, stack trace, or HTML error page rather than a corrupted tool output. ## EXAMPLES [REPAIR_EXAMPLES] Repair the malformed response now.
Adaptation guidance: Replace [MALFORMED_RESPONSE] with the raw string or partial JSON returned by the failed tool call. [OUTPUT_SCHEMA] should be a complete JSON Schema or a structured description of every expected field, its type, and whether it is required. [TOOL_CALL_ARGUMENTS] provides the original request context, which helps the repair model distinguish between a malformed response and a valid empty result. [REPAIR_CONSTRAINTS] is a critical safety field: define which fields must never be fabricated, list acceptable default values, and set [MAX_MISSING_RATIO] (e.g., 0.3 for 30%) to trigger the unsafe repair flag. [REPAIR_EXAMPLES] should include 2-3 few-shot examples showing a malformed input, the repair constraints, and the correct repaired output with metadata. Before deploying, validate that the repair model's output passes your existing tool response schema validator. If the unsafe_repair flag is true, route the payload to a human review queue instead of passing it downstream.
Prompt Variables
Required inputs for the Malformed Tool Response Repair Prompt. Each variable must be populated before the prompt is assembled and sent to the model. Missing or invalid inputs will cause the repair to fail silently or produce an unsafe coercion.
| Placeholder | Purpose | Example | Validation Notes |
|---|---|---|---|
[MALFORMED_PAYLOAD] | The raw, schema-violating tool response that needs repair | {"user": {"nm": "Kim"}} | Must be a non-empty string or JSON object. Check that the payload is parseable as the declared content type before passing to the repair prompt. If unparseable, route to a syntax-error recovery path instead. |
[EXPECTED_SCHEMA] | The target schema definition the output must conform to | {"type": "object", "properties": {"name": {"type": "string"}}, "required": ["name"]} | Must be a valid JSON Schema, TypeScript interface, or structured type definition. Validate the schema itself is well-formed before use. A malformed schema will produce a malformed repair instruction. |
[TOOL_NAME] | The name of the tool that produced the malformed response | get_user_profile | Must be a non-empty string matching the tool registry. Used to retrieve tool-specific coercion rules and error history. If unknown, set to 'unknown_tool' and disable tool-specific repair heuristics. |
[ERROR_CONTEXT] | The validation error messages or exception details from the schema check | Required field 'name' is missing; 'nm' is not a recognized property | Must be a non-empty string or array of error strings. If no validation was run, set to 'no validation errors provided' and flag the repair as low-confidence. The repair quality depends on specific error messages. |
[COERCION_RULES] | Explicit field mapping, type coercion, and default-value rules for this tool | {"field_mappings": {"nm": "name"}, "defaults": {"id": null}, "strict": false} | Optional. If provided, must be a valid JSON object with field_mappings, defaults, and strict keys. If null, the model will infer mappings from the schema alone. Explicit rules reduce hallucinated coercions. |
[REPAIR_BUDGET] | Maximum number of repair attempts allowed before escalation | 3 | Must be a positive integer. Used to decide whether the repair prompt should attempt aggressive normalization or return a partial result with flags. If the budget is exhausted, the prompt should produce a stop-and-escalate output instead of a best-effort repair. |
[UNSAFE_COERCION_LIST] | Fields or transformations that must never be performed during repair | ["amount", "authorized_by", "signature"] | Optional. Must be an array of field name strings. If any field in this list would be altered by the repair, the prompt must refuse repair and escalate. Critical for financial, auth, and legal fields where silent coercion creates risk. |
[CONFIDENCE_THRESHOLD] | Minimum confidence score required to accept the repaired output automatically | 0.85 | Must be a float between 0.0 and 1.0. Outputs below this threshold must be flagged for human review. If set to 1.0, all repairs require review. If set to 0.0, all repairs are auto-accepted, which is unsafe for production. |
Implementation Harness Notes
How to wire the malformed tool response repair prompt into a production application with validation, retries, and safety gates.
The malformed tool response repair prompt is designed to sit inside a post-tool-call validation loop, not as a standalone chat interaction. When a tool returns a payload that fails schema validation, the application should catch the validation error, extract the raw malformed response and the expected schema, and feed both into this prompt. The model's job is to produce a repair instruction—a set of normalization, coercion, or reconstruction steps—that the application can then apply programmatically or use to guide a second model call. This prompt is a decision-support tool for the repair orchestrator, not a replacement for deterministic schema coercion logic.
Wiring pattern: The application should implement a repair_or_escalate function that receives the raw tool output, the expected JSON Schema, and any validation error messages. This function calls the repair prompt with [MALFORMED_PAYLOAD], [EXPECTED_SCHEMA], and [VALIDATION_ERRORS] as inputs. The model returns a structured repair plan containing: (1) a repair_strategy enum (COERCE, RECONSTRUCT, DROP_FIELDS, UNSAFE_TO_REPAIR), (2) a repaired_payload if safe, and (3) a confidence_score between 0.0 and 1.0. The orchestrator should gate on confidence_score: if below a configurable threshold (start with 0.85), escalate for human review instead of applying the repair. For UNSAFE_TO_REPAIR, always escalate. Log every repair attempt with the original payload, the repair plan, and the final outcome for auditability.
Retry and fallback integration: This prompt should be called at most once per tool invocation failure. If the repaired payload also fails validation, do not loop—escalate immediately. The repair prompt is not a retry mechanism; it is a one-shot normalization attempt. For transient failures like timeouts or 5xx errors, use a separate retry-with-backoff prompt from the Error Handling pillar. For cases where the tool consistently returns malformed responses, the fix belongs in the tool implementation or schema definition, not in repeated repair attempts. Wire the repair prompt into your observability stack: emit metrics on repair attempt rate, repair success rate, and escalation rate to detect systemic tool quality degradation early.
Model choice and latency budget: Use a fast, instruction-following model for this prompt (e.g., GPT-4o-mini, Claude 3.5 Haiku, or a fine-tuned smaller model if repair patterns are stable). The repair prompt adds latency to the tool call path, so set a strict timeout (500ms–2s depending on payload size). If the repair model times out, treat it as UNSAFE_TO_REPAIR and escalate. For high-throughput systems, consider caching repair strategies keyed by (tool_name, error_type, schema_version) to skip the model call for known failure patterns. Never apply a cached repair without re-validating the output against the current schema.
Safety and human review: In regulated or high-risk domains (finance, healthcare, legal), set the confidence_score threshold higher (0.95+) and require human approval for any repair that modifies field values, not just types. The repair prompt must never invent missing required data—if a required field is absent and cannot be derived from the malformed payload, the repair must fail with UNSAFE_TO_REPAIR. Implement a repair audit log that records every repair decision, the human reviewer if involved, and the final payload that was accepted. This log is essential for compliance reviews and debugging silent data corruption caused by over-aggressive repair.
Expected Output Contract
Defines the structure, types, and validation rules for the repaired tool response payload. Use this contract to parse the model's output programmatically and gate downstream consumption.
| Field or Element | Type or Format | Required | Validation Rule |
|---|---|---|---|
repair_status | enum: success | partial | unsafe | Must be one of the three allowed values. If 'unsafe', the payload must not be consumed by downstream systems. | |
repaired_payload | object (schema-defined) | Must conform to the [EXPECTED_SCHEMA] provided in the prompt. Validate with JSON Schema or equivalent structural check. | |
repair_actions | array of strings | Each string must describe a concrete action taken (e.g., 'coerced field X to string', 'dropped unknown key Y'). Array must not be empty if repair_status is 'partial'. | |
missing_fields | array of strings | List of required fields from [EXPECTED_SCHEMA] that were absent in the malformed input. Must be empty if repair_status is 'success'. | |
confidence_score | number (0.0-1.0) | Model's confidence in the repair. Must be a float. If below [CONFIDENCE_THRESHOLD], downstream systems should treat the repair as 'unsafe'. | |
original_error_signature | string | A hash or summary of the original validation error to correlate the repair with the failure. Null allowed if no error context was provided. | |
human_review_required | boolean | Must be true if repair_status is 'unsafe' or confidence_score is below [CONFIDENCE_THRESHOLD]. Gates automatic consumption of the repaired payload. |
Common Failure Modes
When a tool returns a malformed payload, the repair prompt becomes a critical control point. These are the most common ways repair logic fails in production and how to guard against them.
Silent Hallucination of Missing Fields
What to watch: The model invents plausible values for required fields that are missing or null in the malformed payload, producing a valid-looking but incorrect output. Guardrail: Require the repair prompt to explicitly mark any field it could not source from the original payload with a confidence flag and a source annotation. Validate that all required fields have a non-hallucinated origin before accepting the repair.
Over-Coercion of Incompatible Types
What to watch: The model aggressively coerces a fundamentally wrong data type (e.g., a narrative string into a numeric ID) to satisfy the schema, destroying information. Guardrail: Add a strict coercion boundary in the prompt: allow only safe casts (string to number if parseable, null to empty list) and require the model to return an unrepairable_fields array for anything that would require guesswork. Validate that no field in unrepairable_fields appears in the repaired output.
Repair Loop Exhaustion Without Escalation
What to watch: The repair prompt is called in a loop, each time producing a slightly different but still invalid output, consuming the retry budget without making progress. Guardrail: Implement a repair budget (max 2-3 attempts) and a staleness check. If the repaired output's structural validity score does not improve between attempts, break the loop and escalate to a human or a static fallback. Log the sequence of repair attempts for debugging.
Loss of Critical Business Context
What to watch: In trying to normalize the payload, the model strips out unstructured text or metadata that contained critical business context not captured in the target schema. Guardrail: Instruct the repair prompt to preserve the original malformed payload in a _raw_backup field within the repaired output. This ensures downstream systems or human reviewers can audit what was lost and recover critical information.
Unsafe Repair of Write-Operation Payloads
What to watch: The repair prompt is applied to the response of a mutating tool (e.g., a database write or API POST), and the "repaired" output masks a critical failure or alters the intended side effect. Guardrail: Classify the tool call as read or write before invoking the repair prompt. For write operations, never auto-repair a malformed success/failure confirmation; instead, escalate for human review or re-query state to verify the outcome independently.
Schema Drift Between Repair Prompt and Validator
What to watch: The target schema described in the repair prompt drifts out of sync with the actual downstream application validator, causing the "repaired" output to be rejected again. Guardrail: Generate the repair prompt's target schema dynamically from the canonical source of truth (e.g., a Pydantic model's model_json_schema() or an OpenAPI spec). Never hardcode the expected schema in the prompt template. Add an integration test that validates the prompt's schema against the live validator.
Evaluation Rubric
Use this rubric to test the output quality of the Malformed Tool Response Repair Prompt before shipping. Each criterion targets a specific failure mode in production repair workflows.
| Criterion | Pass Standard | Failure Signal | Test Method |
|---|---|---|---|
Schema Compliance | Output is valid JSON that passes a structural parse against the expected [OUTPUT_SCHEMA]. | JSON.parse throws an error or required fields are missing. | Automated schema validation with a JSON Schema validator against a golden set of 20 malformed payloads. |
Type Coercion Correctness | String-to-number, string-to-boolean, and null-to-default coercions match the [COERCION_RULES] without data loss. | A numeric ID is converted to a float when an integer is required, or a boolean string 'false' is coerced to true. | Assert field types in the repaired output match the schema exactly using a type-checking harness. |
Missing Field Handling | Required fields absent from the input are populated with [DEFAULT_VALUES] or null as specified; optional fields are omitted. | A required field is silently dropped, or an optional field is populated with a hallucinated value. | Diff the input and output field sets against the schema definition for 15 cases with known missing fields. |
Hallucination Resistance | No new data is invented. Repaired values are derived exclusively from the input payload or [DEFAULT_VALUES]. | A missing 'user_name' field is filled with 'John Doe' instead of null or the specified default. | Manual review of 10 repair outputs for invented content, plus automated string-distance check against input. |
Unsafe Repair Abstention | The prompt returns a valid [UNSAFE_FLAG] object instead of a repaired payload when the input is too corrupt. | A critically malformed payload with conflicting identifiers is repaired silently, merging incompatible records. | Test with 5 intentionally unsafe payloads (e.g., conflicting IDs, truncated arrays) and assert the abstention flag is set. |
Truncation Recovery | Truncated strings or arrays are either repaired with an [INCOMPLETE_FLAG] or completed with a safe terminator. | A truncated JSON array is closed with a guessed value, or a truncated string is left unclosed. | Inject 10 payloads truncated at random points and verify the output is either valid or flagged as incomplete. |
Nested Object Repair | Malformed nested objects are normalized to the correct depth and structure without flattening or losing children. | A nested object with a missing closing brace is repaired by attaching all subsequent fields to the parent. | Validate the depth and key paths of repaired nested objects against the schema for 8 complex payloads. |
Confidence Flag Accuracy | The [CONFIDENCE] score in the repair envelope is 0.0 for fully valid inputs and decreases proportionally to repair extent. | A heavily repaired payload receives a confidence score of 1.0, or a perfect payload receives a score of 0.5. | Correlate the number of repair operations performed with the output confidence score across 25 test cases. |
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 no external validation harness. Focus on getting a reasonable repair for common schema violations (missing fields, type mismatches, extra keys).
codeSYSTEM: You are a tool output repair agent. Given the expected schema [SCHEMA] and the malformed output [MALFORMED_OUTPUT], produce a corrected JSON object that conforms to the schema. If a field cannot be repaired, set it to null and add a "_repair_notes" field explaining what was missing.
Watch for
- The model hallucinating plausible values for missing required fields instead of nulling them
- No validation after repair, so downstream code still breaks
- Overly aggressive coercion that changes data meaning (e.g., converting a string ID to a number)

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