Skip to main content
LearnMLAcademy
Advanced10 min read

Tool Calling & Reliable Tool Design

Master AI agent tool calling, schema validation, and safe error retries, with workflow diagrams, tool-use traces, and safety-focused exercises.

What you will master in this lesson
Intuitive core mechanisms & practical real-world intuition
Step-by-step mathematical breakdown & visual diagrams
Runnable Python implementation & practical trade-offs

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?

Model proposal
tool name + JSON arguments

Trusted application boundary

Schema
Identity + authorization
Policy + idempotency
Execute
Compact observation
status, useful fields, receipt/error
Schema-valid JSON is only a proposal. Identity, authorization, policy, idempotency, execution, and result minimization belong to the trusted application boundary.

Read tools and action tools need different safeguards

Read tools and action tools need different safeguards
Tool kindExamplesApprovalRetry ruleIdempotencyUseful observation
Read / dataSearch policy, get orderUsually not for low-risk authorized readsBounded retry for transient failuresHelpful but often optionalStatus, selected fields, source and timestamp
Action / writeRefund, send message, delete recordOften required for consequential actionsRetry only when outcome is known or operation is idempotentExpectedCompleted / already completed / rejected, receipt and reason

From a proposed tool call to a verified receipt

  1. Give each tool one narrow purpose, a precise name and description, and a typed input schema.

  2. Let the model select a tool and propose arguments; do not treat the proposal as permission.

  3. Validate identity, authorization, schema, ranges, rate limits, and whether the tool reads data or causes a side effect.

  4. Execute with least privilege, timeouts, and predictable structured success or error results.

  5. Return only the useful observation so the model can decide whether to answer, retry safely, choose another tool, or stop.

  6. 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.

  1. 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.
  2. 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.
  3. 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

Refund R-731: the observable tool-call trace
StageObservable inputOperation and reasonOutput / next decision
ProposalUser asks to refund order O-204; order lookup says refundable amount is $48Model proposes refund_order with {order_id: 'O-204', amount: 48}; this expresses intent onlyPass proposal to trusted checks—not to the payment service
Schemaorder_id string; amount numberValidator checks required fields and typesValid structure; authorization is still unknown
OwnershipSigned-in user U-17; order owner U-17Application compares authenticated identity with the authoritative order recordAuthorized owner; continue
Policy$48 requested; $48 refundable; $100 self-service limitBusiness rules check range and approval thresholdPermitted without reviewer escalation
ExecutionIdempotency key refund:O-204:48Payment service performs one write and records the keyRefund succeeds; receipt R-731
Observation{status: 'completed', receipt: 'R-731', amount: 48}Application returns only fields needed to explain the resultModel tells the user the refund completed and cites R-731

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

Receipt R-731 Trace

The model proposes structured arguments. Trusted application code strictly validates schema, ownership, policy, and idempotency before executing.

1. User Request“Refund $48 O-204”2. Model Proposalissue_refund({order: 'O-204', $48})SchemaGateINVALID400 Bad RequestReprompt ModelPASSPolicyOwner & $UNAUTH403 ForbiddenAbort WritePASS3. Execution EngineKey: refund:O-204:48Atomic Write to DBGenerates Receipt R-7314. Observation (Receipt){status: "completed",receipt: 'R-731', amount: 48}Lost-Response Retry: Reuses Key refund:O-204:48

Interactive Step 1..6 Trace Inspector (Mobile Friendly)

Step 1 of 6
Input Stage

Step 1: User Refund Request

Customer prompt arrives at the agent application

Input Data:
“Please refund $48 for my order O-204.”
Action Performed:

Application receives raw user message, verifies authentication token (user_id: U-17), and injects available tool definitions into model context.

Resulting Output / State:
Model prompt assembled with tools: [issue_refund, check_order_status]
The model proposes structured arguments. Trusted code separately validates structure, ownership, policy, and idempotency before execution. A retry reuses the key and returns receipt R-731 instead of issuing a second refund.

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.

Illustrative API fragment
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)
Learner note: Illustrative application-side tool schema and execution boundary. Helper functions such as authorize() and run_with_timeout() represent application code.

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.

new_refund_writes = accepted_unique_requests; identical retries add 0 writes
Two network attempts are not two financial operations. With key refund-204, actor U-17, order O-204 and amount 4,800 cents, the second matching attempt returns the first receipt.
  1. Validate the amount and verify order ownership before touching the ledger.
  2. Execute the first authorized $48.00 refund and store its fingerprint with receipt R-001.
  3. Repeat the same request with the same key: return R-001 without changing the balance.
  4. 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

An authorized first refund stores R-001. An identical retry returns R-001; a changed payload is rejected. Only one write occurs.Key: refund-204 · amount: 4,800 centsAttempt 1authorizedLedgerstore R-001Attempt 2same fingerprintReplay R-001no new writeSame key, same operationChanged payload → conflictWrong owner → denied2 accepted attempts · 1 financial write
The fingerprint binds actor, order and amount. The receipt ledger accepts a matching retry but rejects changed requests and unauthorized actors.

The fingerprint binds actor, order and amount. The receipt ledger accepts a matching retry but rejects changed requests and unauthorized actors.

Complete Python ExercisepythonRunnable
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"])
Run with Python 3 using only its standard library. No API key, paid service or model download is required. Model proposals and external observations are explicitly simulated; the application logic really executes.
Output from This Exact ProgramOutput
executed R-001
replayed R-001
rejected: idempotency key conflict
rejected: not the order owner
refund writes: 1
remaining cents: 0
Captured with Python 3.12. Fixture timings, prices and evaluation results are teaching inputs, not provider benchmarks.

What This Run Shows

  1. Authorization occurs even on a replay, so possession of an idempotency key is not sufficient to retrieve another customer’s receipt.
  2. The changed amount is rejected before a new write. A retry must preserve the meaning of the original request.
  3. 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

From the Exercise to an Application
SituationPractical choiceImportant qualification
Transient timeoutRetry with the original key and unchanged payloadFirst check the service’s idempotency contract.
Changed amount or recipientCreate a newly authorized operationNever quietly reuse an already executed key.
Denied authorizationStop or request legitimate permissionRetries and prompt changes cannot create authority.
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.

Apply this concept in a real hands-on project

You have studied the idea. Now use it in working Python code, see the calculation and output, and explain what changed. Each project includes step-by-step instructions, full source and tests.

Practice challenge: predict an outcome first, run the code, and explain the difference.

Track Your Progress0% curriculum done

Finished "Tool Calling & Reliable Tool Design"?

Mark this lesson as completed to update your progress bar and track your milestones across the full curriculum.

Overall Progress0 / 167 lessons

Was this tutorial helpful?

Your feedback helps us continuously refine and improve our open-access tutorials.

Knowledge Check

Progress: 0/5

Test your active recall. Choose one answer for each question, then check it to reveal the step-by-step reasoning.

Question 1 of 5conceptual
Who should actually authorize and execute a consequential tool call?
Question 2 of 5application/scenario
A tool schema accepts amount=5000, but the signed-in user is allowed to refund only 500. What should happen?
Question 3 of 5conceptual
Why is an idempotency key useful for a payment or refund tool?
Question 4 of 5practical selection
Which tool design is preferable?
Question 5 of 5debugging/diagnostic
A write tool times out after the server may already have processed the request. What is the safest default?

Knowledge Check Review & Explanations

Review the questions, verified correct answers, and conceptual explanations for this lesson.

1Who should actually authorize and execute a consequential tool call?▼

Correct Answer: Trusted application code after validation

The model proposes a call; deterministic application code should validate identity, authorization, policy, and arguments before execution.

2A tool schema accepts amount=5000, but the signed-in user is allowed to refund only 500. What should happen?▼

Correct Answer: Reject or require the appropriate authorization/approval

Schema validity does not imply authorization. Application policy must enforce the user’s permitted amount.

3Why is an idempotency key useful for a payment or refund tool?▼

Correct Answer: It prevents an accidental retry from applying the same side effect twice

Idempotency lets a repeated request return the original outcome instead of duplicating a completed side effect.

4Which tool design is preferable?▼

Correct Answer: Separate narrow tools with precise descriptions and typed inputs

Narrow, well-described tools are easier for the model to select correctly and easier for the application to validate and secure.

5A write tool times out after the server may already have processed the request. What is the safest default?▼

Correct Answer: Check idempotency/status before retrying the side effect

When completion is uncertain, retrying blindly can duplicate the action. The system should use idempotency or status checks first.

Keep moving through the path

Continue Learning

Free Download: ML Interview Cheatsheet

100 essential Machine Learning interview questions and answers covering foundations, algorithms, evaluation, deep learning, Python, system design and interview strategy. Enter your email to download it instantly.

Next