Skip to content
Tech Atlas, home
Search
Esc
  • All roadmapsBrowse every learning path
  • ExploreFind a technology area
  • ProjectsGuided projects and builds
  • My AtlasYour learning dashboard
Lesson 4 of 6 · Worked example · 20 min · revision 3

Validating Arguments and Returning Useful Errors

Build a refund tool that checks argument shape, then ownership, state and limits, refunds at most once per request, and answers every failure with an error the model can act on, sent in the Claude and OpenAI formats. Negative tests included.

Contentsand lesson path

What you will learn

  • Validate tool arguments before execution and return actionable error messages the model can recover from.

Prerequisites: LLM API Integration

01. The problem

The order tools from lesson 2 include request_refund, the one tool that moves money. Here are calls a model really makes to a tool like this, each for a different reason:

  • {"order_id": "1044", "amount": 50}: the customer typed digits, and the amount came as a number.
  • {"order_id": "ORD-1044", "amount": "500.00", ...}: the customer asked for more than the order cost.
  • {"order_id": "ORD-2001", ...}: a real order, but it belongs to another customer, perhaps because a web page the agent read contained an instruction.
  • The same refund twice: the first request timed out on the model's side, so it tried again.

A handler that only parses the arguments and runs the refund gets every one of these wrong, and two of them cost money. A handler that raises an exception gets them wrong in a different way: the loop crashes, or the model sees a stack trace and repeats the same call. This worked example builds the handler step by step and proves each safeguard with a negative test. It uses only the Python standard library (Python 3.12 or later).

02. Step 1: Two tiers of validation

Split validation into two tiers, because they catch different problems:

  1. Shape: are the arguments what the schema says? Known fields only, required fields present, the order ID matches its pattern, the reason is one of the listed values. Strict mode constrains this at generation time, but keep the check: strict mode may be off for one provider, some schema features are not supported in strict mode, and Claude's documentation notes that enum values can come back with different capitals. The check is cheap and its message helps the model fix the call.
  2. State: do the arguments make sense right now, for this caller? The order exists, it belongs to the signed-in customer, it was delivered, and the amount is no more than what is still refundable. No schema can know any of this. It needs your data, so it lives in the handler, before the side effect.

Two inputs never come from the model: who is calling (caller) and which conversation this is (conversation). Your loop passes them from the session, as keyword-only arguments, so a model cannot change them.

03. Step 2: The handler

Save this as refunds.py. ORDERS and DONE stand in for database tables.

Python · refunds.py
"""request_refund: check the shape, then the state, then act at most once per key."""
import re
from decimal import Decimal

ORDERS = {
    "ORD-1044": {"account": "ACC-100", "status": "delivered",
                 "total": Decimal("120.00"), "refunded": Decimal("0.00")},
    "ORD-2001": {"account": "ACC-200", "status": "delivered",
                 "total": Decimal("80.00"), "refunded": Decimal("0.00")},
}
DONE = {}  # idempotency key -> the result we returned the first time

FIELDS = {  # name: (pattern, what to tell the model)
    "order_id": (r"ORD-[0-9]{4,6}", "an order ID such as ORD-1044"),
    "amount": (r"[0-9]+\.[0-9]{2}", "a string with two decimals, e.g. 49.99"),
    "reason": (r"damaged|not_received|wrong_item|other",
               "one of damaged, not_received, wrong_item, other"),
}


def fail(kind: str, message: str, retryable: bool) -> dict:
    return {"ok": False,
            "error": {"type": kind, "message": message, "retryable": retryable}}


def check_shape(args: dict) -> list:
    """Tier 1: the arguments match the schema (strict mode may do this)."""
    problems = [f"unknown argument '{k}'" for k in args if k not in FIELDS]
    for name, (pattern, hint) in FIELDS.items():
        value = args.get(name)
        if value is None:
            problems.append(f"'{name}' is required: {hint}")
        elif not isinstance(value, str) or not re.fullmatch(pattern, value):
            problems.append(f"'{name}' must be {hint} (got {value!r})")
    return problems


def request_refund(args: dict, *, caller: str, conversation: str) -> dict:
    problems = check_shape(args)
    if problems:
        return fail("invalid_arguments",
                    "; ".join(problems) + ". Fix these and call again.", True)
    # Tier 2: the arguments make sense for this caller and this order.
    key = (conversation, args["order_id"], args["amount"])
    if key in DONE:  # the model retried: return the first result again
        return DONE[key]
    order = ORDERS.get(args["order_id"])
    if order is None or order["account"] != caller:
        # Same answer for "missing" and "someone else's": leak nothing.
        return fail("order_not_found",
                    f"No order {args['order_id']} on this account. Ask the "
                    "customer to check the ID, or call list_orders.", False)
    if order["status"] != "delivered":
        return fail("not_refundable",
                    f"Order {args['order_id']} is {order['status']}; only "
                    "delivered orders can be refunded. Tell the customer.",
                    False)
    amount = Decimal(args["amount"])
    left = order["total"] - order["refunded"]
    if amount > left:
        return fail("amount_too_high",
                    f"{amount} is more than the {left} still refundable on "
                    f"{args['order_id']}. Call again with at most {left}, or "
                    "explain the limit to the customer.", True)
    order["refunded"] += amount  # in production: one DB transaction
    result = {"ok": True, "refund_id": f"rf-{len(DONE) + 1:03d}",
              "refunded": str(amount), "still_refundable": str(left - amount)}
    DONE[key] = result
    return result

Walk through the order of the checks:

  • Shape first, and every problem at once, so the model can fix them in one retry instead of three.
  • Idempotency before any state change. The key is the conversation, the order and the amount. Why not the tool call id? Because when the model retries, it sends a new call with a new id, and a key built from the id would refund twice. The cost of this key is that a genuine second refund of the same amount in the same conversation returns the first result; route that rare case to a person.
  • Ownership with the same answer as "missing". Telling the model "this order belongs to someone else" confirms that the order exists, which leaks information. This is the classic broken object-level authorisation problem from API security, and an agent makes it easier to exploit, because anyone who can influence the model's input can try IDs.
  • Money as Decimal from a string with two decimals. Floats cannot represent 0.10 exactly; the tests show why that matters.

In production the idempotency check, the limit check and the update must be one database transaction, with a unique constraint on the key, or two concurrent retries can both pass the checks.

04. Step 3: Errors the model can act on

Every failure above returns the same structure: type, a message and retryable. The message is written for the model and follows three parts: what was wrong, the rule or the current state, and what to do next. Compare:

  • Weak: KeyError: 'ORD-9921', 422 Unprocessable Entity, Invalid input, please try again.
  • Useful: 500.00 is more than the 120.00 still refundable on ORD-1044. Call again with at most 120.00, or explain the limit to the customer.

The weak versions describe your internals, or nothing at all, so the model often repeats the same call or invents an explanation for the customer. The useful version gives it two concrete ways forward. retryable and type are for your own loop: a loop can stop after two failures with the same type, alert on order_not_found spikes, or skip retries when retryable is false.

Keep messages free of secrets and of other customers' data, and do not paste raw exception text: it can contain SQL, file paths or tokens.

05. Step 4: Send the error in the provider format

The handler result is the same for every provider; only the wrapper differs. Claude has an explicit error flag on the tool_result block. The OpenAI Responses API has none, so the output text itself must make the failure obvious, which the "ok": false and "error" keys do.

Python · wire.py
"""Send a handler result back in each provider's format."""
import json


def claude_block(call_id: str, result: dict) -> dict:
    block = {"type": "tool_result", "tool_use_id": call_id,
             "content": json.dumps(result.get("error", result))}
    if not result["ok"]:
        block["is_error"] = True  # Claude's explicit error flag
    return block


def openai_item(call_id: str, result: dict) -> dict:
    # No error flag in the Responses API: the output text says it failed.
    return {"type": "function_call_output", "call_id": call_id,
            "output": json.dumps(result)}

Now replay three calls the way a model might send them in one conversation: a badly shaped call, an amount that is too high, and a correct call.

Python · demo.py
"""Three refund attempts, as a model might make them, and the replies."""
import json
import textwrap

from refunds import request_refund
from wire import claude_block, openai_item

calls = [
    ("toolu_01", {"order_id": "1044", "amount": 50, "reason": "damaged"}),
    ("toolu_02", {"order_id": "ORD-1044", "amount": "500.00",
                  "reason": "damaged"}),
    ("toolu_03", {"order_id": "ORD-1044", "amount": "120.00",
                  "reason": "damaged"}),
]
for call_id, args in calls:
    result = request_refund(args, caller="ACC-100", conversation="conv-7")
    block = claude_block(call_id, result)
    print(f"{call_id}  is_error={block.get('is_error', False)}")
    body = json.loads(block["content"])
    text = body.get("message") or json.dumps(body)
    print(textwrap.fill(text, 76, initial_indent="  ",
                        subsequent_indent="  "))

item = openai_item("call_02", request_refund(
    calls[1][1], caller="ACC-100", conversation="conv-8"))
print("OpenAI output for an error:", sorted(json.loads(item["output"])))
Terminal
python3 demo.py
Expected output
toolu_01  is_error=True
  'order_id' must be an order ID such as ORD-1044 (got '1044'); 'amount'
  must be a string with two decimals, e.g. 49.99 (got 50). Fix these and
  call again.
toolu_02  is_error=True
  500.00 is more than the 120.00 still refundable on ORD-1044. Call again
  with at most 120.00, or explain the limit to the customer.
toolu_03  is_error=False
  {"ok": true, "refund_id": "rf-001", "refunded": "120.00",
  "still_refundable": "0.00"}
OpenAI output for an error: ['error', 'ok']

The first message names both bad fields and gives the expected form of each, so a single retry can fix both. The second states the limit and two ways forward. How often a model recovers from such messages depends on the model and the task, so do not take a number from a blog post: count it. The harness in lesson 5 can record whether the call after an error is valid. Claude's documentation describes the model retrying an invalid call a few times with corrections before it apologises, which is one more reason for your loop to cap repeated failures.

06. Step 5: Prove each safeguard with a negative test

Each test attacks one rule: someone else's order, a retried refund, too high an amount, a badly shaped call that also tries to smuggle in an account, and float rounding. Run them whenever the handler changes. The sed at the end of the command removes the run time from the Ran 5 tests line, because it differs on every run.

Python · test_refunds.py
"""Negative tests for request_refund. Run: python3 -m unittest -v"""
import unittest
from decimal import Decimal

import refunds
from refunds import request_refund

GOOD = {"order_id": "ORD-1044", "amount": "30.00", "reason": "damaged"}


class RefundTests(unittest.TestCase):
    def setUp(self):  # fresh state for every test
        for order in refunds.ORDERS.values():
            order["refunded"] = Decimal("0.00")
        refunds.DONE.clear()

    def test_foreign_order_refused(self):
        args = dict(GOOD, order_id="ORD-2001")  # belongs to ACC-200
        result = request_refund(args, caller="ACC-100", conversation="c1")
        self.assertEqual(result["error"]["type"], "order_not_found")
        self.assertEqual(refunds.ORDERS["ORD-2001"]["refunded"], 0)

    def test_retry_refunds_once(self):
        first = request_refund(GOOD, caller="ACC-100", conversation="c1")
        again = request_refund(GOOD, caller="ACC-100", conversation="c1")
        self.assertEqual(first, again)
        self.assertEqual(refunds.ORDERS["ORD-1044"]["refunded"],
                         Decimal("30.00"))

    def test_amount_over_limit(self):
        args = dict(GOOD, amount="500.00")
        result = request_refund(args, caller="ACC-100", conversation="c1")
        self.assertTrue(result["error"]["retryable"])
        self.assertIn("at most 120.00", result["error"]["message"])

    def test_bad_shape_named(self):
        args = {"order_id": "1044", "amount": 50, "account": "ACC-200"}
        result = request_refund(args, caller="ACC-100", conversation="c1")
        message = result["error"]["message"]
        for word in ("order_id", "amount", "reason", "unknown argument"):
            self.assertIn(word, message)

    def test_no_float_rounding(self):
        for i in range(3):  # three different conversations, 0.10 each
            request_refund(dict(GOOD, amount="0.10"), caller="ACC-100",
                           conversation=f"c{i}")
        self.assertEqual(refunds.ORDERS["ORD-1044"]["refunded"],
                         Decimal("0.30"))


if __name__ == "__main__":
    unittest.main()
Terminal
python3 -m unittest -v test_refunds 2>&1 | sed -E 's/ in [0-9.]+s$//'
Expected output (Python 3.12)
test_amount_over_limit (test_refunds.RefundTests.test_amount_over_limit) ... ok
test_bad_shape_named (test_refunds.RefundTests.test_bad_shape_named) ... ok
test_foreign_order_refused (test_refunds.RefundTests.test_foreign_order_refused) ... ok
test_no_float_rounding (test_refunds.RefundTests.test_no_float_rounding) ... ok
test_retry_refunds_once (test_refunds.RefundTests.test_retry_refunds_once) ... ok

----------------------------------------------------------------------
Ran 5 tests

OK

07. Check your understanding

Practice check · 3 questions

Reading the refund handler

Use refunds.py from this lesson. Each question has one best answer.

Q1. Why is the idempotency key built from the conversation, order and amount rather than the tool call id?
Q2. The model asks to refund ORD-2001, which exists but belongs to another customer. What does the handler return?
Q3. Suppose the `DONE` lookup moved from before the order lookup to just before the refund is booked. A refund of 120.00 on ORD-1044 succeeds, and the model retries the same call after a timeout. What does the retry get?
Practice only: not graded, not saved, not evidence.

08. Apply it

In the practice project, give all three tools (look up an order, list a customer's orders, request a refund) a shape check and a state check, take the customer from the session, and return errors in the type/message/retryable structure. Write at least one negative test per tool, including "another customer's order" for the lookup. Then run your tool loop from lesson 3 with a scripted call that fails once and check that the model's next call is valid.

09. Review prompt

Without looking back:

  1. Which checks belong to the shape tier and which to the state tier? Why keep shape checks when strict mode is on?
  2. What are the three parts of a useful tool error message, and what should it never contain?
  3. How do you mark a failed tool call for Claude, and for the OpenAI Responses API?
  4. Why must the idempotency check and the refund happen in one transaction in production?

References

Your progress

Reading state

Sign in to save that you finished reading this lesson.

Sign in to mark reading complete

Prove this skill

8 questions · about 6 minutes · scored automatically. Marking a lesson as read never demonstrates a skill.
Take the skill check