Inferensys

Prompt

Agent Escalation Circuit Breaker Prompt

A practical prompt playbook for using the Agent Escalation Circuit Breaker Prompt in production AI workflows to protect systems from cascading failures.
Developer demonstrating multi-agent tool use, agent tool selection interface on laptop, casual tech demo moment.
PROMPT PLAYBOOK

When to Use This Prompt

Understand the job-to-be-done, ideal user, required context, and when not to use the Agent Escalation Circuit Breaker Prompt.

This prompt is designed for SRE and platform engineering teams who need to protect multi-agent systems from cascading failures. Its job is to act as an automated decision point that evaluates recent failure history for a specific agent or tool and determines whether the circuit should be OPEN (stop routing work), HALF_OPEN (allow a single probe request), or CLOSED (resume normal routing). The ideal user is an engineer building or operating an agent orchestration layer that can programmatically enforce routing decisions based on the structured circuit state output. You should use this prompt when you have a system where a single failing agent can cause upstream backpressure, resource exhaustion, or degraded user experience across the entire agent graph.

To use this prompt effectively, you must provide a structured input containing recent failure events (with timestamps and error types), the current circuit state, and your configured thresholds for failure count, failure rate, and cooldown duration. The prompt is not a simple retry wrapper or a static timeout mechanism. It performs a reasoned state transition by weighing the recency and density of failures against your recovery parameters. For example, if an agent has experienced 5 timeout errors in the last 60 seconds and your threshold is 3, the prompt should recommend transitioning from CLOSED to OPEN and specify a cooldown period before attempting HALF_OPEN. The output includes the new state, a rationale, and a recommended cooldown timestamp, which your orchestration layer can consume directly.

Do not use this prompt for simple retry logic where a static exponential backoff is sufficient, or in systems where failure is expected and handled gracefully without affecting other components. It is also inappropriate for workflows where the cost of stopping all traffic to an agent is higher than the cost of occasional failures—for instance, in best-effort advisory agents that do not block critical paths. Before implementing this prompt, ensure your orchestration layer can enforce the circuit state transitions and that you have a monitoring system to track state changes, failure counts, and recovery success rates. Human review of circuit state transitions is recommended during initial tuning and for high-risk production systems where an incorrect OPEN state could cause widespread service degradation.

PRACTICAL GUARDRAILS

Use Case Fit

Where the Agent Escalation Circuit Breaker Prompt works and where it does not. Use these cards to decide if this prompt fits your reliability workflow before you integrate it.

01

Good Fit: Multi-Agent Pipelines with Cascading Failure Risk

Use when: you have a chain or graph of agents where one agent's failure can trigger downstream failures. Guardrail: wire the circuit breaker prompt as a pre-handoff gate that inspects recent failure counts and agent health before allowing the next agent to receive work.

02

Bad Fit: Single-Agent, Stateless Workflows

Avoid when: your system has only one agent with no handoffs or the agent is stateless per request. Guardrail: a circuit breaker adds latency and complexity without benefit here. Use a simple retry-with-backoff pattern instead.

03

Required Inputs: Failure Count, Cooldown Window, and Agent Health State

What to watch: the prompt cannot make a safe decision without accurate failure tracking. Guardrail: ensure your harness provides a structured input with failure_count, last_failure_timestamp, cooldown_period_seconds, and target_agent_status before invoking the prompt.

04

Operational Risk: Stale Circuit State Causing False Positives

What to watch: if the failure counter is not reset after a successful recovery, the circuit breaker may permanently block a healthy agent. Guardrail: implement an automatic reset on first successful health check after the cooldown period and log every state transition for audit.

05

Operational Risk: Threshold Tuning Without Production Data

What to watch: hardcoded failure thresholds chosen during development rarely survive production traffic patterns. Guardrail: deploy the prompt with configurable thresholds and run a shadow mode that logs what decisions would have been made before enforcing circuit breaks.

06

Not a Replacement for Infrastructure Circuit Breakers

What to watch: this prompt governs agent-level routing logic, not network timeouts or service mesh circuit breaking. Guardrail: layer this prompt on top of infrastructure circuit breakers. The prompt decides who to route to; the infrastructure enforces how long to wait.

PROMPT PLAYBOOK

Copy-Ready Prompt Template

A reusable prompt with square-bracket placeholders for evaluating agent circuit state transitions.

This prompt template is the core decision engine for an agent escalation circuit breaker. It is designed to be wired into your orchestration layer, receiving structured inputs about recent agent failures, the current circuit state, and operational thresholds. The model's job is not to execute the agent's task, but to act as a reliability safeguard, evaluating whether the system should continue, pause, or reroute work to prevent cascading failures. The template uses square-bracket placeholders for all dynamic inputs, making it ready for parameterization in your application code before each inference call.

text
You are a circuit breaker controller for an autonomous agent system. Your sole responsibility is to evaluate the health of an agent execution path and decide whether to allow, throttle, or block further requests.

# CURRENT CIRCUIT STATE
- Circuit State: [CIRCUIT_STATE]
- Consecutive Failures: [FAILURE_COUNT]
- Total Requests in Window: [REQUEST_COUNT]
- Window Duration (seconds): [WINDOW_DURATION]
- Last Failure Timestamp: [LAST_FAILURE_TIME]
- Last Failure Type: [LAST_FAILURE_TYPE]

# CONFIGURATION THRESHOLDS
- Failure Threshold for Open: [FAILURE_THRESHOLD]
- Cooldown Period (seconds): [COOLDOWN_PERIOD]
- Half-Open Max Test Requests: [HALF_OPEN_MAX_REQUESTS]

# RECENT FAILURE DETAILS (last 5)
[FAILURE_DETAILS]

# AVAILABLE FALLBACK PATHS
[FALLBACK_PATHS]

# INSTRUCTIONS
1. Analyze the current circuit state and failure history against the configuration thresholds.
2. Determine the next circuit state: CLOSED, OPEN, or HALF_OPEN.
3. If the state is OPEN, calculate the remaining cooldown time and recommend a fallback path from the provided list.
4. If the state is HALF_OPEN, specify the maximum number of test requests to allow.
5. Provide a concise, evidence-based rationale for the decision.

# OUTPUT SCHEMA
Return a single JSON object with the following fields:
- "decision": {
    "next_state": "CLOSED" | "OPEN" | "HALF_OPEN",
    "allow_request": boolean,
    "cooldown_remaining_seconds": number | null,
    "max_test_requests": number | null
  },
- "fallback_routing": {
    "recommended_fallback": string | null,
    "reason": string | null
  },
- "rationale": "A concise explanation of the decision, referencing specific thresholds and failure counts.",
- "risk_assessment": "LOW" | "MEDIUM" | "HIGH"

# CONSTRAINTS
- Do not invent failure data. Only use the provided inputs.
- If the circuit is CLOSED and failure count is below the threshold, allow the request.
- If the circuit is OPEN and the cooldown period has not elapsed, block the request and recommend a fallback.
- If the circuit is OPEN and the cooldown period has elapsed, transition to HALF_OPEN.
- If the circuit is HALF_OPEN and a test request fails, immediately transition back to OPEN.

To adapt this template, replace each square-bracket placeholder with live data from your circuit breaker state store. The [FAILURE_DETAILS] placeholder should be populated with a structured list of recent errors, including timestamps and error codes, to give the model enough context to distinguish between transient and systemic failures. The [FALLBACK_PATHS] placeholder should contain a list of available alternative agents or static responses, each with a capability description, so the model can make an informed routing decision. Before deploying, run this prompt against a golden dataset of known circuit state transitions to calibrate the [FAILURE_THRESHOLD] and [COOLDOWN_PERIOD] values against your specific agent reliability targets.

IMPLEMENTATION TABLE

Prompt Variables

Inputs the Agent Escalation Circuit Breaker Prompt needs to work reliably. All placeholders must be populated by the calling application before the LLM request. Validation rules are actionable checks to prevent runtime failures.

PlaceholderPurposeExampleValidation Notes

[AGENT_ID]

Unique identifier for the agent being monitored for failure cascades.

order-fulfillment-agent-v2

Must match a known agent in the orchestration registry. Reject if null or empty string.

[FAILURE_COUNT]

Current consecutive failure count for this agent within the active window.

7

Must be a non-negative integer. If null, default to 0. Parse check: parseInt must succeed.

[FAILURE_THRESHOLD]

Maximum allowed consecutive failures before the circuit opens.

5

Must be a positive integer. Schema check: value >= 1. If null, use system default of 3.

[COOLDOWN_SECONDS]

Minimum time in seconds the circuit must remain open before attempting recovery.

60

Must be a positive integer. Parse check: parseInt must succeed. If null, use system default of 30.

[LAST_FAILURE_TIMESTAMP]

ISO 8601 timestamp of the most recent agent failure.

2025-03-15T10:30:00Z

Must be a valid ISO 8601 string. If null, circuit is considered closed. Schema check: Date.parse must not return NaN.

[FALLBACK_AGENT_IDS]

Comma-separated list of agent IDs eligible to receive escalated work.

support-agent-v1,human-review-queue

Must be a non-empty string. Each ID must match a known agent. If null, escalate directly to human review.

[AGENT_CAPABILITY_CONTEXT]

Brief description of what this agent is supposed to handle, used to select appropriate fallback routing.

Handles order fulfillment, inventory checks, and shipping label generation.

Must be a non-empty string. If null, fallback routing will be generic. Approval required if empty in production.

PROMPT PLAYBOOK

Implementation Harness Notes

How to wire the circuit breaker prompt into a reliable agent orchestration loop with state tracking, validation, and safe fallbacks.

The circuit breaker prompt is not a standalone decision engine. It must be embedded in an application harness that maintains persistent state for failure counts, cooldown windows, and circuit state transitions. The harness is responsible for calling the prompt only when a state evaluation is needed, feeding it the current counters and timestamps, and then applying the model's decision to update the circuit state. Without this harness, the prompt has no memory of prior failures and cannot enforce cooldown periods across invocations.

Implement the harness as a state machine with three states: CLOSED (normal operation), OPEN (circuit tripped, requests blocked), and HALF_OPEN (probing for recovery). Store failure_count, last_failure_time, last_open_time, and cooldown_seconds in a durable store such as Redis, a database, or an in-memory cache with persistence. Before each agent action, check the current state. If CLOSED, proceed normally and increment the failure counter on errors. When failure_count exceeds a configured threshold, invoke the prompt with [FAILURE_COUNT], [THRESHOLD], [FAILURE_WINDOW_SECONDS], and [RECENT_FAILURE_DETAILS] to get a structured decision. Parse the output against a strict schema requiring circuit_state, cooldown_recommendation_seconds, fallback_routing, and rationale. Validate that circuit_state is one of the allowed enum values and that cooldown_recommendation_seconds is a positive integer within your operational bounds (e.g., 30–3600 seconds). If validation fails, default to OPEN with a conservative cooldown and log the parse error.

For the HALF_OPEN state, allow a single probe request through after the cooldown expires. If the probe succeeds, transition back to CLOSED and reset the failure counter. If it fails, return to OPEN and double the cooldown duration up to a configured maximum. Log every state transition, the prompt's raw output, the validated decision, and the probe outcome. This audit trail is essential for tuning thresholds and diagnosing false-positive trips. Wire the fallback_routing field into your agent dispatcher so that when the circuit is OPEN, requests are automatically routed to the specified fallback agent, queue, or human review inbox. Never silently drop requests when the circuit is open—always route to a fallback or return a clear 503 with a Retry-After header.

Model choice matters here. Use a fast, instruction-following model (e.g., Claude 3.5 Haiku, GPT-4o-mini) because circuit breaker decisions are latency-sensitive and the reasoning is bounded. Avoid models that over-explain or hallucinate state transitions. Set temperature=0 to get deterministic decisions. Implement a timeout of 2–5 seconds for the prompt call. If the model times out or returns an unparseable response, treat it as a circuit trip: transition to OPEN with a default cooldown and log the model failure as a separate incident. This prevents the circuit breaker itself from becoming a reliability risk.

Before deploying, test the full harness with a suite of scenarios: rapid successive failures, recovery probes that succeed, recovery probes that fail, cooldown expiry edge cases, and model timeout injection. Measure the end-to-end latency added by the circuit breaker evaluation and ensure it stays under your p95 target. Monitor circuit_trip_rate, false_positive_trip_rate (trips where the fallback succeeded immediately), and model_eval_timeout_rate in production. When tuning thresholds, adjust [FAILURE_THRESHOLD] and [FAILURE_WINDOW_SECONDS] based on observed error patterns rather than guessing. Start conservative and loosen only after reviewing trip audit logs.

IMPLEMENTATION TABLE

Expected Output Contract

Fields, types, and validation rules for the circuit breaker decision JSON. Use this contract to build a parser and validator before wiring the prompt into an agent harness.

Field or ElementType or FormatRequiredValidation Rule

circuit_state

enum: CLOSED | HALF_OPEN | OPEN

Must be exactly one of the three enum values. Reject any other string.

failure_count

integer >= 0

Must match the count of distinct failures tracked in [FAILURE_LOG]. Parse as int and confirm non-negative.

failure_threshold

integer >= 1

Must equal the configured [FAILURE_THRESHOLD] value. Reject if the model invents a different threshold.

cooldown_seconds

integer >= 0

When circuit_state is OPEN, must be > 0 and <= [MAX_COOLDOWN_SECONDS]. When CLOSED, must be 0.

fallback_agent

string | null

When circuit_state is OPEN or HALF_OPEN, must be a non-empty agent ID from [FALLBACK_AGENTS]. When CLOSED, must be null.

decision_rationale

string (1-200 chars)

Must contain a concise reason referencing failure_count vs threshold. Reject if empty, over 200 chars, or purely generic.

recovery_conditions

string[] (1-3 items)

When circuit_state is OPEN, must list 1-3 specific conditions for transitioning to HALF_OPEN. When CLOSED, must be empty array.

timestamp_utc

ISO 8601 string

Must parse as valid UTC datetime. Reject if missing timezone offset or unparseable.

PRACTICAL GUARDRAILS

Common Failure Modes

Circuit breaker prompts fail in predictable ways when deployed in production agent systems. These are the most common failure modes and the guardrails that prevent them.

01

Threshold Oscillation During Recovery

What to watch: The circuit trips, enters cooldown, and immediately re-trips on the first retry because the failure count threshold is too low or the cooldown window is too short. This creates a rapid open-close-open cycle that masks the underlying issue. Guardrail: Implement a minimum cooldown duration and require a consecutive success count before transitioning from half-open to closed. Log every state transition with timestamps for postmortem analysis.

02

Silent State Drift Between Agents

What to watch: The circuit breaker prompt returns a state decision, but the calling agent ignores it or applies stale circuit state from a previous evaluation cycle. Downstream agents proceed as if the circuit is closed when it is actually open. Guardrail: Include the circuit state in a structured handoff payload with a monotonic evaluation ID. Require downstream agents to validate the circuit state before acting and refuse execution if the state ID is older than the current evaluation.

03

Failure Count Inflation from Cascading Errors

What to watch: A single root-cause failure triggers errors across multiple dependent agents, each incrementing the failure counter independently. The circuit opens prematurely because the count reflects symptom count rather than distinct incidents. Guardrail: Deduplicate failures by correlating on a root cause identifier or trace ID within the evaluation window. Count distinct failure sources, not total error events. Include a deduplication key in the prompt input schema.

04

Cooldown Expiry Without Health Verification

What to watch: The cooldown timer expires and the circuit transitions to half-open, but no health check validates that the downstream dependency has actually recovered. The first retry fails and the cycle repeats. Guardrail: Require a health-check probe as a precondition for transitioning from open to half-open. The prompt should output a health_check_required flag and the harness should block the state transition until the probe succeeds.

05

Fallback Routing to an Equally Broken Path

What to watch: The circuit breaker correctly escalates away from a failed agent but routes to a fallback that shares the same broken dependency, database, or API. The fallback fails identically and the escalation provides no resilience. Guardrail: Include dependency topology awareness in the fallback selection logic. The prompt should receive a dependency graph or capability matrix and reject fallback candidates that share a known-failed dependency. Validate fallback independence in pre-deployment tests.

06

Missing Human Review on Manual Override

What to watch: An operator manually forces the circuit closed to restore service quickly, bypassing the cooldown and health checks. The underlying failure persists and causes a larger incident because the guardrail was removed without documentation. Guardrail: Log every manual state override with operator identity, timestamp, and reason. Require a short-lived override TTL after which the circuit reverts to its evaluated state. Surface override events in operational dashboards and post-incident reviews.

IMPLEMENTATION TABLE

Evaluation Rubric

Run these scenarios against a golden dataset to test the Agent Escalation Circuit Breaker Prompt before shipping. Each criterion validates a specific circuit breaker behavior under production-like conditions.

CriterionPass StandardFailure SignalTest Method

Circuit State Transition Accuracy

Correctly transitions between CLOSED, OPEN, and HALF_OPEN states based on [FAILURE_COUNT] and [COOLDOWN_PERIOD] inputs

State remains CLOSED when failure threshold exceeded; state transitions to OPEN without cooldown recommendation

Run 50 golden cases with known failure counts and timestamps; assert state matches expected circuit breaker state machine

Failure Count Tracking Precision

Accurately increments and reports [FAILURE_COUNT] from input history without off-by-one errors

Reported count differs from actual failure events in input; count resets prematurely during HALF_OPEN

Inject 20 test sequences with known failure event counts; compare output count to ground truth

Cooldown Duration Calculation

Recommends [COOLDOWN_SECONDS] proportional to failure severity with minimum 30s floor

Cooldown of 0 seconds after threshold breach; cooldown exceeds 24 hours for minor failures

Validate output cooldown against configured [MAX_COOLDOWN] and [MIN_COOLDOWN] bounds across 30 test cases

Fallback Routing Completeness

Provides valid [FALLBACK_AGENT] or [FALLBACK_HUMAN] target for every OPEN state decision

Missing fallback target when circuit is OPEN; fallback agent name not in allowed [AGENT_REGISTRY]

Check all OPEN state outputs contain non-null fallback field; validate against allowed agent list

Threshold Boundary Behavior

Escalates exactly at [FAILURE_THRESHOLD] value; does not escalate one below threshold

Escalation triggers at threshold-1; no escalation at threshold value

Test boundary cases at threshold-1, threshold, threshold+1 with 100 samples each; assert correct escalation decision

Recovery Test Handling

Allows single probe request in HALF_OPEN state and returns to CLOSED on success

Multiple requests allowed during HALF_OPEN; successful probe does not reset failure count

Simulate HALF_OPEN state with probe success and failure scenarios; verify state transitions match recovery spec

Malformed Input Resilience

Returns structured error with [CIRCUIT_STATE]: ERROR when [FAILURE_COUNT] or [TIMESTAMP] fields are missing

Returns CLOSED state when required fields absent; hallucinates failure counts from missing data

Send 15 malformed payloads with missing, null, or wrong-type fields; assert ERROR state and no fabricated values

ADAPTATION OPTIONS

Adapt This Prompt

How to adapt

Start with the base circuit breaker prompt but relax strict schema enforcement. Use a simpler output format (plain text decision + reason) instead of the full JSON circuit state object. Replace the failure count tracking harness with a single [RECENT_FAILURE_LOG] text blob. Skip cooldown duration calculation—just output OPEN, HALF_OPEN, or CLOSED. Use a lightweight model call without tool definitions.

Watch for

  • The model may invent failure counts instead of counting them
  • Cooldown recommendations will be vague without explicit duration instructions
  • No structured logging means you can't replay decisions later
  • Threshold tuning is guesswork without the eval harness
Prasad Kumkar

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.