How a model asks software to do something
Tool calling lets a model propose a named function and structured arguments. The model does not execute the function itself: trusted application code validates the proposal, checks authorization, runs the tool, and returns a compact success or error result as the next observation. Reliable tool design makes that boundary explicit.
What You Will Learn
- Explain the boundary between a model proposal and application execution.
- Design narrow tools with typed arguments and compact observations.
- Separate structural validation from authorization and policy checks.
- Use timeouts, idempotency, and approvals for reliable side effects.
A valid tool call is not an authorized action
A schema can prove that an amount is a number and an order ID is a string. It cannot prove that the signed-in user owns that order, that the amount is within policy, or that the action is safe. Those checks belong to trusted application code after the model proposes the call and before the tool executes.
The tool should return a small structured observation: the fields needed for the next decision, a clear status, and a recoverable error category. Returning an entire database record or verbose log wastes context space and may expose data the model does not need.
Instructional figure
A tool call crosses a trust boundary
Which parts are proposals, and which parts must be enforced by trusted code?
Trusted application boundary
Read tools and action tools need different safeguards
From a proposed tool call to a verified receipt
Give each tool one narrow purpose, a precise name and description, and a typed input schema.
Let the model select a tool and propose arguments; do not treat the proposal as permission.
Validate identity, authorization, schema, ranges, rate limits, and whether the tool reads data or causes a side effect.
Execute with least privilege, timeouts, and predictable structured success or error results.
Return only the useful observation so the model can decide whether to answer, retry safely, choose another tool, or stop.
For payments, messages, and other side effects, use an idempotency key so a retry cannot repeat a completed action.
Retries depend on what the tool does
A read-only lookup is usually safe to retry after a transient timeout. A write may already have succeeded even when its response was lost. Use an idempotency key for side effects so the service can recognize a repeated logical request and return the earlier result instead of performing the action twice.
Worked Example: One refund request, two safety branches
The authenticated user U-17 requests a $48 refund for order O-204. The order service supplies the owner, refundable amount, and policy limit; the model does not invent those values.
- Success: the model proposes structured arguments. Schema validation passes, U-17 matches the order owner, $48 is within both the refundable balance and the $100 policy limit, and the application executes with idempotency key refund:O-204:48. Receipt R-731 proves the write completed.
- Unauthorized branch: if the same schema-valid call is made by U-88, the ownership comparison fails. The application returns {status: 'rejected', reason: 'not_order_owner'} and never calls the payment service.
- Lost-response branch: suppose the payment write succeeds but the network drops before the application sees R-731. A retry sends the same idempotency key. The service finds the recorded operation and returns existing receipt R-731 instead of issuing a second refund.
What the result means: JSON validity answers only 'is the proposal well formed?' Identity, ownership, policy, and idempotency answer whether and how it may execute. The final response is based on the receipt, not on the model's proposal.
Refund R-731: the observable tool-call trace
Instructional figure
Tool-call lifecycle: proposal, permission, execution, and receipt
What happens between a user's refund request and a trustworthy final response?
Tool-Call Lifecycle: Proposal, Validation Gates, Execution & Idempotency
The model proposes structured arguments. Trusted application code strictly validates schema, ownership, policy, and idempotency before executing.
Interactive Step 1..6 Trace Inspector (Mobile Friendly)
Step 1 of 6Step 1: User Refund Request
Customer prompt arrives at the agent application
Application receives raw user message, verifies authentication token (user_id: U-17), and injects available tool definitions into model context.
A Realistic Example: Looking up an order without risking a duplicate refund
A lookup tool accepts only an order ID owned by the signed-in user and returns a compact status. A separate refund tool requires authorization, an amount limit, approval where needed, and the task ID as an idempotency key. If a timeout causes a retry, the service returns the original result instead of paying twice.
Read the Mechanism in Code
Use the label and note to understand what this block represents before reading each line.
refund_schema = {
"name": "refund_order",
"description": "Refund one order owned by the signed-in user",
"parameters": {
"type": "object",
"properties": {
"order_id": {"type": "string"},
"amount": {"type": "number", "minimum": 0},
},
"required": ["order_id", "amount"],
"additionalProperties": False,
},
}
def execute_tool(call, user, task_id):
validate_schema(call, refund_schema)
authorize(user, call["name"], call["arguments"]["order_id"])
enforce_refund_limit(call["arguments"]["amount"])
return run_with_timeout(call, idempotency_key=task_id)Hands-On Runnable Python Lab: Make a Refund Retry Safe—and Reject a Changed Request
Order O-204 belongs to U-17 and has $48.00 refundable. Amounts use integer cents, avoiding floating-point money arithmetic. The example keeps an in-memory ledger of receipts.
- Validate the amount and verify order ownership before touching the ledger.
- Execute the first authorized $48.00 refund and store its fingerprint with receipt R-001.
- Repeat the same request with the same key: return R-001 without changing the balance.
- Try a different amount with that key, then a different user. Reject both and confirm the ledger still contains one write.
A retry reuses a receipt, not a financial side effect
The fingerprint binds actor, order and amount. The receipt ledger accepts a matching retry but rejects changed requests and unauthorized actors.
orders = {"O-204": {"owner": "U-17", "remaining": 4800}}
ledger = {}
def refund(actor, order_id, cents, key):
if type(cents) is not int or cents <= 0:
raise ValueError("positive integer cents required")
order = orders[order_id]
if actor != order["owner"]:
raise PermissionError("not the order owner")
fingerprint = (actor, order_id, cents)
if key in ledger:
original, receipt = ledger[key]
if original != fingerprint:
raise ValueError("idempotency key conflict")
return receipt, "replayed"
if cents > order["remaining"]:
raise ValueError("amount exceeds refundable balance")
receipt = f"R-{len(ledger) + 1:03d}"
order["remaining"] -= cents
ledger[key] = (fingerprint, receipt)
return receipt, "executed"
for _ in range(2):
receipt, status = refund("U-17", "O-204", 4800, "refund-204")
print(status, receipt)
for actor, amount in [("U-17", 1000), ("U-99", 4800)]:
try:
refund(actor, "O-204", amount, "refund-204")
except (ValueError, PermissionError) as error:
print("rejected:", error)
print("refund writes:", len(ledger))
print("remaining cents:", orders["O-204"]["remaining"])
executed R-001
replayed R-001
rejected: idempotency key conflict
rejected: not the order owner
refund writes: 1
remaining cents: 0What This Run Shows
- Authorization occurs even on a replay, so possession of an idempotency key is not sufficient to retrieve another customer’s receipt.
- The changed amount is rejected before a new write. A retry must preserve the meaning of the original request.
- The balance reaches zero only once, while both accepted attempts receive the same receipt.
Reliable tool design makes the application’s invariants explicit. The model can help fill arguments, but it cannot grant itself ownership or decide that a duplicate write is harmless.
From the Exercise to an Application
Experiment: Change the second call to use a new idempotency key.
It is treated as a different operation. Here the zero remaining balance rejects it, but that balance check is not a substitute for idempotency: a larger balance could otherwise allow an unintended second refund.
Summary / Key Takeaways
- A tool call is a model proposal for a named capability and structured arguments; it is not the execution itself.
- Trusted application code must validate schema, identity, authorization, ranges, and policy before executing a tool.
- Read/data tools and action/write tools need different risk controls because write tools can create external side effects.
- Clear, narrow tool names, descriptions, and schemas improve tool selection and reduce ambiguous behavior.
- Tool results should be structured and compact so the next model step receives the useful observation without unnecessary context.
- Retries are safe only when the failure type and side-effect semantics allow them; idempotency prevents duplicate consequential actions.
- Least privilege, predictable errors, bounded retries, approvals, and auditability make tool use reliable in production.
Verified Further Reading
These primary research papers and current official specifications support the concepts and implementation guidance in this lesson. The explanations, analogies, exercises, and code above remain original teaching material.
OpenAI API: Function Calling
Current API documentation for tool schemas, strict structured arguments, application-side execution, and returning tool results.
Toolformer: Language Models Can Teach Themselves to Use Tools
Original research on learning when to call APIs, what arguments to pass, and how to use returned results.
Model Context Protocol: Server Tools (2026-07-28)
Normative tool discovery and invocation guidance, including validation, access control, human approval, and untrusted tool metadata.