DEV Community

Cover image for Your Agent Invented an Order ID and Refunded It: Catching Action Hallucinations with Near-Zero-Cost Checks
vivek
vivek

Posted on AI-assisted

Your Agent Invented an Order ID and Refunded It: Catching Action Hallucinations with Near-Zero-Cost Checks

Most hallucination content on the internet is about chatbots saying wrong things: a fake citation, an invented statistic, an API method that doesn't exist.

That's a real problem. But once your model can call tools, it's no longer the worst one.

Consider these two failures:

Agent: "Our refund window is 60 days."          # policy says 30
Enter fullscreen mode Exit fullscreen mode
Agent → refund_order(order_id="ORD-44718", amount=82.00)
# ORD-44718 never appeared anywhere in the conversation.
# It belongs to a different customer.
Enter fullscreen mode Exit fullscreen mode

The first gives a user wrong information. The second moves real money to the wrong place. And the second one is, conveniently, much easier to catch. You don't need a judge model or a research paper. You need the trace and about forty lines of Python.

This is Part 1 of a two-part series:

  • Part 1 (this post): action and outcome hallucinations, and the cheap checks that run on every request
  • Part 2: content hallucinations, judge models, semantic entropy, and a layered production pipeline

Three kinds of agent hallucination

This breakdown of hallucination detection for production agents splits agent hallucinations into three types, and the split is the key to detecting them cheaply:

Type What it looks like Example Damage
Content A claim not supported by sources "Refund window is 60 days" (policy says 30) User gets wrong info
Action An invented tool, argument or value refund_order with an ID that appears nowhere earlier A real action on the wrong thing
Outcome Saying something happened when it didn't "I've cancelled your subscription" with no cancel call User thinks the problem is solved

Content hallucinations need semantic judgment, which is expensive (that's Part 2).

Action and outcome hallucinations are structural. They leave evidence in the trace: an argument with no origin, a claim with no matching tool call. Structural problems get structural checks, and structural checks cost almost nothing.


Check 1: Argument provenance

The idea: every ID, amount or identifier passed into a write tool should have come from somewhere earlier in the trace: the user's message, a tool result, or retrieved context. If it didn't, the model typed it from thin air.

import re
from dataclasses import dataclass

# Things that should never be invented
IDENTIFIER_PATTERNS = {
    "order_id":   re.compile(r"\bORD-\d{5,}\b"),
    "account_id": re.compile(r"\bACC-[A-Z0-9]{6,}\b"),
    "email":      re.compile(r"[\w.+-]+@[\w-]+\.[\w.]+"),
}

@dataclass
class ProvenanceIssue:
    tool: str
    arg: str
    value: str

def seen_values(spans: list[dict]) -> str:
    """Concatenate everything the agent legitimately saw before acting."""
    parts = []
    for s in spans:
        a = s["attributes"]
        for key in ("app.user_message", "app.tool.response", "app.retrieved_context"):
            if key in a:
                parts.append(str(a[key]))
    return "\n".join(parts)

def check_provenance(spans: list[dict], write_tools: set[str]) -> list[ProvenanceIssue]:
    issues = []
    for i, s in enumerate(spans):
        a = s["attributes"]
        tool = a.get("gen_ai.tool.name")
        if tool not in write_tools:
            continue
        history = seen_values(spans[:i])          # only what came BEFORE this call
        for arg, value in a.get("app.tool.args_dict", {}).items():
            value = str(value)
            is_identifier = any(p.fullmatch(value) for p in IDENTIFIER_PATTERNS.values())
            if is_identifier and value not in history:
                issues.append(ProvenanceIssue(tool, arg, value))
    return issues
Enter fullscreen mode Exit fullscreen mode

Running it on the trace from the intro:

>>> check_provenance(spans, write_tools={"refund_order", "cancel_subscription", "send_email"})
[ProvenanceIssue(tool='refund_order', arg='order_id', value='ORD-44718')]
Enter fullscreen mode Exit fullscreen mode

A few details that matter:

  • Only look backwards. spans[:i] means the value must appear before the tool call. An ID that shows up later (say, in the tool's own response) doesn't count.
  • Focus on write tools. Read-only lookups with a bad ID usually just fail. Write tools are where invented arguments cause damage.
  • Amounts need care. 82.00 vs 82 vs $82 is a normalisation problem. For money, compare against parsed numeric values from earlier spans, and flag any amount that doesn't match one.
def amounts_in(text: str) -> set[float]:
    return {float(m.replace(",", "")) for m in re.findall(r"\$?(\d[\d,]*\.?\d*)", text)}

def check_amount(value: float, history: str, tolerance=0.01) -> bool:
    return any(abs(value - seen) <= tolerance for seen in amounts_in(history))
Enter fullscreen mode Exit fullscreen mode

Run it as a guardrail before the tool executes, not just as a post-hoc check. Then a provenance failure blocks the action instead of just logging it.


Check 2: Claim vs. trace

The idea: compare what the agent says it did in its final reply with what the trace shows it actually did.

A regex lookup table works as a first pass, but it misses paraphrases ("all sorted, you won't be charged next month" is a cancellation claim). A sturdier approach: have a small, cheap model extract structured claims, then match them deterministically.

import json

EXTRACT_PROMPT = """List every action the assistant claims to have COMPLETED in
the message below. Return only JSON: a list of objects with keys
"action" (one of: refund, cancel_subscription, send_email, reset_password,
update_address, none) and "target" (the ID or email mentioned, or null).

Message:
{reply}"""

ACTION_TO_TOOL = {
    "refund": "refund_order",
    "cancel_subscription": "cancel_subscription",
    "send_email": "send_email",
    "reset_password": "reset_password",
    "update_address": "update_address",
}

def extract_claims(reply: str, small_model) -> list[dict]:
    raw = small_model.complete(EXTRACT_PROMPT.format(reply=reply))
    try:
        return [c for c in json.loads(raw) if c["action"] != "none"]
    except (json.JSONDecodeError, KeyError, TypeError):
        return [{"action": "unparseable", "target": None}]

def successful_calls(spans: list[dict]) -> list[dict]:
    return [
        {"tool": s["attributes"]["gen_ai.tool.name"],
         "args": s["attributes"].get("app.tool.args_dict", {})}
        for s in spans
        if s["attributes"].get("gen_ai.operation.name") == "execute_tool"
        and s["status"] == "OK"
    ]

def outcome_hallucinations(reply: str, spans: list[dict], small_model) -> list[dict]:
    calls = successful_calls(spans)
    problems = []
    for claim in extract_claims(reply, small_model):
        tool = ACTION_TO_TOOL.get(claim["action"])
        matching = [c for c in calls if c["tool"] == tool]
        if not matching:
            problems.append({**claim, "reason": "no successful tool call"})
        elif claim["target"] and not any(claim["target"] in map(str, c["args"].values())
                                         for c in matching):
            problems.append({**claim, "reason": "tool called on a different target"})
    return problems
Enter fullscreen mode Exit fullscreen mode
reply: "Done! I've cancelled your subscription and emailed you a confirmation."

>>> outcome_hallucinations(reply, spans, small_model)
[{'action': 'send_email', 'target': None, 'reason': 'no successful tool call'}]
Enter fullscreen mode Exit fullscreen mode

The cancellation was real. The confirmation email wasn't. The user will now wait for an email that never comes, then contact support, annoyed.

Notes:

  • Only count successful calls. A tool that was called and errored didn't do anything. Filtering on status == "OK" is what catches "I've refunded you" after the payment API returned a 500.
  • Check the target, not just the tool. "I've refunded order 4471" when the refund went to 4417 is an outcome hallucination too.
  • The extractor is a small model on a narrow task. Cheap, fast, and easy to test. You're not asking it to judge truth, only to list claims.

Check 3: Rule-based output validation

The boring one, and it still catches a lot. Validate formats, schemas and value ranges on every tool argument and every structured output.

from pydantic import BaseModel, Field, field_validator
from typing import Literal

class RefundArgs(BaseModel):
    order_id: str = Field(pattern=r"^ORD-\d{5,}$")
    amount: float = Field(gt=0, le=500)
    reason: Literal["damaged", "not_received", "wrong_item", "other"]

    @field_validator("order_id")
    @classmethod
    def must_exist_and_belong(cls, v, info):
        order = orders.get(v)
        if order is None:
            raise ValueError("order does not exist")
        if order.customer_id != info.context["customer_id"]:
            raise ValueError("order belongs to a different customer")
        return v
Enter fullscreen mode Exit fullscreen mode

Enums are underrated here. If reason can only be one of four values, the model can't invent a fifth.


Prevention beats detection: three design patterns

Detection tells you how often action and outcome hallucinations happen. These patterns make them happen less:

1. Let the agent pick, not type

Don't let the model type IDs from memory. Have it select from tool results.

# Instead of: refund_order(order_id: str)
# Give it:    refund_order(order_ref: int)  -- an index into the last lookup result

def refund_order(order_ref: int, amount: float, ctx):
    order = ctx.last_lookup_results[order_ref]   # the model can only point at real rows
    return payments.refund(order.id, amount)
Enter fullscreen mode Exit fullscreen mode

2. Confirm before acting

For high-impact actions, have the agent restate the target, then check the restatement against the trace before the tool runs.

Agent (internal): CONFIRM refund order=ORD-44171 amount=82.00
Guardrail: ORD-44171 seen in lookup_orders response ✅  amount matches line total ✅
→ execute
Enter fullscreen mode Exit fullscreen mode

3. Build the reply from tool results

The surest way to make claims match actions: generate the final message from tool results, not from the model's plan.

def final_reply(calls: list[dict], llm) -> str:
    facts = [
        f"- {c['tool']} succeeded with {c['args']}" for c in calls
    ] or ["- No actions were completed."]
    return llm.complete(
        "Write a short, friendly reply to the customer. Mention ONLY the actions "
        "listed below as completed. Do not claim anything else was done.\n\n"
        + "\n".join(facts)
    )
Enter fullscreen mode Exit fullscreen mode

It's still worth running claim vs. trace on the output; this just shrinks the gap.


Where these checks sit

All three checks are near-zero cost, so they run on every request:

tool call requested
   ├─ schema / enum validation         ← block on failure
   ├─ argument provenance              ← block on failure (write tools)
   └─ execute tool

final reply drafted
   └─ claim vs. trace                  ← flag, or regenerate reply from tool results
Enter fullscreen mode Exit fullscreen mode

Tie every flag to its trace, so whoever investigates can see which step produced the invented value. For more on structuring those traces, see this guide to AI agent observability.


TL;DR

  • Agents hallucinate content, actions and outcomes. The last two touch real systems.
  • Action and outcome hallucinations are structural, so they're cheap to catch on every run.
  • Argument provenance: every ID and amount in a write tool must appear earlier in the trace.
  • Claim vs. trace: every action the reply claims must match a successful tool call on the right target.
  • Prevent them by design: pick don't type, confirm before acting, build replies from tool results.

In Part 2, we'll tackle the harder kind: content hallucinations. We'll build a groundedness judge, calibrate it against human labels, implement semantic entropy, and wire everything into a cost-layered pipeline, following the layered approach in this guide to detecting hallucinations in AI agents.


Has an agent of yours ever confidently "done" something it never did? How did you find out? 👻

Top comments (1)

Collapse
 
nexusfoundry profile image
Nexus Foundry •

The order-id example is the cleanest demonstration I've seen of why action hallucinations are a different species: the failure isn't linguistic, it's referential. The model generated a plausible identifier that was never grounded in tool output.

The check I'd add to your forty lines: provenance, not just existence. "Does ORD-44718 exist?" is one query. "Did ORD-44718 appear in a tool result earlier in this trace?" is the stronger invariant — an ID the agent invented will usually fail both, but the second check also catches a subtler bug: the agent echoing a real ID from a different customer's context window. We hit that variant in testing — the refund was for a real order, just not this user's.

Second layer worth stating explicitly: checks like yours are post-hoc unless you put them before the tool call executes. A trace audit tells you the refund happened; a pre-execution gate that validates arguments against trace state stops it. Both are cheap, but they answer different questions — "did it happen" vs "can it happen." Most agent frameworks only ship the first.