DEV Community

Cover image for How LLM Tool Calling Actually Works (The AI Never Runs Your Code)
Muiduzzaman Lipu for Refactorly

Posted on

How LLM Tool Calling Actually Works (The AI Never Runs Your Code)

When an AI assistant "checks your order" or "looks up the weather", it feels like the model runs code. It doesn't. The model only writes a function name and some JSON arguments. Your code does everything else. Let's build the whole loop from scratch with a local model and look at every step.

Setup: llama3.2:3b in Ollama with the ollama Python library (0.6). Every output below is real.

Video version:

The loop in 4 steps

  1. You → model: the question, plus a list of tools it may ask for.
  2. Model → you: "please call get_order_status with order_id='A-1042'".
  3. Your code runs the function.
  4. You → model: the result. The model writes the final answer.

Step 1: describe the tool

tools = [{
  "type": "function",
  "function": {
    "name": "get_order_status",
    "description": "Look up the shipping status of an order",
    "parameters": {
      "type": "object",
      "properties": {"order_id": {"type": "string", "description": "like A-1042"}},
      "required": ["order_id"],
    },
  },
}]
Enter fullscreen mode Exit fullscreen mode

The model never sees your function's code, only this description. Write it like documentation for a new teammate.

Step 2: the model writes JSON, nothing else

import json, ollama

msgs = [{"role": "user", "content": "Where is my order A-1042?"}]
r = ollama.chat(model="llama3.2:3b", messages=msgs, tools=tools)
Enter fullscreen mode Exit fullscreen mode
>>> r.message.content
''
>>> r.message.tool_calls
[ToolCall(function=Function(name='get_order_status', arguments={'order_id': 'A-1042'}))]
Enter fullscreen mode Exit fullscreen mode

No text, just a request. Nothing has run yet.

Steps 3 & 4: run it, send the result back

ORDERS = {"A-1042": {"status": "shipped", "eta": "2026-12-02"}}

def get_order_status(order_id):
    return ORDERS.get(order_id, {"error": "order not found"})

msgs.append(r.message)
for call in r.message.tool_calls:
    result = get_order_status(**call.function.arguments)   # YOUR code runs here
    msgs.append({"role": "tool",
                 "tool_name": call.function.name,
                 "content": json.dumps(result)})

final = ollama.chat(model="llama3.2:3b", messages=msgs, tools=tools)
print(final.message.content)
Enter fullscreen mode Exit fullscreen mode
Your order A-1042 has been shipped. The estimated delivery date is December 2, 2026. ...
Enter fullscreen mode Exit fullscreen mode

The model turned {"status": "shipped", "eta": "2026-12-02"} into a sentence. It never touched the "database".

One detail that bit me: with this small model, leaving tools= out of the second call made it ignore the tool result and reply "I don't have access to real-time information". Passing the same tools again fixed it.

The catch: the model picks the arguments

I asked: "What's the capital of France?" with the same tool available, 10 times:

get_order_status(order_id='Paris')        ×4
get_order_status(order_id='Paris-1234')   ×2
get_order_status(order_id='France')       ×1
get_order_status(order_id='Paris-1')      ×1
get_order_status(order_id='FR-1234')      ×1
get_order_status(order_id='None')         ×1
Enter fullscreen mode Exit fullscreen mode

10 out of 10 runs called the order tool, with made-up IDs. That's a small 3B model, but any model can produce arguments you didn't expect, and with prompt injection, an attacker can try to steer them.

Treat tool arguments like user input

import re

def get_order_status(order_id):
    if not re.fullmatch(r"A-\d+", order_id):
        return {"error": "invalid order id"}
    return ORDERS.get(order_id, {"error": "order not found"})
Enter fullscreen mode Exit fullscreen mode
>>> get_order_status("Paris")
{'error': 'invalid order id'}
Enter fullscreen mode Exit fullscreen mode

In a real app, also check that the current user owns that order, in your code. Never rely on the prompt for permissions. Returning a clear error lets the model ask the user for a valid ID.

Where MCP fits

MCP (Model Context Protocol) is a standard way to describe and share tools like this between apps, so one tool server works in many AI clients. Under the hood, it's the same loop: a description goes in, a tool call comes out, your code runs it.

Cheat sheet

  • The model never runs code: it returns a tool call (a name + JSON arguments).
  • A tool = name + description + JSON schema for the parameters.
  • Your code runs the function and sends the result back as a tool message.
  • Tool arguments are a guess: validate them like user input.
  • Check permissions in your code, not in the prompt.
  • MCP = a standard way to share these tools.

What tool would you give your AI first? 👇


I post one tested coding tip every day on YouTube at Refactorly. The 30-second version of this one is here.

Top comments (1)

Collapse
 
ahmetozel profile image
Ahmet Özel •

Walking through all four turns in plain Python makes it crystal clear that the model never touches your database—it only emits structured intent while your application validates arguments, runs the function, and injects the serialized result back into message history.

That small-model gotcha where omitting tools= on the second Ollama call caused llama3.2:3b to ignore the returned tool payload and claim it lacked real-time access is a super practical catch. Always validating tool arguments against a strict schema before execution—and testing irrelevant prompts like "capital of France" to ensure the model does not spuriously invoke order lookup—closes the most common beginner loop bugs.