Inferensys

Prompt

Agent State Reconciliation Prompt After Tool Error

A practical prompt playbook for using Agent State Reconciliation Prompt After Tool Error 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

Recover agent state consistency after a tool error or partial result without restarting the entire task.

This prompt is designed for the moment an agent's internal state becomes unreliable—when a tool call returns an error, a partial payload, or a timeout, and the agent's scratchpad or memory now contains conflicting, incomplete, or stale information. The job-to-be-done is state reconciliation: producing a single, coherent summary of what is true, what is complete, and what must happen next. The ideal user is an AI reliability engineer or agent-framework builder who needs the agent to resume execution safely without discarding all prior progress. Required context includes the original goal, the last stable state snapshot, the failed tool call and its error, and any partial results that were returned.

Do not use this prompt when the failure is catastrophic and the entire trajectory is suspect—for example, when the agent's core reasoning loop itself produced the error or when the environment has changed so much that prior state is no longer valid. In those cases, a full re-plan or human escalation is more appropriate. This prompt is also not a substitute for proper error handling in the tool layer; if the tool error is transient and the agent can retry with corrected arguments, use a narrower tool-call retry prompt instead. Reserve state reconciliation for moments when the agent's understanding of what happened is the primary thing that broke.

Before wiring this prompt into your harness, ensure you have a reliable mechanism for capturing the agent's state before the failed tool call. The prompt's effectiveness depends on the quality of the pre-failure snapshot. If your harness cannot distinguish between completed steps, in-progress steps, and steps that never started, the reconciliation output will be unreliable. Implement a state-diff check after the model responds: compare the reconciled state to the pre-failure snapshot and flag any contradictions—such as a completed step being re-marked as pending or a constraint being dropped. For high-stakes agent workflows, route contradictions to a human reviewer before the agent resumes execution.

PRACTICAL GUARDRAILS

Use Case Fit

Where the Agent State Reconciliation Prompt delivers value and where it introduces risk. Use these cards to decide if this prompt fits your agent architecture before wiring it into a production harness.

01

Good Fit: Multi-Step Agent Workflows

Use when: your agent executes 3+ sequential tool calls and a mid-sequence error corrupts the accumulated state. Guardrail: the prompt requires a structured state snapshot as input—never rely on the model's memory of prior turns alone.

02

Bad Fit: Stateless Single-Tool Calls

Avoid when: the agent makes one tool call per user request with no state carried forward. Risk: reconciliation overhead adds latency and token cost without benefit. Guardrail: route single-turn tool errors to a lightweight argument-correction retry prompt instead.

03

Required Input: Structured State Snapshot

What to watch: the prompt cannot reconcile state it cannot see. Guardrail: always pass a machine-readable state object (completed steps, pending actions, tool outputs, error payloads) as [PRE_ERROR_STATE]. Never pass only a natural-language summary.

04

Operational Risk: State Contradiction Drift

What to watch: the model may silently drop a completed step or invent a field to resolve ambiguity. Guardrail: run a post-reconciliation eval that diffs the input state against the reconciled state and flags any dropped, altered, or hallucinated fields before the agent resumes.

05

Operational Risk: Infinite Reconciliation Loops

What to watch: a malformed error payload can cause the prompt to produce an invalid continuation plan, triggering the same error again. Guardrail: enforce a reconciliation retry budget (max 2 attempts) and escalate to a human operator with the full state trace if the budget is exhausted.

06

Good Fit: Partial Tool Output Recovery

Use when: a tool returns a partial result (e.g., 200 of 500 records) before failing. Guardrail: the prompt must distinguish completed work from unprocessed work in the reconciled state to prevent duplicate processing or data loss on retry.

PROMPT PLAYBOOK

Copy-Ready Prompt Template

A copy-ready prompt that reconciles agent state after a tool error, producing a corrected state summary and a continuation plan.

This prompt is designed to be injected into an agent harness immediately after a tool call returns an error or a partial result that may have corrupted the agent's internal state. Its job is to force the model to explicitly list what it believes is still true, what is now uncertain, and what the next safe action should be. Do not use this prompt for simple retries where the state is clearly unchanged; it is intended for cases where the agent's understanding of the world may have diverged from reality.

text
SYSTEM: You are an agent state reconciliation module. Your task is to repair the agent's internal state after a tool error.

CONTEXT:
- Original Goal: [ORIGINAL_GOAL]
- Plan Before Error: [PLAN_BEFORE_ERROR]
- Last Action Attempted: [LAST_ACTION]
- Tool Called: [TOOL_NAME]
- Error Received: [ERROR_MESSAGE]
- Partial Output (if any): [PARTIAL_OUTPUT]
- State Before Action: [STATE_BEFORE_ACTION]

INSTRUCTIONS:
1.  **State Audit:** List every fact the agent believed to be true before the error. For each fact, classify it as:
    - CONFIRMED: Still valid.
    - UNCERTAIN: May have been invalidated by the error.
    - INVALIDATED: Proven false by the error or partial output.
2.  **Gap Analysis:** Identify any critical information that is now missing and was required for the next step in the plan.
3.  **Reconciliation:** Produce a new, concise state object in valid JSON format that represents the best-known state of the world. Use `null` for any field whose value is now unknown.
4.  **Continuation Plan:** Propose the single next action to take. This can be:
    - A retry of the failed action with corrected arguments.
    - A new action to gather the missing critical information.
    - A request for human intervention if the path forward is blocked.

OUTPUT SCHEMA:
{
  "state_audit": [
    {
      "fact": "string",
      "status": "CONFIRMED | UNCERTAIN | INVALIDATED",
      "rationale": "string"
    }
  ],
  "missing_critical_info": ["string"],
  "reconciled_state": {},
  "continuation_plan": {
    "action_type": "RETRY | NEW_ACTION | ESCALATE",
    "action_description": "string",
    "tool_name": "string | null",
    "tool_args": {} | null,
    "escalation_reason": "string | null"
  }
}

CONSTRAINTS:
- Do not invent facts to fill gaps; use null for unknowns.
- The continuation plan must be a single, atomic action.
- If the error indicates a fundamental plan flaw, action_type must be ESCALATE.

To adapt this template, replace the square-bracket placeholders with runtime values from your agent's execution context. The STATE_BEFORE_ACTION should be a snapshot of the agent's working memory or a structured representation of known facts. The OUTPUT_SCHEMA is a contract for your harness; parse the reconciled_state JSON and use it to overwrite the agent's current state before executing the continuation_plan. If the action_type is ESCALATE, your harness must route the escalation_reason to a human operator or a dead-letter queue and halt the agent loop. For high-risk domains, always log the full audit trail and require human approval before executing any RETRY or NEW_ACTION that modifies external systems.

IMPLEMENTATION TABLE

Prompt Variables

Inputs the Agent State Reconciliation Prompt needs to produce a reliable reconciled state summary and continuation plan after a tool error.

PlaceholderPurposeExampleValidation Notes

[ORIGINAL_GOAL]

The agent's top-level objective before the tool error occurred

Complete the quarterly financial close for Q3 2025

Must be a non-empty string. Validate that the goal has not been mutated or lost from the initial plan context.

[PLAN_STEPS_COMPLETED]

Ordered list of plan steps successfully executed before the error

["Pull general ledger", "Reconcile AR subledger"]

Must be a valid JSON array. Each step must include a step ID and a completion status. Null allowed if no steps completed.

[CURRENT_STEP]

The specific plan step that was in progress when the tool error occurred

{"step_id": "step-3", "description": "Reconcile AP subledger"}

Must be a valid JSON object with step_id and description fields. Validate that step_id exists in the original plan.

[TOOL_ERROR_PAYLOAD]

The raw error object returned by the tool, including error code, message, and partial output if any

{"error_code": "TIMEOUT", "message": "AP subledger query timed out after 30s", "partial_output": null}

Must be a valid JSON object. Validate that error_code is present and message is non-empty. Partial output can be null.

[AGENT_STATE_SNAPSHOT]

The full agent state dictionary immediately before the tool call that failed

{"variables": {"fiscal_period": "Q3-2025"}, "artifacts": ["gl_report.csv"]}

Must be a valid JSON object. Validate that all required state keys are present. Used to detect state corruption or drift.

[RETRY_BUDGET_REMAINING]

Number of retries remaining for this step before escalation is required

2

Must be a non-negative integer. If 0, the prompt must produce an escalation summary instead of a retry plan. Validate against the harness retry policy.

[OUTPUT_SCHEMA]

The expected JSON schema for the reconciled state and continuation plan

{"reconciled_state": {}, "continuation_plan": [], "escalation_required": false}

Must be a valid JSON Schema object. Validate that the prompt output conforms to this schema before passing to the next agent step.

PROMPT PLAYBOOK

Implementation Harness Notes

How to wire the state reconciliation prompt into an agent harness with validation, retry logic, and safe state mutation.

This prompt is designed to be called by an agent harness immediately after a tool returns an error or a partial result that leaves the agent's internal state inconsistent. The harness should not proceed to the next planning step until it receives a validated reconciled state from this prompt. The prompt expects three inputs: the agent's pre-error state snapshot, the tool call that failed, and the raw error or partial result payload. The harness must capture these inputs atomically before invoking the reconciliation prompt to avoid state drift during the recovery window.

Wire the prompt into a dedicated recovery step within your agent loop. When a tool call returns a non-2xx status, a timeout, or a malformed payload that fails schema validation, the harness should: (1) freeze the current agent state and log the pre-error snapshot to an append-only state journal, (2) call this reconciliation prompt with the frozen state, the failed tool invocation, and the error payload, (3) validate the output against a strict reconciliation schema that requires reconciled_state, continuation_plan, and missing_fields arrays, and (4) diff the reconciled state against the pre-error snapshot to detect contradictions or silent field loss. If the diff reveals a contradiction—such as a field value changing without an explicit correction note—reject the reconciliation and escalate to a human operator or a higher-cost model for review. Log every reconciliation attempt with the pre-error state hash, the error type, the reconciled state hash, and the diff result for observability.

Retry logic must be bounded. If the reconciliation prompt itself fails—returns malformed JSON, exceeds token limits, or produces a state that fails the contradiction diff—retry once with the same inputs and a stronger constraint instruction appended to the prompt. If the second attempt also fails, stop retrying and escalate. Do not loop reconciliation attempts; the cost of a corrupted agent state is higher than the cost of human intervention. For high-risk domains such as healthcare or finance, require human approval on any reconciliation that modifies more than three state fields or alters a field tagged as critical in the agent's state schema. Model choice matters: use a model with strong instruction-following and structured output capabilities (e.g., GPT-4o, Claude 3.5 Sonnet) for reconciliation tasks. Avoid smaller or older models that are more likely to hallucinate state changes or miss contradictions.

IMPLEMENTATION TABLE

Expected Output Contract

Fields, types, and validation rules for the reconciled state summary and continuation plan produced by the agent state reconciliation prompt after a tool error. Use this contract to parse, validate, and route the model response in your agent harness.

Field or ElementType or FormatRequiredValidation Rule

reconciliation_summary

string

Must be 1-3 sentences. Must reference the failed tool name and error type. Must not contain unresolved placeholders.

pre_failure_state

object

Must include all state fields present before the tool call. Schema must match the agent's canonical state schema. Missing required fields is a failure.

tool_error_analysis

object

Must contain 'error_type' (string, from allowed enum), 'root_cause' (string), and 'is_transient' (boolean). 'error_type' must match one of [TIMEOUT, SCHEMA_ERROR, AUTH_ERROR, RATE_LIMIT, PARTIAL_RESULT, UNKNOWN].

partial_results_salvaged

array or null

If the tool returned partial data, this must be an array of successfully completed items. If no partial results exist, must be null. Each item must include an 'id' field.

state_contradictions

array

List of detected contradictions between pre-failure state and tool error context. Each entry must have 'field', 'expected_value', 'observed_value', and 'resolution' fields. Empty array if no contradictions found.

reconciled_state

object

The corrected state after incorporating salvaged results and resolving contradictions. Must be a complete, valid instance of the agent state schema. No partial objects allowed.

continuation_plan

object

Must contain 'next_action' (string), 'action_args' (object), and 'rationale' (string). 'next_action' must be a valid action name from the agent's action registry. 'action_args' must pass the tool's input schema validation.

escalation_required

boolean

Set to true if the error is non-transient, retry budget is exhausted, or state contradictions cannot be resolved automatically. False otherwise. Must be consistent with 'continuation_plan' (escalation actions only when true).

PRACTICAL GUARDRAILS

Common Failure Modes

Agent state reconciliation after a tool error is brittle. These are the most common production failure modes and how to guard against them before they corrupt downstream agent actions.

01

Phantom State Contradiction

What to watch: The reconciliation prompt produces a state summary that contradicts the actual tool error payload (e.g., claiming success when the tool returned a timeout). This happens when the model over-trusts its prior plan and ignores the error signal. Guardrail: Include the raw error payload verbatim in the prompt and instruct the model to cite specific error fields when summarizing state. Add an eval that diffs the reconciled state against the error payload for contradiction.

02

Missing Field Silent Drop

What to watch: The reconciled state omits fields that were present before the error but not explicitly mentioned in the error message. The model assumes they are unchanged, but the tool failure may have left them in an unknown state. Guardrail: Require the prompt to enumerate all state fields explicitly and mark each as confirmed, unknown, or stale. Add a harness check that flags any pre-error field absent from the reconciled output.

03

Continuation Plan Hallucination

What to watch: The model generates a continuation plan that references tool capabilities or parameters that do not exist, fabricating recovery steps that look plausible but are unexecutable. Guardrail: Constrain the continuation plan to only reference tools present in the provided tool manifest. Validate the plan against the tool schema before execution. Reject any step that calls an undefined tool or passes invalid arguments.

04

Error Cause Misattribution

What to watch: The model misdiagnoses the root cause of the tool error (e.g., blaming an auth failure on a malformed argument) and produces a recovery action that repeats the same failure. Guardrail: Include the tool's error code and message in a structured block. Instruct the model to classify the error category before proposing recovery. Add an eval that checks whether the proposed fix addresses the actual error class.

05

Premature Goal Abandonment

What to watch: After a single tool error, the model rewrites the original goal to something easier rather than attempting recovery. This is especially common when the error message is verbose and distracts from the objective. Guardrail: Anchor the prompt with the original goal and constraints as immutable context. Add a goal-preservation eval that measures semantic similarity between the original goal and the reconciled plan's objective. Escalate if drift exceeds threshold.

06

Retry Loop Without State Change

What to watch: The reconciliation prompt produces a continuation plan that retries the same tool call with identical arguments, creating an infinite loop. The model fails to recognize that the error requires an argument change or fallback. Guardrail: Include a retry budget counter in the prompt context. Instruct the model to vary at least one argument or select a fallback tool on any retry. Add a harness check that compares the proposed action to the failed action and blocks identical retries.

IMPLEMENTATION TABLE

Evaluation Rubric

Use this rubric to test the quality of the reconciled state summary and continuation plan before shipping the prompt into an agent harness. Each criterion targets a specific failure mode common in state reconciliation after tool errors.

CriterionPass StandardFailure SignalTest Method

State Contradiction Detection

Output explicitly flags any contradiction between the pre-error state and the tool error message, with a null field if none exist.

Output silently merges contradictory states or ignores the error message content.

Provide a pre-error state and a tool error that directly contradicts a field value. Assert the contradiction is listed in the output.

Missing Field Recovery

All required fields from [STATE_SCHEMA] are present in the reconciled state, populated with either recovered values, error notes, or explicit nulls.

Required fields are absent from the output or silently dropped without explanation.

Run against 5 tool error scenarios each removing a different required field. Assert 100% field presence in the reconciled state.

Error Source Attribution

The output correctly identifies which tool call failed and maps the error to the specific state field(s) affected.

The error is attributed to the wrong tool or the affected fields are misidentified.

Provide a multi-tool state where tool 'B' failed. Assert the output names tool 'B' and only marks fields modified by tool 'B' as affected.

Continuation Plan Actionability

The continuation plan contains at least one concrete next action with a tool name, arguments, and a clear dependency on the reconciled state.

The continuation plan is vague, empty, or suggests restarting the entire workflow without justification.

Parse the continuation plan. Assert it contains a valid tool name from [TOOL_LIST] and arguments that reference fields from the reconciled state.

No Fabricated Recovery Data

All recovered values are derived from the pre-error state, the error message, or marked as unknown. No invented data fills gaps.

The output contains a plausible but unsupported value not present in any input source.

Provide a tool error that destroys a field with no backup. Assert the reconciled state marks that field as 'unknown' or 'lost' rather than inventing a value.

Idempotency Marker Presence

The output includes a reconciliation ID or hash that changes only when the reconciled state changes, enabling downstream deduplication.

No stable identifier is present, or the identifier changes on every run with identical inputs.

Run the prompt twice with identical inputs. Assert the reconciliation ID is identical across both runs.

Escalation Trigger Correctness

When the error is classified as unrecoverable per [ESCALATION_RULES], the output sets an escalation flag to true and includes a human-readable summary.

An unrecoverable error is treated as recoverable, or the escalation flag is set but no summary is provided.

Provide a tool error matching an unrecoverable pattern from [ESCALATION_RULES]. Assert escalation_flag is true and escalation_summary is non-empty.

Pre-Error Progress Preservation

Completed actions from the pre-error state are preserved in the reconciled state and not re-planned unless invalidated by the error.

The continuation plan re-executes actions already marked complete in the pre-error state without justification.

Provide a pre-error state with 3 completed actions. Assert all 3 appear in the reconciled state as complete and none appear in the continuation plan.

ADAPTATION OPTIONS

Adapt This Prompt

How to adapt

Wrap the prompt in a harness that enforces a strict [OUTPUT_SCHEMA] with fields: reconciled_state, contradictions_found, missing_fields, continuation_plan, and requires_escalation. Add a pre-prompt instruction: Compare [PRE_ERROR_STATE] with [POST_ERROR_STATE] field by field. Flag any field that changed without a successful tool confirmation. Include a retry budget counter in the harness context.

Watch for

  • Silent state corruption when the model assumes success on partial writes
  • The continuation plan re-executing already-completed side effects
  • Schema drift when the harness evolves but the prompt still references old field names
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.