Monday , November 30 2026
How LLM function calling and tool use work: the tool loop simulated in tested Python, JSON Schema tools, OpenAI and Anthropic examples and safety tips.

LLM Function Calling and Tool Use Explained (Python)

Updated: 29 November 2026Level: IntermediateReading time: about 10 minutesPython · tested simulation + OpenAI / Anthropic SDK

Function calling (also called tool use) lets an LLM ask your code to run a function – check the weather, query a database, send an email – and then use the result in its answer. It is the building block of every AI agent.

What You Will Learn

  • The tool-use loop
  • Describe tools with JSON Schema
  • Simulate the loop in plain Python
  • Real code with the OpenAI and Anthropic APIs
  • Safety rules for tools

Prerequisites

OpenAI API.

How It Works

  1. You send the user message plus a list of tools (name, description, parameters).
  2. The model either answers directly or returns a tool call: a function name and JSON arguments. The model never runs code itself.
  3. Your code runs the function and sends the result back.
  4. The model writes the final answer – or calls another tool. Repeat until done.

The Loop in Plain Python

Here a fake LLM stands in for the real one so you can see the control flow without an API key.

Example
import json

def get_weather(city: str) -> dict:
    data = {"Ludhiana": 18, "Delhi": 21, "Mumbai": 29}       # pretend weather service
    return {"city": city, "temp_c": data.get(city)}

TOOLS = {"get_weather": get_weather}

def fake_llm(messages):
    last = messages[-1]
    if last["role"] == "user":                                # decide to call a tool
        return {"tool_call": {"name": "get_weather", "arguments": json.dumps({"city": "Ludhiana"})}}
    result = json.loads(last["content"])                      # use the tool result
    return {"content": f"It is {result['temp_c']}°C in {result['city']} right now."}

messages = [{"role": "user", "content": "What's the weather in Ludhiana?"}]
while True:
    reply = fake_llm(messages)
    if "tool_call" in reply:
        call = reply["tool_call"]
        args = json.loads(call["arguments"])
        print("model asks for:", call["name"], args)
        result = TOOLS[call["name"]](**args)
        messages.append({"role": "tool", "name": call["name"], "content": json.dumps(result)})
    else:
        print("final answer:", reply["content"])
        break
Output
model asks for: get_weather {'city': 'Ludhiana'}
final answer: It is 18°C in Ludhiana right now.

Explanation: This while loop is the core of every agent: call the model, execute any requested tools, append results, repeat until the model returns plain text.

With the OpenAI API

OpenAI Responses API (not run here – needs an API key; model names change, check the docs)
from openai import OpenAI
import json
client = OpenAI()
tools = [{"type": "function",
          "name": "get_weather",
          "description": "Current temperature for a city",
          "parameters": {"type": "object",
                         "properties": {"city": {"type": "string"}},
                         "required": ["city"]}}]
inp = [{"role": "user", "content": "What's the weather in Ludhiana?"}]
resp = client.responses.create(model="gpt-4.1-mini", input=inp, tools=tools)
for item in resp.output:
    if item.type == "function_call":
        result = get_weather(**json.loads(item.arguments))
        inp += [item, {"type": "function_call_output", "call_id": item.call_id,
                       "output": json.dumps(result)}]
final = client.responses.create(model="gpt-4.1-mini", input=inp, tools=tools)
print(final.output_text)

With the Anthropic API

Anthropic Messages API (not run here – needs an API key)
import anthropic
client = anthropic.Anthropic()
tools = [{"name": "get_weather", "description": "Current temperature for a city",
          "input_schema": {"type": "object", "properties": {"city": {"type": "string"}},
                           "required": ["city"]}}]
msg = client.messages.create(model="claude-sonnet-5-5", max_tokens=500, tools=tools,
                             messages=[{"role": "user", "content": "Weather in Ludhiana?"}])
# if msg.stop_reason == "tool_use": run the tool, then send a "tool_result" block back

Writing Good Tools

Tip Why
Clear names and descriptions The model chooses tools from the description
Strict JSON Schema with required fields and enums Fewer malformed arguments
Return small, structured JSON Saves tokens, easier to reason about
Validate arguments in your code Models can still produce wrong values
Return helpful error messages The model can retry with fixed arguments
Note: Safety: treat tool arguments as untrusted input. Never pass them straight into SQL, shell commands or file paths. Ask for human confirmation before irreversible actions (payments, emails, deletions). Content returned by tools (web pages, emails) can contain prompt-injection text – see LLM Hallucinations & Risks.

To share tools across many apps instead of re-defining them per API, use the Model Context Protocol (MCP).

Series

Generative AI series: Intro to GenAI · LLM Fundamentals · Tokenization · Embeddings · Prompt Engineering · RAG · Vector DBs · Function Calling · AI Agents · Agent Frameworks · MCP · Hallucinations · Run LLMs Locally · Diffusion Models

Interview Questions

Q: Does the LLM execute the function?
No. It returns the function name and arguments; your application executes it and returns the result.

Q: How are tools described to the model?
With a name, a natural-language description and a JSON Schema for parameters.

Q: What is parallel tool calling?
The model requests several independent tool calls in one turn, which your code can run concurrently.

Practice Exercises

  1. Add a convert_currency(amount, to) tool to the simulation and route a second question to it.
  2. Connect the loop to a real API and limit it to 5 iterations to avoid infinite loops.

Summary

Function calling = model proposes a call, your code runs it, the result goes back. Describe tools clearly, validate arguments, limit iterations and confirm risky actions.

Next: AI Agents · Model Context Protocol

About Machine Learning

Check Also

LLM Hallucinations and Prompt Injection: Causes and Fixes

Why LLMs hallucinate, types of hallucination, techniques like RAG and grounding to reduce them, prompt injection risks and a safety checklist for LLM apps.