Tool use
A tool call is a request, not an execution. Everything that makes tool use safe happens in the space between the model proposing an action and your code carrying it out.
3.1What a tool call actually is
A language model cannot call a function. It has no interpreter, no network socket, no file descriptor. What it can do is emit tokens. Tool calling is the convention by which some of those tokens are interpreted by the host program as a structured request to run code.
Everything else in this chapter is engineering built on that mechanism. The model proposes an action; the host decides whether it happens.
Concretely, you add a tools array to your request. Each entry is a name, a description, and a JSON Schema describing the arguments. The provider serialises these into the prompt in a format the model was trained to recognise. If the model decides a tool is warranted, it emits a structured block naming the tool and supplying arguments, and the API sets a stop reason indicating it is waiting.
Then the request ends and the connection closes. Nothing has executed. Your program holds a JSON object saying, in effect, that it would like you to run a particular function with particular arguments. Whether that happens, and with what privileges, is entirely your decision.
Two features of this design have large consequences. The model never sees your credentials, your network, or your filesystem, so an injected instruction cannot directly exfiltrate them — it can only try to induce the host into doing so. And because the model is emitting text parsed into a schema, argument generation fails in ways ordinary function calls do not: a required field missing, an integer arriving as a string, an enum holding a value you never defined.
tools = [{
"name": "get_weather",
"description": "Current weather for a city. Use for present\n conditions, not forecasts.",
"input_schema": {
"type": "object",
"properties": {
"city": {"type": "string"},
"unit": {"type": "string", "enum": ["c", "f"]},
},
"required": ["city"],
},
}]# stop_reason == "tool_use"
[
{"type": "text", "text": "Let me look that up."},
{"type": "tool_use",
"id": "toolu_01A9dK3", # the correlation handle
"name": "get_weather",
"input": {"city": "Paris", "unit": "c"}},
]
# Nothing has run. This is a request, not a result.| STAGE | WHO PERFORMS IT | FAILURE IF SKIPPED |
|---|---|---|
| Declare the schema | You | The model invents argument names |
| Decide to call | The model | The only step the model owns |
| Validate arguments | You | Malformed input reaches your code |
| Authorise | You | An injected instruction runs with your privileges |
| Execute | You | Nothing happens; the loop stalls |
| Return the result | You | The next request is rejected as malformed |
3.2The raw loop, written by hand
Build the loop yourself once before using a framework. It runs to about forty lines, and the frameworks later in this chapter wrap those same forty lines. An engineer who has written them can debug an agent; an engineer who has not can only guess at it.
The loop has a single invariant: the message array is an append-only transcript that both you and the model can replay. Each turn appends the assistant’s response verbatim, then appends your tool results. You never edit history in place — doing so breaks cache prefixes and invalidates signatures on reasoning blocks.
Send the messages and the schemas. Inspect the stop reason. If the model is done, the last text block is your answer. If it wants tools, extract every request from the content list, validate each against its declared schema, decide whether the call is permitted, and only then execute. Append the assistant message unchanged, then append one user message holding one result per request, and loop.
The append-verbatim rule is the one most often broken. Appending only the text you extracted leaves the next request with a call that has no result, or a result that has no call. Both are rejected by the API. Never paraphrase the transcript.
messages = [{"role": "user", "content": user_input}]
for turn in range(MAX_TURNS): # always bound the loop
resp = client.messages.create(
model=MODEL, max_tokens=4096,
tools=tools, messages=messages,
)
if resp.stop_reason != "tool_use":
break
# Append the assistant turn verbatim, never a summary of it.
messages.append({"role": "assistant", "content": resp.content})
results = [dispatch(b) for b in resp.content
if b.type == "tool_use"]
messages.append({"role": "user", "content": results})
else:
raise RuntimeError("tool loop did not converge")import jsonschema
def dispatch(block):
out = {"type": "tool_result", "tool_use_id": block.id}
try:
jsonschema.validate(block.input, SCHEMAS[block.name])
if not authorized(block.name, block.input):
raise PermissionError(f"{block.name} needs approval")
out["content"] = str(REGISTRY[block.name](**block.input))
except Exception as e:
# Report the error to the model; do not crash the loop.
out["content"] = f"{type(e).__name__}: {e}"
out["is_error"] = True
return out| STOP REASON | MEANING | CORRECT ACTION |
|---|---|---|
| end_turn | The model finished normally | Read the final text and exit |
| tool_use | One or more tools are requested | Execute, append results, loop |
| max_tokens | The output cap was hit mid-generation | Raise the cap; do not treat as an answer |
| pause_turn | A long server-side run paused | Resend history unchanged to resume |
| refusal | A safety classifier declined | Do not retry identically |
3.3Identifiers, parallelism, and errors
Each request carries an identifier because one assistant turn may contain several. Without it, results returned as a list would be matched by position, and any reordering from concurrent execution would silently attribute one answer to another question.
Parallel calls are the default on current models, and three properties follow. Results may return in any order provided each carries its matching identifier. All results for one turn must go in a single message — splitting them is malformed, and over several turns it teaches the model that parallel calls do not work, so it stops making them. A failed call still needs a result marked as an error, or the pairing breaks.
Concurrency is your responsibility alone. The model has no idea whether the two functions it requested are safe to run simultaneously; it emitted them together because they looked independent. If they are not safe to interleave, your dispatcher must serialise them. This is the strongest argument for narrow dedicated tools over one general shell tool: your scheduler can know that a search is parallel-safe and a push is not, but it cannot know that about an opaque command string.
Error handling has three cases wanting different treatments. Malformed arguments should go back to the model as an error string, because it can often correct itself — validation failures are recoverable feedback, not exceptions. Timeouts should also return as errors, but under a budget, since a model retrying a hanging tool will burn the whole loop.
Non-idempotent failures are harder. When a payment call times out, the host does not know whether the payment was sent, and reporting a timeout invites a retry the model has no basis for judging. No prompt instruction solves this. Attach an idempotency key generated by the host from the call arguments, so that a retry reaches a deduplicating server rather than issuing a second charge. Where an operation cannot be made idempotent, the loop must not retry it at all: return a terminal error and escalate to a person.
from concurrent.futures import ThreadPoolExecutor
calls = [b for b in resp.content if b.type == "tool_use"]
safe = [c for c in calls if PARALLEL_SAFE[c.name]]
unsafe = [c for c in calls if not PARALLEL_SAFE[c.name]]
with ThreadPoolExecutor(max_workers=8) as pool:
results = list(pool.map(dispatch, safe))
results += [dispatch(c) for c in unsafe] # serialised
# Order does not matter; the identifier does. One message, all results.
messages.append({"role": "user", "content": results})| FAILURE | RETURN TO MODEL? | HOST-SIDE ACTION |
|---|---|---|
| Schema violation | Yes, marked as error | None; the model self-corrects |
| Unknown tool name | Yes, marked as error | Log it — usually a stale schema |
| Timeout, idempotent | Yes, marked as error | Allow a bounded retry |
| Timeout, non-idempotent | Terminal error only | Idempotency key, or escalate |
| Authorisation denied | Yes, with the reason | Write an audit record |
| Executor crashed | Yes, sanitised | Never leak traces or paths |
3.4The Model Context Protocol
Everything so far assumed you wrote the tool. In practice most tools wrap somebody else’s system — a tracker, a warehouse, a design tool. Without a shared convention, connecting M applications to N systems needs M×N bespoke integrations, each re-implementing discovery, invocation, and error semantics. A protocol turns that into M + N.
The architecture has three roles, and the terms are routinely confused. A host is the application the user interacts with, and it alone holds the model and runs the agent loop. A client is a connector inside the host managing one connection. A server is a separate process exposing capabilities; it does not call models and does not make decisions. Messages are JSON-RPC.
Servers offer three primitives, distinguished by who controls them. Tools are functions for the model to invoke, mapping exactly onto the mechanism in 3.1. Resources are data identified by URI for the application or user to read — application-controlled, not model-invoked. Prompts are templated workflows surfaced to the user, typically as slash commands. In the other direction, a server may ask the host to collect information from the user mid-operation.
Transports come in two shapes. Standard input and output launches the server as a subprocess, which is right for anything local. For remote servers the original HTTP-with-server-sent-events transport was replaced by streamable HTTP, using a single endpoint and streaming responses when useful rather than holding a side channel open.
The specification is versioned by date and it moves. The revision most course material cites has been superseded twice. The November 2025 revision added tool calling within sampling, URL-mode elicitation, icons, and discovery for authorisation. The current revision, dated 28 July 2026, is a larger break: it removes the initialisation handshake and the session header entirely, making the core stateless so requests route to any instance without sticky sessions, and it deprecates roots, sampling, and protocol-level logging.
The protocol standardises discovery and invocation. It does not standardise planning, the agent loop, the memory model, or any authorisation decision. A server that advertises a destructive function with a reassuring description has been granted no privilege by doing so. The specification states that descriptions from an untrusted server are untrusted data, and that hosts must obtain consent before invoking a tool. Integration became cheaper; the trust boundary did not move.
// host -> server
{"jsonrpc": "2.0", "id": 1, "method": "tools/list"}
// server -> host
{"jsonrpc": "2.0", "id": 1, "result": {"tools": [
{"name": "search_issues",
"description": "Search the issue tracker.",
"inputSchema": {"type": "object",
"properties": {"q": {"type": "string"}},
"required": ["q"]}}]}}
// host -> server, after the model asked for it
{"jsonrpc": "2.0", "id": 2, "method": "tools/call",
"params": {"name": "search_issues", "arguments": {"q": "crash"}}}# The protocol gives you discovery. The loop from 3.2 is unchanged.
mcp_tools = await session.list_tools()
tools = [{"name": t.name,
"description": t.description,
"input_schema": t.inputSchema} for t in mcp_tools.tools]
async def dispatch_mcp(block):
# Authorisation is still yours. The server does not decide.
if not authorized(block.name, block.input):
return {"type": "tool_result", "tool_use_id": block.id,
"content": "denied", "is_error": True}
r = await session.call_tool(block.name, block.input)
return {"type": "tool_result", "tool_use_id": block.id,
"content": r.content[0].text}| REVISION | NOTABLE CHANGE |
|---|---|
| 2025-03-26 | Streamable HTTP replaces the server-sent-events transport |
| 2025-06-18 | Elicitation; structured tool output; OAuth resource server |
| 2025-11-25 | Tool calling in sampling; URL elicitation; icons; tasks |
| 2026-07-28 | Handshake and sessions removed; stateless core; roots, sampling and logging deprecated |
3.5The same tool in five frameworks
The following pages implement one function five ways. Compare them by asking what each abstraction removes from view, since that is what an engineer needs back when diagnosing a failure under time pressure.
The raw SDK is the baseline from the previous section. You write the schema, the loop, the validation, and the dispatch table. Nothing is hidden and nothing is provided.
LangGraph derives a schema from your type hints and docstring, and supplies a graph node that reads tool calls off the last message, runs them, and emits results. The routing between “call a tool” and “finish” becomes an edge condition. What moves out of view is the message array itself, now living inside graph state.
LlamaIndex takes plain callables and infers schemas from signatures. Its centre of gravity is retrieval, so tools often wrap query engines rather than arbitrary functions. Prompt assembly and event plumbing are what it hides.
The OpenAI Agents SDK generates the schema and validates arguments before your function runs. Its distinctive feature is the handoff: passing another agent in a list exposes it to the model as a transfer function, so control moves between agents through what is mechanically still a tool call. That indirection is convenient and is the thing to remember when a trace looks strange.
DSPy is the outlier. You do not write a prompt or a description in the usual sense; you declare an input–output contract and hand tools to a module. The module builds the prompt and an optimiser can later rewrite it.
A pattern runs through all five. Every framework abstracts schema generation, and every framework abstracts the loop. Almost none abstract authorisation, and none abstract idempotency. The components that most determine whether an agent is safe are the ones no library provides.
from langchain_core.tools import tool
from langgraph.prebuilt import ToolNode, tools_condition
from langgraph.graph import StateGraph, MessagesState, START
@tool
def get_weather(city: str) -> str:
"""Current weather for a city."""
return f"18C and clear in {city}"
llm = model.bind_tools([get_weather])
g = StateGraph(MessagesState)
g.add_node("agent", lambda s: {"messages": [llm.invoke(s["messages"])]})
g.add_node("tools", ToolNode([get_weather]))
g.add_conditional_edges("agent", tools_condition)from agents import Agent, Runner, function_tool
@function_tool
def get_weather(city: str) -> str:
"""Current weather for a city."""
return f"18C and clear in {city}"
weather = Agent(name="Weather", tools=[get_weather])
triage = Agent(
name="Triage",
instructions="Route weather questions to the weather agent.",
handoffs=[weather], # exposed as transfer_to_weather
)
result = await Runner.run(triage, "Weather in Paris?")import dspy
def get_weather(city: str) -> str:
"""Current weather for a city."""
return f"18C and clear in {city}"
class Answer(dspy.Signature):
"""Answer the question using the available tools."""
question: str = dspy.InputField()
answer: str = dspy.OutputField()
agent = dspy.ReAct(Answer, tools=[get_weather], max_iters=5)
print(agent(question="Weather in Paris?").answer)| FRAMEWORK | SCHEMA FROM | LOOP DRIVER | WHAT IT HIDES AT DEBUG TIME |
|---|---|---|---|
| Raw SDK | You write it | Your own loop | Nothing |
| LangGraph | Type hints | Tool node and edge condition | The message array, behind graph state |
| LlamaIndex | Function signature | Agent workflow | Prompt assembly and event plumbing |
| OpenAI Agents | Decorator plus validation | The runner | Handoffs, which are really tool calls |
| DSPy | Signature field types | The module | The entire prompt, by design |
3.6DSPy: programming rather than prompting
Every framework so far assumed you write the prompt. DSPy assumes you should not. The claim behind the slogan is that hand-tuned prompt strings are the assembly language of this field — model-specific, brittle under upgrade, and impossible to improve systematically. Write the program structure instead, and let a compiler produce the strings.
A signature is a declarative input–output contract. It names the fields, and the class form adds types and per-field descriptions. What it is not is a prompt: it contains no instructions about tone, no examples, no formatting demands. It says what goes in and what comes out.
A module is a strategy for satisfying a signature. One asks once. Another adds a reasoning field before the output. A third runs the tool loop from earlier in this chapter, interleaving thought and action until it can answer. Modules compose like layers, and the analogy is deliberate.
The parameters being optimised are the prompt itself: the instruction text attached to each predictor, and the demonstrations placed in its context. Once you have a program, a training set, and a metric, you have an optimisation problem, and prompts are the thing being optimised.
Bootstrapping is how demonstrations are found without hand-labelling. Run the unoptimised program on training inputs, keep the traces where the metric says the output was correct, and use those as examples. What this gives you is correct examples of your program’s intermediate steps, including tool calls — not just correct final answers.
The stronger optimiser searches instructions and demonstrations jointly in three stages: bootstrap candidate demonstration sets, have a proposer read a summary of your data and write candidate instructions for each predictor, then treat the combination as a search problem and evaluate candidates against the metric.
The honest costs. The optimised prompt is machine-written and often reads oddly. Your metric is now the specification, so one that rewards the wrong thing produces a program that is confidently wrong. Compilation costs real money in evaluation calls. And a prompt optimised against one model is not guaranteed to transfer to another.
from dspy.teleprompt import MIPROv2
def metric(example, pred, trace=None):
return float(pred.verdict.strip().lower() == example.verdict)
opt = MIPROv2(metric=metric, auto="medium")
compiled = opt.compile(FactCheck(search), trainset=train,
max_bootstrapped_demos=4)
compiled.save("factcheck.json") # the artifact is the prompts
# Always read the generated prompt before shipping it.
for name, predictor in compiled.named_predictors():
print(name, "->", predictor.signature.instructions)
print(" demos:", len(predictor.demos))| LAYER | WRITTEN BY | CHANGES WHEN |
|---|---|---|
| Signature | You | The task’s contract changes |
| Module composition | You | The strategy changes |
| Metric | You | Your definition of success changes |
| Instructions | The optimiser | You recompile |
| Demonstrations | The optimiser | You recompile |
3.7GEPA: reflective prompt evolution
The optimiser above treats a rollout as a number. The program ran, the metric returned a score, and that scalar is the entire signal used to update the search. GEPA starts from the observation that this throws away nearly everything the run produced — the trace holds the reasoning, the tool calls, the error messages, and the reason the answer was wrong.
The central claim is that natural language is a richer learning medium for a language model than a gradient derived from a sparse scalar. So the optimiser reads its own failures: it samples a minibatch, collects full traces, and asks a reflection model to diagnose what went wrong and propose a revised instruction.
The second idea is the selection rule, and it is where the name comes from. Hill-climbing on aggregate score collapses to a single lineage and gets stuck — one prompt wins on average and every mutation descends from it. Tracking instead the best score any candidate achieved on each individual training instance preserves candidates that are strong somewhere even if mediocre overall, and sampling from that frontier keeps the search diverse.
The reported numbers are strong. Across six tasks it beats a reinforcement-learning baseline by about six per cent on average and up to twenty, while using as much as thirty-five times fewer rollouts — the baseline ran twenty-four thousand rollouts, and the reflective method matched validation scores with as few as thirty-two to a hundred and seventy-nine in some settings. Against the joint optimiser it is over ten per cent better overall, with substantially shorter prompts.
Note that published figures differ between the preprint and the conference version, so a citation you find quoting a single headline number may be stale. The six-task figures above are from the later version.
When does it win? When your evaluation produces rich textual feedback and failures are diagnosable in language — a stack trace, a failing assertion, a compiler message, a rubric comment. And when rollouts are expensive, since it converges in far fewer. It wins less when the metric is a bare scalar with no diagnostics, because then the reflection model has nothing to read. The paper is also explicit that it optimises instructions only, which is why it is complementary to demonstration search rather than a replacement.
import dspy
def metric(gold, pred, trace=None, pred_name=None, pred_trace=None):
ok = pred.code_passes_tests
# This string is what the reflection model reads to
# diagnose the failure. Vague feedback wastes the method.
fb = ("All tests passed." if ok
else f"Failed {gold.test_name}: {pred.stderr[:400]}")
return dspy.Prediction(score=float(ok), feedback=fb)
opt = dspy.GEPA(metric=metric, max_metric_calls=150,
reflection_lm=dspy.LM("openai/gpt-5", temperature=1.0))
optimized = opt.compile(student=MyProgram(), trainset=train, valset=val)| STEP | WHAT HAPPENS |
|---|---|
| Select | Sample a candidate from the frontier |
| Execute | Run on a minibatch, capturing traces and feedback |
| Reflect | A model reads the traces and diagnoses failures in language |
| Mutate | Propose a revised instruction incorporating the diagnosis |
| Accept | If improved, add to the pool and update per-instance bests |
| Merge | Optionally combine complementary modules from two lineages |
3.8Choosing a level of abstraction
The order in which this chapter presents the material reflects how it should be learned. Write the loop by hand first. Every layer above it wraps those forty lines, and the responsibilities no framework assumes — authorisation, idempotency, concurrency safety — determine whether the resulting system is safe.
Reach for a protocol when you are integrating systems you did not write, and remember that it standardises discovery and invocation rather than trust. Reach for a framework when its operational abstractions solve a demonstrated need: durable state, branching, retries, tracing. Reach for a compiler when you have a metric you believe in and enough data to search against it.
An abstraction earns its place when it remains transparent under inspection. If the prompt, the tool arguments, the state mutation, and the termination condition cannot all be examined, the abstraction exceeds what the current debugging problem can afford.
A practical debugging order, when an agent misbehaves: read the raw message array first, then the tool arguments, then the authorisation decisions, and only then the prompt. Most failures that look like reasoning failures are schema failures, and most that look like schema failures are description failures.
| SYMPTOM | LIKELY CAUSE | WHERE TO LOOK FIRST |
|---|---|---|
| The model never calls a tool | The description does not match the task | The docstring or description text |
| Arguments are consistently malformed | The schema is ambiguous or under-constrained | The JSON schema, then examples |
| The loop never terminates | No step budget, or a repeated state | The stopping rule |
| A call ran that should not have | Authorisation was advisory, not enforced | The dispatcher, not the prompt |
| Behaviour changed after an upgrade | A prompt tuned for the old model | Recompile or re-tune |
Implement, then abstract
Build a two-tool agent loop with no framework. Add trace identifiers, schema validation, timeouts, and a step budget. Then rebuild the same loop inside one orchestration framework and document precisely which responsibilities moved into it.