Lesson 6 of 39 · Tools
Function Tools
Give Agent Framework agents Python function tools: the @tool decorator, type hints and schemas, async tools, tool_choice, loop limits and tool errors.
- 19 min read
- Intermediate
- Reviewed
- Explain the tool loop: how a model uses your Python functions without running them
- Turn functions into tools with @tool, docstrings, Annotated and Field
- Write async tools, and give tools to an agent or to a single run
- Steer tool use with tool_choice and ToolMode
- Limit the tool loop with FunctionInvocationConfiguration and handle tool errors
What a tool is
A model only writes text. On its own it can't check your stock, read a database or book a repair. Tools fix that.
The model never runs code. It writes a request such as "call get_price with {"model": "Commuter 3"}". Agent Framework runs your function, adds the result to the conversation and calls the model again, which now answers with real data. This back-and-forth is the tool loop, also called function calling. Here it is in plain Python:
# The tool loop in plain Python. The model can't look anything up, so it asks for a tool call;
# your code runs the function and sends the result back; then the model answers.
import json
def get_price(model):
return {"model": model, "price_eur": {"Commuter 3": 1299, "Gravel X": 1890}[model]}
TOOLS = {"get_price": get_price} # name -> function, like tools=[get_price]
def fake_model(messages):
last = messages[-1]
if last["role"] == "user": # 1. the model asks for a tool call
return {"role": "assistant", "tool_call": {"name": "get_price", "arguments": '{"model": "Commuter 3"}'}}
price = json.loads(last["content"])["price_eur"]
return {"role": "assistant", "content": f"The Commuter 3 costs {price} EUR."} # 3. it answers
messages = [{"role": "user", "content": "How much is the Commuter 3?"}]
while True:
reply = fake_model(messages)
messages.append(reply)
if "tool_call" not in reply: # no tool call: this is the final answer
break
call = reply["tool_call"]
result = TOOLS[call["name"]](**json.loads(call["arguments"])) # 2. YOUR function runs here
messages.append({"role": "tool", "content": json.dumps(result)})
print("tool", call["name"], "->", messages[-1]["content"])
print(reply["content"])
print(len(messages), "messages: question, tool call, tool result, answer")Each trip to the model and back is one iteration. Agent Framework runs this loop for you, inside the chat client's FunctionInvocationLayer: it calls your function, sends the result back to the model, and repeats until the model answers without asking for a tool.
Your first tool
import asyncio
from typing import Annotated
from agent_framework import Agent, tool
from agent_framework.openai import OpenAIChatClient
PRICES = {"Commuter 3": 1299, "Gravel X": 1890, "City Kid 20": 349}
@tool
def get_price(model: Annotated[str, "The bike model, for example 'Commuter 3'"]) -> str:
"""Look up the price of a bike sold at Velo."""
price = PRICES.get(model)
return f"{model} costs {price} EUR." if price else f"Velo doesn't sell a bike called {model}."
async def main():
agent = Agent(
client=OpenAIChatClient(model="MODEL_NAME"),
instructions="You are Velo's shop assistant. Use your tools for prices and never guess.",
tools=[get_price],
)
response = await agent.run("How much are the Commuter 3 and the Gravel X?")
for message in response.messages:
for content in message.contents:
if content.type == "function_call":
print("call: ", content.name, content.arguments)
elif content.type == "function_result":
print("result:", content.result)
print(response.text)
asyncio.run(main())call: get_price {"model": "Commuter 3"}
call: get_price {"model": "Gravel X"}
result: Commuter 3 costs 1299 EUR.
result: Gravel X costs 1890 EUR.
The Commuter 3 costs 1299 EUR and the Gravel X costs 1890 EUR.@toolturns the function into aFunctionTool. Its name is the function's name, and its description is the docstring.Annotated[str, "..."]adds a description to one parameter.tools=[get_price]gives the tool to the agent. The model asked for two calls in one turn, one per bike.response.messagesshows the whole loop: thefunction_callcontents the model wrote, thefunction_resultcontents your function produced, and the final answer.
How type hints become a schema
The model receives each tool as a JSON schema, a standard description of the parameters. Agent Framework builds it from your type hints:
from typing import Annotated, Literal
from pydantic import Field
from agent_framework import tool
@tool(name="book_service", description="Book a repair slot in Velo's workshop.")
def book(
day: Literal["mon", "tue", "wed", "thu", "fri", "sat"],
hours: Annotated[int, Field(ge=1, le=4, description="How long the repair takes")] = 1,
parts: list[str] | None = None,
) -> str:
return f"Booked {hours} h on {day}."
print(type(book).__name__, "|", book.name, "|", book.description)
schema = book.parameters() # the JSON schema the model receives
for name, field in schema["properties"].items():
print(name, field)
print("required:", schema["required"])FunctionTool | book_service | Book a repair slot in Velo's workshop.
day {'enum': ['mon', 'tue', 'wed', 'thu', 'fri', 'sat'], 'title': 'Day', 'type': 'string'}
hours {'default': 1, 'description': 'How long the repair takes', 'maximum': 4, 'minimum': 1, 'title': 'Hours', 'type': 'integer'}
parts {'anyOf': [{'items': {'type': 'string'}, 'type': 'array'}, {'type': 'null'}], 'default': None, 'title': 'Parts'}
required: ['day']| Python | What the model sees |
|---|---|
str, int, float, bool | string, integer, number, boolean |
list[str] | an array of strings |
Literal["mon", "tue"] | an enum: only these values are allowed |
X | None = None | the value may be null; optional |
| any default value | optional: the parameter isn't in required |
Annotated[T, "text"] | a description for the parameter |
Annotated[T, Field(ge=1, le=4, description="...")] | a description plus limits (Pydantic's Field) |
| a Pydantic model | a nested object; your function receives it as a plain dict |
Before your function runs, the framework checks the model's arguments against the schema. If they don't fit, for example hours=10 here, your function isn't called and the model gets Error: Argument parsing failed. as the result, so it can correct itself.
Plain functions and FunctionTool
You don't always need the decorator:
import asyncio
from pydantic import BaseModel, Field
from agent_framework import Agent, FunctionTool
from agent_framework.openai import OpenAIChatClient
def get_opening_hours(day: str) -> str:
"""Return Velo's opening hours for a day of the week."""
return "closed" if day.lower() == "sunday" else "9:00 to 18:00"
class StockArgs(BaseModel):
model: str = Field(description="The bike model, for example 'Commuter 3'")
def count_bikes(model: str) -> int:
return {"Commuter 3": 4, "Gravel X": 0}.get(model, 0)
get_stock = FunctionTool(
name="get_stock",
description="Count how many bikes of a model are in the shop.",
func=count_bikes,
input_model=StockArgs, # the schema comes from this Pydantic model
)
async def main():
agent = Agent(
client=OpenAIChatClient(model="MODEL_NAME"),
instructions="You are Velo's shop assistant.",
tools=[get_opening_hours, get_stock], # a plain function is wrapped with tool() for you
)
print([(t.name, type(t).__name__) for t in agent.default_options["tools"]])
print((await agent.run("Are you open on Sunday, and is the Gravel X in stock?")).text)
asyncio.run(main())[('get_opening_hours', 'FunctionTool'), ('get_stock', 'FunctionTool')]
We're closed on Sundays, and the Gravel X is sold out at the moment.- A plain function in
tools=[...]is wrapped withtool()for you, using its name, docstring and type hints. - Use the decorator when you want to change something:
@tool(name=..., description=..., schema=..., approval_mode=..., max_invocations=...).schema=takes a Pydantic model or a JSON schema dictionary instead of the type hints. FunctionTool(...)builds a tool without a decorator: aname, adescription, thefuncto run and aninput_modelfor the parameters.approval_mode="always_require"makes the agent ask a person before the tool runs, which is the next lesson.
A FunctionTool with func=None is declaration only: the model can call it, but the agent doesn't run anything. The function_call comes back in response.messages for your own code to handle, for example to show a map in a phone app.
Async tools
Tools that wait for something, such as a web request or a database, should be async:
import asyncio
from agent_framework import Agent, tool
from agent_framework.openai import OpenAIChatClient
log = []
@tool
async def get_weather(city: str) -> str:
"""Get the current weather for a city."""
log.append(f"start {city}")
await asyncio.sleep(1) # stands in for a slow web request
log.append(f"end {city}")
return f"{city}: 19 °C and sunny"
async def main():
agent = Agent(client=OpenAIChatClient(model="MODEL_NAME"), instructions="You plan bike trips.", tools=[get_weather])
response = await agent.run("What's the weather like in Porto and in Braga?")
print(response.text)
print(log) # both calls started before either one ended
asyncio.run(main())Both cities are at 19 °C and sunny: a great day for a ride. ['start Porto', 'start Braga', 'end Porto', 'end Braga']
- An
async deftool is awaited. Use one for anything that waits on the network, a database or a file. - When the model asks for several calls in one turn, the framework runs them at the same time: both calls started before either ended, so the two one-second waits took about one second in total.
- A normal
deftool runs in a separate thread, so a slow one doesn't freeze the rest of your async program.
What a tool can return
- A string is sent as it is.
- Numbers, lists, dictionaries and Pydantic models are turned into JSON text, such as
{"model": "Commuter 3", "price_eur": 1299}. Contentitems, such as an image made withContent.from_data(...), are passed on unchanged for models that accept them.Nonebecomes an empty result.
Every result goes back to the model and costs tokens, so return what the model needs, not a whole database row.
Agent tools and run tools
Tools given to Agent(tools=...) are available in every run. Tools given to run(tools=...) are added for that run only:
import asyncio
from agent_framework import Agent, tool
from agent_framework.openai import OpenAIChatClient
@tool
def get_price(model: str) -> str:
"""Look up the price of a bike sold at Velo."""
return {"Commuter 3": "1299 EUR"}.get(model, "unknown")
@tool
def get_stock(model: str) -> int:
"""Count how many bikes of a model are in the shop."""
return {"Commuter 3": 4}.get(model, 0)
async def main():
agent = Agent(client=OpenAIChatClient(model="MODEL_NAME"), instructions="You are Velo's shop assistant.",
tools=[get_price]) # agent level: every run
response = await agent.run("How much is the Commuter 3, and is it in stock?",
tools=[get_stock]) # run level: this run only
print(response.text)
asyncio.run(main())The Commuter 3 costs 1299 EUR, and we have 4 in the shop.
The run could use both get_price and get_stock; the next run gets only get_price again. Run tools are handy when the tools depend on who's asking, for example staff-only tools for a staff member. Every tool in a run needs a different name.
Steering tool use with tool_choice
By default the model decides whether to call a tool. The tool_choice option changes that, for one run or, in default_options, for every run:
import asyncio
from agent_framework import Agent, ToolMode, tool
from agent_framework.openai import OpenAIChatClient
@tool
def get_price(model: str) -> str:
"""Look up the price of a bike sold at Velo."""
return {"Commuter 3": "1299 EUR"}.get(model, "unknown")
async def main():
agent = Agent(client=OpenAIChatClient(model="MODEL_NAME"), instructions="You are Velo's shop assistant.",
tools=[get_price])
hello = await agent.run("Hi! Who are you?", options={"tool_choice": "none"}) # no tool calls allowed
print(hello.text)
must_price = ToolMode(mode="required", required_function_name="get_price") # must call get_price
about = await agent.run("Tell me about the Commuter 3.", options={"tool_choice": must_price})
print(about.text)
print(must_price) # ToolMode is a dict
asyncio.run(main())Hi! I'm Velo's shop assistant: ask me about bikes, prices and repairs.
The Commuter 3 is our best-selling e-bike, and it costs 1299 EUR.
{'mode': 'required', 'required_function_name': 'get_price'}tool_choice | The model... |
|---|---|
"auto" | decides for itself (the default) |
"required" | must call at least one tool |
"none" | must answer without tools |
ToolMode(mode="required", required_function_name="get_price") | must call get_price |
ToolMode(mode="auto", allowed_tools=["get_price"]) | may use only the listed tools. OpenAIChatClient and GeminiChatClient support this; some clients ignore it with a warning, and OllamaChatClient raises an error |
ToolModeis a typed dictionary, so{"mode": "required", ...}works too.- After the first round of tool calls, the framework switches
requiredback to normal. Otherwise the model would have to call tools forever and could never write its answer. - The option
allow_multiple_tool_callssays whether the model may ask for several calls in one turn.
Limits for the tool loop
A confused model can call tools again and again, and every round costs time and money. FunctionInvocationConfiguration sets the limits for the loop:
import asyncio
from agent_framework import Agent, FunctionInvocationConfiguration, tool
from agent_framework.openai import OpenAIChatClient
@tool
def check_stage(stage: int) -> str:
"""Check whether one stage of the Douro bike route is open."""
return f"Stage {stage} is open."
async def main():
client = OpenAIChatClient(
model="MODEL_NAME",
function_invocation_configuration=FunctionInvocationConfiguration(
max_iterations=5, # at most 5 rounds of tool calls per run
max_function_calls=6, # at most about 6 tool calls per run
max_consecutive_errors_per_request=2, # give up on tools after 2 failing rounds in a row
include_detailed_errors=False, # the model only sees "Error: Function failed."
),
)
agent = Agent(client=client, instructions="Check every stage the user asks about.", tools=[check_stage])
response = await agent.run("Are all 12 stages of the Douro route open?")
calls = [c for m in response.messages for c in m.contents if c.type == "function_call"]
print(len(calls), "tool calls")
print(response.text)
print(client.function_invocation_configuration["max_iterations"])
asyncio.run(main())8 tool calls Stages 1 to 8 are open. I couldn't check stages 9 to 12, so please ask me again for those. 5
The model asked for four stages per round. After the second round, 8 calls had passed the limit of 6, so the framework switched tools off and asked the model for a final answer. Limits are checked after each round, so a run can go a little over.
| Setting | Default | Meaning |
|---|---|---|
max_iterations | 40 | Rounds of tool calls per run. Then one last call without tools |
max_function_calls | None (no limit) | Tool calls per run, in all |
max_duration_seconds | None | A time budget for the loop |
max_consecutive_errors_per_request | 3 | Failing rounds in a row before tools are switched off |
include_detailed_errors | False | Send the exception's text to the model |
terminate_on_unknown_calls | False | Raise an error when the model calls a tool that doesn't exist, instead of telling the model |
allow_concurrent_invocation | True | Run the calls of one turn at the same time |
enabled | True | False turns the tool loop off |
additional_tools | [] | Tools the loop may run that aren't offered to the model |
The configuration belongs to the client: pass it when you create the client, or change one key later, as in client.function_invocation_configuration["max_iterations"] = 8. Every agent that shares the client shares its limits.
When a tool fails
Real tools fail: a database is down, a website times out. Raising an exception doesn't crash the run:
import asyncio
from agent_framework import Agent, tool
from agent_framework.exceptions import ToolException
from agent_framework.openai import OpenAIChatClient
@tool
def get_stock(model: str) -> int:
"""Count how many bikes of a model are in the shop."""
raise ToolException("The stock database is offline.") # any exception behaves the same way
async def main():
agent = Agent(client=OpenAIChatClient(model="MODEL_NAME"), instructions="You are Velo's shop assistant.",
tools=[get_stock])
response = await agent.run("Is the Gravel X in stock?")
result = next(c for m in response.messages for c in m.contents if c.type == "function_result")
print("the model saw:", result.result)
print("the error was:", result.exception)
print(response.text)
asyncio.run(main())the model saw: Error: Function failed. the error was: The stock database is offline. Sorry, I can't check the stock right now. Please try again later or call the shop.
Your terminal also shows a warning:
Function 'get_stock' raised an exception; returning an error result to the model. Set include_detailed_errors=True for the full detail.
- The framework catches the exception and sends
Error: Function failed.to the model as the tool's result. The model can then apologise, try another tool or ask the user. - The real message stays in your program (
result.exception) and your logs. It reaches the model only withinclude_detailed_errors=True; switch that on only when error messages can't contain secrets, such as passwords in a database URL. - A model that calls a tool that doesn't exist gets
Error: Requested function "..." not found.
Agent Framework's own tool errors live in agent_framework.exceptions. ToolException is the base class for every tool error. ToolExecutionException is the subclass for "a tool failed while running", raised for example by MCP tools and agents used as tools. You can raise either in your tools, or any other exception; the loop treats them all the same. Outside the loop, when you call a tool yourself, nothing is caught:
from agent_framework import tool
from agent_framework.exceptions import ToolException, ToolExecutionException
@tool(max_invocations=1) # this tool object may run only once, ever
def send_welcome_coupon(email: str) -> str:
"""Send a one-time 10% discount coupon to a new customer."""
return f"Coupon sent to {email}."
print(send_welcome_coupon(email="[email protected]")) # a FunctionTool can be called like the function
try:
send_welcome_coupon(email="[email protected]")
except ToolException as error:
print(type(error).__name__, "->", error)
print(issubclass(ToolExecutionException, ToolException))Coupon sent to [email protected]. ToolException -> Function 'send_welcome_coupon' has reached its maximum invocation limit, you can no longer use this tool. True
max_invocations counts calls over the whole life of the tool object, across all runs and all users, and max_invocation_exceptions does the same for failures. For a limit per run, use max_function_calls instead.
Data the model must not choose
Some values must come from your program, never from the model: the logged-in customer's ID, for example. A parameter typed FunctionInvocationContext is filled in by the framework and hidden from the model:
import asyncio
from agent_framework import Agent, FunctionInvocationContext, tool
from agent_framework.openai import OpenAIChatClient
ORDERS = {"C-17": ["#1042 Commuter 3, shipped"], "C-99": ["#2001 City Kid 20, in the workshop"]}
@tool
def my_orders(ctx: FunctionInvocationContext) -> str:
"""List the orders of the customer who is chatting."""
customer_id = ctx.kwargs["customer_id"] # set by your code, never by the model
return "; ".join(ORDERS.get(customer_id, [])) or "No orders."
async def main():
agent = Agent(client=OpenAIChatClient(model="MODEL_NAME"), instructions="You are Velo's shop assistant.",
tools=[my_orders])
print(my_orders.parameters()["properties"]) # ctx is hidden from the model
response = await agent.run("Where is my order?", function_invocation_kwargs={"customer_id": "C-17"})
print(response.text)
asyncio.run(main()){}
Your order #1042, a Commuter 3, has been shipped.ctx.kwargs holds what you passed as function_invocation_kwargs to run(). A customer can't trick the model into reading someone else's orders, because the model never sees or sets the ID. The lesson Middleware shows more of what the context holds.
Common mistakes
Write the part of the @tool decorator that turns a function's name, docstring and type hints into a tool description.
import inspect
def book_service(day: str, hours: int = 1, express: bool = False):
"""Book a repair slot at Velo."""
JSON_TYPES = {str: "string", int: "integer", float: "number", bool: "boolean"}
# Describe book_service the way a tool schema does. First print "<name>: <docstring>",
# then one line per parameter: "<name>: <JSON type>", adding " (required)" if it has no default.
A tool raises an exception while an agent is running. What happens by default?
Summary
- A tool is a function the model asks your program to run; the tool loop runs it and sends the result back until the model answers.
@tool(or a plain function) becomes aFunctionTool: the docstring is its description, and type hints,AnnotatedandFieldbecome its JSON schema.async deftools are awaited, and calls from one turn run at the same time.Agent(tools=...)serves every run;run(tools=...)adds tools for one run.tool_choice("auto","required","none"or aToolMode) steers tool use;FunctionInvocationConfigurationlimits rounds, calls, time and errors.- A failing tool sends
Error: Function failed.to the model;ToolExceptionandToolExecutionExceptionare the framework's tool errors.
Next: Tool Approval and User Input.
Finished reading? Tick it off to track your progress.