Inferensys

Prompt

Agent Tool Failure Injection Test Prompt

A practical prompt playbook for using Agent Tool Failure Injection Test Prompt 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

Define the job, reader, and constraints for the Agent Tool Failure Injection Test Prompt.

This prompt is for reliability engineers and AI quality engineers who need to verify that an agent handles tool failures gracefully before it reaches production. The job-to-be-done is generating a structured test plan that injects specific failure modes—timeouts, authentication errors, malformed responses, rate limits—into tool calls and defines the expected agent behavior for each scenario. You should use this prompt when you have a defined tool contract, a known set of failure modes you want to exercise, and a need for pass/fail criteria that can be automated in a CI pipeline or manual review gate.

The ideal user has access to the tool's API specification, error catalog, and the agent's system prompt or behavior policy. Required context includes the tool's name, its argument schema, the expected success response shape, and a list of failure modes to inject. You must also provide the agent's expected behavior policy—such as retry limits, fallback tools, escalation rules, and user communication requirements—so the generated test plan can define precise pass/fail criteria. Do not use this prompt for testing the tool implementation itself; it tests the agent's reaction to tool failures, not the tool's internal logic. It is also not a substitute for load testing, security penetration testing, or end-to-end integration tests that require live tool endpoints.

Before running this prompt, ensure you have a mock tool harness or simulation layer that can inject the specified failures without touching production systems. The generated test plan will assume you can control tool responses. After generating the plan, review each scenario for completeness against your operational runbooks—missing a timeout threshold or an idempotency requirement can cause the agent to loop, hallucinate, or silently drop work in production. Wire the pass/fail criteria into your eval framework so that every agent deployment is gated on these failure-mode tests.

PRACTICAL GUARDRAILS

Use Case Fit

Where this prompt works and where it does not. Use these cards to decide if the Agent Tool Failure Injection Test Prompt fits your current testing stage and operational context.

01

Good Fit: Pre-Production Resilience Testing

Use when: you are in a staging or CI/CD environment and need to validate agent behavior against tool failures before production deployment. Guardrail: Run this prompt as a gated step in your release pipeline, blocking promotion if critical failure modes are not handled.

02

Bad Fit: Live Production Traffic

Avoid when: you are tempted to inject failures into live user-facing agents. This prompt generates test plans for controlled environments, not chaos engineering in production. Guardrail: Use a dedicated test harness with mocked tool endpoints; never point failure injection at production tool proxies.

03

Required Input: Complete Tool Contract

What to watch: the prompt requires a full tool contract including argument schemas, output schemas, error codes, timeout values, and retry policies. Missing or incomplete contracts produce vague test plans. Guardrail: Validate your tool contract with the Tool Contract Validation Prompt before feeding it into failure injection planning.

04

Required Input: Expected Agent Behavior Spec

What to watch: without a clear specification of how the agent should behave under each failure mode, the generated pass/fail criteria will be generic. Guardrail: Pair this prompt with your agent's behavioral requirements document or runbook, and review generated criteria against your defined SLOs.

05

Operational Risk: Overly Permissive Test Scenarios

Risk: the prompt may generate test scenarios that assume destructive tool actions are safe to execute. Guardrail: Always review generated test plans for destructive operations and add explicit safety constraints before execution. Use read-only tool proxies or sandboxed endpoints for initial runs.

06

Operational Risk: False Confidence from Synthetic Failures

Risk: passing synthetic failure injection tests does not guarantee production resilience if the injected failures do not match real-world failure distributions. Guardrail: Periodically update your failure injection catalog with patterns observed in production traces and tool observability logs.

PROMPT PLAYBOOK

Copy-Ready Prompt Template

A reusable prompt that generates a structured failure injection test plan for agent tool calls, including failure modes, expected behaviors, and pass/fail criteria.

This prompt template is the core of the failure injection test plan generator. It takes a tool contract, a set of failure modes to inject, and the agent's expected behavioral contract, then produces a structured test plan that reliability engineers can execute directly. The template is designed to be wired into a test harness where mocked tool responses are injected and the agent's actual behavior is compared against the plan's assertions.

text
You are a reliability engineer designing failure injection tests for an AI agent that uses external tools.

Your task is to produce a structured test plan that injects specific failure modes into tool calls and defines the expected agent behavior for each failure scenario.

## INPUTS

[TOOL_CONTRACT]
[AGENT_BEHAVIOR_CONTRACT]
[FAILURE_MODES_TO_INJECT]
[CONSTRAINTS]

## INSTRUCTIONS

For each failure mode specified in [FAILURE_MODES_TO_INJECT], generate a test case with the following structure:

1. **Failure Injection**: Describe exactly what the mocked tool returns or does. Include:
   - The tool name and specific endpoint or function
   - The injected response (status code, error body, timeout duration, malformed payload)
   - Any preconditions required before injection (e.g., "agent must have completed authentication step first")

2. **Expected Agent Behavior**: Define what the agent must do when it receives this failure. Include:
   - Whether the agent should retry, fall back, escalate, or abort
   - The maximum number of retry attempts allowed
   - The expected user-facing message or system signal
   - Any state changes the agent should or should not make

3. **Pass/Fail Criteria**: Define observable, automatable assertions that determine whether the agent handled the failure correctly. Each criterion must be:
   - Binary (pass or fail, no partial credit)
   - Observable in logs, agent output, or system state
   - Independent of other test cases

4. **Risk Level**: Classify the test case as LOW, MEDIUM, HIGH, or CRITICAL based on:
   - Data integrity risk (could the agent corrupt state?)
   - User impact (would the user see incorrect results?)
   - Recovery difficulty (can the agent self-recover?)

## OUTPUT SCHEMA

Return a JSON object with this exact structure:

{
  "test_plan_id": "string",
  "generated_at": "ISO-8601 timestamp",
  "tool_under_test": "string (tool name from contract)",
  "failure_categories_covered": ["string"],
  "test_cases": [
    {
      "test_id": "string (unique, kebab-case)",
      "failure_mode": "string (e.g., timeout, auth_error, malformed_response, rate_limit, internal_error)",
      "risk_level": "LOW | MEDIUM | HIGH | CRITICAL",
      "injection": {
        "tool_name": "string",
        "mocked_response": {},
        "preconditions": ["string"]
      },
      "expected_behavior": {
        "action": "retry | fallback | escalate | abort | ignore",
        "max_retries": "integer or null",
        "fallback_tool": "string or null",
        "user_signal": "string (expected message or indicator)",
        "state_changes": "string (description of allowed or forbidden state mutations)"
      },
      "pass_criteria": [
        {
          "criterion_id": "string",
          "description": "string (observable assertion)",
          "check_method": "log_assertion | output_assertion | state_assertion | metric_assertion",
          "expected_value": "string"
        }
      ]
    }
  ],
  "coverage_gaps": ["string (failure modes not covered and why)"],
  "execution_order": ["string (test_id sequence with dependency notes)"]
}

## CONSTRAINTS

- Do not invent failure modes not listed in [FAILURE_MODES_TO_INJECT]
- Every pass criterion must be automatable—no manual judgment required
- If a failure mode cannot be safely tested (e.g., destructive side effects), flag it in coverage_gaps with the reason
- Respect [CONSTRAINTS] if provided (e.g., "no production endpoints", "read-only tools only")
- If [AGENT_BEHAVIOR_CONTRACT] is incomplete for a failure mode, note the ambiguity and suggest the contract gap

To adapt this template, replace each square-bracket placeholder with concrete inputs. [TOOL_CONTRACT] should contain the full tool definition including endpoints, argument schemas, and expected success responses. [AGENT_BEHAVIOR_CONTRACT] should describe the agent's documented retry policy, fallback chain, escalation path, and user communication rules. [FAILURE_MODES_TO_INJECT] should be a specific list drawn from your production incident history—timeouts, 429 rate limits, 503 service unavailable, malformed JSON responses, and authentication expiry are the minimum starting set. [CONSTRAINTS] is optional but critical for safety: always include "no production endpoints, no destructive writes, use mocked responses only" when generating tests that will be executed automatically. After copying the template, validate that the output JSON matches the schema before feeding it into your test runner.

IMPLEMENTATION TABLE

Prompt Variables

Required inputs for the Agent Tool Failure Injection Test Prompt. Each placeholder must be populated before the prompt can generate a reliable test plan. Validate inputs against the notes below to prevent ambiguous or untestable failure scenarios.

PlaceholderPurposeExampleValidation Notes

[TOOL_CONTRACT]

The complete tool definition including name, description, argument schema, output schema, and declared error modes

{"name": "search_kb", "args": {"query": "string"}, "output": {"results": "array"}, "errors": ["TIMEOUT", "AUTH_ERROR"]}

Schema parse check: must be valid JSON with required fields name, args, output. Reject if error catalog is empty or missing.

[FAILURE_MODES_TO_INJECT]

List of specific failure modes to test, selected from the tool's declared error catalog or common infrastructure failures

["TIMEOUT", "MALFORMED_JSON", "AUTH_EXPIRED", "RATE_LIMITED", "NULL_REQUIRED_FIELD"]

Enum check: each value must match a declared error in [TOOL_CONTRACT] or a standard infrastructure failure. Reject if list is empty or contains undefined modes.

[AGENT_BEHAVIOR_SPEC]

The expected agent behavior contract including retry policy, fallback rules, escalation triggers, and user communication rules

{"max_retries": 2, "backoff": "exponential", "fallback_tool": "local_search", "escalate_on": ["AUTH_EXPIRED"], "user_message": true}

Schema check: must include max_retries, fallback_tool or null, escalate_on array. Reject if retry policy is undefined or fallback references a tool not in the agent's tool registry.

[AGENT_TOOL_REGISTRY]

Full list of tools available to the agent, including primary and fallback tools, with their contracts

[{"name": "search_kb", ...}, {"name": "local_search", ...}, {"name": "submit_ticket", ...}]

Schema check: must be a non-empty array of valid tool contracts. Cross-reference: every fallback_tool in [AGENT_BEHAVIOR_SPEC] must exist in this registry.

[INJECTION_POINT]

The specific step or tool call index in the agent's execution plan where the failure should be injected

{"step": 2, "tool": "search_kb", "call_index": 1}

Range check: step and call_index must be positive integers. Tool name must exist in [AGENT_TOOL_REGISTRY]. Reject if injection point is out of bounds for the planned execution sequence.

[PASS_CRITERIA_TEMPLATE]

The evaluation rubric template defining what constitutes a pass for each failure scenario, including agent behavior assertions

{"must_not_hallucinate": true, "must_retry": true, "must_fallback": true, "must_escalate": false, "max_latency_ms": 5000}

Boolean and threshold checks: all behavior flags must be true or false. max_latency_ms must be a positive integer. Reject if criteria contradict the [AGENT_BEHAVIOR_SPEC].

[OUTPUT_SCHEMA]

The expected structure of the generated test plan, including test cases, assertions, and expected behaviors per scenario

{"test_plan": {"test_cases": [{"scenario_id": "string", "injected_failure": "string", "expected_behavior": "object", "assertions": ["string"]}]}}

Schema parse check: must be valid JSON Schema or example structure. Must include scenario_id, injected_failure, expected_behavior, and assertions fields. Reject if assertions array is empty.

[CONTEXT_WINDOW_LIMIT]

The maximum token budget available for the test plan output, constraining scenario count and description verbosity

8192

Integer range check: must be a positive integer matching a supported model context window. Used to cap the number of generated test scenarios. Reject if below 1024 or above 128000 without explicit model justification.

PROMPT PLAYBOOK

Implementation Harness Notes

How to wire the failure injection test plan prompt into a reliability engineering workflow with validation, model selection, and automated execution gates.

This prompt is designed to be the planning stage of an automated reliability pipeline, not a one-off chat interaction. The output is a structured test plan (JSON) that should be parsed by a test runner or orchestration engine. Do not treat the generated plan as a final artifact—it must pass through a validation layer that checks for schema completeness, scenario coverage against your tool registry, and safety constraints before any failure injection is executed against a live or staging agent.

Wire the prompt into a three-stage harness: (1) Generation—call the model with the prompt template, supplying your tool contract schemas, known failure catalog, and risk tolerance. Use a model with strong structured output support (GPT-4o, Claude 3.5 Sonnet, or equivalent) with response_format set to json_schema if available. (2) Validation—run the output through a deterministic validator that checks: every scenario has a unique ID, every injected failure maps to a tool in your registry, pass/fail criteria are non-empty, and no destructive mutations (DELETE, DROP, production-write) are present unless explicitly allowed. Reject and retry with error feedback if validation fails. (3) Execution—feed validated scenarios one at a time into your test harness, which mocks the tool at the boundary, invokes the agent, and evaluates behavior against the pass/fail criteria. Log every scenario outcome with the scenario ID, actual agent behavior, and a pass/fail determination.

For high-risk production agents (those with write access to databases, financial systems, or user data), add a human approval gate between validation and execution. The validated test plan should be surfaced in a review UI showing: which tools are targeted, what failure modes are injected, and whether any scenario could cause side effects in connected staging environments. Only after explicit approval should the harness proceed. For regression use, store validated test plans alongside your agent version so that every agent release re-runs the same failure injection suite. Track pass rates over time and flag regressions where an agent previously handled a failure mode correctly but now hallucinates, loops, or times out.

IMPLEMENTATION TABLE

Expected Output Contract

Fields, format, and validation rules for the Agent Tool Failure Injection Test Prompt output. Use this contract to parse, validate, and gate the generated test plan before execution.

Field or ElementType or FormatRequiredValidation Rule

test_plan_id

string (uuid)

Must be a valid UUID v4 string. Reject if missing or malformed.

failure_scenarios

array of objects

Array length must be >= 1. Each element must conform to the failure_scenario schema below.

failure_scenarios[].scenario_id

string (kebab-case)

Must match pattern ^[a-z]+(-[a-z]+)*$. Must be unique within the array.

failure_scenarios[].failure_mode

enum string

Must be one of: timeout, auth_error, malformed_response, rate_limit, internal_server_error, null_field, oversized_payload, dependency_failure.

failure_scenarios[].tool_name

string

Must match a tool name from the provided [TOOL_REGISTRY]. Reject if tool is not in registry.

failure_scenarios[].injection_point

enum string

Must be one of: pre_call, mid_response, post_call. Defines when the failure is injected.

failure_scenarios[].expected_agent_behavior

object

Must contain action (enum: retry, fallback, escalate, abort, ask_user) and max_retries (integer >= 0).

failure_scenarios[].pass_criteria

array of strings

Array length must be >= 1. Each string must be a verifiable assertion (e.g., 'agent does not hallucinate a result').

PRACTICAL GUARDRAILS

Common Failure Modes

What breaks first when you inject tool failures into an agent and how to guard against it.

01

Agent Hallucinates Tool Results

What to watch: When a tool call fails silently or returns an error, the agent fabricates a plausible result instead of reporting the failure. This is most common with timeout and 5xx errors where the model fills the gap. Guardrail: Require the agent to always cite the raw tool response status code and timestamp before interpreting results. Add an eval that compares agent-summarized output against the actual mocked response.

02

Infinite Retry Loop on Transient Errors

What to watch: The agent retries a failing tool call indefinitely because the retry condition is too broad or the stop condition is missing. Rate limits and 429 responses are the most common triggers. Guardrail: Define explicit max-retry and backoff parameters in the test plan. Inject a persistent failure after N retries and verify the agent escalates or degrades rather than looping.

03

Silent State Corruption After Partial Failure

What to watch: A multi-step tool chain fails at step 3 of 5, but the agent continues with stale or inconsistent state from steps 1 and 2. The output looks valid but is built on corrupted data. Guardrail: Inject a mid-chain failure and assert that the agent either rolls back, requests re-execution, or explicitly flags the inconsistency. Never let partial state propagate unmarked.

04

Tool Contract Mismatch Goes Undetected

What to watch: The mocked response schema doesn't match what the agent expects—missing fields, type changes, or renamed keys—and the agent proceeds without detecting the mismatch. Guardrail: Include schema compliance checks in the test harness. Verify the agent validates response structure before acting on it. Inject a response with a missing required field and confirm the agent rejects or flags it.

05

Permission Boundary Bypass via Error Handling

What to watch: An agent attempts an out-of-scope tool call, receives an auth error, and then retries with a different tool or argument pattern that accidentally succeeds. The error path becomes an escalation vector. Guardrail: Test permission boundaries explicitly. Inject 403 and 401 responses and verify the agent does not attempt alternative paths to the same restricted resource. Log every permission denial for audit.

06

Timeout Handling Masks Real Failures

What to watch: The agent treats all timeouts as transient and retries identically, even when the root cause is a payload size issue or a downstream outage that won't resolve. This wastes resources and delays user-visible degradation. Guardrail: Differentiate timeout types in the test plan—network timeout, read timeout, and connection timeout. Verify the agent applies different strategies per type and escalates after deadline propagation rules are exceeded.

IMPLEMENTATION TABLE

Evaluation Rubric

Use this rubric to evaluate the quality of a generated Agent Tool Failure Injection Test Plan before integrating it into your CI pipeline or manual QA process. Each criterion targets a specific failure mode of the test plan itself.

CriterionPass StandardFailure SignalTest Method

Failure Mode Coverage

Plan includes at least one scenario for timeouts, 4xx auth errors, 5xx server errors, and malformed JSON responses.

Plan only covers happy-path or a single generic error type.

Parse the generated plan. Count distinct error categories. Fail if count < 4.

Tool Contract Fidelity

All injected error responses conform to the provided [TOOL_CONTRACT] schema for the error shape.

Injected error is missing a required field like error.code or uses an incorrect type.

Validate each injected error response against the [TOOL_CONTRACT] JSON Schema. Fail on any validation errors.

Expected Agent Behavior Specificity

For each failure scenario, the expected behavior describes a concrete action: retry, fallback to [FALLBACK_TOOL], escalate, or abort.

Expected behavior is vague, such as 'handle the error gracefully' or 'inform the user'.

Check each scenario's expected behavior string. Fail if it does not contain one of the allowed action verbs: retry, fallback, escalate, abort.

Idempotency and Retry Logic

For timeout and 5xx scenarios, the plan specifies max retries, backoff strategy, and idempotency key reuse.

Retry logic is missing, or suggests infinite retries without a circuit breaker.

Regex search for 'max_retries' and 'backoff' in the retry scenario. Fail if absent or if max_retries > 5.

Non-Destructive Test Design

All test scenarios are marked as safety: read-only or safety: sandbox and target a staging endpoint.

A test scenario targets a production endpoint or a destructive action like DELETE or UPDATE without a safety flag.

Scan all scenario definitions for the safety field. Fail if any value is not 'read-only' or 'sandbox'.

Pass/Fail Criteria Definition

Each scenario includes a measurable pass/fail condition, such as 'Agent must not call [TOOL_NAME] again' or 'Agent must respond with FALLBACK_MESSAGE'.

A scenario lacks a pass/fail condition or uses a subjective measure like 'Agent seems correct'.

Assert that every scenario object has a non-null pass_condition string. Fail if any are missing.

Hallucination Prevention

The plan explicitly instructs the evaluator to compare the agent's summary of the tool error against the raw injected error.

No instruction exists to check for fabricated error details in the agent's final output.

Search the plan for the phrase 'compare agent output to raw injected error'. Fail if not found.

ADAPTATION OPTIONS

Adapt This Prompt

How to adapt

Start with the base failure injection template but relax strict pass/fail criteria. Focus on generating 3–5 core failure scenarios (timeout, auth error, malformed JSON) with simple expected behaviors. Use manual review instead of automated eval gates.

code
Generate a test plan for [TOOL_NAME] that injects these failure modes:
- Timeout after [TIMEOUT_MS]ms
- 401 Unauthorized
- Malformed JSON response

For each, describe the expected agent behavior in 1–2 sentences.

Watch for

  • Overly broad expected behaviors that can't be verified
  • Missing edge cases like partial responses or rate-limit headers
  • No distinction between transient and permanent failures
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.