Tool Calling in Python: Describe a Function With JSON Schema, Run It, Send the Result Back
The problem: the model cannot run your code, it can only ask
Tool calling (also called function calling) sounds like the model runs functions. It does not. The model writes a structured request that says "call this function with these arguments". Your code decides whether to run it, runs it, and sends the result back. OpenAI's function calling guide describes it as a multi step conversation between your application and the model, and Ollama's tool calling docs describe the same flow.
That split is useful: you keep full control over what actually happens. But it means you must get three things exactly right:
- The description, so the model knows when to call the tool and what arguments to send.
- The parsing, so you turn the model's request into a real function call.
- The reply, so the model can match each result to the request it made.
The agent loop in lesson 2 did all three quickly. This lesson slows down and looks at each step on its own, using a currency converter for the trip helper.
Step by step: one tool call, printed
Save this as one_tool_call.py next to your llm.py:
python# file: one_tool_call.py import json from llm import client, MODEL # Made-up exchange rates for the course, not live data. FAKE_RATES_TO_EUR = {"EUR": 1.0, "USD": 0.92, "JPY": 0.0061, "INR": 0.011, "NOK": 0.085} def convert_currency(amount: float, from_currency: str, to_currency: str) -> dict: src, dst = from_currency.upper(), to_currency.upper() if src not in FAKE_RATES_TO_EUR or dst not in FAKE_RATES_TO_EUR: return {"error": f"Unsupported currency. Use one of {sorted(FAKE_RATES_TO_EUR)}."} value = amount * FAKE_RATES_TO_EUR[src] / FAKE_RATES_TO_EUR[dst] return {"amount": round(value, 2), "currency": dst} convert_tool = { "type": "function", "function": { "name": "convert_currency", "description": "Convert an amount of money from one currency to another.", "parameters": { "type": "object", "properties": { "amount": {"type": "number", "description": "How much money, e.g. 120.5"}, "from_currency": {"type": "string", "description": "ISO code, e.g. USD"}, "to_currency": {"type": "string", "description": "ISO code, e.g. JPY"}, }, "required": ["amount", "from_currency", "to_currency"], }, }, } messages = [{"role": "user", "content": "How much is 200 USD in Japanese yen?"}] # Request 1: the model sees the tool description and decides to call it. first = client.chat.completions.create(model=MODEL, messages=messages, tools=[convert_tool], temperature=0) choice = first.choices[0] print("finish_reason:", choice.finish_reason) if not choice.message.tool_calls: raise SystemExit("The model answered without a tool call: " + str(choice.message.content)) call = choice.message.tool_calls[0] print("call id:", call.id) print("function name:", call.function.name) print("raw arguments (a JSON string):", call.function.arguments) # Your code runs the function. The model never does. args = json.loads(call.function.arguments) result = convert_currency(**args) print("result:", result) # Request 2: send back the assistant turn plus a tool message with the same id. messages.append(choice.message) messages.append({"role": "tool", "tool_call_id": call.id, "content": json.dumps(result)}) second = client.chat.completions.create(model=MODEL, messages=messages, tools=[convert_tool], temperature=0) print("final answer:", second.choices[0].message.content)
When this was run with qwen2.5:1.5b on Ollama, the output was:
textfinish_reason: tool_calls call id: call_65959y6k function name: convert_currency raw arguments (a JSON string): {"amount":200,"from_currency":"USD","to_currency":"JPY"} result: {'amount': 30163.93, 'currency': 'JPY'} final answer: 200 USD is approximately 30,163.93 Japanese yen.
The id will be different every time. The amount comes from the made-up rates in the code, not from real exchange rates. Now look at each piece.
sequenceDiagram autonumber actor U as User participant P as Your code participant M as Model participant F as convert_currency U->>P: How much is 200 USD in Japanese yen? P->>M: Request 1: messages + tool JSON Schema M-->>P: finish_reason tool_calls, id, arguments Note over P,M: arguments is a JSON string:<br/>amount 200, USD to JPY P->>F: json.loads, then convert_currency(**args) F-->>P: amount 30163.93, currency JPY P->>M: Request 2: assistant turn + tool message, same id M-->>P: 200 USD is about 30,163.93 yen P-->>U: Final answer
Diagram: One tool call: the schema goes in, the model asks, your code runs the function, the result goes back with the same id.
The tool definition, field by field
pythonconvert_tool = { "type": "function", "function": { "name": "convert_currency", "description": "Convert an amount of money from one currency to another.", "parameters": { ... JSON Schema ... }, }, }
typeis always"function"for your own functions.nameis the identifier the model writes back. Use plainsnake_caseverbs likeconvert_currency. Names are part of the prompt; vague names likedo_itortool1make the model guess.descriptionis read by the model to decide when the tool applies. It is the most important text you write for a tool. Lesson 4 is about writing it well.parametersis a JSON Schema object.
The JSON Schema part
JSON Schema is a standard way to describe the shape of JSON data. For tool arguments you mostly need a small part of it:
json{ "type": "object", "properties": { "amount": {"type": "number", "description": "How much money, e.g. 120.5"}, "from_currency": {"type": "string", "description": "ISO code, e.g. USD"}, "to_currency": {"type": "string", "description": "ISO code, e.g. JPY"} }, "required": ["amount", "from_currency", "to_currency"] }
- The top level is always
"type": "object": arguments arrive as one JSON object with named keys. propertieslists each argument with its type:string,number,integer,boolean,arrayorobject.- A
descriptionper argument helps a lot, especially for format details like "ISO code". requiredlists the arguments the model must always send.enumlimits a string to a fixed set of values. Lesson 4 uses it.
OpenAI also supports a strict option for function definitions that makes the model's arguments follow your schema exactly, with extra rules such as additionalProperties: false. Strict mode is a feature of OpenAI's own models; when you run on another server, check its documentation and validate arguments in your code anyway.
Reading the model's reply
When the model decides to use a tool:
choice.finish_reasonis"tool_calls".choice.message.tool_callsis a list. Each item has anid, atypeof"function", and afunctionobject withnameandarguments.choice.message.contentis often empty.
The detail that trips people up: arguments is a string containing JSON, not a Python dict. Always parse it:
pythonargs = json.loads(call.function.arguments)
The model can produce invalid JSON or wrong keys, especially smaller models. In this lesson the code trusts it to keep things short. Lesson 4 adds a dispatcher that catches every one of those failures and turns it into an error message the model can read.
Sending the result back
The second request needs two new messages, in this order:
- The assistant message that contains the tool call (
choice.message). The SDK object can be appended directly. - A
toolmessage with the result:
python{"role": "tool", "tool_call_id": call.id, "content": json.dumps(result)}
The tool_call_id links the result to the request. If the model asked for three tools, you send three tool messages, each with its own id. Content is a string; JSON is a good choice because the model reads structured data well and you can log it easily.
Then you call the API again with the same tools list. The model now sees the number and writes the final sentence.
Animation: The model only asks. Your code parses the JSON arguments, runs convert_currency, and sends the result back with the same tool_call_id.
Generate schemas from Python functions
Writing JSON Schema by hand for every tool gets old quickly, and hand written schemas drift away from the real function signature. Python's type hints already contain most of the information. Save this as schema_from_function.py:
python# file: schema_from_function.py import inspect import json from typing import get_type_hints PY_TO_JSON = {str: "string", int: "integer", float: "number", bool: "boolean"} def tool_from_function(fn) -> dict: """Build an OpenAI style tool definition from a typed Python function.""" hints = get_type_hints(fn) properties, required = {}, [] for name, param in inspect.signature(fn).parameters.items(): properties[name] = {"type": PY_TO_JSON.get(hints.get(name, str), "string")} if param.default is inspect.Parameter.empty: required.append(name) return { "type": "function", "function": { "name": fn.__name__, "description": inspect.getdoc(fn) or "", "parameters": {"type": "object", "properties": properties, "required": required}, }, } def get_weather(city: str, days: int = 3) -> dict: """Get the weather forecast for a city for the next few days.""" return {"city": city, "days": days, "forecast": "sunny"} def convert_currency(amount: float, from_currency: str, to_currency: str) -> dict: """Convert an amount of money from one currency to another, using ISO codes like USD.""" return {} if __name__ == "__main__": for fn in (get_weather, convert_currency): print(json.dumps(tool_from_function(fn), indent=2))
Run it and it prints two complete tool definitions. The function's docstring becomes the description, each typed parameter becomes a property, and parameters without a default value become required. In the get_weather example, days has a default, so only city is required.
This helper only maps simple types. For lists, nested objects or enums, you can either extend it or use pydantic, which generates full JSON Schema from a model class with model_json_schema(). You will use that in lesson 5. The MCP SDK in lesson 13 does the same thing for you on the server side.
Several tool calls in one turn
Ask a question that needs two lookups and many models request both at once. Save this as parallel_calls.py:
python# file: parallel_calls.py import json from llm import client, MODEL from schema_from_function import tool_from_function FAKE_WEATHER = {"lisbon": "sunny, 22 C", "oslo": "cloudy, 6 C", "kyoto": "light rain, 17 C"} def get_weather(city: str) -> dict: """Get today's weather for one city. Call once per city.""" return {"city": city, "weather": FAKE_WEATHER.get(city.lower(), "unknown city")} FUNCTIONS = {"get_weather": get_weather} TOOLS = [tool_from_function(get_weather)] messages = [{"role": "user", "content": "Compare the weather in Lisbon and Oslo today."}] for _ in range(4): response = client.chat.completions.create(model=MODEL, messages=messages, tools=TOOLS, temperature=0) msg = response.choices[0].message messages.append(msg) if not msg.tool_calls: print("answer:", msg.content) break print(f"the model asked for {len(msg.tool_calls)} tool call(s) in one turn") for call in msg.tool_calls: # one tool message per call id, in any order result = FUNCTIONS[call.function.name](**json.loads(call.function.arguments)) print(" ", call.function.name, call.function.arguments, "->", result) messages.append({"role": "tool", "tool_call_id": call.id, "content": json.dumps(result)})
In the tested run, qwen2.5:1.5b asked for two get_weather calls in a single reply, one for Lisbon and one for Oslo, then compared them in the final answer. The loop handles this with no special code because it already iterates over every item in tool_calls and sends one tool message per id.
Some things to know about multiple calls:
- The OpenAI guide advises assuming a response can contain zero, one or several calls.
- The calls in one reply are meant to be independent. If one depends on another's result, the model will usually ask for them across separate turns.
- You can run independent calls concurrently (threads or
asyncio) to save time when tools are slow. The model does not care about the order of the tool messages, only that every id gets a reply. - OpenAI's chat completions API has a
parallel_tool_callsparameter to turn this behaviour off. Not every OpenAI compatible server supports every parameter, so check your server's docs before relying on it.
Forcing or blocking tool use
The tool_choice parameter controls whether the model may call tools. In the OpenAI API, "auto" lets the model decide, "none" blocks tools, "required" forces at least one call, and you can name one specific function. Ollama's OpenAI compatibility page lists tool_choice among its request fields, but support can differ between servers and versions, so the code in this course does not depend on it. Clear descriptions and a system rule like "use tools for facts" work across providers.
Common mistakes
- Treating
argumentsas a dict. It is a JSON string. Parse it. - Forgetting to resend
toolson the second call. The model may want another tool after reading the first result. - One tool message for several calls. Each call id needs its own tool message.
- Returning Python objects as content. Convert to a string;
json.dumpswithdefault=strhandles dates and other awkward types. - Trusting argument values. The model can send a negative amount or a currency you do not support. Validate in your function (lesson 4).
What to try next
- Ask
one_tool_call.pya question with no money in it, such as "Tell me a joke". The code exits early because no tool was called. That is the model correctly deciding a tool is not needed. - Add a
days: int = 3parameter toparallel_calls.py'sget_weatherand check that the generated schema marks it as optional. - Ask "Compare Lisbon, Oslo and Kyoto" and count the calls in one turn.
- Write a third tool with the helper, such as
get_local_time(city: str), and add it toFUNCTIONSandTOOLS.
Module 1 is done: you can call a model, keep a conversation, and run a full tool loop. Module 2 makes the tools themselves reliable, starting with how to design them so a model uses them correctly.
Sources
Turn a typed Python function into a tool definition
The model only sees a description of your tool, written as JSON Schema. Writing it by hand drifts out of date, so generate it from the function.
Write tool_schema(fn) that returns:
{"type": "function", "function": {"name": fn's name, "description": its docstring (stripped, "" if none), "parameters": {"type": "object", "properties": {...}, "required": [...]}}}
Each parameter becomes a property whose "type" comes from its annotation: int is "integer", float is "number", str is "string", bool is "boolean". A parameter is required only if it has no default value. Keep parameters in the order they are defined.
Tip: the inspect module gives you inspect.signature(fn).parameters.
The worked solution unlocks after your first attempt.
Check what you learned
Answer all 3 questions. You need at least 2 right to pass.
1. What type is call.function.arguments in the chat completions response?
2. The model asks for two tool calls in one reply. What should your code send back?
3. In the generated schema, why is days not in required for get_weather(city, days=3)?