Inferensys

Prompt

Agent Tool Health Self-Check Prompt Template

A practical prompt playbook for using Agent Tool Health Self-Check Prompt Template in production AI workflows.
Developer demonstrating multi-agent tool use, agent tool selection interface on laptop, casual tech demo moment.
PROMPT PLAYBOOK

When to Use This Prompt

Defines the job-to-be-done, ideal user, required context, and boundaries for the Agent Tool Health Self-Check Prompt.

This prompt is for agent developers and platform reliability engineers who need their agents to assess tool health before execution. It produces a structured self-check that evaluates tool availability, recent failure patterns, and degraded-mode readiness. Use this when your agent must decide whether to proceed with a tool call, switch to a fallback, or halt and escalate. The prompt acts as a pre-flight gate, forcing the agent to reason explicitly about the risk of a tool call before committing to an operation that might fail, time out, or corrupt state.

You should use this prompt when building agents that interact with external APIs, databases, or services where failures are routine and costly. Ideal contexts include multi-step agent workflows where a single tool failure can cascade, high-traffic systems where retry storms risk overwhelming degraded backends, and regulated environments where failed writes or partial commits create audit problems. The prompt requires the agent to have access to recent tool interaction history, including error codes, latency metrics, and any circuit breaker state. Without this context, the self-check becomes speculative and loses its value as a reliability gate.

This is not a replacement for external monitoring, circuit breakers, or health checks in the application layer. It is a prompt-level health gate that gives the agent explicit reasoning before it commits to a tool call. Do not use this prompt when the agent has no access to recent failure data, when the tool is stateless and idempotent with negligible failure cost, or when the latency overhead of the self-check itself exceeds the tool call timeout. In high-frequency loops where every millisecond counts, move health gating to the application layer and keep the agent's prompt focused on execution. After reading this section, you should understand whether your agent's reliability requirements justify a prompt-level health gate, and proceed to the prompt template to adapt it for your tool ecosystem.

PRACTICAL GUARDRAILS

Use Case Fit

Where this prompt works, where it fails, and what you must provide before deploying it in a production agent loop.

01

Good Fit: Pre-Flight Health Gates

Use when: the agent must decide whether to proceed with a tool call or route to a fallback before execution. Guardrail: Run the self-check as a blocking step in the agent's planning phase, not as a background diagnostic.

02

Bad Fit: Real-Time Latency Budgets Under 200ms

Avoid when: the agent's tool-calling loop has a strict sub-200ms latency budget. Guardrail: Use pre-computed health signals or a circuit breaker state store instead of an LLM call for every tool invocation.

03

Required Input: Recent Tool Call Telemetry

Risk: The self-check hallucinates tool health when it lacks concrete failure counts, latency samples, and error codes. Guardrail: Inject a structured telemetry block with the last N tool call results, timestamps, and status codes into the prompt's [TOOL_TELEMETRY] placeholder.

04

Required Input: Degradation Policy Reference

Risk: The agent selects an inappropriate degradation mode because it doesn't know what fallbacks are available. Guardrail: Provide a concise [DEGRADATION_POLICY] block listing available fallback tools, stale cache TTLs, and user communication templates.

05

Operational Risk: Self-Check Becomes a Bottleneck

Risk: Running a full LLM call before every tool invocation doubles latency and cost. Guardrail: Cache the self-check result with a short TTL (e.g., 5-30 seconds) and invalidate on any tool failure event.

06

Operational Risk: Blind to Silent Failures

Risk: The self-check reports healthy when a tool returns valid-looking but incorrect data. Guardrail: Combine the self-check with output validation checks and anomaly detection on tool response payloads, not just status codes.

PROMPT PLAYBOOK

Copy-Ready Prompt Template

Paste this prompt into your agent's pre-tool-execution step to generate a structured health self-check before any tool call.

This prompt template is designed to be injected into your agent's execution loop immediately before it invokes an external tool. It forces the agent to assess the current health of the target tool by examining recent failure patterns, latency signals, and the readiness of any pre-configured fallback or degraded modes. The output is a structured health card that downstream logic can use to decide whether to proceed, switch to a fallback, or abort the operation. Replace every square-bracket placeholder with runtime values from your observability layer, such as a tool's recent error rate or its circuit breaker state.

text
You are an agent about to execute a tool call. Before proceeding, perform a structured health self-check on the target tool. Your goal is to prevent cascading failures by detecting degradation early.

**Tool to Assess:** [TOOL_NAME]
**Tool Description:** [TOOL_DESCRIPTION]
**Current Circuit Breaker State:** [CIRCUIT_BREAKER_STATE]
**Recent Error Rate (last 5 min):** [RECENT_ERROR_RATE]
**P95 Latency (ms, last 5 min):** [RECENT_P95_LATENCY]
**Available Fallback Tools (in priority order):** [FALLBACK_TOOL_LIST]
**Retry Budget Remaining:** [RETRY_BUDGET_REMAINING]
**Degraded Mode Policy:** [DEGRADED_MODE_POLICY]

**Instructions:**
1.  **Analyze Signals:** Evaluate the provided metrics against standard health thresholds (e.g., error rate > 5%, latency > 2x baseline).
2.  **Classify Health Status:** Assign one of the following statuses: `HEALTHY`, `DEGRADED`, `UNHEALTHY`, or `UNKNOWN`.
3.  **Recommend Action:** Based on the status, recommend one of: `PROCEED`, `USE_FALLBACK`, `SHED_LOAD`, or `ALERT_AND_ABORT`.
4.  **Select Fallback:** If the recommendation is `USE_FALLBACK`, specify which tool from the `[FALLBACK_TOOL_LIST]` is the best candidate and explain why.
5.  **Justify Decision:** Provide a concise, evidence-based rationale for your classification and recommendation.

**Output Format:**
Produce a JSON object with the following schema:
{
  "tool_name": "string",
  "health_status": "HEALTHY | DEGRADED | UNHEALTHY | UNKNOWN",
  "recommended_action": "PROCEED | USE_FALLBACK | SHED_LOAD | ALERT_AND_ABORT",
  "selected_fallback": "string | null",
  "rationale": "string"
}

To adapt this template, start by integrating it into your agent's middleware or pre-tool-call hook. The placeholders like [RECENT_ERROR_RATE] and [CIRCUIT_BREAKER_STATE] must be populated by a real-time observability system, not hardcoded. For high-risk tools where an incorrect health assessment could cause data loss or a significant user-facing outage, always route the UNKNOWN status to a human-in-the-loop review queue. The primary failure mode for this prompt is an agent that hallucinates metrics when the observability system fails to provide them; prevent this by strictly validating the input placeholders before the prompt is assembled.

IMPLEMENTATION TABLE

Prompt Variables

Inputs the agent needs to perform a reliable tool health self-check. Source these from your tool observability layer, not from the model's memory.

PlaceholderPurposeExampleValidation Notes

[TOOL_REGISTRY]

Current list of available tools with their status, endpoint, and capability metadata

{"tools": [{"name": "search_index", "status": "degraded", "latency_p99_ms": 4500}]}

Must be a valid JSON array. Each tool object requires 'name' and 'status' fields. Source from service discovery, not model generation.

[RECENT_FAILURE_LOG]

Structured log of tool call failures from the last N minutes, including error codes and timestamps

{"failures": [{"tool": "db_write", "error_code": "CONNECTION_REFUSED", "timestamp": "2025-01-15T10:03:22Z", "retry_count": 3}]}

Must contain at least 'tool', 'error_code', and 'timestamp' per entry. Null allowed if no failures. Validate timestamp freshness against current time.

[LATENCY_BASELINE]

Historical latency percentiles per tool for comparison against current performance

{"search_index": {"p50_ms": 120, "p95_ms": 350, "p99_ms": 800}}

Must be a map keyed by tool name. Each entry requires p50, p95, and p99 in milliseconds. Source from metrics store, not model inference.

[CIRCUIT_BREAKER_STATE]

Current state of each tool's circuit breaker and its transition history

{"db_write": {"state": "half_open", "failure_count": 4, "last_transition": "2025-01-15T10:02:00Z"}}

State must be one of 'closed', 'open', 'half_open'. Failure count must be a non-negative integer. Source from circuit breaker store.

[DEGRADATION_POLICY]

Predefined degradation modes and their activation criteria for each tool

{"search_index": {"modes": [{"name": "stale_cache", "trigger": "p99_latency > 2000ms", "max_duration_seconds": 300}]}}

Each tool must have at least one degradation mode defined. Trigger conditions must be parseable boolean expressions. Validate policy completeness before self-check runs.

[RETRY_BUDGET_REMAINING]

Remaining retry budget per tool for the current window

{"db_write": {"remaining": 2, "window_total": 5, "window_reset_seconds": 60}}

Remaining must be <= window_total. Window reset must be a positive integer. Source from rate limiter or retry governor, not model memory.

[ACTIVE_DEPENDENCY_GRAPH]

Directed graph of tool dependencies showing which tools call which other tools

{"nodes": ["search_index", "db_write"], "edges": [{"from": "search_index", "to": "db_write", "type": "write_back"}]}

Must be a valid graph structure with nodes and edges arrays. Each edge requires 'from', 'to', and 'type'. Source from service topology, not model inference.

[CURRENT_USER_IMPACT]

Estimated number of affected users or requests if each tool is degraded or unavailable

{"search_index": {"affected_users_estimate": 1200, "critical_journeys": ["checkout", "product_search"]}}

Affected users must be a non-negative integer. Critical journeys must reference defined journey names. Source from traffic analysis, not model estimation.

PROMPT PLAYBOOK

Implementation Harness Notes

How to wire the Agent Tool Health Self-Check into a production agent loop with validation, retries, and observability.

The self-check prompt is not a standalone diagnostic; it is a pre-flight gate that runs before the agent commits to a tool call. Wire it into the agent's execution loop as a synchronous step after tool selection but before argument assembly and invocation. The agent should call this prompt with the target tool's recent call history, current latency metrics, and any circuit breaker state. The output is a structured health assessment that the agent's control logic uses to decide whether to proceed, switch to a fallback tool, or enter a degraded mode. This harness must treat the self-check as a blocking decision point—if the check fails or times out, the agent must not silently proceed with the tool call.

Validation and retry logic: Parse the model's output against a strict schema that includes tool_status (one of healthy, degraded, unavailable), confidence (0.0–1.0), evidence_summary (string), and recommended_action (one of proceed, retry_with_backoff, use_fallback, abort). If parsing fails or confidence is below a configured threshold (start with 0.7), retry the self-check once with the same input plus the parse error or low-confidence flag. If the second attempt also fails, treat the tool as degraded and log the self-check failure as an observability event. Model choice: Use a fast, cheap model for self-checks (e.g., a small Haiku-class model) because latency added here directly impacts the user experience. Reserve larger models for the actual tool-use reasoning. Tool use and RAG: The self-check prompt itself should not call tools. Feed it pre-computed metrics—error counts, latency p95, circuit breaker state, and recent failure signatures—from the agent's telemetry store. Do not ask the model to query live monitoring systems.

Observability and logging: Log every self-check decision with the tool name, input metrics, model output, parse result, and final action taken. Attach a trace span that links the self-check to the subsequent tool call or fallback. This trace is essential for tuning thresholds and detecting when the self-check itself becomes a bottleneck. Human review gates: For high-risk tools (write operations, financial transactions, clinical actions), add a rule that any self-check result of degraded or unavailable must escalate to a human reviewer before the agent proceeds with a fallback. The harness should queue the decision context—tool name, health assessment, proposed fallback—into a review interface rather than blocking the agent indefinitely. What to avoid: Do not run self-checks on every tool call if the tool is stateless and idempotent; cache the health assessment for a short TTL (5–30 seconds, tuned to your tool's failure dynamics). Do not let the self-check prompt grow into a general diagnostic—keep it focused on go/no-go decisions. If the agent's control logic starts second-guessing the self-check output, the prompt's thresholds or evidence requirements need recalibration, not ad-hoc overrides in code.

IMPLEMENTATION TABLE

Expected Output Contract

Structured contract for the agent's self-check response. Use this to validate the model output before the agent proceeds with tool execution.

Field or ElementType or FormatRequiredValidation Rule

overall_status

enum: HEALTHY | DEGRADED | UNAVAILABLE

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

tool_health_checks

array of objects

Array must not be empty. Each object must contain tool_name, status, and evidence fields.

tool_health_checks[].tool_name

string

Must match a tool name from the provided [TOOL_REGISTRY] list. Case-sensitive exact match.

tool_health_checks[].status

enum: HEALTHY | DEGRADED | UNAVAILABLE

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

tool_health_checks[].evidence

object

Must contain at least one of: recent_error_count, avg_latency_ms, last_success_timestamp, or error_signature. Values must match their declared types.

tool_health_checks[].evidence.recent_error_count

integer

If present, must be a non-negative integer. Null not allowed if field is included.

tool_health_checks[].evidence.avg_latency_ms

integer

If present, must be a positive integer. Null not allowed if field is included.

degraded_mode_readiness

object

Must contain fallback_tools_available (boolean) and recommended_action (string). recommended_action must be one of: PROCEED_NORMALLY, USE_FALLBACK, QUEUE_AND_RETRY, or ESCALATE_TO_HUMAN.

PRACTICAL GUARDRAILS

Common Failure Modes

Production tool dependencies fail in ways that naive retry loops make worse. These are the most common failure modes when agents run self-checks, and how to prevent them.

01

Self-Check Becomes a Self-Fulfilling Prophecy

What to watch: The agent interprets a single slow response as systemic degradation, flips to degraded mode prematurely, and then never probes again because degraded mode avoids the tool. The tool recovers but the agent never notices. Guardrail: Require the self-check to sample multiple recent interactions across a configurable window. Separate transient latency from persistent failure using a threshold count, not a single observation. Include a mandatory half-open probing step after N minutes in degraded mode.

02

Health Check Overhead Causes the Degradation It Detects

What to watch: The self-check prompt adds non-trivial token cost and latency to every tool call. Under load, the check itself saturates the context window or rate limits, causing the very failures it was designed to prevent. Guardrail: Decouple the health check from the hot path. Run it as a periodic background assessment (every N calls or T seconds) rather than inline before every invocation. Cache the health state and only re-evaluate when the cache expires or a tool call fails.

03

Stale Health State Masks Silent Failures

What to watch: The agent caches a healthy state, but a dependency degrades between checks. Tool calls fail with partial results or timeouts while the agent continues operating as if everything is normal. Guardrail: Invalidate the health cache on any unexpected tool response (non-2xx, timeout, malformed output). Pair the periodic check with an event-driven invalidation trigger. Require the agent to re-assess health before retrying a failed call, not after.

04

Degraded Mode Selection Is Too Coarse

What to watch: The self-check produces a binary healthy/degraded signal, and the agent applies the same degraded mode (e.g., full fallback to stale cache) regardless of which tool failed or how severely. A minor latency increase on a non-critical tool triggers the same response as a complete outage on a core dependency. Guardrail: Structure the self-check output as a per-tool health vector, not a single system-wide flag. Map each tool to its own degradation policy. Allow partial degradation where only the affected tool's consumers switch modes.

05

Self-Check Prompt Drift Under Model Version Changes

What to watch: The self-check prompt relies on the model's internal reasoning about error patterns, but a model upgrade changes how the model interprets latency thresholds, error codes, or severity. The same tool behavior now triggers different health assessments. Guardrail: Externalize thresholds and decision rules from the prompt into application-layer configuration. Use the prompt only for structured evidence extraction (error counts, latency percentiles, failure types) and apply deterministic rules in code to produce the health state. Test the self-check against a golden dataset of known tool behaviors across model versions.

06

Health Check Lacks Observability Into Its Own Decisions

What to watch: The agent enters degraded mode, but operators cannot determine why because the self-check prompt output is not logged, versioned, or traced. Incident response requires guessing whether the degradation was justified or a prompt error. Guardrail: Emit structured trace spans from every self-check execution, including the raw assessment, thresholds applied, evidence considered, and the resulting health state. Version the self-check prompt and include the version in trace metadata. Make health state transitions observable as distinct events in monitoring dashboards.

IMPLEMENTATION TABLE

Evaluation Rubric

Run these checks against a golden dataset of health scenarios to validate the Agent Tool Health Self-Check Prompt before deployment. Each criterion targets a specific failure mode observed in production tool-awareness prompts.

CriterionPass StandardFailure SignalTest Method

Tool Availability Accuracy

Self-check correctly identifies available, degraded, and unavailable tools against ground-truth tool status

Agent reports a tool as available when it is actually returning 5xx errors or timing out

Inject controlled tool failures into a mock MCP server and compare self-check output to injected state

Recent Failure Pattern Detection

Self-check identifies failure patterns (e.g., 3 consecutive timeouts for [TOOL_NAME]) and reports them with correct counts and timestamps

Agent misses a clear failure pattern or reports incorrect failure counts for a tool with known error history

Pre-seed tool call history with known failure sequences and verify pattern extraction accuracy

Degraded Mode Readiness Assessment

Self-check correctly evaluates whether fallback tools, caches, or degraded paths are viable given current state

Agent claims degraded mode is ready when fallback tool is also unavailable or cache is expired beyond [MAX_STALENESS_SECONDS]

Configure fallback tool states and cache freshness in test harness; verify readiness assessment matches expected viability

Latency Baseline Comparison

Self-check compares current tool latency against [BASELINE_P95_MS] and flags anomalies exceeding [ANOMALY_THRESHOLD_MULTIPLIER]x baseline

Agent fails to flag a 10x latency spike or flags normal variance within 2x baseline as anomalous

Inject synthetic latency values above and below threshold; verify anomaly flagging precision and recall

Error Type Classification Correctness

Self-check classifies errors into correct categories: transient, persistent, auth, rate-limit, timeout, data-corruption

Agent misclassifies a 429 rate-limit error as a persistent failure or a 401 auth error as transient

Provide error responses with known HTTP/gRPC status codes and verify classification against expected category mapping

Self-Check Runtime Overhead

Self-check completes within [MAX_SELF_CHECK_MS] milliseconds and consumes fewer than [MAX_SELF_CHECK_TOKENS] tokens

Self-check exceeds time budget by more than 20% or consumes more than 2x token budget

Measure wall-clock time and token usage across 50 self-check runs with varying tool counts; verify P95 within budget

False Positive Rate on Healthy Tools

Self-check reports zero critical warnings when all tools are healthy, responsive, and within latency baselines

Agent flags a healthy tool as degraded or unavailable when no failures or anomalies exist

Run self-check against a fully healthy tool environment 20 times; verify zero false-positive degradation flags

Context Window Budget Awareness

Self-check output fits within [SELF_CHECK_OUTPUT_TOKEN_LIMIT] and does not crowd out subsequent tool call context

Self-check output exceeds token budget by more than 10% or leaves insufficient context for planned tool execution

Measure self-check output token count against configured limit; verify remaining context budget meets minimum threshold for next action

ADAPTATION OPTIONS

Adapt This Prompt

How to adapt

Start with the base self-check template but relax the evidence requirements. Instead of requiring structured metrics and historical baselines, allow the agent to report qualitative assessments ("feels slow," "returned errors recently"). Remove the [FAILURE_PATTERN_THRESHOLD] and [LATENCY_BASELINE] constraints. Focus on getting the self-check flow working before tightening the data contract.

Prompt snippet

code
Run a lightweight tool health self-check before executing [TOOL_NAME]. Report: (1) Is the tool reachable? (2) Any recent errors in your context window? (3) Do you have a fallback ready? Answer in plain text. No metrics required.

Watch for

  • Overconfident assessments without evidence
  • Agent skipping the check entirely when context is long
  • No distinction between transient and persistent failures
  • Self-check adding unacceptable latency in fast loops
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.