Inferensys

Prompt

Tool Output Confidence Scoring Prompt After Error

A practical prompt playbook for agent developers who need to decide whether to trust partial or recovered tool output. Scores output confidence based on error context, recovery method, and data completeness, with a threshold for safe downstream use.
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 production context for scoring tool output confidence after an error, including the ideal user, required inputs, and strict boundaries for when this prompt should not be used.

This prompt is designed for agent developers and reliability engineers who are building production tool-calling loops where failures are a routine operational reality. The core job-to-be-done is making a safe, structured decision about whether to trust recovered or partial tool output before it contaminates downstream systems. After a tool call fails and you have recovered data through retries, fallback mechanisms, or partial result extraction, you cannot simply pass that data forward blindly. This prompt evaluates the error context, the recovery method used, and the completeness of the data to produce a structured confidence score and a binary safe_for_downstream decision. The ideal user is an AI platform engineer who understands that the cost of acting on bad data—such as corrupting a database, sending a faulty command, or presenting false information to a user—far exceeds the cost of discarding potentially recoverable data.

To use this prompt effectively, you must provide it with specific, structured inputs. These include the raw error output, the recovery method employed (e.g., retry_with_modified_args, fallback_to_cached_result, partial_parse), the recovered data payload, and the expected output schema. The prompt is designed to be wired into an automated harness where it acts as a gating function. For example, in an agent loop, the output of a tool call is caught by an error handler, which then attempts a recovery strategy. Before the recovered data is passed to the next tool or used to formulate a user response, this prompt is called. Its safe_for_downstream boolean output directly controls a conditional gate in the application code, preventing unsafe data from proceeding. This is not a prompt for real-time, safety-critical systems where any uncertainty requires immediate human review; in those contexts, a safe_for_downstream value of false should trigger an immediate escalation to a human operator, not another automated fallback.

You should not use this prompt when the failure mode is unknown or the error context is empty. The prompt's evaluation logic depends on understanding how the data was recovered to assess its reliability; a partial_parse of a malformed JSON response carries a different risk profile than a successful retry with modified arguments. Avoid using this prompt as a substitute for proper output validation. Schema validation should always occur before this confidence scoring step. The prompt's job is to assess the semantic trustworthiness of already-validated data, not to check for structural correctness. Finally, do not use this prompt for non-deterministic or creative generation tasks where there is no ground truth for 'correct' output. Its value is in high-stakes, structured data pipelines where a single bad record can have cascading effects. The next step after implementing this prompt is to pair it with an evaluation harness that specifically tests for overconfidence after recovery and unnecessary rejection of good data.

PRACTICAL GUARDRAILS

Use Case Fit

Where the Tool Output Confidence Scoring Prompt adds value and where it introduces risk.

01

Good Fit: Post-Recovery Validation

Use when: a tool call has failed, a retry or fallback has produced partial or recovered output, and you need a structured confidence score before passing data downstream. Guardrail: Always run this prompt after a recovery step, never on raw initial failures.

02

Bad Fit: Real-Time Hard SLAs

Avoid when: the system has a strict latency budget under 200ms and the confidence scoring call would add unacceptable overhead. Guardrail: Pre-compute confidence thresholds offline or use a lightweight heuristic for time-critical paths.

03

Required Input: Structured Error Context

Risk: Scoring without the original error type, recovery method, and partial output produces meaningless confidence values. Guardrail: Enforce a strict input schema that includes error_type, recovery_method, partial_output, and expected_schema before invoking the prompt.

04

Operational Risk: Overconfidence After Recovery

Risk: The model assigns high confidence to recovered data that is subtly corrupted or incomplete, leading to silent downstream failures. Guardrail: Pair confidence scores with a mandatory completeness check against the expected schema and flag any missing required fields regardless of score.

05

Operational Risk: Unnecessary Rejection

Risk: The model assigns low confidence to valid recovered data due to conservative bias, causing the agent to discard usable results and escalate unnecessarily. Guardrail: Calibrate the confidence threshold using a golden dataset of known-good and known-bad recoveries, and log all rejections for review.

06

Integration Pattern: Threshold Gating

Use when: you need a binary pass/fail decision for downstream consumers. Guardrail: Define an explicit CONFIDENCE_THRESHOLD in your application config. Scores above the threshold proceed; scores below trigger fallback, human review, or abort. Never hardcode the threshold in the prompt itself.

PROMPT PLAYBOOK

Copy-Ready Prompt Template

A copy-ready prompt template for scoring confidence in tool output after an error, with placeholders for runtime values.

This prompt template is designed to be pasted directly into your agent's evaluation step immediately after a tool call has failed and been recovered, or has returned partial data. Its job is to produce a structured confidence score that your application can use to decide whether the output is safe for downstream consumption. The prompt forces the model to reason about the error context, the recovery method, and the completeness of the data before assigning a score, preventing the common failure mode of blindly trusting a successful retry.

text
You are an output integrity evaluator for an AI agent. Your task is to assess the confidence we should have in a tool's output after an error occurred.

**Tool Name:** [TOOL_NAME]
**Tool Description:** [TOOL_DESCRIPTION]
**Intended Use of Output:** [DOWNSTREAM_USE]

**Error Context:**
- Error Type: [ERROR_TYPE]
- Error Message: [ERROR_MESSAGE]
- Recovery Method: [RECOVERY_METHOD]
- Retry Count: [RETRY_COUNT]

**Output to Evaluate:**
```json
[TOOL_OUTPUT]

Expected Output Schema:

json
[OUTPUT_SCHEMA]

Evaluation Criteria:

  1. Schema Compliance: Does the output match the expected schema? Are all required fields present and of the correct type?
  2. Data Completeness: Are there any null, empty, or truncated fields that should contain data? Is the volume of data consistent with a successful call?
  3. Error Residue: Does the output contain any error messages, stack traces, or partial failure indicators?
  4. Semantic Coherence: Does the data make logical sense given the tool's purpose? Are there any impossible values or contradictions?
  5. Recovery Risk: Given the recovery method used, what is the risk that the data is stale, corrupted, or duplicated?

Instructions:

  1. Analyze the output against each criterion.
  2. Assign a confidence score between 0.0 and 1.0, where 1.0 is perfect confidence.
  3. Provide a concise reason for the score, citing specific evidence from the output.
  4. Flag any specific fields that are untrustworthy.

Output Format: Respond ONLY with a valid JSON object matching this schema: { "confidence_score": <float 0.0-1.0>, "score_reason": "<string>", "untrustworthy_fields": ["<field_path>", ...], "recommendation": "<ACCEPT | REJECT | HUMAN_REVIEW>" }

To adapt this template, replace the square-bracket placeholders at runtime. [TOOL_OUTPUT] should be the raw, serialized output from the tool after recovery. [OUTPUT_SCHEMA] should be the expected JSON Schema or a plain-text description of required fields. [RECOVERY_METHOD] is critical context—be specific (e.g., "retry with exponential backoff after 429," "used cached result from T-5min," "parsed partial JSON from truncated stream"). The [DOWNSTREAM_USE] field helps the model calibrate risk; a score of 0.8 might be acceptable for generating a draft summary but unacceptable for a financial transaction. For high-risk domains, always set a HUMAN_REVIEW threshold in your application logic that overrides the model's recommendation if the confidence score falls below it.

After pasting this prompt, you must validate the model's output against the declared JSON schema before allowing any downstream action. A common failure mode is the model returning a confidence score above your threshold but with an empty score_reason or an untrustworthy_fields list that contradicts the score. Implement a post-processing check: if the recommendation is ACCEPT but untrustworthy_fields is not empty, force a HUMAN_REVIEW outcome. Wire this prompt into a dedicated evaluation step that runs after every tool error recovery, and log the full evaluation payload for auditability.

IMPLEMENTATION TABLE

Prompt Variables

Inputs the prompt needs to work reliably. Provide these at runtime from your agent's tool execution context.

PlaceholderPurposeExampleValidation Notes

[TOOL_NAME]

Identifies the tool that produced the output being scored

billing_api_lookup

Must match a registered tool ID in the agent's tool registry; reject if tool is not in the approved tool list

[TOOL_OUTPUT]

The partial, recovered, or complete output payload from the tool execution

{"customer_id": "C123", "balance": null, "error": "timeout on invoice fetch"}

Must be valid JSON or structured text; null allowed only if tool returned no output; validate parseability before scoring

[ERROR_CONTEXT]

Structured error information from the tool execution including error type, status code, and message

{"error_type": "TIMEOUT", "status_code": 504, "message": "upstream billing service did not respond within 30s"}

Must include error_type field from the standard agent error taxonomy; reject if error_type is missing or unrecognized

[RECOVERY_METHOD]

Description of how the output was obtained after the error occurred

retry_with_backoff_succeeded_on_attempt_3

Must be one of the registered recovery methods in the agent's recovery catalog; reject unknown recovery methods

[REQUIRED_FIELDS]

List of fields that must be present and non-null for the output to be considered complete

["customer_id", "balance", "last_payment_date"]

Must be a JSON array of field name strings; validate that each field exists in the tool's output schema definition

[CONFIDENCE_THRESHOLD]

Minimum confidence score required to use the output downstream without human review

0.85

Must be a float between 0.0 and 1.0; reject values outside range; default to 0.80 if not explicitly provided

[DOWNSTREAM_ACTION]

What the agent intends to do with this output if accepted

update_customer_balance_in_crm

Must be a registered action in the agent's action catalog; reject if action requires higher confidence than threshold allows

PROMPT PLAYBOOK

Implementation Harness Notes

How to wire the Tool Output Confidence Scoring Prompt into an agent's tool execution loop with validation, thresholds, and safe defaults.

This prompt is designed to sit directly after a tool error recovery attempt, receiving the raw or partial output alongside structured error context. It is not a standalone prompt but a decision node in a larger agent orchestration loop. The primary integration point is inside a tool execution wrapper that catches exceptions, applies a recovery strategy (retry, fallback, partial result extraction), and then calls this prompt to score the resulting output before passing it downstream. The agent should treat the confidence score as a gate: outputs scoring below a configurable threshold (e.g., 0.7) are blocked from automatic consumption and must follow an escalation path.

To wire this into an application, build a ToolOutputEvaluator class or function that accepts the raw tool output, the error context object (including exception type, recovery method, and retry count), and the expected output schema. The function constructs the prompt by injecting these values into the [OUTPUT_PAYLOAD], [ERROR_CONTEXT], and [EXPECTED_SCHEMA] placeholders. After receiving the model's structured response—which must include confidence_score, completeness_flags, and rationale—validate the JSON strictly. If the score is below your threshold, route the output to a human review queue or a secondary fallback tool. If the score is above the threshold but completeness_flags indicate missing required fields, treat it as a degraded result and attach a warning to the downstream context. Log every evaluation, including the score, rationale, and final routing decision, to create an audit trail for debugging confidence drift over time.

Model choice matters here. Use a model with strong instruction-following and structured output capabilities (e.g., GPT-4o, Claude 3.5 Sonnet) because the prompt requires nuanced reasoning about data integrity and error impact. Avoid smaller or older models that may default to overconfidence after a successful retry or underconfidence after a fallback. Implement a retry budget for the scoring prompt itself: if the model fails to return valid JSON after two attempts, default to a conservative score of 0.0 and escalate. For high-risk domains like finance or healthcare, never allow an automatic pass based solely on the model's confidence score; always require a secondary validation step, such as schema completeness checks and, where feasible, human sampling of scored outputs. The most common production failure mode is the model assigning high confidence to a well-formed but semantically wrong output after a fallback tool substituted different data—test for this explicitly in your evals.

IMPLEMENTATION TABLE

Expected Output Contract

Defines the structured JSON output for the Tool Output Confidence Scoring Prompt. Use this contract to validate model responses before allowing downstream consumption of partial or recovered tool results.

Field or ElementType or FormatRequiredValidation Rule

confidence_score

number (0.0 to 1.0)

Must be a float between 0.0 and 1.0 inclusive. Reject if out of range or non-numeric.

score_rationale

string

Must be non-empty. Must reference specific evidence from [ERROR_CONTEXT] or [RECOVERY_METHOD].

data_completeness

object

Must contain 'total_expected_fields' (integer) and 'fields_present' (integer). Reject if fields_present > total_expected_fields.

recovery_method_assessment

string (enum)

Must be one of: 'full_recovery', 'partial_recovery', 'fallback_substitution', 'no_recovery'. Reject if value is not in the allowed set.

error_impact_remaining

string (enum)

Must be one of: 'none', 'minor_data_loss', 'major_data_loss', 'integrity_compromised'. Reject if value is not in the allowed set.

safe_for_downstream_use

boolean

Must be true only if confidence_score >= [CONFIDENCE_THRESHOLD] and error_impact_remaining is 'none' or 'minor_data_loss'. Reject if boolean logic is inconsistent with score and impact.

contamination_risk

string (enum)

Must be one of: 'none', 'low', 'medium', 'high'. Reject if 'high' and safe_for_downstream_use is true.

human_review_recommended

boolean

Must be true if contamination_risk is 'medium' or 'high', or if safe_for_downstream_use is false. Reject if recommendation is missing when risk conditions are met.

PRACTICAL GUARDRAILS

Common Failure Modes

Confidence scoring after tool errors is inherently tricky. The model must weigh error context, recovery method, and data completeness without becoming overconfident in a partial fix or rejecting usable data. These are the most common failure patterns and how to guard against them.

01

Overconfidence After Successful Retry

What to watch: The model assigns a high confidence score simply because a retry returned a 200 OK, ignoring that the recovered payload is incomplete, stale, or semantically different from the original request. Guardrail: Require the prompt to compare the retry output against the original expected schema and flag missing or substituted fields before scoring confidence.

02

Penalizing Valid Degraded Results

What to watch: The model assigns a low confidence score to a perfectly usable fallback result because it carries a warning flag or came from a secondary source. This causes unnecessary escalation or workflow abandonment. Guardrail: Include explicit instructions that a fallback source is not inherently low-confidence; score based on field completeness and semantic relevance, not provenance alone.

03

Ignoring Error Context in Scoring

What to watch: The model scores output confidence without considering the error type. A timeout-recovered partial result is very different from an auth-failure fallback, but the prompt treats all errors as equivalent. Guardrail: Require the error classification as a required input to the confidence prompt and include per-error-type scoring heuristics in the instructions.

04

Confidence Score Drift Across Retries

What to watch: After multiple retries with modified arguments, the model gradually accepts a degraded result that has drifted far from the original intent, but the incremental changes mask the cumulative degradation. Guardrail: Always include the original query and arguments in the confidence-scoring context, and instruct the model to measure drift from the original intent, not just from the previous attempt.

05

Threshold Gaming for Downstream Safety

What to watch: The model learns to score just above the configured acceptance threshold to avoid triggering human review, even when the output has known gaps. This is especially common when the threshold is exposed in the prompt. Guardrail: Do not expose the numeric threshold in the prompt. Ask for a structured rationale first, then derive the score. Use a separate evaluator to spot-check rationales against scores.

06

Silent Null Handling in Partial Recovery

What to watch: The model treats null fields in a recovered payload as acceptable omissions rather than missing required data, inflating the confidence score for incomplete results. Guardrail: Provide a required-field list in the prompt schema and instruct the model to treat any null in a required field as a confidence penalty, regardless of recovery method.

IMPLEMENTATION TABLE

Evaluation Rubric

Run these test cases against your Tool Output Confidence Scoring Prompt to validate output quality before shipping. Each criterion targets a specific failure mode common in post-error confidence assessment.

CriterionPass StandardFailure SignalTest Method

Overconfidence After Partial Recovery

Confidence score is ≤ 0.6 when >20% of required fields are missing or reconstructed

Confidence ≥ 0.8 despite missing critical fields like [REQUIRED_FIELD_LIST]

Feed partial JSON with 3 of 10 required fields present; assert confidence ≤ threshold

Underconfidence on Clean Retry

Confidence score is ≥ 0.85 when a retry returns complete, schema-valid output with no errors

Confidence ≤ 0.5 on a successful retry with full data integrity

Simulate a transient timeout then successful retry; assert confidence meets minimum

Error Context Sensitivity

Confidence drops proportionally to error severity: auth failures reduce score more than timeouts

Same confidence score for 401 Unauthorized and 504 Gateway Timeout

Run prompt with different [ERROR_TYPE] values; verify score ordering matches severity ranking

Recovery Method Weighting

Fallback tool output scores lower than retry-with-modified-args output when data completeness is equal

Fallback and retry outputs receive identical confidence scores

Pair test: same partial data, different [RECOVERY_METHOD]; assert fallback score < retry score

Null Field Penalty

Each null required field reduces confidence by at least 0.1 from baseline

Confidence remains at 0.9 with 4 null required fields

Feed output with incrementally more null fields; verify monotonic confidence decrease

Threshold Decision Accuracy

Binary safe/unsafe decision matches threshold rule: safe when score ≥ [CONFIDENCE_THRESHOLD]

Safe flag is true when confidence is below configured threshold

Boundary test at threshold ± 0.01; assert decision flips correctly

Rationale Grounding

Confidence rationale cites specific error context, recovery method, and data completeness evidence

Rationale contains generic statements like 'output looks reasonable' without evidence

Parse rationale field; assert presence of [ERROR_TYPE], [RECOVERY_METHOD], and field completeness count

Schema Drift Detection

Confidence ≤ 0.4 when retry output passes validation but field semantics differ from expected schema

High confidence on output where 'temperature' field contains currency values

Feed schema-mismatched output that passes type checks; assert low confidence and schema drift flag

ADAPTATION OPTIONS

Adapt This Prompt

How to adapt

Use the base prompt with a single confidence score field and lighter validation. Accept the model's raw 0-100 score without enforcing strict threshold gating. Focus on getting the scoring logic directionally correct before adding production constraints.

Simplify the output schema to:

json
{
  "confidence_score": [0-100],
  "rationale": "string"
}

Watch for

  • Overconfidence after successful retries when the recovery method silently dropped fields
  • Scores that don't correlate with actual output completeness
  • Missing rationale that makes scores unactionable for debugging
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.