Use this prompt when you are a backend engineer or platform developer responsible for defining the structured error outputs that an AI model will receive after a tool call fails. The job-to-be-done is not just writing an error message, but designing a machine-readable contract—a JSON schema for error responses—that enables the model to correctly interpret what went wrong, decide whether to retry, select a fallback tool, or escalate to a human. This prompt is ideal when you are building an AI agent, copilot, or any system where a model orchestrates external API calls and must recover gracefully from failures such as timeouts, validation errors, permission denials, or rate limits. The required context includes your tool's operational failure modes, the retry and idempotency characteristics of your endpoints, and the downstream user experience you need to protect.
Prompt
Error Response Schema Design Prompt

When to Use This Prompt
Define the job, reader, and constraints for the Error Response Schema Design Prompt.
Do not use this prompt if you are only designing user-facing error messages for a traditional web application with no AI intermediary. This prompt is specifically for the contract between your system and the model. It is also inappropriate if you are in the earliest prototyping phase and haven't yet identified the common failure modes of your tool; the output will be speculative and may lead to brittle recovery logic. The prompt assumes you can enumerate concrete error categories (e.g., TEMPORARY_SERVER_ERROR, INVALID_ARGUMENT, PERMISSION_DENIED) and that you have a clear policy on retries and human escalation. If your tool's side effects are not well-understood, start with the Side-Effect Documentation Prompt for Tools first.
Before running this prompt, gather your tool's existing error codes, HTTP status mappings, and any retry-after headers or idempotency keys you support. The output will be a complete error schema with codes, retry hints, and user-facing message templates, but its real value is in the evaluation harness: you will test whether the model, upon receiving each error type, chooses the correct recovery action. After generating the schema, you must integrate it into your tool's OpenAPI or function definition and run the provided eval cases. Avoid the temptation to hand-wave error handling; a model that misinterprets a 500 as a permanent failure when it should retry will silently degrade your product.
Use Case Fit
Where the Error Response Schema Design Prompt works and where it does not. Use these cards to decide if this prompt fits your current task before investing in integration.
Good Fit: Structured API Error Contracts
Use when: You are designing the error response body for a REST or gRPC API that an AI model will call as a tool. The model needs machine-readable error codes, retry hints, and user-facing message templates to self-correct or escalate gracefully. Guardrail: Provide the full tool schema and expected success response shape as input so the prompt can align error fields with existing contracts.
Bad Fit: Human-Only Error Pages
Avoid when: Your only goal is to write a user-facing error message for a web app or mobile UI with no model in the loop. This prompt produces structured schemas with fields like retryable and error_code that add overhead without benefit for human-only consumption. Guardrail: Use a UX writing prompt instead if the consumer is exclusively a person reading a screen.
Required Inputs: Tool Context and Failure Modes
Risk: Without a clear list of known failure modes (timeouts, auth failures, validation errors, rate limits), the prompt will generate generic schemas that miss domain-specific recovery paths. Guardrail: Always supply a catalog of expected failure conditions, the tool's side-effect classification, and any existing HTTP status code conventions before running the prompt.
Operational Risk: Overly Permissive Retry Hints
Risk: The prompt may mark non-idempotent write operations as retryable: true, leading to duplicate charges, double-sent messages, or corrupted state when models retry automatically. Guardrail: Pair this prompt with the Idempotency Flag Description Prompt and require a human to review every retryable field on write tools before deployment.
Operational Risk: Inconsistent Error Codes Across Tools
Risk: Running this prompt independently for each tool produces divergent error code vocabularies, making it impossible for a model to write a single recovery policy across tools. Guardrail: Run the Cross-Tool Consistency Check Prompt after generating error schemas and maintain a shared error code registry that all tool schemas reference.
Good Fit: Pre-Deployment Eval Harness
Use when: You need to verify that a model can parse the error schema and take the correct recovery action before shipping the tool to production. This prompt includes eval criteria for model behavior after receiving each error type. Guardrail: Run the eval with at least three models you intend to support and flag any error type where recovery behavior diverges across providers.
Copy-Ready Prompt Template
A reusable prompt for generating a structured error response schema that models can interpret and act on.
This prompt template is designed to produce a machine-readable error schema for a given API endpoint or tool. It forces the model to define error codes, retry hints, and user-facing message templates, creating a contract that your application and the AI can both rely on. Use this when you are defining the error surface of a new tool or auditing an existing one for gaps in recoverability.
textYou are an API design expert. Your task is to produce a structured error response schema for the tool or endpoint described below. The schema must be interpretable by another AI model to decide whether to retry, ask the user for clarification, or fail permanently. [TOOL_DESCRIPTION] Generate a JSON object that conforms to the following [OUTPUT_SCHEMA]: { "error_responses": [ { "error_code": "STRING_IDENTIFIER", "http_status": 400, "condition": "Description of what triggers this error.", "retry_strategy": "no_retry | retry_with_backoff | retry_with_modified_args | ask_user", "retry_hint": "A brief instruction for the calling AI on how to modify its request.", "user_message_template": "A human-readable message with a [VARIABLE] placeholder.", "log_level": "ERROR | WARN" } ] } [CONSTRAINTS] - Include at least one error for invalid input, one for a server-side failure, and one for a permission or rate-limit issue. - The `retry_hint` must be a direct instruction to the AI, not the end user. - The `user_message_template` must not expose internal system paths or stack traces. - If the tool has a [RISK_LEVEL] of 'high', include an error for a required human approval step.
To adapt this template, replace [TOOL_DESCRIPTION] with a clear, plain-text description of what your API endpoint or tool does, including its side effects. The [OUTPUT_SCHEMA] can be extended with additional fields like error_category for analytics, but avoid removing the retry_strategy and retry_hint fields, as they are critical for downstream AI recovery logic. The [CONSTRAINTS] section is your policy lever; add rules here for compliance, security, or domain-specific error masking. After generating the schema, you must validate it against real failure modes by running the evaluation harness described in the testing section of this playbook.
Prompt Variables
Placeholders required by the Error Response Schema Design Prompt. Replace each with concrete values before running the prompt. Validation notes describe how to check that the input is well-formed and safe.
| Placeholder | Purpose | Example | Validation Notes |
|---|---|---|---|
[TOOL_NAME] | Identifies the tool or function the error schema applies to | create_order | Must match an existing tool name in the tool catalog; no whitespace or special characters |
[TOOL_DESCRIPTION] | Short summary of what the tool does, used to contextualize error semantics | Creates a new customer order with line items and payment method | Must be 1-3 sentences; must not contain PII or secrets |
[ERROR_CATEGORIES] | List of error classes the schema must cover, such as validation, auth, timeout, or business-rule failures | ["INVALID_ARGUMENT", "PERMISSION_DENIED", "RESOURCE_EXHAUSTED", "INTERNAL"] | Must be a valid JSON array of strings; each category should map to a known gRPC or HTTP error code family |
[RETRY_POLICY_CONTEXT] | Describes which errors are retryable and under what conditions, so the schema can embed retry hints | Timeout and rate-limit errors are retryable with exponential backoff; validation errors are not retryable | Must explicitly state retryable vs non-retryable categories; null allowed if no retry logic is expected |
[USER_FACING_LANGUAGE] | Target language or locale for user-facing error message templates | en-US | Must be a valid BCP-47 language tag; default to en-US if not specified |
[OUTPUT_FORMAT] | Desired output format for the error schema definition | JSON Schema | Must be one of JSON Schema, OpenAPI error object, or typed TypeScript interface; reject unsupported formats |
[EXISTING_ERROR_EXAMPLES] | Optional set of current error responses to normalize or improve | ["{"error": "bad request"}", "{"code": 500}"] | If provided, must be a valid JSON array of objects; null allowed if no existing errors exist |
[MAX_USER_MESSAGE_LENGTH] | Character limit for user-facing error message templates to prevent overly verbose responses | 280 | Must be a positive integer; typical range 140-500; reject values below 50 or above 2000 |
Implementation Harness Notes
How to wire the error response schema design prompt into a production application with validation, retries, and model recovery evaluation.
The error response schema design prompt is not a one-off query—it is a schema generation step in a larger tool-authoring workflow. In practice, you will call this prompt whenever a new API endpoint is being exposed as a tool, or when an existing tool's error contract changes. The prompt expects a [TOOL_NAME], [TOOL_DESCRIPTION], and a list of [FAILURE_MODES] as input. The output is a structured error schema (typically JSON Schema) that defines error codes, retry hints, and user-facing message templates. This schema becomes part of the tool's output contract, consumed by the orchestration layer and by downstream recovery prompts.
Wire the prompt into your tool-registration pipeline as a pre-commit or CI step. After generating the error schema, run it through a JSON Schema validator to confirm structural correctness. Then execute a set of eval harness tests that simulate the model receiving each defined error type. For each error code, verify that the model's subsequent behavior matches the retry hint: for example, a TEMPORARY error should trigger a retry with backoff, while a PERMANENT error should cause the model to escalate or ask the user for clarification. Log the model's recovery action and compare it against expected behavior. If the model ignores the retry hint or retries a permanent error, flag the schema for revision. This eval loop is critical because a well-structured error schema is useless if the model cannot interpret it correctly under production conditions.
For high-risk tools—those that mutate state, send communications, or access sensitive data—add a human review gate before the error schema is deployed. The review should confirm that error codes are unambiguous, that retry hints do not cause infinite loops, and that user-facing message templates do not leak internal system details. Store the approved schema in a versioned registry alongside the tool definition. When the tool is called at runtime, the orchestration layer should parse the error response against this schema, validate it, and then feed the structured error back to the model for recovery. Avoid the temptation to let the model generate ad-hoc error interpretations; the schema is the contract, and the model's job is to follow it.
Expected Output Contract
Defines the structured error response the model must generate when a tool call fails. Use this contract to validate that the model's output is parseable, actionable, and safe for downstream recovery logic.
| Field or Element | Type or Format | Required | Validation Rule |
|---|---|---|---|
error_code | string (enum) | Must match one of the defined error codes in [ERROR_CODE_ENUM]. No free-text codes allowed. | |
error_message | string | Must be a single sentence under 200 characters. Must not expose internal stack traces, API keys, or raw database errors. | |
retry_hint | string (enum) | Must be one of: 'immediate', 'backoff', 'no_retry', 'user_action_required'. Must be consistent with the error_code's retry policy. | |
user_facing_message | string or null | If provided, must be a non-technical, polite message suitable for display in a chat UI. Must not contain PII or system identifiers. | |
recovery_tool | string or null | If provided, must be the exact name of a tool in [AVAILABLE_TOOLS] that can resolve the error. Null if no automated recovery exists. | |
recovery_args | object or null | If recovery_tool is not null, must be a valid arguments object conforming to the recovery tool's parameter schema. Null otherwise. | |
escalation_required | boolean | Must be true if retry_hint is 'user_action_required' or if the error_code is in [CRITICAL_ERROR_CODES]. False otherwise. | |
trace_id | string (uuid) | Must be a valid UUID v4 string matching the [TRACE_ID] from the original tool call request for log correlation. |
Common Failure Modes
Error response schemas fail when the model ignores error codes, retries without fixing arguments, or exposes internal details to users. These cards cover the most common production failures and how to prevent them.
Model Ignores Error and Retries Blindly
What to watch: The model receives a structured error but retries the same invalid tool call without modifying arguments, creating infinite loops. Guardrail: Include a retry_strategy field in the error schema with explicit hints (e.g., "retry_strategy": "fix_missing_field") and enforce a max-retry counter in the application layer.
Internal Error Details Leak to Users
What to watch: The model surfaces raw error messages, stack traces, or system identifiers in user-facing responses. Guardrail: Separate internal_message (for model reasoning) from user_message (for display) in the error schema. Validate that user_message fields contain no internal paths, IDs, or technical jargon before rendering.
Model Hallucinates Recovery Actions
What to watch: When the error schema lacks explicit recovery guidance, the model invents tool calls or parameter fixes that don't exist. Guardrail: Provide a closed enum of allowed recovery_actions in the error schema (e.g., ["retry_with_fix", "ask_user", "escalate", "abort"]) and reject any model output that proposes actions outside this set.
Error Codes Are Too Generic
What to watch: Using broad codes like "error": true or "status": "failed" gives the model no signal for differential recovery. Guardrail: Define granular, machine-readable error codes (e.g., MISSING_REQUIRED_FIELD, VALUE_OUT_OF_RANGE, PERMISSION_DENIED) and map each to a specific retry or escalation path in the prompt.
Model Misinterprets Transient vs. Permanent Failures
What to watch: The model retries permanent errors (e.g., invalid credentials) or abandons transient errors (e.g., rate limits) because the schema doesn't distinguish them. Guardrail: Include a failure_type field with values TRANSIENT or PERMANENT in every error response. Instruct the model to retry only transient failures and escalate permanent ones.
Missing Context Causes Wrong Recovery
What to watch: The error schema omits which parameter or tool caused the failure, so the model guesses and fixes the wrong thing. Guardrail: Always include failed_tool, failed_parameter, and received_value fields in the error payload. Validate that recovery attempts target the exact parameter identified in the error.
Evaluation Rubric
Use this rubric to test whether the generated error response schema is production-ready before integrating it into your tool contract. Each criterion targets a specific failure mode observed when models attempt to recover from structured errors.
| Criterion | Pass Standard | Failure Signal | Test Method |
|---|---|---|---|
Error Code Uniqueness | Every error code is distinct and non-overlapping with HTTP status codes or other tool error codes in the system | Model confuses two error types and executes the wrong recovery path | Parse the generated schema and assert no duplicate codes; run a pairwise confusion test with 10 simulated error scenarios |
Retry Hint Accuracy | Retryable errors include a retry-after field or boolean flag; non-retryable errors explicitly forbid retry | Model retries a non-retryable error and enters an infinite loop | Inject a non-retryable error and assert the model does not call the same tool again within 3 turns |
User-Facing Message Safety | User-facing message templates contain no internal system details, stack traces, or PII placeholders | Generated user message leaks internal endpoint names or database identifiers | Regex scan for internal paths, hostnames, and error codes in the user-facing message field |
Schema Conformance | Output matches the defined JSON Schema exactly with all required fields present | Missing required field causes downstream parser to reject the error response | Validate 50 generated error responses against the schema using a JSON Schema validator; require 100% pass rate |
Recovery Instruction Clarity | Each error type includes a machine-readable recovery hint that maps to exactly one corrective action | Model selects an ambiguous recovery action or does nothing | Parse the recovery hint field and assert it resolves to a single action from the allowed recovery action enum |
Confidence Threshold Behavior | When the model is uncertain which error occurred, it selects a safe fallback error code and requests human review | Model guesses a specific error code with low confidence and triggers a wrong recovery path | Simulate 5 ambiguous failure scenarios and assert the model returns the fallback error code and sets requires_human_review to true |
Timeout Handling | Timeout errors include the elapsed wait duration and a flag indicating whether partial results are available | Model treats a timeout as a permanent failure and abandons the task instead of retrying with backoff | Inject a timeout error with partial results available; assert the model retries with the provided retry-after delay |
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
Start with the base prompt and a single error type. Remove the eval harness and multi-error constraints. Focus on getting one error schema shape correct before expanding.
Simplify the prompt template:
codeGenerate a JSON error response schema for [ERROR_TYPE] with fields: code, message, retry_hint.
Watch for
- Missing
retry_hintfield causing downstream retry loops - Overly generic error codes that prevent model recovery
- No distinction between client and server errors

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