Function calling lets a language model ask your program to run a function instead of guessing the answer. With llama.cpp you can do this completely locally: the model only returns the name of a function and its arguments as JSON, and your Python code runs it. This tutorial shows function calling with llama.cpp from the first request to a small tool loop, including what happens with bad arguments and how reliable a small model is. I tested it with llama.cpp 1.1.0-dev (build 12826), Python 3 and the model Qwen3.5-4B (Q4_K_M) on a machine with 8 CPU cores and no GPU. All results are from 2 December 2026 and apply to this setup only.
How function calling works in llama.cpp
The model never executes anything. You send the normal chat request to the server and add a list of tools, each with a name, a description and a JSON schema for the parameters. The model decides whether it needs one. If so, the answer does not contain text but a tool call, and the finish reason is tool_calls. Your program runs the function, appends the result as a message with the role tool and asks again. Now the model writes the final answer. This is the same message format that the OpenAI API uses, and the llama.cpp server accepts it on /v1/chat/completions. If you want to use an existing OpenAI client library, you only change the base URL.
Which tool call formats a model can produce depends on its chat template, which is part of the GGUF file. The function calling documentation of llama.cpp lists the supported model families and flags. In my setup I did not need a special flag for Qwen3.5. For other models, check that page first.
Start the server
If you have not set up llama.cpp yet, the tutorial Run a Local LLM with the llama.cpp Server covers the installation. For this tutorial one command is enough:
llama serve -hf ggml-org/Qwen3.5-4B-GGUF --no-mmproj --reasoning off -c 8192 --port 9931
The first start downloads the model from Hugging Face. I use --reasoning off so that the model answers directly without a thinking phase; I did not compare this with thinking switched on. The server listens on port 9931 and generated about 21 tokens per second on my CPU. A question with one tool call, which means two requests with the function output in between, took about 3 seconds in each of three runs.
The first request: what a tool call looks like
A tool definition is a JSON object. The classic example in the OpenAI documentation is a function for the current weather. That needs an external service, so I use three functions that run on any machine: free disk space of a directory, the SHA-256 hash of a file in a demo folder, and the addition of two numbers. The parameters are described with a JSON schema, and the descriptions are what the model reads to choose the right function.
This is the complete script tools.py. It contains the three tools, a function chat for the request, a function run_tool that executes a call safely, and the loop ask:
import hashlib, json, os, shutil, urllib.request
URL = "http://127.0.0.1:9931/v1/chat/completions"
TOOLS = [
{"type": "function", "function": {
"name": "disk_free",
"description": "Return free and total disk space in gigabytes for a directory path.",
"parameters": {"type": "object",
"properties": {"path": {"type": "string", "description": "Directory path, e.g. /tmp"}},
"required": ["path"]}}},
{"type": "function", "function": {
"name": "sha256_of_file",
"description": "Return the SHA-256 hash of a file inside the demo folder.",
"parameters": {"type": "object",
"properties": {"filename": {"type": "string", "description": "File name inside the demo folder"}},
"required": ["filename"]}}},
{"type": "function", "function": {
"name": "add",
"description": "Add two numbers.",
"parameters": {"type": "object",
"properties": {"a": {"type": "number"}, "b": {"type": "number"}},
"required": ["a", "b"]}}},
]
DEMO_DIR = os.path.abspath("demo_files")
def disk_free(path):
usage = shutil.disk_usage(path)
return {"free_gb": round(usage.free / 1e9, 1), "total_gb": round(usage.total / 1e9, 1)}
def sha256_of_file(filename):
full = os.path.abspath(os.path.join(DEMO_DIR, filename))
if os.path.dirname(full) != DEMO_DIR: # block ../ and absolute paths
return {"error": "file is outside the demo folder"}
with open(full, "rb") as f:
return {"sha256": hashlib.sha256(f.read()).hexdigest()}
def add(a, b):
return {"sum": a + b}
REGISTRY = {"disk_free": disk_free, "sha256_of_file": sha256_of_file, "add": add}
def chat(messages, **extra):
payload = {"model": "local", "messages": messages, "tools": TOOLS, "temperature": 0, **extra}
req = urllib.request.Request(URL, json.dumps(payload).encode(), {"Content-Type": "application/json"})
with urllib.request.urlopen(req, timeout=300) as resp:
return json.load(resp)["choices"][0]
def run_tool(call):
name = call["function"]["name"]
try:
args = json.loads(call["function"]["arguments"])
return json.dumps(REGISTRY[name](**args))
except Exception as exc: # unknown tool, bad JSON, wrong arguments
return json.dumps({"error": f"{type(exc).__name__}: {exc}"})
def ask(question, max_rounds=4, verbose=True):
messages = [{"role": "user", "content": question}]
for _ in range(max_rounds):
choice = chat(messages)
message = choice["message"]
messages.append(message)
calls = message.get("tool_calls")
if not calls:
return message["content"]
for call in calls:
result = run_tool(call)
if verbose:
print(f" -> {call['function']['name']}({call['function']['arguments']}) = {result}")
messages.append({"role": "tool", "tool_call_id": call["id"], "content": result})
return "(stopped after max_rounds)"
if __name__ == "__main__":
import sys
print(ask(" ".join(sys.argv[1:])))
One detail is easy to miss: the field arguments in the response is a string, not an object. You have to run json.loads on it yourself. This is the raw response for the question “What is 1234 plus 5678?” (shortened to the relevant fields):
{
"finish_reason": "tool_calls",
"message": {
"role": "assistant",
"content": "",
"tool_calls": [{
"type": "function",
"function": {"name": "add", "arguments": "{\"a\":1234,\"b\":5678}"},
"id": "C59uLhUuoPQMJPwveEFuvxKr10Sf8KMP"
}]
}
}
With the script, the whole round trip looks like this. The output below is an example from my run; the numbers will differ on your disk:
$ python3 tools.py "How much free disk space does /tmp have?"
-> disk_free({"path":"/tmp"}) = {"free_gb": 129.7, "total_gb": 136.9}
Several tool calls in one turn
A common question is whether local models can call multiple tools in one turn. In my test the 4B model did. I asked “What is the SHA-256 of notes.txt, and what is 1234 + 5678?” and got both calls in one response, in the order of the question. The script ran both, sent both results back, and the model wrote one answer with both values. I checked the hash with sha256sum; it matched. Example output (hash shortened):
-> sha256_of_file({"filename":"notes.txt"}) = {"sha256": "d8c44f1c...3ae9d1"}
-> add({"a":1234,"b":5678}) = {"sum": 6912}
The model returned two entries in tool_calls, and the loop in ask handles every entry, so no extra code was needed. A test with a single prompt shows that it can work, not how often it does.
Errors and safety: never trust the arguments
The model produces the arguments, so treat them like user input. In the script, sha256_of_file joins the file name with the demo folder and refuses everything that ends up outside of it. I called run_tool directly with ../../etc/passwd and with /etc/passwd; both were blocked. When I asked the model in plain language for the hash of ../../etc/passwd, it refused by itself and did not call the tool at all, but you should not rely on that. The check in your code is what protects you.
Errors are returned to the model as JSON instead of crashing the program. These are the results for a path outside the folder, an unknown tool, broken JSON and a missing argument, each tested directly against run_tool:
{"error": "file is outside the demo folder"}
{"error": "KeyError: 'rm_rf'"}
{"error": "JSONDecodeError: Expecting ',' delimiter: line 1 column 8 (char 7)"}
{"error": "TypeError: add() missing 1 required positional argument: 'b'"}
I did not test whether the model corrects itself after such an error message. If you build an agent that does more than a few calls, limit the number of rounds, as max_rounds does here, and never give a model a function that deletes or sends something without a confirmation step.
Two traps with tool_choice
The parameter tool_choice controls whether the model may or must call a tool. Both extreme values behaved differently from what I expected:
"none"should forbid tool calls. With the question “What is 1234 plus 5678?” the server answered with finish reasonstopand the following text as normal content. The model wrote the tool call as plain text instead of a structured call, so a program that only looks attool_callswould show this text to the user."required"should force a call. With the prompt “Say hello.” the model did not call a tool. It wrote a normal answer that did not stop until I setmax_tokensto 150 (finish reasonlength). Without that limit I stopped the request after more than 1600 generated tokens.
<tool_call>
<function=add>
<parameter=a>
1234
</parameter>
<parameter=b>
5678
</parameter>
</function>
</tool_call>
So in this build, do not use tool_choice as a security mechanism. Filter the tool list you send, check the content for <tool_call> if you use "none", and set max_tokens as an upper limit. I only tested these two values with this one model, and a newer llama.cpp version may behave differently.
How reliable is a small model? A measurement
I wrote a small test with 12 prompts, in English and German: three for each of the three tools and three questions that need no tool at all. A prompt counted as correct only if the first response contained the right function with the right arguments, or no call (and no raw tool text) for the questions without tool. Temperature was 0 and every prompt ran once.
| Model | Correct | Failure |
|---|---|---|
| Qwen3.5-4B Q4_K_M | 12 of 12 | none |
| Qwen3.5-0.8B Q8_0 | 11 of 12 | German prompt for the SHA-256 hash: no tool call |
Twelve prompts are far too few for a statement about quality, and they were easy ones: one clear tool per question. The result only shows that even the 0.8B model handled most simple cases; its one failure was a German prompt, and with a single run I cannot say whether that is a pattern. If you rely on it, run your own tests with your real tools and prompts. How a smaller quantization affects such tests is something I did not measure; for the quality loss in general, see GGUF Quantization Comparison.
Where to go from here
The same tool functions can be offered to other programs through a standard protocol. The tutorial Build an MCP Server in Python shows how. For a model that answers from your own documents instead of calling functions, see Build a Local RAG with Python. The script in this article is a learning example: it has no timeouts for tools, no logging and no authentication, and the safety check covers only the one function that touches files.




