Tool / function calling
The model never runs anything: it emits a tool name plus JSON arguments, your code validates and executes it, and the result goes back as a message so the model can continue.
Analogy: A manager who can only act through request forms: "refund order A-123". Finance checks the form, does the refund and sends back a receipt. The manager never touches the bank.
How it works
- Each tool definition (name, description, JSON Schema) costs ~50–300 prompt tokens, sent on every call.
tool_choicesets whether the model may, must or must not call a tool, or forces one.- Independent calls can arrive in one parallel turn: run them concurrently and return all results together.
- Strict schemas guarantee the arguments' shape, not their values: validate and authorize every call in code.
- Return errors as results so the model can recover, and treat all tool output as untrusted input.
Check yourself
Answer to mark it learned; your answers aren't scored.
Security review of a banking assistant: the tool search_transactions(account_id, start, end) gets account_id from the model, which reads it from the conversation. A tester's injected prompt pulls another customer's transactions. Best fix?
Go deeper
Full explanation
Tool calling (function calling) lets a model use your code. The protocol:
- You send the conversation plus tool definitions:
name,descriptionand a JSON Schema for the parameters. They cost prompt tokens on every call. - If a tool helps, the model replies with a structured call instead of prose, e.g.
get_order({"order_id": "A-123"}), tagged with a call id. - Your code parses, validates, authorizes and executes it. The model never runs anything itself.
- You append the result as a message tied to that id (
toolrole in OpenAI, atool_resultblock in Anthropic) and call the model again. - It answers or asks for more calls. That cycle is the agent loop (ReAct: the agent loop).
Controls worth knowing:
tool_choice:auto(model decides),required/any(must call one), a named tool (forced), ornone.- Parallel calls: one turn can hold several independent calls; run them concurrently and return all results together. Disable it when order matters.
- Strict schemas (
strict: truein OpenAI and Anthropic, constrained decoding as in Structured outputs & JSON mode): arguments always match the schema, but can still be wrong. Validate values. - Errors are results: return
Error: order A-123 not found(Anthropic:is_error: true) so the model can recover.
Treat tool results as untrusted input: a Prompt injection (direct & indirect) vector.
Code Minimal tool loop with the Anthropic SDK
import anthropic
client = anthropic.Anthropic()
MODEL = "claude-sonnet-4-5" # any tool-capable model
TOOLS = [{
"name": "get_order",
"description": "Look up one order by id. Returns status, items and refund state.",
"input_schema": {
"type": "object",
"properties": {"order_id": {"type": "string", "description": "Like A-123"}},
"required": ["order_id"],
},
}]
IMPL = {"get_order": get_order} # your real functions
def run(user_msg: str, max_turns: int = 6) -> str:
messages = [{"role": "user", "content": user_msg}]
for _ in range(max_turns):
resp = client.messages.create(model=MODEL, max_tokens=1024,
tools=TOOLS, messages=messages)
if resp.stop_reason != "tool_use": # plain answer: done
return "".join(b.text for b in resp.content if b.type == "text")
messages.append({"role": "assistant", "content": resp.content}) # keep the calls
results = []
for b in [b for b in resp.content if b.type == "tool_use"]: # may be parallel
try: # validate + authorize here: the model only *asked*
out, err = str(IMPL[b.name](**b.input)), False
except Exception as e:
out, err = f"Error: {e}", True # let the model recover
results.append({"type": "tool_result", "tool_use_id": b.id,
"content": out, "is_error": err})
messages.append({"role": "user", "content": results}) # all results, one message
raise RuntimeError("no final answer within max_turns")Real example
A banking assistant gets "How much did I spend on Uber last month?". The model returns search_transactions(merchant="Uber", start="2026-10-01", end="2026-10-31"). The schema has no account_id parameter: your code injects it from the session, so an injected prompt can't query someone else's account. It runs a read-only query and returns 7 rows as ~150 tokens of compact JSON, not 40 raw fields per row. The model answers "$143.20 across 7 rides": two model calls, ~2 s. Moving money goes through a separate tool that requires explicit user confirmation.
Trade-offs +4 · −3
+ You gain
- Turns the model into a planner over real systems: APIs, databases, search, code execution.
- Schema-shaped arguments instead of parsing free text with regex.
- Your code stays the security boundary: every action passes your validation and authorization.
- Parallel calls collapse independent lookups into one round trip.
− You pay
- Every round trip is another full model call: latency and tokens add up.
- Tool definitions are re-sent on every request and eat context.
- Valid-looking arguments can still be wrong: wrong id, wrong date range, invented values.
Use it when
Whenever the model needs fresh or private data, exact computation, or to take actions: lookups, search, SQL, code execution, tickets, emails. Also a reliable way to get structured output (force one tool).
Avoid it when
When your code already knows which call to make: run it yourself and put the result in the prompt, skipping a round trip. Keep dangerous actions out of the toolset entirely.
Numbers to know 4
- τ-bench (2024): gpt-4o function-calling agents solved <50% of tasks, and pass^8 (all 8 retries succeed) was <25% in retail.
- Anthropic adds a hidden tool-use system prompt whenever tools are passed: ~290–680 tokens depending on the model (e.g. 497 on Sonnet 4.6, 286 on Opus 5.5; docs, Nov 2026).
- Rule of thumb: a tool definition costs ~50–300 tokens, so 30 tools add several thousand tokens to every call.
- Latency: N sequential tool steps ≈ N model calls; independent calls returned in one parallel turn cost one.
Common pitfalls 4
- Letting the model supply identity or tenant ids: inject them server-side from the session.
- Dropping the assistant turn that holds the calls, or mismatching call ids: the API rejects the request.
- Raising exceptions instead of returning errors as results: the loop dies where the model could have retried.
- Returning raw 10K-row payloads: truncate, paginate and summarize (Designing tools for agents (ACI)).
Interview questions 2
Answer out loud first, then reveal.
Does the model execute the function? Why does it matter?Show answer
No. It only emits a name and JSON arguments; my code decides whether anything runs. That makes my code the security boundary: I validate arguments against the schema and business rules, take identity and permissions from the session rather than from the model, and require confirmation for irreversible actions. Side effects are mine to make safe too: idempotency keys on writes, timeouts, and errors returned as tool results so the model can recover instead of the loop crashing.
The agent must choose among 150 internal tools. How do you design it?Show answer
I don't put 150 definitions in every prompt: they cost thousands of tokens per call and selection accuracy drops as tools overlap. First I consolidate into fewer task-shaped tools with namespaced names. Then I scope by context: a router or the current workflow step exposes only the 10–20 relevant ones, or the model searches a tool catalog and loads definitions on demand. I measure tool-selection and argument accuracy on an eval set built from real traces, before and after.