Tool Calling: Models Asking for Functions

The model never runs code. It writes a request in JSON: which tool, which arguments. Your program reads it, runs the function, and sends back the result.

AI · beginner · 8 min · 11 steps · free

What you'll learn

tool_calling.py

import json

# The program tells the model which tools exist, described like this.
schema = {"name": "get_weather", "parameters": {"city": "string"}}

def get_weather(city):
    return {"Chennai": 33, "Delhi": 28}.get(city)

tools = {"get_weather": get_weather}

# The model does not run anything. It replies with a request, written as JSON.
reply = '{"tool": "get_weather", "arguments": {"city": "Chennai"}}'

call = json.loads(reply)
result = tools[call["tool"]](**call["arguments"])
message = {"role": "tool", "content": str(result)}
print(message)

Step by step

  1. json reads and writes the JSON text that models use for tool requests.
  2. The schema: a description of the tool, sent to the model along with the question. It says the tool is called get_weather and takes a city.
  3. The real function, in your program.
  4. A table from tool names to functions, so a name in the model's reply can be looked up.
  5. The model's reply to "How hot is it in Chennai?": not an answer, but a request in JSON.
  6. json.loads turns the text into a Python dict.
  7. Look up the tool by name and call it with the arguments. ** passes the dict as named arguments: city="Chennai".
  8. The tool looks up Chennai: 33.
  9. The result is 33.
  10. Wrap the result in a "tool" message to send back to the model.
  11. This message goes back to the model, which can now write: "It is 33°C in Chennai." The agent lesson runs this same exchange in a loop.

Common mistakes

Best practices

Key takeaways

Check yourself

The model replies {"tool": "get_weather", "arguments": {"city": "Delhi"}}. What does your program do?

Answer: Call get_weather(city="Delhi") and send back 28. The program runs the tool and returns its result to the model.

Why check the arguments before running a tool?

Answer: The model can make mistakes or be tricked. Treat the model's request like any untrusted input.

·

More in Building with Models