This prompt is for agent infrastructure developers who are building the orchestration layer for complex, multi-step agent workflows. The job-to-be-done is not simply deciding whether to retry a single failed tool call; it's about managing the entire lifecycle of a task through multiple failure domains. You need a prompt that acts as a deterministic state machine, consuming the current retry state, error context, and workflow progress to output the next valid state transition, associated actions, and guard conditions. The ideal user is an engineer wiring this prompt into a workflow engine (like Temporal, Prefect, or a custom async job runner) where the AI's output directly controls system behavior.
Prompt
Retry State Machine Prompt for Complex Agent Workflows

When to Use This Prompt
Define the job, reader, and constraints for the Retry State Machine Prompt.
Use this prompt when your agent workflow has more than two retry stages (e.g., immediate retry, backoff retry, argument modification, fallback tool, human escalation, dead-letter queue). It is appropriate when the transition logic is too complex for a simple if/else block but must be auditable and free of hallucinated states. You must provide the prompt with a strict [STATE_DEFINITIONS] schema, the [CURRENT_STATE], [ERROR_CONTEXT], and [WORKFLOW_PROGRESS]. The prompt is not a general-purpose error handler; it requires a pre-defined state machine graph. Do not use this prompt for simple single-tool retries where a Retry Decision Prompt for Transient Failures would suffice, or as a replacement for a proper workflow engine's built-in retry policies.
Before implementing, map out your complete state machine on paper. The prompt's primary failure mode is suggesting a transition that is not in your defined state graph, which can cause the orchestrator to crash or loop infinitely. To mitigate this, the implementation harness must validate the output against your state definitions and reject invalid transitions. This prompt is a high-risk control-plane component; a bug here can deadlock an entire fleet of agents. Always pair it with a Retry Budget Exhaustion Escalation Prompt for terminal states and ensure every state has a defined timeout to prevent infinite loops.
Use Case Fit
Where the Retry State Machine Prompt delivers reliable agent recovery and where it introduces unnecessary complexity or risk.
Good Fit: Multi-Step Agent Workflows with Recoverable Failures
Use when: your agent orchestrates 3+ tool calls where transient failures (timeouts, rate limits, temporary unavailability) are expected and recovery is possible. The state machine prompt excels at tracking progress, applying backoff, and resuming from the last known good state without re-executing completed steps. Guardrail: define a maximum state depth and total retry budget before the workflow begins to prevent infinite loops.
Bad Fit: Single Atomic Tool Calls
Avoid when: the workflow consists of a single tool call with no intermediate state to preserve. A full retry state machine adds latency and complexity without benefit. A simpler retry decision prompt or idempotency check is more appropriate. Guardrail: route single-call retries to a lightweight retry eligibility prompt instead, and reserve the state machine for workflows with 3+ distinct steps.
Required Inputs: Workflow Progress, Error Context, and Retry Budget
What to watch: the state machine prompt cannot make sound decisions without knowing which steps succeeded, which failed, what error was returned, and how many retries remain. Missing any of these inputs leads to duplicate execution or premature abandonment. Guardrail: enforce a strict input schema that includes completed_steps, failed_step, error_classification, retry_count, max_retries, and deadline_remaining before invoking the prompt.
Operational Risk: Deadlock from Circular State Transitions
What to watch: poorly constrained state machines can oscillate between retry and fallback states without making progress, consuming retry budget and wall-clock time. This is especially dangerous when two states each consider the other a valid next transition. Guardrail: implement a state transition validator that rejects cycles shorter than 3 transitions and enforces a monotonic progress metric (e.g., retry count must increase or state must advance toward a terminal condition).
Operational Risk: State Drift from Partial Execution
What to watch: when a tool call partially succeeds before failing, the agent's state may not reflect reality. The state machine might assume a step completed when side effects were only partially applied, leading to inconsistent recovery. Guardrail: require each tool to report an atomic success/failure status with a partial_result flag. The state machine must treat partial_result: true as a special state requiring reconciliation before advancing.
Operational Risk: Deadline Overrun in Time-Sensitive Workflows
What to watch: the state machine may continue retrying steps even as the overall task deadline approaches, producing a complete but late result that is useless to the caller. Guardrail: inject deadline_remaining into every state evaluation. When remaining time drops below the estimated duration of the next retry cycle, force a terminal decision: abort, return partial results, or escalate to a human.
Copy-Ready Prompt Template
A reusable prompt that drives a retry state machine for agent tool calls, producing the next state, guard conditions, and actions from current workflow context.
This prompt template implements a deterministic retry state machine for complex agent workflows. It expects the current retry state, error context, workflow progress, and a defined state transition table as input. The model's job is not to invent retry logic but to apply the provided transition rules to the current context and output the next state, associated actions, and guard conditions in a structured format. This separation keeps retry policy auditable and testable outside the model while letting the model handle the messy work of matching real error signals to the right state transition.
textYou are a retry state machine executor for an agent workflow. Your task is to evaluate the current state, error context, and workflow progress against a provided state transition table, then output the next state with associated actions and guard conditions. ## STATE TRANSITION TABLE [STATE_TRANSITION_TABLE] ## CURRENT STATE - Current retry state: [CURRENT_STATE] - Retry count for current operation: [RETRY_COUNT] - Total retries consumed in workflow: [TOTAL_RETRIES] - Retry budget remaining: [RETRY_BUDGET] - Workflow deadline: [DEADLINE] - Current time: [CURRENT_TIME] ## ERROR CONTEXT - Tool name: [TOOL_NAME] - Error classification: [ERROR_CLASSIFICATION] - Error message: [ERROR_MESSAGE] - HTTP/gRPC status code (if applicable): [STATUS_CODE] - Retry-After header value (if present): [RETRY_AFTER] - Partial result available: [PARTIAL_RESULT_AVAILABLE] - Idempotency status of operation: [IDEMPOTENCY_STATUS] ## WORKFLOW PROGRESS - Completed steps: [COMPLETED_STEPS] - Remaining steps: [REMAINING_STEPS] - Dependency graph: [DEPENDENCY_GRAPH] - Fallback chain for failed tool: [FALLBACK_CHAIN] - Circuit breaker status for [TOOL_NAME]: [CIRCUIT_BREAKER_STATUS] ## OUTPUT SCHEMA Return a valid JSON object with these fields: { "next_state": "string (must match a state defined in the transition table)", "confidence": "float between 0.0 and 1.0", "actions": [ { "action_type": "string (retry | fallback | escalate | abort | wait | circuit_break | partial_continue)", "target_tool": "string | null", "modified_arguments": "object | null", "wait_duration_seconds": "integer | null", "reason": "string" } ], "guard_conditions": [ { "condition": "string (condition that must be true before executing actions)", "evaluation_context": "string (what to check to verify this condition)" } ], "escalation_packet": { "summary": "string (human-readable failure summary)", "attempted_recoveries": ["string"], "partial_results_summary": "string | null", "recommended_human_action": "string | null" }, "audit_log_entry": "string (machine-readable log line for observability)" } ## CONSTRAINTS - Do not transition to a state not defined in [STATE_TRANSITION_TABLE]. - If [RETRY_BUDGET] is zero, do not output a retry action. - If [DEADLINE] minus [CURRENT_TIME] is less than the estimated retry duration, prefer abort or escalate. - If [IDEMPOTENCY_STATUS] is "non-idempotent" and [PARTIAL_RESULT_AVAILABLE] is true, include a guard condition that checks for duplicate side effects before retrying. - If [CIRCUIT_BREAKER_STATUS] is "open", do not output a retry action for [TOOL_NAME]. - Never include credentials, tokens, or secrets in any output field. - If confidence is below 0.7, include an escalation_packet even if the action is not escalate. ## EXAMPLES [EXAMPLES]
To adapt this template, replace each square-bracket placeholder with data from your agent runtime. The [STATE_TRANSITION_TABLE] is the most critical input: define it as a structured object mapping each valid state to its permitted next states, transition criteria, and associated actions. The [EXAMPLES] placeholder should contain 2-4 worked examples showing correct state transitions for common failure patterns (transient timeout, auth failure, rate limit, partial result). Wire the output through a JSON schema validator before acting on it. For high-risk workflows, add a human approval gate when next_state is escalate or abort. Test this prompt against a golden set of error scenarios where the correct next state is known, and measure exact-match accuracy on next_state plus structural validity of actions and guard_conditions.
Prompt Variables
Required inputs for the Retry State Machine Prompt. Each variable must be populated before the prompt is assembled. Missing or malformed inputs will cause incorrect state transitions or deadlock.
| Placeholder | Purpose | Example | Validation Notes |
|---|---|---|---|
[CURRENT_STATE] | The active state in the retry state machine before evaluation | RETRYING_WITH_MODIFIED_ARGS | Must match one of the defined state enum values. Reject unknown states before prompt assembly. |
[STATE_MACHINE_DEFINITION] | Full JSON definition of all valid states, transitions, and guard conditions | {"states": ["IDLE", "RETRYING", ...], "transitions": [...]} | Parse as JSON. Validate that all states referenced in transitions exist. Check for unreachable states and missing terminal states. |
[ERROR_CONTEXT] | Structured error object from the failed tool call including type, code, message, and headers | {"error_type": "RATE_LIMITED", "status_code": 429, "retry_after_seconds": 30} | Must include error_type and status_code at minimum. Validate error_type against known taxonomy. Null allowed only if state is IDLE. |
[WORKFLOW_PROGRESS] | Current progress snapshot including completed steps, remaining steps, and partial results | {"completed_steps": 3, "total_steps": 7, "partial_results": {...}} | Parse as JSON. Validate that completed_steps <= total_steps. Check for missing required fields in partial_results if state is RECOVERING. |
[RETRY_BUDGET_REMAINING] | Number of retry attempts still available before escalation is required | 2 | Must be a non-negative integer. If 0, the prompt must not output a RETRYING transition. Validate type before prompt assembly. |
[DEADLINE_REMAINING_SECONDS] | Seconds remaining before the overall task SLA expires | 45 | Must be a positive number or null if no deadline exists. If present and below estimated retry duration, the prompt must output ABORT or ESCALATE. |
[TOOL_IDEMPOTENCY_MAP] | Map of tool names to boolean idempotency flags for retry safety checks | {"create_order": false, "fetch_status": true} | Parse as JSON. Every tool in the workflow must have an entry. Missing entries should be treated as false (non-idempotent) by default. |
[PREVIOUS_STATE_HISTORY] | Ordered list of states visited in this workflow for loop and deadlock detection | ["IDLE", "RETRYING", "RETRYING_WITH_BACKOFF"] | Must be a JSON array. Check for repeated consecutive states exceeding threshold (default 3) as deadlock signal. Empty array allowed for initial invocation. |
Implementation Harness Notes
How to wire the retry state machine prompt into a production agent orchestrator with validation, deadlock detection, and audit logging.
The retry state machine prompt is not a standalone decision-maker; it is a deterministic state transition engine wrapped in a language model call. The implementation harness must treat the prompt output as a structured state transition record that the orchestrator enforces, not as a suggestion. The harness owns the state machine definition, validates every transition against the allowed state graph, enforces guard conditions, and logs every transition for debugging and audit. The prompt's job is to interpret the current state, error context, and workflow progress to propose the next state and associated actions. The harness's job is to accept or reject that proposal based on hard rules.
Wire the prompt into your agent orchestrator as a dedicated state transition function. The function receives the current retry state (e.g., INITIAL_ATTEMPT, FIRST_RETRY, BACKOFF_WAIT, FALLBACK_ACTIVE, CIRCUIT_OPEN, ESCALATE_TO_HUMAN, ABORT), the error context (tool name, error classification, attempt count, retry budget remaining, deadline timestamp), and workflow progress (completed steps, remaining steps, partial results). The prompt returns a JSON object with next_state, actions (an array of tool calls, wait instructions, or escalation payloads), guard_conditions (boolean checks the harness must verify before applying the transition), and rationale. Before executing the transition, the harness validates that next_state is a legal transition from current_state using a predefined adjacency matrix. If the proposed transition is illegal, the harness logs a state machine violation and falls back to a safe default (typically ESCALATE_TO_HUMAN or ABORT depending on risk level).
Deadlock detection is critical. The harness must track the state transition history and detect cycles that indicate the agent is oscillating between states without making progress. Common deadlock patterns include FIRST_RETRY → BACKOFF_WAIT → FIRST_RETRY loops without argument modification, or FALLBACK_ACTIVE → FALLBACK_ACTIVE chains where fallback tools repeatedly fail. Implement a maximum transition count per workflow step and a cycle detector that flags repeated state sequences. When deadlock is detected, the harness forces an ESCALATE_TO_HUMAN transition with the full transition history attached. For high-risk workflows, require human approval on any transition to ABORT or CIRCUIT_OPEN states. Log every transition with a correlation ID, timestamp, current state, proposed state, validation result, and the full prompt input/output for traceability. Use structured logging that your observability stack can query—this is essential for debugging production retry storms and auditing agent behavior.
Model choice matters for this prompt. The retry state machine requires strict schema adherence and low-latency responses, not creative reasoning. Use a fast, instruction-tuned model with strong JSON mode support (e.g., GPT-4o with structured outputs, Claude 3.5 Sonnet with tool use, or a fine-tuned smaller model if your state space is limited). Set temperature=0 to eliminate variance in state transition decisions. Implement a response timeout of 2-5 seconds; if the model call exceeds this, treat it as a transient failure and retry the prompt call itself once before falling back to a hardcoded safe transition. Cache the state adjacency matrix and guard condition evaluators in the harness, not in the prompt—these are deterministic rules that should never depend on model interpretation. The prompt should only handle the fuzzy parts: interpreting error context, assessing workflow progress, and generating rationale.
Before shipping, build a test harness that exercises every legal state transition and at least three illegal transitions per state. Verify that the harness rejects illegal transitions and that deadlock detection triggers within the expected cycle count. Test with real tool failure scenarios: timeouts, 429 rate limits, 5xx server errors, malformed JSON responses, and empty result sets. Measure end-to-end latency from failure detection to next action; if the prompt call adds more than 500ms to your retry loop, consider caching common transition patterns or using a smaller model for high-frequency retry decisions. Finally, ensure your audit logs capture enough context to answer 'why did the agent retry this call seven times?' without reconstructing state from scattered log lines.
Expected Output Contract
The retry state machine prompt must produce a deterministic state transition object. Use this contract to validate the output before the agent acts on it. Every field is required unless noted.
| Field or Element | Type or Format | Required | Validation Rule |
|---|---|---|---|
current_state | string (enum: IDLE | RETRYING | WAITING | FALLBACK | ESCALATED | ABORTED | COMPLETED) | Must match one of the defined state enum values exactly. Reject unknown states. | |
next_state | string (enum: IDLE | RETRYING | WAITING | FALLBACK | ESCALATED | ABORTED | COMPLETED) | Must be a valid state. Must differ from current_state unless state is COMPLETED or ABORTED. Reject self-transitions on active states. | |
transition_reason | string | Non-empty string summarizing why the transition occurred. Must reference specific error context or progress evidence from [ERROR_CONTEXT] or [WORKFLOW_PROGRESS]. | |
action | object | Must contain action_type (string) and params (object). action_type must be one of: retry, wait, fallback, escalate, abort, complete. params schema must match action_type. | |
action.action_type | string (enum: retry | wait | fallback | escalate | abort | complete) | Must be consistent with next_state. retry -> RETRYING, wait -> WAITING, fallback -> FALLBACK, escalate -> ESCALATED, abort -> ABORTED, complete -> COMPLETED. | |
action.params | object | Schema depends on action_type. retry requires retry_attempt (int), backoff_seconds (int), modified_args (object|null). wait requires duration_seconds (int). fallback requires fallback_tool_name (string). escalate requires escalation_target (string) and handoff_packet (object). abort requires reason_code (string). complete requires output_summary (string). | |
guard_conditions | array of objects | Each object must have condition (string) and satisfied (boolean). At least one guard condition required. All conditions must be satisfied for the transition to be valid. Reject if any guard is false. | |
deadlock_risk | boolean | Must be true if the transition could create a cycle without progress (e.g., retry -> same error -> retry with no argument change). Agent must escalate if deadlock_risk is true and retry_budget is exhausted. |
Common Failure Modes
State machine prompts fail in predictable ways when deployed in production agent workflows. These cards cover the most common failure modes and the guardrails that prevent them.
Deadlock from Missing Transition
What to watch: The state machine reaches a state with no defined outgoing transition for the current error condition, causing the agent to hang indefinitely or loop on a no-op. This happens when error taxonomies evolve but the state machine prompt isn't updated. Guardrail: Include a catch-all UNHANDLED transition in every state that escalates to a human operator or a safe abort state. Validate state machine completeness by fuzzing every state with every error category before deployment.
Infinite Retry Loop on Non-Transient Errors
What to watch: The prompt misclassifies a permanent failure (schema mismatch, auth error, invalid argument) as transient and authorizes retries that will never succeed. The agent burns its retry budget with identical failing calls. Guardrail: Require the prompt to output a failure_classification field before deciding to retry. Gate all retry transitions on classification != 'PERMANENT'. Add a hard max_retries_per_state counter in the harness, not just in the prompt.
State Drift from Accumulated Context
What to watch: Over multiple retry cycles, the prompt's context window accumulates stale error messages, partial results, and earlier state decisions. The model begins reasoning from outdated state and proposes transitions that don't match the current situation. Guardrail: Truncate or summarize error history before each state evaluation. Include only the current state, the most recent error, the retry count, and the remaining budget. Test with long retry chains to detect context pollution.
Premature Escalation Under Deadline Pressure
What to watch: When a deadline or SLA is mentioned in the prompt, the model may escalate to a human or abort too early—even when one more retry with modified arguments would likely succeed. The prompt overweights time pressure and underweights recovery probability. Guardrail: Separate deadline evaluation from recovery decision logic. Require the prompt to output a recovery_viability_score before considering deadline pressure. Test with edge-case deadlines to ensure the model doesn't abandon viable retries.
Silent Argument Corruption on Retry
What to watch: The prompt modifies tool arguments for a retry attempt but introduces semantic drift—changing a filter value, dropping a required field, or coercing a type in a way that produces valid-looking but incorrect results. The agent proceeds with corrupted data. Guardrail: Require the prompt to output both original_arguments and modified_arguments with a modification_rationale field. Validate that modified arguments still satisfy the tool's input schema. Flag any modification that changes enumerated values or removes required fields.
Unbounded State Space Explosion
What to watch: The prompt defines states that multiply combinatorially—retry count × error type × tool × fallback depth—creating a state space too large for the model to reason about reliably. The prompt produces inconsistent transitions for the same logical situation. Guardrail: Keep the state machine prompt to a finite set of named states (ideally under 12). Push combinatorial logic into the harness as pre-computed flags (retry_exhausted, fallback_available, deadline_remaining) passed as input fields rather than asking the model to derive them.
Evaluation Rubric
Criteria for testing the retry state machine prompt before deployment. Each row targets a specific failure mode common in stateful retry logic.
| Criterion | Pass Standard | Failure Signal | Test Method |
|---|---|---|---|
State Transition Validity | Every transition maps to a defined state in the allowed state enum | Output contains an undefined state or skips a required intermediate state | Parse output against state machine schema; reject any state not in [IDLE, RETRYING, WAITING, FALLBACK, ESCALATED, ABORTED, COMPLETED] |
Deadlock Detection | Prompt identifies when the same [RETRY_STATE] repeats with identical [ERROR_CONTEXT] and no progress | Output suggests another retry without modified arguments or increased backoff when retry count exceeds [MAX_RETRIES] | Feed looped state with count=MAX_RETRIES; assert transition is ESCALATED or ABORTED, not RETRYING |
Guard Condition Enforcement | Transition includes required guard fields: backoff_ms, modified_args, reason | Output proposes RETRYING but omits backoff_ms or uses backoff_ms=0 for a rate-limit error | Validate output JSON schema; assert backoff_ms > 0 when error_type is RATE_LIMITED |
Idempotency Risk Flagging | Prompt flags non-idempotent operations before retrying and suggests state reconciliation | Output recommends retry for a POST /payments call without checking previous partial state | Provide error_context with idempotency_hint=false; assert output contains idempotency_warning=true or transition is ESCALATED |
Deadline Awareness | Prompt compares estimated retry duration against remaining [TASK_DEADLINE_MS] and aborts if retry would exceed deadline | Output proposes retry when retry_duration_estimate > remaining_time_budget | Set deadline=5000ms, retry_estimate=8000ms; assert transition is ABORTED or FALLBACK, not RETRYING |
Fallback Chain Completeness | When transitioning to FALLBACK, output includes fallback_tool, capability_gap, and expected_degradation | Output transitions to FALLBACK but fallback_tool is null or matches the failed tool | Provide tool_registry with valid fallbacks; assert fallback_tool is in registry and differs from failed_tool |
Escalation Packet Quality | When transitioning to ESCALATED, output includes failure_summary, attempted_recoveries, partial_results, and recommended_human_action | Output escalates with failure_summary='see logs' or omits partial_results when data exists | Provide partial tool output in context; assert escalation packet contains all four required fields with non-empty values |
Retry Budget Exhaustion | Prompt tracks [RETRY_COUNT] against [MAX_RETRIES] and escalates when budget is exhausted | Output proposes RETRYING when retry_count >= max_retries | Set retry_count=3, max_retries=3; assert transition is not RETRYING |
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
Add a strict JSON output schema with fields: next_state, action, guard_conditions_met, and transition_reason. Include the full state machine definition in the prompt with all valid transitions. Add a pre-flight check: "If [CURRENT_STATE] is a terminal state, return next_state: CURRENT_STATE with action: NOOP." Implement a post-processing validator that rejects invalid state transitions before executing the action.
Watch for
- Hallucinated transitions that violate the state machine definition
- The model getting stuck in
RETRYwithout progressing toFALLBACK - Silent format drift in
guard_conditions_met(e.g., strings instead of booleans)

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