This playbook addresses a specific and dangerous failure mode in agent systems: the tool call executed without error, but the response body violates the expected output contract. This is distinct from a tool call that fails with an error code or a malformed request. Here, the tool returned a 200 OK, but the JSON structure, field types, or required fields do not match the schema your downstream code expects. Use this prompt when your validator rejects a tool response and you need the model to adjust its arguments to elicit a conformant response, or to escalate when the tool itself appears broken.
Prompt
Tool Call Output Contract Violation Retry Prompt Template

When to Use This Prompt
Defines the specific failure mode this prompt addresses and the operational context required before deploying it in an agent harness.
Before using this prompt, you must have a validated output schema for the tool in question and a concrete list of violations produced by your validator. The prompt is designed to be injected into a retry loop where the model receives the original arguments, the invalid response, and the specific schema violations. It is not a general-purpose repair prompt for malformed JSON—it assumes the tool call itself was well-formed but the tool's response broke the contract. This prompt is most effective when your harness already distinguishes between transport-layer errors (4xx, 5xx, timeouts) and application-layer contract violations (schema mismatches, missing fields, type errors).
Do not use this prompt when the tool is returning consistent, well-formed errors that indicate a permanent failure (e.g., 'resource not found' with a valid error schema). In those cases, the tool is working correctly, and retrying with adjusted arguments is wasteful. Also avoid this prompt when you lack a machine-readable output schema—without one, the model cannot reliably distinguish between a valid response and a contract violation. If the tool's output schema is undocumented or unstable, invest in schema extraction or tool replacement before building retry logic around it.
Use Case Fit
Where the Tool Call Output Contract Violation Retry Prompt Template works, where it fails, and the operational prerequisites for safe deployment.
Good Fit: Deterministic Schema Violations
Use when: The tool call succeeded at the transport level (HTTP 200) but the response body fails a strict JSON Schema, Protobuf, or type-strict validation. Guardrail: Inject the exact schema and the specific validation error into the retry prompt so the model can map the violation to a corrected argument set.
Good Fit: Argument-Induced Output Drift
Use when: The tool returned a valid but semantically wrong output because an argument was ambiguous, poorly typed, or missing context. Guardrail: Include the original intent and the unexpected output in the retry instruction so the model adjusts arguments rather than repeating the same mistake.
Bad Fit: Broken or Unreliable Tools
Avoid when: The tool itself is non-deterministic, returns random errors, or has a bug that no argument change can fix. Guardrail: Track failure rates per tool endpoint. If the same tool fails across multiple unrelated calls, escalate to the tool owner and stop retrying.
Bad Fit: Semantic Ambiguity Without Ground Truth
Avoid when: The output contract is vague or the violation depends on subjective judgment. Guardrail: Require a machine-validatable schema before enabling automatic retry. If the contract cannot be expressed as a strict schema, route to human review instead.
Required Input: Output Schema and Validation Error
Risk: Without the expected schema and the specific violation message, the model guesses what went wrong and often produces the same invalid call. Guardrail: Always inject the full output schema and the exact validator error into the retry prompt. Never rely on the model to infer the contract from examples alone.
Operational Risk: Retry Loop Amplification
Risk: A retry prompt that keeps producing invalid outputs can burn tokens, hit rate limits, and delay the user without making progress. Guardrail: Set a hard retry budget (e.g., 2 attempts) and escalate after exhaustion. Log every attempt with the violation diff so operators can diagnose systemic tool or prompt issues.
Copy-Ready Prompt Template
A copy-ready retry prompt that corrects tool call arguments when the tool succeeded but its response violates the expected output schema.
This prompt template is designed for the retry step in an agent harness after a tool call has returned a successful HTTP status but the response body fails validation against the expected output contract. The prompt instructs the model to analyze the violation, adjust the original tool call arguments to elicit a conformant response, and either produce a corrected call or escalate if the tool itself appears broken. Replace every square-bracket placeholder with runtime values before sending the prompt to the model.
textSYSTEM: You are an agent recovery assistant. Your job is to correct tool call arguments when a tool returned a response that violates the expected output schema. CONTEXT: - Original user intent: [USER_INTENT] - Tool called: [TOOL_NAME] - Original arguments: [ORIGINAL_ARGUMENTS] - Expected output schema: [OUTPUT_SCHEMA] - Actual tool response: [ACTUAL_RESPONSE] - Validation errors: [VALIDATION_ERRORS] INSTRUCTIONS: 1. Analyze the validation errors against the expected output schema. 2. Determine whether the violation is likely caused by incorrect arguments or by a broken tool. 3. If incorrect arguments: produce a corrected set of arguments designed to elicit a schema-conformant response. Explain which arguments changed and why. 4. If the tool appears broken (e.g., returns HTML instead of JSON, missing entire required sections, or returns data that cannot be coerced to the schema regardless of arguments): set escalation_required to true and provide a clear explanation. 5. If you are uncertain, prefer escalation. OUTPUT FORMAT: { "analysis": "string explaining the likely cause of the violation", "escalation_required": boolean, "corrected_arguments": { /* adjusted arguments object, or null if escalating */ }, "argument_changes": [ { "parameter": "string", "original_value": "any", "new_value": "any", "reason": "string" } ], "escalation_reason": "string or null" } CONSTRAINTS: - Do not invent arguments not present in the original call unless required by the schema. - Preserve the user's original intent. Do not change what the user asked for. - If the tool response contains partial valid data, note it in the analysis. - [ADDITIONAL_CONSTRAINTS]
To adapt this template, populate the placeholders from your harness state. [OUTPUT_SCHEMA] should be the exact JSON Schema or type definition the tool response must satisfy. [VALIDATION_ERRORS] should be the raw error messages from your validator, not a summary. For high-risk domains such as finance or healthcare, add a human review gate before resubmitting corrected arguments. Wire the model's JSON output into a structured parser that checks escalation_required before retrying the tool call. If the model escalates, route to a human operator with the full failure context. If the model produces corrected arguments, validate them against the tool's input schema before retrying.
Prompt Variables
Each placeholder must be populated at runtime. Validation notes describe what makes each variable safe and complete.
| Placeholder | Purpose | Example | Validation Notes |
|---|---|---|---|
[ORIGINAL_INTENT] | The user's original request or goal that triggered the tool call | Get all open tickets for customer ID 48291 | Must be a non-empty string. Preserve verbatim from the initial user input. Do not summarize or reinterpret. |
[FAILED_TOOL_CALL] | The complete tool call payload that produced the contract-violating response | {"function":"get_tickets","args":{"customer_id":"48291"}} | Must be valid JSON. Include the full function name and arguments. Validate parseable before injection. |
[VIOLATED_OUTPUT_SCHEMA] | The expected output schema that the tool response failed to match | {"type":"object","required":["tickets","count"],"properties":{"tickets":{"type":"array"},"count":{"type":"integer"}}} | Must be a valid JSON Schema object. Inject the exact schema the tool contract requires, not a summary. |
[ACTUAL_RESPONSE] | The raw response body returned by the tool that violated the contract | {"results":[],"total":0} | Must be the unmodified tool response. Truncate only if exceeding token limits, with a truncation marker. Do not redact fields. |
[VIOLATION_DETAILS] | Specific schema violations detected by the validator | Missing required field 'tickets'. Field 'count' expected integer, got null. | Must be a plain-text list of violations. Generate from a schema validator, not manually. Include field paths and expected vs actual types. |
[RETRY_ATTEMPT_NUMBER] | Current retry count for this specific tool call | 2 | Must be an integer >= 1. Track per-tool-call, not globally. Used to decide escalation threshold. |
[MAX_RETRIES] | Maximum allowed retry attempts before escalation | 3 | Must be a positive integer. Configure per tool or per workflow. When [RETRY_ATTEMPT_NUMBER] >= [MAX_RETRIES], trigger escalation path. |
[ESCALATION_TARGET] | Where to send the failure when retries are exhausted | human_review_queue | Must be a valid escalation endpoint: human_review_queue, dead_letter_topic, or on_call_channel. Null if escalation is not yet triggered. |
Implementation Harness Notes
How to wire the output contract violation retry prompt into an agent harness with validation, retry loops, and escalation paths.
The output contract violation retry prompt is not a standalone fix—it is a recovery step inside a structured agent harness. The harness must detect the violation, prepare the retry context, invoke the prompt, validate the corrected arguments, and decide whether to re-execute the tool or escalate. This section covers the harness components you need before and after the prompt fires, with concrete validation checks, retry budget logic, and escalation triggers.
Start with a post-execution validator that inspects the tool's response against the expected output schema. The validator should check for missing required fields, type mismatches, enum violations, and structural non-conformance at the specific JSONPath where the violation occurred. Capture the exact validation error message, the violating field path, and the received value. If the response passes validation, skip the retry prompt entirely—only invoke it when a contract violation is confirmed. Log the violation details, the tool name, the original arguments, and the attempt count before calling the retry prompt.
The harness must inject three pieces of context into the retry prompt: the original tool call arguments that produced the bad response, the expected output schema for the tool's return value, and the specific violation details including the field path and the validation error message. Do not send the full tool response unless it is small and relevant—sending large payloads wastes tokens and can distract the model. Instead, extract the violating portion and include it alongside the schema snippet for that subtree. This keeps the prompt focused on the repair task rather than overwhelming the model with conformant data.
Wrap the retry prompt in a retry budget controller. Define a maximum number of output-contract retries per tool call—typically 2 or 3 before escalating. Track the attempt count per tool invocation, not globally, so a single bad tool doesn't consume the budget for unrelated calls. After each retry, validate the new arguments before re-executing the tool. If the model produces arguments that still fail validation, increment the counter and retry with the updated violation feedback. If the model produces the same invalid arguments twice, break the loop immediately—the model is stuck and further retries will waste resources.
When the retry budget is exhausted, the harness must escalate, not loop. Format an escalation payload that includes the original user intent, the tool name, all attempted argument sets, the validation errors for each attempt, and the final tool response if one exists. Route this to a human review queue, a fallback model, or a degraded-response path depending on your system's reliability requirements. Never silently drop the failure—output contract violations often indicate a tool that has changed its behavior, a schema that is out of date, or a model that fundamentally misunderstands the tool's contract. Each of these requires investigation beyond prompt-level recovery.
Expected Output Contract
The model must return a JSON object matching this structure. Validate before using the decision. This contract defines the shape of the retry instruction or escalation payload produced by the prompt.
| Field or Element | Type or Format | Required | Validation Rule |
|---|---|---|---|
decision | string enum: retry | escalate | clarify | Must be exactly one of the three allowed values. Reject any other string. | |
retry_instruction | object | Required if decision is retry. Must contain corrected_tool_call and correction_summary fields. Reject if present when decision is escalate or clarify. | |
retry_instruction.corrected_tool_call | object | Must match the target tool's input schema exactly. Validate against the provided [TOOL_SCHEMA]. All required parameters must be present. | |
retry_instruction.correction_summary | string | Must describe the specific violation and the correction applied. Cannot be empty or a generic placeholder. | |
escalation_payload | object | Required if decision is escalate. Must contain failure_summary, original_tool_call, and violation_details. Reject if present when decision is retry or clarify. | |
escalation_payload.failure_summary | string | Must explain why retry is not possible and what broke. Minimum 20 characters. Cannot be a generic error message. | |
clarification_question | string | Required if decision is clarify. Must ask the user a specific, actionable question about the missing or ambiguous information. Reject if present when decision is retry or escalate. | |
confidence | number | Must be a float between 0.0 and 1.0 representing the model's confidence in its decision. Values outside this range trigger a format error. |
Common Failure Modes
Tool call output contract violations break agent execution pipelines silently. The tool succeeded, but the response shape is wrong. These cards cover the most common failure patterns and the guardrails that prevent them from reaching production.
Silent Schema Drift After Tool Updates
What to watch: The tool's output schema changes, but the agent harness still validates against the old contract. The model receives a valid response, but downstream parsing fails with cryptic type errors. Guardrail: Version the output schema alongside the tool definition and inject the current schema into every retry prompt. Compare the actual response shape against the expected schema before passing it to the next step.
Partial Success with Missing Required Fields
What to watch: The tool returns a 200 but omits required fields like id, status, or timestamp. The harness treats this as a complete response and propagates nulls downstream. Guardrail: Validate required field presence immediately after tool execution. On violation, construct a retry prompt that lists the missing fields explicitly and asks the model to adjust arguments that might elicit a complete response.
Type Mismatch in Nested Structures
What to watch: A deeply nested field returns a string instead of a number, or an object instead of an array. Top-level validation passes, but the error surfaces three steps later in a different agent. Guardrail: Recursive schema validation that traverses the full response tree. Include the specific JSONPath to the violating field in the retry prompt so the model can target its argument correction.
Enum Violation from Model-Generated Arguments
What to watch: The model passes an argument like "sort": "newest" but the tool only accepts "asc" or "desc". The tool returns a default-sorted result instead of rejecting the call, masking the error. Guardrail: Inject the valid enum values into the retry prompt and instruct the model to map its original intent to the closest allowed value. Flag responses where the output doesn't match the requested sort order.
Truncated Response from Token Limits
What to watch: The tool response hits a token limit mid-JSON, producing an unparseable fragment. The harness retries the same call repeatedly without adjusting the arguments to request less data. Guardrail: Detect truncation by validating JSON completeness before retrying. On retry, instruct the model to add pagination, filters, or field selection arguments that reduce the response size below the limit.
Retry Loop Exhaustion Without Escalation
What to watch: The harness retries the same tool call with minor argument variations, consuming the entire retry budget without converging. The user waits, and the pipeline eventually fails with a generic timeout. Guardrail: Track retry count and argument deltas. After two failed retries with similar arguments, escalate to a different recovery strategy—try an alternative tool, request human clarification, or return a partial result with an error annotation.
Evaluation Rubric
Test this prompt against known cases before deploying to production. Score each criterion on a pass/fail basis.
| Criterion | Pass Standard | Failure Signal | Test Method |
|---|---|---|---|
Output Schema Conformance | Retry instruction JSON matches the [OUTPUT_SCHEMA] exactly; all required fields present and no extra fields | Schema validation error on retry instruction; missing [CORRECTION_HINT] or [RETRY_ARGUMENTS] | Validate retry output against [OUTPUT_SCHEMA] using JSON Schema validator; run against 10 known violation cases |
Violation-Specific Correction | [CORRECTION_HINT] directly addresses the specific contract violation described in [VIOLATION_DETAILS] | Generic hint like 'fix the output' instead of field-level correction; hint references a violation not present in input | Parse [CORRECTION_HINT] against [VIOLATION_DETAILS]; check that hint field paths match violation field paths |
Original Intent Preservation | [RETRY_ARGUMENTS] preserve the semantic intent of [ORIGINAL_ARGUMENTS] while adjusting only the violating parameters | Retry arguments change the tool call purpose; critical parameter values from original call are dropped without justification | Diff [RETRY_ARGUMENTS] against [ORIGINAL_ARGUMENTS]; flag any removed or altered parameters that are unrelated to the violation |
Escalation Threshold Decision | Prompt outputs [ESCALATE]: true when [VIOLATION_DETAILS] indicates the tool response is structurally broken or the tool itself appears non-conformant | Escalation flag set to false when violation is systemic; escalation triggered for minor fixable violations | Test with 5 tool-broken cases and 5 fixable cases; verify escalation decision matches expected threshold |
No Hallucinated Fields | [RETRY_ARGUMENTS] contain only fields defined in [TOOL_SCHEMA]; no invented parameters or guessed values | New parameter appears that is not in [TOOL_SCHEMA]; value filled in without source from [ORIGINAL_ARGUMENTS] or [CONVERSATION_CONTEXT] | Cross-reference [RETRY_ARGUMENTS] keys against [TOOL_SCHEMA] parameter definitions; flag any key not present in schema |
Error Message Grounding | [CORRECTION_HINT] references specific error messages or violation descriptions from [VIOLATION_DETAILS] | Hint is generic with no reference to actual error text; hint contradicts the violation details provided | Search [CORRECTION_HINT] for substrings or field paths from [VIOLATION_DETAILS]; require at least one direct reference |
Clarification Request When Unsafe | When [VIOLATION_DETAILS] indicates missing critical information, prompt outputs a clarification question in [CLARIFICATION_QUESTION] instead of guessing | Missing required value is filled with a hallucinated default; [CLARIFICATION_QUESTION] is null when inference is unsafe | Test with 5 cases where violation requires user input; verify [CLARIFICATION_QUESTION] is non-null and specific to the missing information |
Retry Budget Awareness | Prompt respects [RETRY_ATTEMPT] and [MAX_RETRIES] context; escalation language strengthens as attempts approach budget | Same retry instruction produced on attempt 1 and attempt 5; no acknowledgment of approaching retry limit | Run same violation case with [RETRY_ATTEMPT] values 1, 3, and 5; verify escalation language or strategy shifts as budget depletes |
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 output schema injected inline. Focus on getting the retry loop working before adding production harness features. Replace [OUTPUT_SCHEMA] with a minimal JSON schema containing only the fields your tool contract requires. Start with a single retry attempt and log the before/after payloads.
Watch for
- The model may produce a corrected call that still violates the schema if the schema description is vague
- No idempotency handling—duplicate side effects if the first call partially succeeded
- Missing argument preservation: the retry may drop fields that were valid in the original call

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