How an LLM calls a Python function
Executable Python examples explain tool calls, argument checks and database constraints.
A model requests a tool by returning its name and arguments. Your program validates those arguments, chooses an allowed function and executes it. This tutorial follows the data through each boundary.
All examples below use sample data. Run each independently with Python 3. The printed outputs were checked locally.
A tool call is a request to run code
A model returns a function name and arguments. Your program selects the allowed function, runs it and returns its output. Python calculates the hash in this example. Inspect the request and result separately when debugging an agent.
SHA-256 produces 256 bits. Four bits fit in one hexadecimal digit, so its output has 256 / 4 = 64 digits.
import hashlib
tools = {"sha256_text": lambda text:
hashlib.sha256(text.encode("utf-8")).hexdigest()}
request = {
"name": "sha256_text",
"arguments": {"text": "abc"}}
fn = tools[request["name"]]
result = fn(**request["arguments"])
print(request["name"])
print(result)
print(len(result))
Expected output
sha256_text
ba7816bf8f01cfea414140de5dae2223b00361a396177a9cb410ff61f20015ad
64
Reference: https://docs.ollama.com/capabilities/tool-calling
A character count differs from a byte count
Python stores a string as Unicode text. Encoding it as UTF-8 produces bytes. In café, the precomposed é uses two bytes. Count the encoded bytes when checking a byte limit.
Three ASCII characters use three bytes. The final character uses two. Total = 3 + 2 = 5 bytes for four code points.
text = "café"
print(len(text))
print(len(text.encode("utf-8")))
Expected output
4
5
Reference: https://docs.python.org/3/library/stdtypes.html#str.encode
Decode JSON before calling a function
A JSON object arrives as text. json.loads converts it to a Python dictionary. The number 3 then has an integer type and can be multiplied. Without decoding, you still have the serialized text.
The decoded integer is 3. Applying f(x) = 2x gives f(3) = 6.
import json
arguments = json.loads('{"x": 3}')
print(type(arguments["x"]).__name__)
print(arguments["x"] * 2)
Expected output
int
6
Reference: https://docs.python.org/3/library/json.html
Validate a tool argument before execution
Check the accepted domain before running a tool. Here a square function accepts a non-negative integer. Python treats bool as a subclass of int, so an exact type check excludes True.
The input domain is the set of integers x >= 0. Inputs 3, -1 and True yield valid, invalid and invalid.
def valid(x):
return type(x) is int and x >= 0
print([valid(x) for x in [3, -1, True]])
Expected output
[True, False, False]
Reference: https://docs.python.org/3/library/functions.html#type
Keep a calculation separate from its side effects
A pure function computes a result from its input without writing a file or changing another system. Calling this function twice returns the same result. Side effects need separate tests.
For f(x) = x squared, f(4) = 16 on both calls. Two evaluations produce zero database writes.
def square(x):
return x*x
print(square(4), square(4))
Expected output
16 16
Reference: https://docs.python.org/3/library/functions.html
Preserve the error that identifies a failed step
An invalid JSON string fails at decoding. Catch JSONDecodeError at that boundary and report its line and column. That locates a parsing failure before the tool implementation runs.
The supplied text contains one opening brace and no property. Parsing fails at line 1, column 2.
import json
try:
json.loads("{")
except json.JSONDecodeError as error:
print(error.lineno, error.colno)
Expected output
1 2
Reference: https://docs.python.org/3/library/json.html#json.JSONDecodeError
Compare a tool result with an independent reference
Check the computed SHA-256 hash against a fixed reference for abc. Replacing the first digit makes the comparison fail. Testing the changed value confirms that the check can detect this error.
Equality requires all 64 hexadecimal digits to match. One changed digit is sufficient to fail.
import hashlib
expected = "ba7816bf8f01cfea414140de5dae2223b00361a396177a9cb410ff61f20015ad"
actual = hashlib.sha256(b"abc").hexdigest()
print(actual == expected)
print(("0" + actual[1:]) == expected)
Expected output
True
False
Reference: https://docs.python.org/3/library/hashlib.html
Run the complete local tool-call loop
The short examples above isolate each boundary. This program joins them: the model requests a function, Python validates the fixed request and computes the hash, and a second model call receives the tool result. It uses Python 3 and an already installed local Ollama model named qwen3:14b.
Download the complete Python example, inspect it, and run it with python tool-call.py. Its only network destination is the local Ollama server at 127.0.0.1:11434.
"""Run one local Ollama tool call with Python's standard library.
Requires Ollama running locally with qwen3:14b already installed.
The only network destination is the local Ollama server. Input is the sample 'abc'.
"""
import hashlib
import json
from urllib.request import Request, urlopen
def chat(messages, tools):
payload = {
"model": "qwen3:14b", "stream": False, "think": False,
"messages": messages, "tools": tools,
"options": {"temperature": 0, "num_predict": 160},
}
request = Request(
"http://127.0.0.1:11434/api/chat",
data=json.dumps(payload).encode("utf-8"),
headers={"Content-Type": "application/json"},
)
with urlopen(request, timeout=120) as response:
return json.load(response)["message"]
definition = {
"type": "function",
"function": {
"name": "sha256_text",
"description": "Calculate SHA-256 of a UTF-8 string.",
"parameters": {
"type": "object",
"properties": {"text": {"type": "string"}},
"required": ["text"],
},
},
}
messages = [{
"role": "user",
"content": "Compute the SHA-256 digest of abc using sha256_text. Reply with only the digest.",
}]
first = chat(messages, [definition])
calls = first.get("tool_calls", [])
assert len(calls) == 1, "Expected one tool request; inspect the actual model reply."
call = calls[0]["function"]
assert call["name"] == "sha256_text" and call["arguments"] == {"text": "abc"}
digest = hashlib.sha256(call["arguments"]["text"].encode("utf-8")).hexdigest()
assert digest == "ba7816bf8f01cfea414140de5dae2223b00361a396177a9cb410ff61f20015ad"
final = chat(messages + [first, {
"role": "tool", "tool_name": "sha256_text", "content": digest,
}], [])
assert digest in final["content"], "The final answer did not reproduce the tool result."
print(json.dumps({"model_request": call, "python_result": digest,
"model_final_answer": final["content"]}, indent=2))
The observed request was sha256_text with text equal to abc. Python returned ba7816bf8f01cfea414140de5dae2223b00361a396177a9cb410ff61f20015ad, and the final model answer contained the same value. The assertions stop the example if the requested function, arguments or final answer differ.
The function schema is a description supplied to the model. The Python implementation stays in the program. Returning a tool request does not execute that implementation. The final chat call is what lets the model see the computed result.
Reference: https://docs.ollama.com/capabilities/tool-calling
Reproduce the output before modifying the program. Change one input or constraint, predict the new result and check it. Keep the function request, execution and observed effect separate in the trace.
The team guide · My original notes on testing coding agents · Working with Lightbulb Partners