All guides

Ollama tool calls: execute a function and return its result

Complete one tool round with fixed weather data, checking function names, arguments and message order.

AINavWritten / Updated Sources checked
On this page

At a glance

Ollama tool calling lets a model propose a function and its arguments. Your application executes the function and sends its result back to the model. This example completes one round using a fixed temperature table: the user asks about New York, the application queries the table, and the model receives the result. The temperatures are teaching data, not live weather. Keep the complete message record and a reply you can check; inspect the response to see whether the model actually requested a tool.

Task flow

  1. Question and function description

    Give the question and the input description of get_temperature to a model that supports tool calling.

  2. Application execution

    Read every tool_calls item, check its function name and arguments, and execute the local function.

  3. Result returned to the model

    Keep the assistant message, append tool messages with tool_name, then make one follow-up chat request.

The arrows show data and checks for this task; branches are explained in the text.

Prepare the model and example

You need a working Ollama service, an available qwen3 model and the Ollama Python library. The documentation uses this model and interface. No service was installed, model downloaded or inference run for this article. Confirm that ordinary chat works in your own environment before saving the script as tool_weather.py.

Define the executable scope

The function accepts one string, city, and reads only a demonstration dictionary. The Python client can use a function directly as a tool description; the name, parameter type and docstring help the model choose a call. The application still validates names and arguments before dispatch. A model response is not permission to run an arbitrary function. Unknown cities return Unknown rather than an invented temperature.

Code for one complete round

Run python tool_weather.py in an already working Python environment. The script handles every tool call in the first response and appends one result message for each. If the follow-up asks for more tools, it stops so that a separate loop can define its limits and termination rules.

Example: tool calling with a fixed temperature table
python
from ollama import chat


def get_temperature(city: str) -> str:
    """Return a temperature from a fixed demonstration dataset.

    Args:
        city: City name in the demonstration dataset.
    """
    temperatures = {"New York": "22°C", "London": "15°C"}
    return temperatures.get(city, "Unknown")


messages = [{"role": "user", "content": "What is the temperature in New York?"}]
response = chat(model="qwen3", messages=messages, tools=[get_temperature], think=True)
messages.append(response.message)

if not response.message.tool_calls:
    print(response.message.content)
else:
    for call in response.message.tool_calls:
        if call.function.name != "get_temperature":
            raise ValueError("Unexpected tool name")
        args = call.function.arguments
        if set(args) != {"city"} or not isinstance(args["city"], str):
            raise ValueError("Unexpected tool arguments")
        result = get_temperature(**args)
        messages.append({
            "role": "tool",
            "tool_name": call.function.name,
            "content": result,
        })
    final = chat(model="qwen3", messages=messages, tools=[get_temperature], think=True)
    if final.message.tool_calls:
        raise RuntimeError("Another tool round requires explicit handling")
    print(final.message.content)

Keep the assistant message

Calling messages.append(response.message) before adding results retains the calls the model actually requested, along with its other returned message fields. Each subsequent role: tool message names the original function and carries its result in content. Sending “22°C” as a new user message loses this tool round context. The documented single and multiple tool examples both preserve this order.

Check the result

Checks for the New York example
LocationWhat to inspect
First responseIf a call exists, its name is get_temperature and city is a string
Function outputNew York maps to the teaching value 22°C; unknown keys return Unknown
Follow-up requestThe assistant message precedes the tool result for every call
Final responseNo further tool call; the prose can be compared with the function result

The model chooses its wording; there is no fabricated observed reply here. If the first response has no tool_calls, the script prints that response. This shows that no tool was requested in that round, not that the function ran.

Stop at the failing step

  • Reject an unexpected function name or argument shape before executing the function.
  • Resolve an unavailable service, missing model or incompatible client before claiming a result. Do not create a successful tool message for an operation that never returned.
  • Stop if the follow-up requests another tool round. A multi-round agent needs explicit limits and termination conditions.

Verification and limits

The official tool-calling documentation and its message interfaces were read. The code is an original teaching example adapted from that material. No service was installed, inference executed or model output observed. This function writes no files, makes no network request and charges nothing itself. Tools with those effects need their own permission, input validation and failure policy.

Article sources

Original editorial content; official descriptions and checking suggestions are distinguished.

  1. Ollama · Official sources
    View details