Sub topic 4
Agents as tools
This chapter assumes you can read Python, know how a model's tool call turns into a function call, and have seen a basic agent loop: the model replies, the program runs any requested tool, and the result is appended to the history. Here you will wrap a whole agent inside a function so that another agent can call it like any other tool.
The idea
A tool is a function the model can request by name, with arguments. The model never sees how the function works. It sees a name, a description, and a result.
An agent can be wrapped in such a function. The function takes a task as a string, runs a complete agent loop internally, and returns the agent's final answer as a string. The calling model cannot tell whether the tool is a database lookup or a second agent with its own tools and reasoning.
This is the building block of the orchestrator pattern, which later chapters cover in full. The key property is that the caller keeps control. A handoff transfers the conversation to another agent. An agent used as a tool returns, and the caller continues.
The wrapper
The wrapper is a closure over a worker agent:
def as_tool(worker: Agent, call_model):
def tool(task: str) -> str:
# The worker starts with a fresh history containing only the task.
_, text = run(worker, [{"role": "user", "content": task}], call_model)
return text
return toolThree details matter.
- The worker gets a fresh history. It sees only the
taskstring. It does not see the user's original request, the orchestrator's instructions, or the other workers' results. If the worker needs a fact, the orchestrator must put it intask. - The return value is a string. Whatever the worker produces, the orchestrator receives text. Structured results need to be serialized, for example as JSON, and the orchestrator's instructions should say what format to expect.
- The worker runs its own loop. It has its own tools, its own
max_turns, and its own failure modes. The orchestrator experiences all of that as one tool call.
A runnable example
The example below defines the minimal Agent and run from the earlier chapters, a scripted stand-in for the model, and an orchestrator with two specialists. The scripted model makes the program deterministic. In real code call_model would call an LLM API.
from dataclasses import dataclass, field
from typing import Callable
@dataclass
class Agent:
name: str
instructions: str
tools: dict[str, Callable] = field(default_factory=dict)
handoffs: dict[str, "Agent"] = field(default_factory=dict)
def run(start: Agent, messages: list, call_model, max_turns: int = 10):
agent = start
for _ in range(max_turns):
reply = call_model(agent, messages)
if reply["type"] == "final":
return agent.name, reply["text"]
if reply["type"] == "handoff":
agent = agent.handoffs[reply["target"]]
continue
result = agent.tools[reply["name"]](**reply["args"])
messages.append({"role": "tool", "name": reply["name"], "content": str(result)})
raise RuntimeError("max_turns exceeded")
def as_tool(worker: Agent, call_model):
def tool(task: str) -> str:
_, text = run(worker, [{"role": "user", "content": task}], call_model)
return text
return tool
def build_orchestrator(researcher: Agent, writer: Agent, call_model) -> Agent:
return Agent(
name="orchestrator",
instructions="Split the request into subtasks, call the specialists, and combine their answers.",
tools={
"research": as_tool(researcher, call_model),
"write": as_tool(writer, call_model),
},
)
def scripted_model(agent, messages):
"""Stands in for an LLM so the example runs without an API key."""
if agent.name == "researcher":
return {"type": "final", "text": "Handoffs transfer control. Orchestrators keep control."}
if agent.name == "writer":
task = messages[0]["content"]
return {"type": "final", "text": f"Draft based on: {task}"}
results = [m for m in messages if m["role"] == "tool"]
if len(results) == 0:
return {"type": "tool", "name": "research", "args": {"task": "Compare handoffs and orchestrators"}}
if len(results) == 1:
return {"type": "tool", "name": "write", "args": {"task": results[0]["content"]}}
return {"type": "final", "text": results[1]["content"]}
researcher = Agent("researcher", "Find facts.")
writer = Agent("writer", "Write clear prose.")
orchestrator = build_orchestrator(researcher, writer, scripted_model)
history = [{"role": "user", "content": "Explain handoffs versus orchestrators."}]
name, answer = run(orchestrator, history, scripted_model)
print(name)
print(answer)
print([m["name"] for m in history if m["role"] == "tool"])Running it prints orchestrator, then the writer's draft, then ['research', 'write']. The last line shows the orchestrator's history. It holds two tool results and none of the workers' internal messages. The writer's draft contains the researcher's output only because the orchestrator copied it into the write task.
The next diagram shows the same sequence of calls.
Agent as tool versus handoff
Both patterns move work to another agent, but they differ in who holds the conversation.
| Property | Agent as tool | Handoff |
|---|---|---|
| Who answers the user | The caller | The receiving agent |
| Specialist sees | Only the task string | Usually the shared history |
| Control after the call | Returns to the caller | Stays with the receiver |
| Caller can combine results | Yes | No |
| Typical use | Subtasks inside one request | Routing a conversation to the right owner |
The fresh history is both the strength and the weakness of agents as tools. It keeps specialists focused and keeps the orchestrator's context small. It also means every call is a lossy summary written by the orchestrator, so vague task strings produce poor work.
Writing good task strings
The model writes the task argument, so your descriptions and instructions shape its quality. A specialist cannot ask the orchestrator a clarifying question, because it runs once and returns.
- Describe the tool in terms of what the specialist can do and what it needs. "Researches a question using the web search tool. Include the full question and any date range." is better than "research".
- Tell the orchestrator to make each task self-contained: the goal, the relevant facts, and the expected output format.
- Keep task and result sizes bounded. A worker that returns 20,000 characters fills the orchestrator's context and raises the cost of every later turn.
Failures inside a wrapped agent
The bare wrapper has a gap. If the worker exceeds max_turns, run raises RuntimeError. That exception propagates through the orchestrator's tool call and crashes the whole run. Often the orchestrator could recover by retrying with a narrower task or by skipping that subtask, but only if it learns about the failure.
A safer wrapper returns the failure as text:
def as_safe_tool(worker: Agent, call_model, max_chars: int = 4000):
def tool(task: str) -> str:
try:
_, text = run(worker, [{"role": "user", "content": task}], call_model, max_turns=6)
except RuntimeError as exc:
return f"ERROR: {worker.name} failed: {exc}"
if len(text) > max_chars:
return text[:max_chars] + "\n[truncated]"
return text
return toolThis version does three things. It gives each worker its own turn budget, so one stuck specialist cannot consume the orchestrator's budget. It turns exceptions into a result the model can read. It caps the size of what flows back.
Catch only the errors you can describe usefully. Programming errors such as a KeyError from a misspelled tool name should still fail loudly in development. Retries and error classification get a full treatment in a later chapter.
Pitfalls
- Hidden recursion. If a worker also has agents as tools, depth and cost multiply. Give each level its own turn limit and consider a depth counter.
- Name collisions and vague names. The model picks tools by name and description. Two agents described as "helper" and "assistant" will be chosen unpredictably.
- Duplicated work. Workers share nothing, so two workers may fetch the same data. Pass shared facts in each task or cache lookups in a tool.
- Lost provenance. A string result carries no record of where facts came from. If you need sources, have the worker include them in its output.
- Permissions inherited by accident. A worker's tools run with your program's credentials. Give each worker only the tools it needs.
Summary of the design
To turn an agent into a tool, you need a name, a description, a function from task string to result string, and a bounded loop inside. Make the task self-contained, bound the output, and report failures as text. The orchestrator then plans and combines, and the specialists do narrow work.
Exercise
In the runnable example, the writer receives only the string the orchestrator puts in its task argument. Name two problems this causes if the orchestrator writes {"task": "Write it up"} for the write call, and one change to the system that reduces them.
Show answer
The writer has no facts to write from, because the researcher's output is not in its history, and it does not know the format, audience, or length expected. It may invent content or return something unusable. Reduce this by instructing the orchestrator to write self-contained tasks that include the facts and the output format, and by describing in the tool's description what the task must contain. A structured task payload with fields such as goal, facts, and constraints also works.
Exercise
A researcher worker loops until max_turns is exceeded. Compare what happens with as_tool and with as_safe_tool, and say why the second behavior can be better.
Show answer
With as_tool, run raises RuntimeError, which is not caught, so the orchestrator and the whole request fail. With as_safe_tool, the exception becomes an ERROR: ... string returned as the tool result. The orchestrator can then read it and retry with a narrower task, try another specialist, or tell the user that part of the work failed. The run degrades instead of crashing.