Inferensys

Prompt

Tool Use Error Categorization and Root Cause Prompt

A practical prompt playbook for using Tool Use Error Categorization and Root Cause 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

Learn when to deploy the error categorization prompt for offline agent diagnosis and when to choose a different tool.

This prompt is built for agent platform teams who have moved beyond simple pass/fail tool-use metrics and need to understand why their agents are failing. The core job-to-be-done is offline root-cause analysis: you have a batch of agent traces with known failures, and you need to prioritize which failure class to fix first. The prompt classifies every tool-use error into a structured taxonomy—wrong tool, bad arguments, timing error, hallucination, misinterpretation—and attributes a root cause. The output is a categorized error report with frequency distributions, designed to feed directly into sprint planning and model improvement backlogs.

Use this prompt when you are conducting a post-mortem on a test suite run, analyzing production traces in a debugging session, or comparing failure profiles across model versions. It is ideal for generating a prioritized backlog of agent improvements. Do not use this prompt for real-time agent decision-making or as a guardrail during live execution. It is an offline evaluation and diagnosis tool, not a runtime classifier. It also assumes you have already identified which traces contain failures; it does not perform the initial pass/fail grading. Pair it with a Tool Call Pass/Fail Gate Criteria Prompt to filter traces first, then feed the failures into this prompt for categorization.

Before using this prompt, ensure you have structured trace data including the agent's reasoning, the tool catalog provided, the tool calls made, their arguments, and the outcomes. The prompt's value scales with trace volume—single-trace analysis is better served by manual inspection. For safety-critical tool-use workflows, always route the final categorized report through a human review step before committing to remediation priorities. The taxonomy itself should be treated as a living artifact; if your agent's failure modes evolve, update the taxonomy in the prompt to prevent drift between what you measure and what actually breaks in production.

PRACTICAL GUARDRAILS

Use Case Fit

Where this prompt works and where it does not. Use these cards to decide if the Tool Use Error Categorization and Root Cause Prompt fits your evaluation pipeline.

01

Good Fit: Agent Regression Testing

Use when: you have a stable test suite of agent traces and need to classify failures before a release. Guardrail: run this prompt against a golden dataset of known tool-use errors to calibrate the taxonomy before production use.

02

Good Fit: Prioritizing Agent Improvements

Use when: you need frequency distributions of error types to decide whether to fix tool descriptions, argument schemas, or planning prompts. Guardrail: aggregate results across at least 50 traces before drawing conclusions; small samples produce noisy distributions.

03

Bad Fit: Real-Time Guardrails

Avoid when: you need to block a bad tool call before execution. This prompt is for post-hoc analysis, not inline intervention. Guardrail: pair this with a lightweight, deterministic schema validator or tool-name allowlist for real-time blocking.

04

Bad Fit: Single-Turn Tool Selection Only

Avoid when: your agent only makes one tool call per turn with no sequencing or dependency. The root cause taxonomy includes timing and chaining categories that won't apply. Guardrail: use a simpler Tool Selection Correctness Grading prompt for single-call workflows.

05

Required Inputs

What you need: a full agent trace including user input, tool definitions, tool calls with arguments, tool responses, and final output. Guardrail: missing tool responses prevent accurate root cause attribution—the judge needs to see what the agent saw to distinguish misinterpretation from hallucination.

06

Operational Risk: Judge Drift

Risk: the LLM judge may apply the error taxonomy inconsistently across traces or over time. Guardrail: periodically sample categorized errors and have a human reviewer confirm the classification. Track inter-rater agreement between the judge and human reviewer across error categories.

PROMPT PLAYBOOK

Copy-Ready Prompt Template

A production-ready prompt for classifying tool-use failures into a structured taxonomy and attributing root causes.

This prompt template is designed to be pasted directly into your evaluation harness. It takes a tool-use trace, the agent's context, and your tool catalog as input, then produces a structured error categorization report. The template uses square-bracket placeholders that you must replace with real data before sending to the model. Every placeholder is documented so you can wire this into an automated pipeline without guessing.

text
You are an expert evaluator of AI agent tool-use behavior. Your task is to analyze a tool-use trace and classify any failures into a predefined error taxonomy, then attribute root causes.

## INPUTS

### Tool Catalog
[TOOL_CATALOG]

### Agent Context
[AGENT_CONTEXT]

### Tool-Use Trace
[TOOL_TRACE]

### Expected Behavior (Optional)
[EXPECTED_BEHAVIOR]

## ERROR TAXONOMY

Classify each failure into exactly one of these categories:

1. **WRONG_TOOL**: The agent selected a tool that is inappropriate for the task, not in the catalog, or clearly suboptimal given available alternatives.
2. **BAD_ARGUMENTS**: The correct tool was selected, but one or more arguments are incorrect, missing required fields, have wrong types, or contain hallucinated values.
3. **TIMING_ERROR**: The tool was called too early (before necessary context was gathered) or too late (after sufficient information was already available).
4. **HALLUCINATION**: The agent invented a tool name, parameter, or capability not present in the provided tool catalog.
5. **MISINTERPRETATION**: The agent misunderstood the tool's purpose, output format, or side effects, leading to incorrect usage despite correct syntax.
6. **REDUNDANT_CALL**: The tool call was unnecessary because the information was already available or a prior call already produced the needed result.
7. **MISSING_CALL**: The agent should have called a tool but did not, either by abstaining incorrectly or by proceeding without required information.
8. **SEQUENCE_ERROR**: Multi-step tool calls were executed in the wrong order, violating dependency constraints.
9. **SAFETY_VIOLATION**: The tool call attempted an unauthorized action, scope escalation, or dangerous parameter combination.
10. **RESULT_MISUSE**: The agent received a correct tool result but misinterpreted, ignored, or incorrectly applied the output in subsequent reasoning.

## OUTPUT SCHEMA

Return a valid JSON object with this exact structure:

{
  "summary": {
    "total_calls": <integer>,
    "failed_calls": <integer>,
    "pass_rate": <float between 0 and 1>,
    "dominant_failure_category": <string or null>
  },
  "failures": [
    {
      "call_index": <integer, 0-based position in trace>,
      "tool_name": <string>,
      "error_category": <one of the taxonomy values above>,
      "severity": <"CRITICAL" | "MAJOR" | "MINOR">,
      "description": <string, concise explanation of what went wrong>,
      "root_cause": <string, attribution to one of: "INSTRUCTION_GAP" | "CONTEXT_INSUFFICIENCY" | "TOOL_DESCRIPTION_AMBIGUITY" | "MODEL_CAPABILITY_LIMIT" | "PROMPT_CONFLICT" | "UNKNOWN">,
      "evidence": <string, direct quote or reference from the trace or context>,
      "suggested_fix": <string, actionable recommendation>
    }
  ],
  "frequency_distribution": {
    "WRONG_TOOL": <integer>,
    "BAD_ARGUMENTS": <integer>,
    "TIMING_ERROR": <integer>,
    "HALLUCINATION": <integer>,
    "MISINTERPRETATION": <integer>,
    "REDUNDANT_CALL": <integer>,
    "MISSING_CALL": <integer>,
    "SEQUENCE_ERROR": <integer>,
    "SAFETY_VIOLATION": <integer>,
    "RESULT_MISUSE": <integer>
  },
  "root_cause_attribution": {
    "INSTRUCTION_GAP": <integer>,
    "CONTEXT_INSUFFICIENCY": <integer>,
    "TOOL_DESCRIPTION_AMBIGUITY": <integer>,
    "MODEL_CAPABILITY_LIMIT": <integer>,
    "PROMPT_CONFLICT": <integer>,
    "UNKNOWN": <integer>
  },
  "improvement_priorities": [
    {
      "category": <string>,
      "impact": <"HIGH" | "MEDIUM" | "LOW">,
      "rationale": <string>
    }
  ]
}

## CONSTRAINTS

- Only classify actual failures. Do not flag correct tool calls as errors.
- If [EXPECTED_BEHAVIOR] is provided, use it as ground truth for determining correctness.
- If a call has multiple failure modes, choose the most impactful category.
- Set severity to CRITICAL if the failure would cause downstream system breakage, data corruption, or safety violations.
- Set severity to MAJOR if the failure produces incorrect results but does not break downstream systems.
- Set severity to MINOR if the failure is suboptimal but still produces usable results.
- For root_cause, prefer specific attributions over UNKNOWN. Use UNKNOWN only when no clear cause is identifiable.
- Base all evidence fields on direct quotes or explicit references from the trace or context.
- Do not invent failures that are not present in the trace.

## EVALUATION INSTRUCTIONS

1. Parse the tool trace to identify each individual tool call.
2. For each call, determine if it was correct given the agent context and expected behavior.
3. For incorrect calls, classify the error using the taxonomy above.
4. Attribute a root cause to each failure.
5. Compute the frequency distribution across all failures.
6. Generate improvement priorities based on failure impact and frequency.
7. Return the complete JSON object as specified.

To adapt this template for your pipeline, replace each placeholder with live data. [TOOL_CATALOG] should contain your full tool definitions including names, descriptions, parameter schemas, and any usage constraints. [AGENT_CONTEXT] should include the user's request, system prompt, conversation history, and any retrieved context the agent had access to. [TOOL_TRACE] should be the complete sequence of tool calls with their arguments and returned results. [EXPECTED_BEHAVIOR] is optional but strongly recommended for regression testing—it should describe the correct tool-use sequence so the evaluator can compare actual behavior against ground truth. If you omit expected behavior, the evaluator will rely on its own judgment of correctness, which reduces reliability for gating decisions.

Before deploying this prompt in a CI/CD gate, validate that your tool catalog format is consistent across test cases. Inconsistent tool descriptions will cause the evaluator to flag MISINTERPRETATION errors that are actually data formatting issues. Run this prompt against a golden dataset of 20-50 annotated traces where you know the correct error categorizations, and measure inter-rater agreement between the LLM judge and your human annotations. If agreement drops below 0.8 on critical failure categories, calibrate by adding few-shot examples to the prompt or refining your taxonomy definitions. For high-risk agent workflows where tool misuse could cause financial transactions or data deletion, always route CRITICAL severity findings to human review before accepting the automated categorization.

IMPLEMENTATION TABLE

Prompt Variables

Every placeholder the Tool Use Error Categorization and Root Cause Prompt expects, why it matters, and how to validate it before sending.

PlaceholderPurposeExampleValidation Notes

[TOOL_CALL_TRACE]

The sequence of tool calls, arguments, and results from an agent run that needs error analysis

{"turn_1": {"tool": "search", "args": {"query": "Q3 revenue"}, "result": "Error: timeout"}, "turn_2": {"tool": "calculate", "args": {"expression": "total / 0"}, "result": "Error: division by zero"}}

Must be valid JSON with at minimum tool name, arguments, and result per call. Reject if empty array or missing result field. Parse check before prompt assembly.

[TOOL_CATALOG]

The complete list of available tools with their schemas, descriptions, and constraints as provided to the agent

{"tools": [{"name": "search", "description": "Search knowledge base", "parameters": {"query": "string"}}, {"name": "calculate", "description": "Perform calculation", "parameters": {"expression": "string"}}]}

Must match the exact tool catalog the agent received. Schema validation required: each tool entry needs name, description, and parameters. Reject if catalog is null or tools array is empty.

[ERROR_TAXONOMY]

The predefined categories of tool-use failures the model should classify errors into

["wrong_tool", "bad_arguments", "timing_error", "hallucinated_tool", "misinterpretation", "missing_prerequisite", "redundant_call"]

Must be a non-empty array of unique string labels. Validate that taxonomy entries are mutually exclusive enough for reliable classification. Reject if taxonomy contains fewer than 3 categories or has duplicates.

[TASK_CONTEXT]

The original user request or agent goal that initiated the tool-use sequence

"Find Q3 2024 revenue and calculate year-over-year growth rate"

Must be a non-empty string. Validate that context is specific enough to judge tool appropriateness. Reject if context is null, empty, or a generic placeholder like 'do the thing'. Minimum 10 characters.

[OUTPUT_SCHEMA]

The expected JSON structure for the error categorization report including fields for error type, root cause, frequency, and affected calls

{"errors": [{"call_id": "turn_1", "category": "timing_error", "root_cause": "Tool called before required context was available", "evidence": "search called before user query was fully specified"}], "summary": {"total_calls": 5, "errors_found": 2, "frequency_distribution": {"timing_error": 1, "bad_arguments": 1}}}

Must be a valid JSON Schema or example object. Validate that required fields include call_id, category, root_cause, and evidence. Reject if schema allows category values outside the provided taxonomy.

[GROUND_TRUTH_LABELS]

Optional human-annotated error labels for calibration and judge alignment scoring

{"turn_1": {"category": "timing_error", "root_cause": "search executed before user constraints were provided"}, "turn_3": {"category": "bad_arguments", "root_cause": "division by zero in calculate expression"}}

If provided, must be a JSON object keyed by call_id with category and root_cause fields. Validate that all categories exist in the taxonomy. Null allowed when running without calibration. If present, check for at least one labeled call.

[CONFIDENCE_THRESHOLD]

Minimum confidence score required for automatic classification before flagging for human review

0.85

Must be a float between 0.0 and 1.0. Default to 0.8 if not specified. Validate range. Reject if threshold is below 0.5 or above 0.99. Use for routing low-confidence classifications to human-in-the-loop queue.

PROMPT PLAYBOOK

Implementation Harness Notes

How to wire the error categorization prompt into an evaluation pipeline with validation, retries, and human review gates.

This prompt is designed to run as a post-execution analysis step, not in the hot path of an agent. After an agent trace completes (or fails), feed the full trace—including user input, reasoning steps, tool calls, tool responses, and final output—into this prompt to produce a structured error report. The prompt expects a complete trace log and a reference tool catalog so it can distinguish between correct tool use and failures. Run this prompt asynchronously after agent execution, not synchronously during it, because the analysis requires the full trace to categorize errors and attribute root causes.

Wire the prompt into an evaluation harness that calls your LLM API with the trace and tool catalog as inputs. Validation is critical: parse the JSON output and verify that every error category in the error_categories array matches your predefined taxonomy. Reject any output that introduces novel categories or omits the root_cause_attribution field. Implement a retry loop with up to 3 attempts if validation fails, appending the validation error message to the next request so the model can self-correct. Log every attempt, the raw output, and the validation result for later audit. For high-stakes agent workflows—such as those involving financial transactions, healthcare data, or safety-critical actions—add a human review gate that queues categorized error reports with severity: "critical" or confidence_below: 0.8 for manual inspection before the report is used to prioritize engineering work.

Choose a model with strong structured output capabilities and a context window large enough to hold your longest agent traces plus the tool catalog. GPT-4o, Claude 3.5 Sonnet, and Gemini 1.5 Pro are suitable defaults. If you're processing traces at high volume, consider batching multiple traces into a single request with clear delimiters and asking for an array of reports to reduce API overhead. Store the categorized error reports in your observability platform alongside the original traces so you can track error frequency distributions over time and measure whether prompt or agent changes reduce specific error categories. Avoid running this prompt on incomplete or truncated traces—if the trace is cut off, skip analysis and flag it for trace buffer size review instead of producing a misleading error report.

IMPLEMENTATION TABLE

Expected Output Contract

The exact fields, types, and validation rules your system should expect from a successful run of the Tool Use Error Categorization and Root Cause Prompt.

Field or ElementType or FormatRequiredValidation Rule

error_categories

array of objects

Must contain at least 1 object. Each object must have category_name (string) and count (integer >= 0). Sum of all counts must equal total_errors.

error_categories[].category_name

string from closed taxonomy

Must match one of the predefined taxonomy values: wrong_tool, bad_arguments, timing_error, hallucinated_tool, misinterpretation, missing_call, redundant_call, other. No external values allowed.

error_categories[].count

integer

Must be >= 0. Must be parseable as integer. Null not allowed.

total_errors

integer

Must equal the sum of all error_categories[].count values. Must be >= 0.

root_cause_attribution

object

Must contain primary_cause (string) and confidence (number between 0.0 and 1.0).

root_cause_attribution.primary_cause

string from closed taxonomy

Must match one of: prompt_ambiguity, missing_tool_definition, context_window_truncation, model_capability_gap, user_input_ambiguity, tool_output_misinterpretation, unknown.

root_cause_attribution.confidence

number

Must be >= 0.0 and <= 1.0. Parse check: must not be string or boolean.

per_instance_details

array of objects

If present, each object must have instance_id (string), error_category (string from taxonomy), and evidence_snippet (string). Array length must not exceed 50 unless explicitly configured.

PRACTICAL GUARDRAILS

Common Failure Modes

What breaks first when the Tool Use Error Categorization and Root Cause Prompt runs in production and how to guard against it.

01

Taxonomy Drift on Novel Errors

What to watch: The model forces genuinely new failure modes into existing taxonomy buckets instead of flagging them as unclassified, producing misleading frequency distributions. Guardrail: Include an 'Other/Unclassified' category with a required justification field. Run periodic human review on items bucketed there to decide if the taxonomy needs expansion.

02

Root Cause Attribution to Wrong Agent Step

What to watch: The judge blames the tool-calling step when the real root cause was an earlier planning or context-retrieval failure. This misdirects engineering effort. Guardrail: Require the prompt to trace the full causal chain backward from the error. Validate a sample of attributions by checking if fixing the cited root cause would actually prevent the error.

03

Hallucinated Error Evidence in Long Traces

What to watch: When analyzing long agent traces, the model invents tool outputs or conversation turns that don't exist to support its error categorization. Guardrail: Require every error classification to cite a specific, verifiable line or step number from the input trace. Implement a post-processing check that all cited evidence exists in the source material.

04

Frequency Distribution Distortion from Ambiguous Cases

What to watch: The model inconsistently categorizes borderline errors across a batch, inflating some categories and deflating others, making frequency reports unreliable for prioritization. Guardrail: Add a confidence score to each classification. Route low-confidence categorizations to a secondary judge or human review queue before they enter aggregate statistics.

05

Overfitting to Surface-Level Error Signals

What to watch: The prompt categorizes based on the immediate error message (e.g., 'invalid argument') without diagnosing whether the argument was hallucinated, mistimed, or derived from a prior tool failure. Guardrail: Structure the prompt to require a two-pass analysis: first categorize the surface error, then diagnose the underlying cause. Reject classifications where the two passes contradict without explanation.

06

Batch Processing Context Collapse

What to watch: When processing many traces in a single context window, the model mixes up details between traces, attributing an error from trace A to trace B. Guardrail: Process one trace per request when accuracy is critical. For batch processing, add a verification step that asks the model to restate the unique trace ID and key distinguishing facts before categorizing.

IMPLEMENTATION TABLE

Evaluation Rubric

Use this rubric to test the quality of the Tool Use Error Categorization and Root Cause Prompt before relying on it for production decisions. Each criterion targets a specific failure mode in error classification and root cause attribution.

CriterionPass StandardFailure SignalTest Method

Error Category Assignment

Every tool-use error in the trace is assigned exactly one category from the defined taxonomy

Errors left uncategorized, assigned to multiple categories, or assigned to categories not in the taxonomy

Parse output and verify each error has exactly one category label matching the taxonomy enum

Root Cause Attribution

Each error's root cause is traced to a specific, verifiable source in the tool call, arguments, context, or timing

Root cause stated as generic claim without traceable evidence, or attributed to model internals without observable signal

For each error, check that the root cause field references a concrete element from the input trace

Frequency Distribution Accuracy

Error frequency counts match the number of errors in the input trace and sum correctly across categories

Count mismatch between total errors in trace and sum of category frequencies, or duplicate counting

Count errors in input trace manually and compare to reported frequencies and cross-category sum

Hallucination vs Misinterpretation Separation

Hallucinated tool names or arguments are classified distinctly from misinterpretation of valid tools

Hallucinated tool name classified as misinterpretation, or fabricated argument values labeled as wrong-tool error

Inject test cases with known hallucinated tool names and verify they land in hallucination category, not misinterpretation

Timing Error Detection

Premature and delayed tool calls are correctly identified with timing justification from the trace

Timing errors missed entirely, or calls flagged as timing errors without evidence of dependency order violation

Use traces with known premature calls and verify timing error category is assigned with dependency chain evidence

Abstention Failure Classification

Missing tool calls where action was required are classified as abstention errors, not ignored

Required tool call absence goes unreported, or abstention error is misclassified as wrong-tool

Provide traces with deliberately omitted required calls and verify abstention error category appears

Output Schema Compliance

Report matches the expected schema with all required fields present and correctly typed

Missing error_categories array, malformed frequency_distribution object, or null root_cause on required entries

Validate output against JSON Schema; reject if required fields are absent or types are wrong

Confidence Calibration

Confidence scores for error classifications correlate with evidence strength and ambiguity in the trace

High confidence assigned to clearly ambiguous cases, or low confidence on unambiguous tool-name hallucinations

Compare confidence scores against human-annotated difficulty ratings on a held-out test set

ADAPTATION OPTIONS

Adapt This Prompt

How to adapt\nUse the base prompt with a small, hand-labeled dataset of 20-50 tool-call traces. Remove strict output schema requirements and accept free-text categorization. Focus on getting the taxonomy right before locking down format.\n\n**Prompt modification:** Replace [OUTPUT_SCHEMA] with: `Return a JSON array of error objects, each with "error_category", "root_cause", and "evidence" fields.` Keep it loose.\n\n### Watch for\n- The model inventing error categories not in your taxonomy\n- Overly verbose root cause explanations that bury the signal\n- Inconsistent category naming across runs (e.g., "wrong_tool" vs "Wrong Tool" vs "incorrect tool selection")\n- Missing evidence citations when the model is uncertain

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.