Tool Use & Function Calling
After this lesson, you will be able to:
- Follow the complete 7-step tool use flow: user asks a question, the AI decides which tool to call, your code runs the tool, and the AI explains the result
- Write a clear tool schema in JSON format so the AI knows what the tool does and what inputs it needs
- Understand the critical separation: the AI *decides* which tool to use, but *your code* actually runs it (the AI never touches the real API)
- Describe tool chaining, how agents call one tool, use the result to decide the next tool, and build multi-step workflows on the fly
- See how the quality of your tool descriptions directly determines whether the AI picks the right tool
Before you start
Lesson scope note: This lesson covers the 7-step tool use flow, JSON Schema tool design, and tool chaining, the conceptual and practical layer that most developers work with daily. For the token-level generation mechanics, parallel execution with asyncio, and Pydantic validation patterns, see Function Calling Internals (Lesson 3).
Tool use is where agents go from "smart talker" to "useful worker." This lesson is the mechanical heart of everything in this track, once you understand these 7 steps, every agent framework and every tool-using AI will make perfect sense.
#Reaching for the Calculator
#The 7-Step Tool Use Flow
The flow has seven distinct steps. Understanding each one is critical because a common misconception is that the LLM "runs" the tool. It absolutely does not. Here is what actually happens:
{"tool": "get_weather", "args": {"city": "San Francisco"}}. This is machine-readable, not human prose.Figure
The work splits across a boundary that matters. On one side the LLM decides: it emits a structured tool call such as {"tool": "get_weather", "args": {"city": "SF"}}. On the other side your code executes: it receives that JSON, validates it, calls the real API, and returns the result. The model never touches the API itself, it only ever asks. Everything that actually runs stays under your control, which is what makes tool use safe to deploy.
#Step 1: User Message
#Step 2: LLM Receives Message + Tool Schemas
get_weather, search_web, send_email. Each tool includes its name, description, and parameter schema in JSON format. The LLM reads all of this before deciding what to do.#Step 3: LLM Decides to Use a Tool
#Step 4: Structured JSON Output
{"tool": "get_weather", "arguments": {"location": "San Francisco, CA", "units": "fahrenheit"}}. This is a precise, machine-readable request, not a natural language description of what it wants.#Step 5: Your Code Executes the Tool
GET https://api.weather.service/v1/current?location=San+Francisco,CA. The API returns: {"temperature": 62, "condition": "Partly cloudy", "humidity": 73}.#Step 6: Result Sent Back to LLM
Your code packages the API response and sends it back to the LLM as a "tool result" message in the conversation. The LLM now has concrete data to work with.
#Step 7: Final Natural Language Response
#Interactive: Function Calling Flow
Step through the complete tool use flow above. Click each node in the flow diagram or use the play controls. Notice the different message types: user messages (cyan), LLM thinking (purple), structured JSON (amber), tool execution (green).
#End-to-End: The Complete Tool Use Flow
#Step 1: User Message
#Step 2: LLM Decides Tool Needed
get_stock_price tool that takes a ticker symbol. I should use it." The decision to call a tool vs. respond directly is the first critical junction.#Step 3: LLM Outputs Structured JSON
{"tool": "get_stock_price", "arguments": {"ticker": "AAPL"}}. This is machine-readable JSON, the tool name plus properly typed arguments matching the schema. The LLM's job is done for now.#Step 4: YOUR CODE Parses the JSON
Your application receives the structured JSON from the LLM API response. Your code validates the tool name exists, checks that required arguments are present, verifies argument types match the schema, and sanitizes inputs. This validation layer is your first line of defense against hallucinated or malicious tool calls.
#Step 5: YOUR CODE Executes the Tool
GET https://api.stockdata.com/v1/price?ticker=AAPL. This is real code running on your server, with your API keys, your error handling, your rate limiting, and your security controls. The LLM never touches your systems directly.#Step 6: Tool Returns Result
{"ticker": "AAPL", "price": 227.43, "change": "+1.2%", "volume": "52.3M"}. Your code captures this result. You can filter, transform, or truncate the data before sending it back, you control exactly what the LLM sees.#Step 7: Result Sent Back to LLM
Your code sends the tool result back to the LLM as a new message in the conversation with the role "tool". The LLM now has the concrete, real-time data it needed. The context has grown: user message + tool call + tool result.
#Step 8: LLM Generates Final Response
#Tool Schemas: Teaching the LLM What Tools Exist
The LLM does not magically know about your tools. You have to describe them, and the quality of your descriptions directly affects how well the LLM uses them. Tool schemas follow a standard format: a name, a description, and a JSON Schema for the parameters.
Tests: Write the calculator tool schema with both properties, clear descriptions with examples, and the correct required fields.
#The Difference Between Good and Bad Schemas
Compare these two schemas for the same tool:
Try it! Open the Anthropic or OpenAI API docs and try sending a simple tool call. Define a tool called "get_weather" with one parameter "city", send the message "What is the weather in Paris?", and watch the model respond with a structured JSON tool call instead of text. You will instantly see the 7-step flow in action.
Bad schema
{
"name": "weather",
"description": "Gets weather",
"parameters": {
"type": "object",
"properties": {
"loc": { "type": "string" }
}
}
}
Good schema
{
"name": "get_weather",
"description": "Get current weather conditions for a location. Use when the user asks about current weather, temperature, or forecast. Do NOT use for historical weather or climate data.",
"parameters": {
"type": "object",
"properties": {
"location": {
"type": "string",
"description": "City and state/country, e.g. 'San Francisco, CA' or 'London, UK'"
},
"units": {
"type": "string",
"enum": ["fahrenheit", "celsius"],
"description": "Temperature units. Default to fahrenheit for US, celsius otherwise."
}
},
"required": ["location"]
}
}
The bad schema leaves the LLM guessing. What does "loc" mean? Is it a city name, a zip code, coordinates? When should the model use this tool? The good schema removes all ambiguity. The description tells when to use it and when not to. The parameter descriptions include format examples. The enum constrains valid values. Every detail reduces the chance of a wrong tool call.
#Anatomy of a Great Tool Schema
Three parts make or break a tool schema:
get_weather is better than weather or weatherAPI. search_products beats products_endpoint. The name is the first signal the model uses for tool selection."location" but "City and state/country, e.g. 'San Francisco, CA' or 'Tokyo, Japan'". The examples serve as few-shot demonstrations embedded in the schema itself.You give an LLM access to 50 tools instead of 5 well-chosen tools. What happens to its tool selection accuracy?
The model emits {"tool": "get_weather", "arguments": {"location": 12345}}. The schema says location is a string. What should your runtime do?
Research consistently shows that tool selection accuracy degrades as the number of tools increases. With 5 well-described tools, models pick the right one almost every time. With 50, they start confusing similar tools, hallucinating parameters, or defaulting to the first tool in the list. The practical solution: give agents only the tools they need for the current task, or use a two-stage approach where one LLM call selects the relevant tools and a second one uses them. Some frameworks call this "tool routing."
#Tool Chaining: When One Tool Is Not Enough
Consider the question: "What is the weather like where my next meeting is?"
- Call
get_calendar(next=true), returns: "Meeting at 2pm, location: 450 Serra Mall, Stanford, CA" - Extract the location from the calendar result: "Stanford, CA"
- Call
get_weather(location="Stanford, CA"), returns: "72 degrees F, sunny" - Respond: "Your next meeting is at 2pm at Stanford. It will be 72 degrees and sunny, no need for a jacket!"
A more complex chain might look like: search for a product, check inventory at the user's nearest store, calculate a price with tax, and generate a summary. Four tools, each output feeding the next, all orchestrated by the LLM's reasoning in real time.
#Parallel Tool Calls
Modern LLM APIs support calling multiple tools simultaneously. If the user asks "What is the weather in New York and San Francisco?", the agent can issue both calls at once rather than waiting for the first result before sending the second:
[
{"tool": "get_weather", "arguments": {"location": "New York, NY"}},
{"tool": "get_weather", "arguments": {"location": "San Francisco, CA"}}
]
Both API calls execute in parallel, the results come back together, and the agent synthesizes them into a single response. This is a significant latency optimization for tasks that require multiple independent pieces of information. The LLM decides whether tools can be called in parallel or must be sequential based on whether there are data dependencies between them.
#When Tools Go Wrong: Error Patterns
In production, tool calls fail more often than they succeed on the first try. Common failure patterns:
#Key Takeaways
- The LLM decides what to call; your code executes it. This critical separation means the LLM generates structured tool call requests (function name + arguments) but never runs code directly, maintaining safety and control
- Tool description quality directly impacts agent performance. Clear, specific descriptions with examples help the LLM choose the right tool and pass correct arguments; vague descriptions cause misuse and errors
- Tool chaining enables complex multi-step workflows. Agents compose simple tools (search, calculate, write) into sophisticated pipelines at runtime, with each tool's output feeding into the next decision
- JSON Schema defines the contract between LLM and tools. Well-structured schemas with types, descriptions, enums, and required fields prevent argument errors and make tool behavior predictable
#Quick Check
In the tool use flow, who actually executes the tool function?