This prompt is for reliability engineers and agent developers who need to turn raw, provider-specific error outputs from REST and gRPC tools into a single, agent-actionable error taxonomy. The job-to-be-done is normalization: an agent receives a 502, a gRPC UNAVAILABLE, or a malformed JSON body from an upstream API, and without a standard classification, the agent's next action—retry, fallback, escalate, abort—is a guess. This prompt takes the raw error context and maps it to a known set of error categories so that downstream retry and fallback logic can operate on clean, predictable signals instead of brittle string matching.
Prompt
API Error Classification Prompt for Agents

When to Use This Prompt
Define the job, reader, and constraints for the API Error Classification Prompt.
Use this prompt when your agent orchestrates multiple API-backed tools and you need a single classification layer before any retry or circuit-breaker decision. It is designed for production tool-calling loops where errors arrive in inconsistent shapes: HTTP status codes, gRPC status enums, cloud provider error objects (e.g., AWS, GCP, Azure), or custom gateway error bodies. The prompt expects a structured input containing the raw error payload, the tool name, and the call context, and it outputs a classification object with a standard error category, a confidence score, and a concise reason. Do not use this prompt for user-facing error translation or for deciding what to do about the error—it only classifies. Pair it with the Retry Decision Prompt or Fallback Tool Selection Prompt to act on the classification.
Before deploying, you must test this prompt against your actual provider error formats. Common failure modes include misclassifying a provider's custom rate-limit header as a generic server error, or treating an authentication failure as a transient network issue. Build an eval set from your production error logs, and require human review of the classification mapping before wiring it into automated retry loops. If your agent operates in a regulated domain where incorrect retries could cause duplicate transactions or data loss, ensure the classification output is logged as part of the audit trail and that a human-in-the-loop gate exists for UNKNOWN or low-confidence classifications.
Use Case Fit
Where the API Error Classification Prompt delivers reliable standardization and where it introduces risk.
Good Fit: Multi-Provider Agent Orchestrators
Use when: your agent calls REST, gRPC, or SDK endpoints across multiple cloud providers or internal services, each with its own error format. Guardrail: map all provider-specific codes to a single internal taxonomy before any retry or fallback logic runs.
Good Fit: Production Reliability Pipelines
Use when: you need structured error logs for dashboards, circuit breakers, or SLA reporting. Guardrail: require the prompt to output a machine-readable severity level and a human-readable summary in every classification.
Bad Fit: Single-Provider, Single-Error-Type Scripts
Avoid when: your agent only calls one well-known API and handles errors with simple try/catch. Guardrail: a static mapping dictionary in application code is cheaper, faster, and more predictable than an LLM call.
Required Inputs
Must include: raw HTTP status code, response body (even if truncated), and the tool's declared purpose. Guardrail: without the response body, the prompt cannot distinguish between a provider-specific quota error and a generic 429, leading to misclassification.
Operational Risk: Latency and Cost Amplification
Risk: adding an LLM call to every tool failure path increases p99 latency and token spend during outages. Guardrail: cache classifications for identical error signatures and bypass the prompt entirely for explicitly listed non-retryable codes.
Operational Risk: Taxonomy Drift
Risk: providers change error formats silently, causing the prompt to default to a catch-all classification. Guardrail: implement an eval that flags when the 'unknown' category exceeds a threshold, triggering a human review of the taxonomy mapping.
Copy-Ready Prompt Template
A reusable prompt that maps raw API error payloads into a standard agent-actionable error taxonomy.
This prompt template is the core classification engine for an agent's error-handling pipeline. It takes a raw error payload—whether a JSON error body from a REST API, a gRPC status object, or a provider-specific error format—and maps it to a standard taxonomy that downstream retry, fallback, and escalation prompts can consume without parsing provider-specific details. The template is designed to be wrapped in a validation harness that checks for missing fields, hallucinated error codes, and incorrect severity assignments before the classification reaches any decision-making prompt.
textYou are an API error classifier for a production agent system. Your job is to parse raw error output from an external tool call and produce a structured classification that downstream retry, fallback, and escalation prompts can act on. ## INPUT Raw error payload: [ERROR_PAYLOAD] Tool context: - Tool name: [TOOL_NAME] - HTTP method: [HTTP_METHOD] - Endpoint: [ENDPOINT] - Request timestamp: [TIMESTAMP] ## TAXONOMY Classify the error into exactly one of these categories: - TRANSIENT_NETWORK: Connection refused, DNS failure, TCP reset, TLS handshake failure. - TIMEOUT: Request exceeded deadline, upstream timed out. - RATE_LIMITED: HTTP 429, quota exceeded, throttling response. - AUTHENTICATION: HTTP 401, expired token, invalid credentials. - AUTHORIZATION: HTTP 403, insufficient permissions, scope mismatch. - INVALID_ARGUMENT: HTTP 400, 422, schema validation failure, missing required field. - NOT_FOUND: HTTP 404, resource does not exist. - CONFLICT: HTTP 409, resource version mismatch, duplicate. - SERVER_ERROR: HTTP 5xx, internal upstream failure. - SERVICE_UNAVAILABLE: HTTP 503, upstream in maintenance, overloaded. - DEPENDENCY_FAILURE: Upstream dependency returned an error that propagated. - UNKNOWN: Does not match any category above. ## OUTPUT SCHEMA Return ONLY valid JSON matching this schema: { "classification": "<category from TAXONOMY>", "severity": "critical|degraded|warning|transient", "is_retryable": true|false, "retry_reasoning": "<one sentence explaining why retry is or is not appropriate>", "provider_error_code": "<the original error code or status string from the provider>", "provider_error_message": "<the original error message, truncated to 500 chars>", "rate_limit_info": { "retry_after_seconds": <integer or null>, "quota_remaining": <integer or null> }, "requires_human_review": true|false, "human_review_reason": "<one sentence if requires_human_review is true, otherwise null>", "partial_result_available": true|false, "partial_result_description": "<description if partial_result_available is true, otherwise null>" } ## CONSTRAINTS - Do not invent error codes. Use only what appears in the raw payload. - If the error payload is empty or unparseable, set classification to UNKNOWN and severity to warning. - Set requires_human_review to true for any AUTHENTICATION or AUTHORIZATION failure that mentions credential expiry, revoked access, or scope changes. - Set severity to critical for any SERVER_ERROR or SERVICE_UNAVAILABLE that affects a write operation (POST, PUT, PATCH, DELETE). - Set severity to transient for TIMEOUT and TRANSIENT_NETWORK. - Extract retry_after_seconds from Retry-After headers or provider-specific rate-limit fields when present. - If the error body contains partial results (e.g., a batch endpoint that processed some items before failing), set partial_result_available to true and describe what was completed. - Do not include the raw error payload in your output.
To adapt this template, replace the taxonomy categories with your organization's standard error classification scheme if one exists. The severity and retryability logic in the CONSTRAINTS section should be tuned to your specific risk tolerance—for example, you may want all write-operation failures to require human review regardless of error type. The OUTPUT SCHEMA can be extended with fields like affected_entities, idempotency_key, or recommended_fallback_tool if your downstream prompts consume them. Before deploying, run this prompt through a validation harness that confirms every required field is present, classification matches one of the allowed enum values, and severity is consistent with the declared rules.
Prompt Variables
Required inputs for the API Error Classification Prompt. Each placeholder must be populated before the prompt is assembled. Validation notes describe how to verify the input is well-formed before sending it to the model.
| Placeholder | Purpose | Example | Validation Notes |
|---|---|---|---|
[ERROR_PAYLOAD] | Raw error body, headers, and status line from the failed API call | HTTP/1.1 429 Too Many Requests x-ratelimit-reset: 1700000000 {"error":{"code":"rate_limit_exceeded","message":"..."}} | Must be a non-empty string. If the tool call produced no error body, use the status code and headers only. Null not allowed; use empty string for no-body cases. |
[TOOL_NAME] | Identifier for the tool that produced the error, used for routing and logging | stripe_create_payment_intent | Must match a tool name in the agent's tool registry. Validate against the active tool manifest before prompt assembly. Non-empty string required. |
[TOOL_CATEGORY] | Functional category of the tool for severity and fallback decisions | payment_processing | Must be one of the allowed categories defined in the agent's tool taxonomy. Validate against the category enum. If unknown, use 'uncategorized' and flag for review. |
[RETRY_COUNT] | Number of previous retry attempts for this tool call | 2 | Must be a non-negative integer. If this is the first attempt, use 0. Validate as integer; reject negative values or non-numeric strings. |
[RETRY_BUDGET] | Maximum allowed retries for this tool call before escalation | 3 | Must be a positive integer. Compare against [RETRY_COUNT] before prompt assembly to detect budget exhaustion early. Reject if budget <= 0. |
[TASK_DEADLINE_ISO] | ISO 8601 timestamp for the overall task deadline, used for time-aware retry decisions | 2025-01-15T14:30:00Z | Must be a valid ISO 8601 datetime string in UTC. If no deadline exists, use null. Validate parseability with Date.parse() or equivalent before prompt assembly. |
[DEPENDENCY_GRAPH] | JSON object describing upstream and downstream tool dependencies for failure propagation analysis | {"upstream":["validate_customer"],"downstream":["send_receipt","update_ledger"]} | Must be valid JSON. If no dependencies exist, use empty object {}. Validate JSON.parse() succeeds. Reject malformed JSON or circular references. |
[ERROR_TAXONOMY_VERSION] | Version of the error taxonomy the model should map to, for schema evolution compatibility | v2.1 | Must match a supported taxonomy version in the agent's error handling config. Validate against the allowed version list. If version is unsupported, abort prompt assembly and alert. |
Implementation Harness Notes
How to wire the API Error Classification prompt into a production agent's tool-call loop with validation, logging, and safe defaults.
This prompt is designed to sit directly in the agent's error-handling path, immediately after a tool call returns a non-2xx HTTP status or a non-OK gRPC status. The agent's orchestrator should catch the raw error object—including the status code, response headers, and response body—and inject it into the [RAW_ERROR] placeholder. The prompt's structured output then becomes the single source of truth for all downstream decisions: whether to retry, fall back, escalate, or abort. Do not pass the raw error string directly to a retry or fallback prompt; the classification step prevents brittle string matching and ensures consistent decision-making across heterogeneous APIs.
Wire the prompt into a dedicated classify_api_error function within your agent's tool execution layer. This function should accept the raw error payload, call the LLM with the classification prompt, and parse the JSON response into a typed error object. Implement a strict output validator that checks for the required fields (error_category, is_retryable, retry_strategy, user_facing_message, severity) and rejects malformed responses. If validation fails, retry the classification call once; if it fails again, default to error_category: "UNKNOWN", is_retryable: false, and severity: "CRITICAL" to force safe escalation. Log every classification result—including the raw error, the classified output, and the validator result—as a structured event for later trace analysis and retry-storm detection.
For model choice, a fast, low-cost model like gpt-4o-mini or claude-3-haiku is sufficient for this classification task, as it requires pattern matching against HTTP/gRPC semantics rather than deep reasoning. Set temperature=0 to maximize output consistency. If your agent uses many provider-specific APIs (Stripe, AWS, Twilio), maintain a provider error registry—a small JSON map of known provider error codes to your standard taxonomy—and pass it into the [PROVIDER_ERROR_MAP] placeholder. This grounds the model in your specific API surface and reduces misclassification of opaque, provider-specific error codes. Do not rely on the model's parametric knowledge of third-party APIs; it will hallucinate error meanings for obscure or versioned endpoints.
The most common production failure mode is silent misclassification of 5xx errors as non-retryable. Always include an eval that tests a sample of 502, 503, and 504 responses against your provider map to confirm they are classified as TRANSIENT_SERVICE_ERROR with is_retryable: true. A second failure mode is information leakage into user-facing messages: the user_facing_message field must never contain stack traces, internal IPs, or raw error bodies. Add a post-classification sanitizer that scans the generated message for patterns like file paths, IP addresses, and stack trace signatures, and replaces the message with a safe fallback if any are detected. Finally, if the agent is operating in a regulated domain, route all CRITICAL severity classifications to a human review queue before any automated fallback or abort action is executed.
Expected Output Contract
Fields, types, and validation rules for the standard agent-actionable error taxonomy produced by the API Error Classification Prompt. Use this contract to validate model output before routing to retry, fallback, or escalation logic.
| Field or Element | Type or Format | Required | Validation Rule |
|---|---|---|---|
error_class | enum string | Must match one of: TRANSIENT, CLIENT_FAULT, SERVER_FAULT, AUTH, RATE_LIMIT, DEPENDENCY, TIMEOUT, UNKNOWN. Reject any value not in this set. | |
status_code | integer or null | Must be a valid HTTP status code (100-599) or null if not applicable. Reject negative numbers or codes outside range. | |
provider_error_code | string or null | If present, must match the provider's documented error code format. Null allowed when provider does not expose a code. | |
retry_eligible | boolean | Must be true or false. Reject truthy/falsy strings. Set to false when error_class is AUTH or CLIENT_FAULT unless overridden by provider-specific retry guidance. | |
retry_strategy | enum string or null | Required when retry_eligible is true. Must be one of: IMMEDIATE, EXPONENTIAL_BACKOFF, FIXED_DELAY, AFTER_REAUTH. Null when retry_eligible is false. | |
fallback_tool_id | string or null | If provided, must match a tool_id in the active tool registry. Null when no suitable fallback exists. Reject non-null values that do not resolve to a registered tool. | |
user_facing_message | string | Must be non-empty. Must not contain raw stack traces, internal IPs, secret keys, or provider-internal error details. Validate with PII and secret scanning regex. | |
classification_confidence | float | Must be a number between 0.0 and 1.0 inclusive. Reject values outside range. Values below 0.7 should trigger human review or secondary classification. |
Common Failure Modes
API error classification prompts fail in predictable ways that silently corrupt agent behavior. These cards cover the most common failure modes and the guardrails that prevent them from reaching production.
Provider-Specific Error Body Drift
What to watch: The prompt relies on parsing error bodies that change across API versions, regions, or undocumented provider updates. A field rename or new error wrapper causes the classifier to default to unknown_error for every failure. Guardrail: Test the prompt against a golden set of real error payloads from each provider version you support. Add a validation rule that flags when unknown_error exceeds 10% of classifications in any 5-minute window.
Status Code Alone Is Insufficient
What to watch: The prompt classifies errors using only HTTP status codes or gRPC codes without inspecting the error body. A 400 with a rate-limit body gets classified as invalid_request instead of rate_limited, causing the retry layer to skip backoff and hammer the endpoint. Guardrail: Require the prompt to extract both the protocol-level code and the provider-specific error type from the body. Add an eval case where a 429 body arrives inside a 400 response to verify correct classification.
Hallucinated Error Taxonomies
What to watch: The model invents error categories that don't exist in your taxonomy when it encounters an unfamiliar error pattern. The agent then branches on a hallucinated category and executes the wrong recovery path. Guardrail: Constrain the output to a closed enum defined in the prompt. Add a post-processing validator that rejects any classification not in the allowed set and routes the raw error to a human review queue.
Retryable vs. Non-Retryable Confusion
What to watch: The prompt misclassifies a permanent error (expired credential, missing resource) as transient, triggering retry loops that waste budget and delay escalation. Or it classifies a transient error (brief overload, DNS blip) as permanent and aborts prematurely. Guardrail: Include explicit examples of boundary cases in the prompt. Add an eval that measures retry classification accuracy against a labeled dataset of transient and permanent failures, with separate precision targets for each class.
Silent Parsing Failures on Malformed Responses
What to watch: The tool returns a non-JSON error body, an HTML page, or a truncated response. The prompt either fails to parse it and returns a generic fallback, or worse, extracts a misleading fragment and classifies it confidently. Guardrail: Add a pre-classification check that validates the error body format before the prompt runs. If the body isn't parseable, bypass classification and emit a malformed_response category with the raw payload attached for diagnosis.
Context Leakage Across Tool Calls
What to watch: The agent's conversation context accumulates error details from previous tool calls. The classification prompt inadvertently uses stale error context from an earlier failure to classify the current error, producing a plausible but wrong category. Guardrail: Isolate each classification request with a fresh prompt instance or explicitly clear prior error context. Add an eval that sends two different errors in sequence and verifies the second classification isn't contaminated by the first.
Evaluation Rubric
Use these criteria to test the API Error Classification Prompt before deployment. Each row targets a specific failure mode common in production tool-calling loops.
| Criterion | Pass Standard | Failure Signal | Test Method |
|---|---|---|---|
HTTP Status Code Mapping | Correctly maps 400, 401, 403, 404, 429, 500, 502, 503 to the standard taxonomy categories (e.g., CLIENT_ERROR, AUTH_ERROR, RATE_LIMIT, SERVER_ERROR). | Misclassifies 429 as SERVER_ERROR or 403 as CLIENT_ERROR. | Run a batch of 100 raw HTTP error responses. Assert classification accuracy > 98%. |
gRPC Status Code Mapping | Correctly maps UNAVAILABLE, DEADLINE_EXCEEDED, PERMISSION_DENIED, RESOURCE_EXHAUSTED to the standard taxonomy. | Maps UNAVAILABLE to UNKNOWN or ignores gRPC-specific codes. | Feed 20 canonical gRPC error payloads. Assert exact match on expected taxonomy category. |
Provider-Specific Error Body Parsing | Extracts the provider error code (e.g., AWS error code, Stripe error type) and maps it to the standard taxonomy when a mapping rule exists. | Ignores the provider-specific field and falls back to a generic HTTP status classification. | Test with 5 distinct provider error bodies (AWS, Stripe, Twilio). Assert the provider code is present in the output and correctly mapped. |
Unknown Error Handling | Classifies any unrecognized error code or body as UNKNOWN and includes the raw error snippet for human review. | Hallucinates a classification (e.g., guessing TIMEOUT) or drops the raw error entirely. | Inject a malformed JSON response and a custom 999 status code. Assert classification is UNKNOWN and raw_error field is populated. |
Retryability Flag Accuracy | Sets retryable: true only for transient errors (TIMEOUT, RATE_LIMIT, SERVER_ERROR_5XX) and false for client errors (AUTH_ERROR, PERMISSION_ERROR, INVALID_ARGUMENT). | Flags a 400 Bad Request as retryable or a 503 Service Unavailable as non-retryable. | Validate the retryable boolean against a labeled test set of 50 transient and non-transient errors. Assert F1 score > 0.95. |
Output Schema Compliance | Output is valid JSON matching the defined [OUTPUT_SCHEMA] with all required fields present. | Output is missing the retryable field, or the error_code is not a string. | Validate output with a JSON Schema validator. Assert no validation errors across 100 test runs. |
Confidence Score Calibration | Assigns a confidence score between 0.0 and 1.0. Score is > 0.9 for clear HTTP status codes and < 0.7 for ambiguous or empty error bodies. | Assigns 1.0 confidence to an UNKNOWN classification or 0.1 confidence to a clear 404. | Run 20 mixed test cases. Assert confidence is a float, and check that the mean confidence for UNKNOWN cases is below 0.7. |
Empty Body Handling | When the response body is empty but an HTTP status code exists, classifies based on the status code and sets raw_error to null. | Fails to produce output or hallucinates an error body. | Send a 502 response with an empty body. Assert classification is SERVER_ERROR and raw_error is null. |
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 taxonomy and a single provider's error format. Use the prompt with a lightweight JSON schema check but skip full retry integration. Focus on getting the classification labels right for your most common errors.
Replace [ERROR_BODY] with raw error text. Replace [TAXONOMY] with a minimal set: TRANSIENT, PERMANENT, AUTH, RATE_LIMIT, UNKNOWN. Drop the [PROVIDER] field if you're only testing one API.
Watch for
- Overly broad
UNKNOWNclassifications masking real failure patterns - Missing schema validation on the output JSON
- Provider-specific error codes that don't map cleanly to your taxonomy

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