Tools and Function Calling
A model can only write words. It cannot do math, check the weather, or look in your database.
Tools fix that. A tool is a Python function you hand to the model.
Think of a toolbox. The model does not swing the hammer. It tells you which tool to use and how. You swing it and report back.
Make a tool
Put @tool on a normal function. Add type hints and a docstring.
The docstring is how the model learns what the tool does. The type hints tell it what arguments to send.
Bad docstring, bad tool use. Write it like a label on a drawer.
Give the tools to the model
bind_tools attaches the toolbox. The model can now ask for a tool instead of answering in words.
Look at the output. The content is empty. The interesting part is in tool_calls.
Reading a tool call
A tool call is a small dictionary. It says which tool and which arguments.
The model did not multiply anything. It only asked for the multiply tool with a=12 and b=7. Running it is your job.
Run the tool and report back
Call tool.invoke(tool_call). It runs the function and returns a ToolMessage ready to send back.
We keep a list of messages. Human question, model request, tool result, then the model writes the final words.
The ToolMessage carries the tool call id so the model knows which request it answers.
A minimal loop
Sometimes the model wants several tools in a row. A while loop handles that.
Ask, run tools, ask again. Stop when the model answers with words and no tool calls. That loop is the heart of an agent.
Tips for good tools
One job per tool. Small tools are easier for the model to pick.
Clear docstring. Say what it does and when to use it.
Type hints on every argument. The model uses them to build the args.
Return short, plain results. The model has to read them.
Remember: the model never runs a tool. It only asks. You run it and send a ToolMessage back.
Test yourself
Three quick questions made just for this lesson. Earn 10 XP per correct answer.