This prompt is a control-plane component for an agent runtime or orchestration layer. Its job is to protect downstream services from cascading retry storms by making a structured, machine-readable decision to open, close, or keep a circuit breaker in its current state. It is not designed for end users or natural-language explanation. The ideal user is an AI engineer or agent infrastructure developer integrating this prompt into an execution loop that monitors tool call outcomes. The prompt must be invoked before every call to a dependency that has recently failed, using a sliding window of recent outcomes, latency metrics, and error classifications as input. The required context includes a failure rate threshold, a latency degradation threshold, a cooldown duration, and a list of error types that should be treated as immediate triggers for opening the breaker.
Prompt
Circuit Breaker Activation Prompt for Failing Dependencies

When to Use This Prompt
Defines the operational context for the circuit breaker prompt, clarifying its role as a control-plane decision point within an agent runtime, not an end-user interaction.
Use this prompt when your agent's tool-calling layer needs a fast, deterministic signal to prevent resource exhaustion on a known-fragile dependency. It is appropriate for production systems where a single degraded API can cause a cascade of retries across multiple agent instances, consuming token budgets and violating latency SLAs. Do not use this prompt for one-off debugging, for dependencies that have no history of failure, or as a replacement for client-side SDK retry policies. It is a state machine decision prompt, not a diagnostic tool. The output is a strict state change instruction (e.g., OPEN, CLOSE, HOLD) with a cooldown duration and a fallback mode, which your application code must enforce. If you need a human-readable summary of why a circuit breaker tripped, pair this prompt with a separate error context collection or human handoff prompt.
Before integrating this prompt, ensure your agent runtime tracks the necessary inputs: a rolling window of call outcomes (success/failure with error types), p50/p95/p99 latency for recent calls, and the current breaker state with its opened_at timestamp. The prompt is designed to be stateless; all state is passed in via the input context. After receiving the output, your application layer is responsible for enforcing the decision—blocking calls, routing to a fallback, or resetting the breaker after the cooldown. Do not rely on the model to remember the breaker state across invocations. For high-risk dependencies where an incorrect decision could cause data loss or a critical outage, always log the full input and output of this prompt and consider a human-in-the-loop approval step before opening a breaker on a previously healthy service.
Use Case Fit
Where the Circuit Breaker Activation Prompt works, where it fails, and what you must provide before deploying it in a production agent harness.
Good Fit: Downstream Dependency Protection
Use when: an agent orchestrator calls external APIs, databases, or internal microservices that can degrade under load. Guardrail: deploy this prompt inside a middleware layer that tracks failure counts and latency per dependency, not as a one-shot reasoning step.
Bad Fit: Single-Step or Stateless Workflows
Avoid when: the agent has no retry loop, no shared state across steps, or calls each dependency exactly once. Guardrail: circuit breakers require persistent state and repeated calls to be meaningful; without them, this prompt adds latency with no protection benefit.
Required Input: Failure History Window
What to watch: the prompt needs a structured failure log with timestamps, error types, and latency measurements for the target dependency. Guardrail: pre-aggregate failure rate, error type distribution, and p95 latency before calling the prompt; do not pass raw unbounded logs.
Required Input: Breaker Configuration Contract
What to watch: the prompt must receive current breaker thresholds, cooldown policy, and allowed fallback modes as explicit constraints. Guardrail: store these in a configuration object outside the prompt and inject them as [BREAKER_CONFIG]; never hardcode thresholds in the system message.
Operational Risk: Threshold Oscillation
Risk: the model may recommend opening and closing the breaker in rapid succession if failure rates hover near the threshold. Guardrail: enforce a minimum cooldown duration in application code regardless of model output, and log every state change with the model's reasoning for audit.
Operational Risk: Silent Fallback Degradation
Risk: when the breaker opens and fallback mode activates, downstream behavior may silently degrade without operator visibility. Guardrail: emit a structured event on every breaker state change and fallback activation; route these to your agent observability pipeline with severity labels.
Copy-Ready Prompt Template
A reusable circuit breaker evaluation prompt that decides whether to open, close, or hold a breaker state based on recent failure history and configured thresholds.
This prompt template is designed to be injected into your agent's pre-call guard or a dedicated circuit breaker evaluation step. It receives a structured snapshot of recent dependency call outcomes, the current breaker state, and your configured thresholds. The model's job is not to execute the breaker logic in application code—that should be handled deterministically—but to reason about edge cases where simple threshold comparisons are insufficient, such as when failures are clustered, error types vary in severity, or partial degradation suggests a different response than pure failure counting.
textYou are a circuit breaker evaluator for an agent infrastructure system. Your role is to analyze recent dependency call history and recommend a breaker state transition based on configured thresholds and failure patterns. ## Current State - Breaker State: [CURRENT_STATE] - Consecutive Successes: [CONSECUTIVE_SUCCESSES] - Cooldown Start Time: [COOLDOWN_START_TIME] - Current Time: [CURRENT_TIME] ## Failure History (most recent first) [FAILURE_HISTORY] Each record includes: - timestamp - error_type (TIMEOUT, CONNECTION_REFUSED, RATE_LIMITED, INTERNAL_ERROR, INVALID_RESPONSE, UNKNOWN) - latency_ms - retry_attempted (true/false) ## Threshold Configuration - Failure Rate Threshold (sliding window): [FAILURE_RATE_THRESHOLD]% - Minimum Requests in Window: [MIN_REQUESTS] - Consecutive Failure Threshold: [CONSECUTIVE_FAILURE_THRESHOLD] - Latency Degradation Threshold: [LATENCY_DEGRADATION_THRESHOLD]% - Cooldown Duration Seconds: [COOLDOWN_DURATION] - Half-Open Max Requests: [HALF_OPEN_MAX_REQUESTS] - Error Type Weights: [ERROR_TYPE_WEIGHTS] ## Evaluation Rules 1. If state is CLOSED and failure rate exceeds threshold with minimum requests met, recommend OPEN. 2. If state is CLOSED and consecutive failures exceed threshold, recommend OPEN. 3. If state is CLOSED and average latency exceeds baseline by degradation threshold, recommend OPEN. 4. If state is OPEN and cooldown duration has elapsed, recommend HALF_OPEN. 5. If state is HALF_OPEN and any request fails, recommend OPEN. 6. If state is HALF_OPEN and all requests in probe succeed, recommend CLOSED. 7. Weight error types by severity: TIMEOUT and CONNECTION_REFUSED indicate infrastructure failure; RATE_LIMITED may indicate self-inflicted load; INVALID_RESPONSE may indicate upstream changes. 8. Consider failure clustering: if failures are concentrated in a short burst followed by recovery, this may indicate a transient spike rather than persistent degradation. ## Output Schema Return a JSON object with: { "recommended_state": "CLOSED" | "OPEN" | "HALF_OPEN", "confidence": 0.0-1.0, "reasoning": "Brief explanation of the decision", "cooldown_seconds": 0 if not opening, otherwise suggested cooldown, "fallback_mode": "NONE" | "CACHED_RESPONSE" | "STALE_DATA" | "DEGRADED_FUNCTIONALITY" | "ERROR_RESPONSE", "risk_flags": ["List of any risk factors identified"], "override_rule": null or "String describing which rule triggered if standard thresholds were bypassed" } ## Constraints - Do not recommend OPEN if minimum requests haven't been met. - Do not recommend CLOSED from HALF_OPEN unless all probe requests succeeded. - If error types are predominantly RATE_LIMITED, consider whether the breaker itself is causing retry storms. - Flag for human review if the pattern doesn't clearly fit threshold rules. Analyze the failure history and current state, then return your recommendation.
To adapt this template for your system, replace the square-bracket placeholders with actual values from your circuit breaker state store and metrics collector. The [FAILURE_HISTORY] should be formatted as a JSON array of failure records. The [ERROR_TYPE_WEIGHTS] placeholder should contain a mapping of error types to numeric weights that reflect your system's severity hierarchy. Before deploying, validate that the model's output conforms to the schema using a JSON validator in your harness, and implement a hard guard that rejects any recommendation violating the explicit constraints—the model's reasoning informs the decision, but your application code must enforce the safety boundaries. For high-risk dependencies where an incorrect breaker state could cause data loss or user-facing outages, route CLOSED-to-OPEN transitions through a human approval queue before execution.
Prompt Variables
Inputs the circuit breaker prompt needs to evaluate dependency health and decide state transitions. Each placeholder must be populated by the agent runtime or monitoring system before the prompt is sent. Missing or stale variables will cause incorrect breaker decisions.
| Placeholder | Purpose | Example | Validation Notes |
|---|---|---|---|
[DEPENDENCY_NAME] | Identifies the downstream service or API being evaluated by the circuit breaker | payment-gateway-primary | Must match the canonical service name in the dependency registry. Non-empty string. |
[FAILURE_WINDOW_SECONDS] | Defines the rolling time window for counting recent failures | 120 | Must be a positive integer. Typical range: 30-300. Reject if zero or negative. |
[FAILURE_COUNT] | Number of failures observed within the failure window | 17 | Must be a non-negative integer. If null, treat as 0. Cannot exceed total request count. |
[TOTAL_REQUEST_COUNT] | Total requests sent to the dependency within the failure window | 100 | Must be a positive integer. Must be >= [FAILURE_COUNT]. Reject if zero when [FAILURE_COUNT] > 0. |
[FAILURE_RATE_THRESHOLD] | The failure rate percentage above which the circuit should open | 0.25 | Must be a float between 0.0 and 1.0. Typical range: 0.1-0.5. Reject if outside bounds. |
[P95_LATENCY_MS] | 95th percentile latency for the dependency in the current window | 4500 | Must be a non-negative integer or null if unavailable. Compare against [LATENCY_THRESHOLD_MS]. |
[LATENCY_THRESHOLD_MS] | Maximum acceptable P95 latency before degradation is flagged | 2000 | Must be a positive integer. Reject if zero. Should be derived from the dependency SLO. |
[ERROR_TYPE_DISTRIBUTION] | JSON map of error categories to counts observed in the window | {"timeout": 12, "connection_refused": 3, "5xx": 2} | Must be valid JSON object. Keys must match known error taxonomy. Counts must sum to [FAILURE_COUNT]. |
Implementation Harness Notes
How to wire the circuit breaker activation prompt into an agent runtime with validation, state management, and safe defaults.
The circuit breaker activation prompt is not a standalone decision-maker. It is a gating step inside an agent's execution loop that runs before every outbound call to a protected dependency. The prompt receives aggregated failure statistics from the last monitoring window and returns a structured breaker state change. The surrounding harness is responsible for collecting those statistics, enforcing the prompt's decision, and preventing the model from overriding breaker logic with unsafe defaults.
Wire this prompt into your agent runtime by placing it after the failure counter update and before the next outbound call attempt. The harness must supply the prompt with real metrics: [FAILURE_COUNT], [TOTAL_CALLS], [WINDOW_DURATION_SECONDS], [ERROR_TYPES] (categorized as timeout, connection_refused, 5xx, 4xx, malformed_response), [CURRENT_BREAKER_STATE] (closed, half_open, open), [LAST_FAILURE_TIMESTAMP], and [LATENCY_P95_MS]. The prompt outputs a JSON decision with fields action (open, close, remain, half_open), cooldown_seconds, fallback_mode (stale_cache, degraded_response, skip_step, escalate), and reasoning. Validate this output before acting on it. Reject any decision where action is open but cooldown_seconds is zero or missing, where action is close while the error rate exceeds the configured threshold, or where the model invents error types not present in the input. These validation rules must live in application code, not in the prompt, because the model cannot be trusted to enforce its own safety constraints.
For production deployments, implement a hard-coded circuit breaker as the primary enforcement layer and use this prompt only for threshold tuning and exception handling. The application should maintain breaker state in a durable store (Redis, Postgres, or in-memory for single-process agents) with atomic state transitions. The prompt's role is to recommend state changes when the situation is ambiguous—for example, when error rates hover near the threshold, when error types suggest different recovery strategies, or when latency degradation indicates a degrading but not yet failed dependency. Never let the prompt's output bypass the hard-coded maximum cooldown cap (e.g., 300 seconds) or the minimum call volume required before opening (e.g., 5 calls in the window). Log every prompt invocation with input metrics, output decision, validation result, and the final action taken by the harness. This trace is essential for tuning thresholds and detecting prompt drift over time.
Model choice matters here. Use a fast, cheap model (e.g., GPT-4o-mini, Claude Haiku, or a fine-tuned small model) because this prompt runs on the critical path of every dependency call during degraded states. Latency added by the prompt must be a fraction of the dependency's own timeout. If the prompt call itself fails or times out, the harness must default to the safest breaker state—typically leaving the breaker in its current position or moving to open if the error rate already exceeds a hard threshold. Never default to close on prompt failure. For agents with strict latency budgets, consider pre-computing breaker decisions from a rules engine and invoking the prompt only when the rules engine returns an ambiguous result.
Before shipping, test this harness against simulated failure patterns: rapid-fire timeouts, slow degradation over 60 seconds, intermittent 5xx errors mixed with successes, and complete dependency disappearance. Verify that the combined prompt-plus-harness system opens the breaker within your target detection window, rejects calls during the cooldown period, transitions to half_open correctly, and closes only after sustained health. The most common production failure is a breaker that never opens because the prompt overweights recent successes or a breaker that never closes because the prompt fixates on a single error spike. Your eval suite should include both cases.
Expected Output Contract
Every field the Circuit Breaker Activation Prompt must return. Validate all fields before the runtime acts on a state-change decision. Reject or repair any output that fails these rules.
| Field or Element | Type or Format | Required | Validation Rule |
|---|---|---|---|
breaker_state | enum: CLOSED | OPEN | HALF_OPEN | Must be one of the three allowed enum values. Reject any other string. | |
action | enum: TRIP | RESET | REJECT | PROBE | Must be exactly one action. TRIP only valid when current state is CLOSED. RESET only valid when current state is HALF_OPEN. REJECT valid when state is OPEN. PROBE only valid when state is OPEN and cooldown has elapsed. | |
failure_rate_observed | number (0.0–1.0) | Must be a float between 0.0 and 1.0 inclusive. Derived from [FAILURE_WINDOW] and [FAILURE_COUNT]. Reject if negative or >1.0. | |
latency_p99_ms | integer >= 0 | Must be a non-negative integer representing the p99 latency in milliseconds over [LATENCY_WINDOW]. Reject if negative or non-integer. | |
cooldown_duration_seconds | integer >= 0 | Required even when breaker is not tripped. Set to 0 if no cooldown is active. Reject if negative. Must match [COOLDOWN_BASE_SECONDS] * backoff_multiplier when state is OPEN. | |
fallback_mode | enum: STALE_CACHE | DEGRADED_ANSWER | STATIC_FALLBACK | EMPTY_RESPONSE | NONE | Must be one of the allowed enum values. NONE only valid when breaker_state is CLOSED. Reject if fallback_mode is NONE and breaker_state is OPEN or HALF_OPEN. | |
decision_reason | string (1–280 chars) | Must be a non-empty string between 1 and 280 characters. Must reference at least one of: failure rate, latency, error type, or cooldown status. Reject if empty or purely generic. | |
error_type_distribution | object: { timeout: int, connection_refused: int, http_5xx: int, http_4xx: int, malformed_response: int, other: int } | All keys required. Each value must be a non-negative integer. Sum must equal [FAILURE_COUNT]. Reject if any key is missing or sum mismatch detected. |
Common Failure Modes
What breaks first when a circuit breaker prompt is deployed in production, and how to prevent each failure mode before it causes a cascading outage.
Threshold Oscillation During Recovery
What to watch: The breaker opens, the cooldown expires, a single probe request succeeds, and the breaker closes immediately—only for the next request to fail again. This creates rapid open/close cycles that hammer the downstream dependency worse than no breaker at all. Guardrail: Require a minimum number of consecutive successful probe requests before closing, and implement a half-open state that limits throughput during recovery validation.
Ignoring Latency Degradation as a Signal
What to watch: The prompt only tracks explicit error rates and misses slow-but-successful responses that violate latency budgets. A dependency can be functionally dead while returning 200 OK after 30 seconds, causing upstream timeouts and resource exhaustion. Guardrail: Include latency percentile thresholds (p95, p99) as a breaker trigger condition alongside error rate, and require the prompt to evaluate both signals before deciding state transitions.
Cooldown Duration Miscalibration
What to watch: The model recommends a cooldown duration that is either too short (dependency hasn't recovered) or too long (unnecessary degradation for users). Without guidance, the prompt defaults to arbitrary values that don't match the dependency's observed recovery profile. Guardrail: Provide the prompt with historical recovery time data and require it to justify the cooldown duration with reference to failure type, dependency criticality, and recent recovery patterns rather than emitting a magic number.
Error Type Misclassification Leading to Wrong Breaker Action
What to watch: The prompt treats all errors as equivalent and opens the breaker for client errors (4xx) that won't be resolved by waiting, while failing to open for systemic server errors (5xx) that indicate real degradation. This causes unnecessary circuit opens for problems the caller should fix, and missed protection for actual downstream failures. Guardrail: Require the prompt to classify errors by type (client, server, timeout, rate-limit) before deciding breaker state, with explicit rules that client errors should not trigger circuit opens and rate-limit errors should increase backoff rather than open the breaker.
Fallback Mode Selection Without Capability Validation
What to watch: The prompt selects a fallback mode (stale cache, degraded response, static default) without verifying that the fallback actually satisfies minimum functional requirements. A circuit breaker that silently switches to an empty response or incorrect cached data is worse than failing loudly. Guardrail: Include a fallback capability matrix in the prompt context that maps each fallback mode to its data freshness, completeness, and accuracy guarantees, and require the prompt to flag when no fallback meets minimum requirements so the system can escalate instead of silently degrading.
Failure Rate Calculation Over Too Short a Window
What to watch: The prompt evaluates failure rate over a window that's too small, causing the breaker to open on transient spikes that self-resolve within seconds. This creates false-positive circuit opens that degrade user experience unnecessarily. Guardrail: Require the prompt to use a sliding window with a minimum sample size before making a breaker decision, and provide both short-window and long-window failure rates so the model can distinguish between transient spikes and sustained degradation.
Evaluation Rubric
Run these checks against a golden dataset of failure windows with known correct breaker decisions. Each row tests a specific failure mode or edge case.
| Criterion | Pass Standard | Failure Signal | Test Method |
|---|---|---|---|
Breaker opens when failure rate exceeds [FAILURE_THRESHOLD] over [WINDOW_SIZE] | Outputs state=open within 1 decision cycle after threshold crossed | State remains closed or half-open despite sustained failure rate above threshold | Golden dataset: 10 consecutive failures in window. Assert open decision within 1 call |
Breaker does not open for transient spikes below threshold | Outputs state=closed when failure rate is below [FAILURE_THRESHOLD] in window | False positive: opens on 2 failures in 100-call window with 2% error rate | Golden dataset: low failure rate windows. Assert state=closed for all |
Latency degradation triggers open when [LATENCY_P95_MS] exceeded | Outputs state=open with reason=latency_degradation when p95 crosses threshold | Ignores latency signal; only reacts to error count | Golden dataset: high-latency windows with zero errors. Assert open on latency breach |
Error type classification gates breaker activation correctly | Opens on 5xx and timeout errors; does not open on 4xx client errors | Opens on 400 Bad Request or 404 Not Found errors | Golden dataset: mixed 4xx and 5xx windows. Assert open only when 5xx/timeout ratio crosses threshold |
Cooldown duration [COOLDOWN_SECONDS] enforced before half-open transition | Outputs state=half-open only after cooldown expires; not before | Transitions to half-open immediately or before cooldown elapsed | Simulate open state with timestamp. Assert half-open not returned until cooldown satisfied |
Half-open probe failure returns to open with backoff | Single failure in half-open state outputs state=open with increased cooldown | Remains half-open after probe failure or resets cooldown to original value | Golden dataset: half-open probe failure. Assert open with cooldown >= previous cooldown * [BACKOFF_MULTIPLIER] |
Half-open probe success transitions to closed | Consecutive successes >= [PROBE_SUCCESS_COUNT] in half-open outputs state=closed | Stays half-open indefinitely or reopens despite probe successes | Golden dataset: [PROBE_SUCCESS_COUNT] consecutive successes. Assert state=closed |
Fallback mode [FALLBACK_MODE] populated when breaker opens | Output includes fallback_mode field matching one of [ALLOWED_FALLBACK_MODES] when state=open | Missing fallback_mode, null, or invalid value when breaker is open | Assert fallback_mode is non-null and in allowed enum for every open decision |
Enabling Efficiency, Speed & Accuracy
Intelligent Analysis, Decision & Execution
We build AI systems for teams that need search across company data, workflow automation across tools, or AI features inside products and internal software.
Talk to Us
Search across company data
Give teams answers from docs, tickets, runbooks, and product data with sources and permissions.
Useful when people spend too long searching or get different answers from different systems.

Automate internal workflows
Use AI to route work, draft outputs, trigger actions, and keep approvals and logs in place.
Useful when repetitive work moves across multiple tools and teams.

Add AI to products and internal tools
Build assistants, guided actions, or decision support into the software your team or customers already use.
Useful when AI needs to be part of the product, not a separate tool.
Adapt This Prompt
How to adapt
Use the base prompt with a simplified output schema. Drop the cooldown duration calculation and fallback mode selection; output only the breaker state change (OPEN/CLOSED/HALF_OPEN) and a one-line reason. Run against a static JSON array of synthetic error events instead of a live metrics stream. Accept any valid JSON response without strict enum or range validation.
Watch for
- The model may invent threshold values instead of using the ones you provide in [THRESHOLDS]
- Without schema enforcement, state values like
"open"vs"OPEN"will drift across runs - Cooldown durations may be hallucinated if you ask for them without providing a time-window context

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