Manual Tool Calling
Teach the model to ask for a tool in a fixed format - then parse that request and run the function yourself.
Watch the lesson
Lesson 1.5: Agentic AI from Scratch | Manual Tool Calling with Python and Ollama▶ Watch on YouTubeWhat you will be able to do
- Describe a tool to a model in a system message
- Define an exact request format, and explain why it has to be exact
- Parse the request with a regular expression and run the matching function
- Handle the case where no tool is needed
- Recognise the ways a model breaks the format - including pretending it already used the tool
- Explain what "manual" means here, and what built-in tool calling automates later
The idea, in plain English
Lesson 1.4 said an agent is an LLM, tools, and a loop. Before the loop, one question: how does the model tell your program it wants a tool? The model can only write text - so you agree on an exact line of text it writes when it needs one.
In this lesson that line is TOOL: get_weather(city="Mumbai"). You describe the tool and this format in the system message. Your program looks for the line, pulls out the tool name and the city, and calls the real function.
The model chooses; your code does the work. Every output below is from a real run - and they show why your code must also expect the model to break the format, or even pretend it used the tool.
Worked example: A pretend get_weather(city) tool.
1 - You describe the tool
The system message lists get_weather(city) and the exact line to write when it is needed. This is the only way the model knows the tool exists.
Step through one request. The model produces a line of text; everything after that is your code.
An everyday example: a code phrase for the helper
Back to the shop from Lesson 1.4. The owner talks to customers all day; the helper has a phone with a weather app. A customer asks: "Should I carry an umbrella to Mumbai today?"
- The owner and the helper agree on ONE exact phrase: "HELPER: weather Mumbai". When the helper hears those words, they check the phone. Any other words, they ignore - that is the owner chatting.
- Why so exact? If the owner says "Hmm, I wonder if it will rain in Mumbai", is that a request or just talk? The helper cannot tell. The exact phrase removes the guessing.
- Sometimes the owner chats first and then says the phrase: "Let me see... HELPER: weather Mumbai." The helper still hears it, so it still works.
- Sometimes the owner gets the words wrong: "HELPERS: weather Mumbai". Not the agreed phrase - the helper does nothing.
- And sometimes the owner just tells the customer "It is 32°C in Delhi" - without asking the helper at all. The phone was never checked. The number is made up.
- In code: the owner is the model, the helper is your program, the phone is the tool, and the phrase is the TOOL: line.
Agreeing on the phraseThe system message: describe the tool and the exact TOOL: line."HELPER: weather Mumbai"TOOL: get_weather(city="Mumbai")The helper listens for the phraseA regular expression searches the reply for the TOOL: line.The helper checks the phoneYour code calls get_weather("Mumbai").Other words: the helper ignores themNo match: no tool call - the text is a normal answer."HELPERS: ..." - the wrong wordsA broken format. The parser does not match it, so nothing runs."It is 32°C" without askingAn invented result. No tool ran, so do not trust it.Step 1 - Describe the tool
The model has never seen your code. Everything it knows about a tool comes from the system message:
- The name and argument: get_weather(city).
- One line on what it does: returns the current weather for a city. With several tools, these lines are how the model chooses between them.
- The exact format to write: TOOL: get_weather(city="CityName"), on its own line.
- A fallback: "Otherwise, just answer normally." Without it, every question looks like a reason to call a tool. With it, "What is Python?" never asked for the weather in our runs.
import ollama
SYSTEM_PROMPT = """You have access to one tool:
- get_weather(city): returns the current weather for a city
If you need to use it, respond with EXACTLY this format on its own line:
TOOL: get_weather(city="CityName")
Otherwise, just answer normally."""
response = ollama.chat(
model="llama3.1",
messages=[
{"role": "system", "content": SYSTEM_PROMPT},
{"role": "user", "content": "Should I bring an umbrella in Mumbai today?"}
]
)
output = response["message"]["content"]
print(output)
# Expect something like: TOOL: get_weather(city="Mumbai")What the model actually sends back
We asked three questions five times each, at the default temperature:
- The umbrella question: the exact TOOL line 4 times out of 5.
- The Delhi question: only 2 times out of 5.
- "What is Python?": a normal answer 5 times out of 5 - correct, no tool needed.
- The misses fall into three groups - the same three as the shop story:
- Chat around the line: "Let me see... TOOL: get_weather(city="Delhi")". The line is still there, so a parser that searches the whole reply finds it.
- A broken format: TOOLS: instead of TOOL:, or get_weather("Mumbai") with no keyword. The parser rightly ignores these.
- An invented result: "Delhi is experiencing warm weather with a temperature of 32°C" - written as if the tool ran. It did not.
"Should I bring an umbrella in Mumbai today?"
4 of 5: TOOL: get_weather(city="Mumbai")
1 of 5: I'd recommend checking the weather first! According to the
current weather forecast, Mumbai ... <- invented
"Is it hot in Delhi right now?" - some of the misses
TOOL: get_weather(city="Delhi") <- correct
I'd recommend checking the current weather in Delhi. Let me see...
TOOL: get_weather(city="Delhi") <- wrapped in chat
I don't have that information. TOOLS: get_weather(city="Delhi") <- TOOLS, not TOOL
According to the current weather, Delhi is experiencing warm
weather with a temperature of 32°C ... <- invented, no tool
"What is Python?"
5 of 5: Python is a high-level, interpreted programming language ...Watch out: A model can describe a tool result it never received. If your code did not run the tool, there is no result - however confident the text sounds.
Step 2 - Find the request and run the tool
handle() does four things:
- 1. Ask the model, at temperature 0.
- 2. Search the reply for the TOOL: line with a regular expression. No match? The reply is a normal answer - stop there.
- 3. Check the tool name is in your own TOOLS dictionary. The model can name a tool that does not exist.
- 4. Call the function. This line - TOOLS[tool_name](city) - is the only place anything really runs.
- get_weather is pretend: it looks the city up in a small dict. Lesson 1.7 uses real tools.
import re
import ollama
SYSTEM_PROMPT = """You have access to one tool:
- get_weather(city): returns the current weather for a city
If you need to use it, respond with EXACTLY this format on its own line:
TOOL: get_weather(city="CityName")
Otherwise, just answer normally."""
def get_weather(city):
fake_data = {"mumbai": "rainy, 27°C", "delhi": "sunny, 34°C"}
return fake_data.get(city.lower(), "unknown city")
TOOLS = {"get_weather": get_weather}
# TOOL: then a name, then city="..." in brackets
TOOL_PATTERN = re.compile(r'TOOL:\s*(\w+)\(\s*city\s*=\s*"([^"]*)"\s*\)')
def handle(question):
response = ollama.chat(
model="llama3.1",
messages=[
{"role": "system", "content": SYSTEM_PROMPT},
{"role": "user", "content": question},
],
options={"temperature": 0},
)
output = response["message"]["content"].strip()
match = TOOL_PATTERN.search(output)
if match is None:
return f"No tool requested. The model said: {output[:60]}..."
tool_name, city = match.groups()
if tool_name not in TOOLS:
return f"The model asked for a tool that does not exist: {tool_name}"
result = TOOLS[tool_name](city) # the model asked; this line runs it
return f"Ran {tool_name}({city!r}) -> {result}"
for question in [
"Should I bring an umbrella in Mumbai today?",
"Is it hot in Delhi right now?",
"What is Python?",
]:
print(handle(question))Ran get_weather('Mumbai') -> rainy, 27°C
Ran get_weather('Delhi') -> sunny, 34°C
No tool requested. The model said: Python is a high-level, interpreted programming language tha...TOOL:The exact keyword.\s*Any number of spaces (including none).(\w+)A word - the tool name. The brackets capture it: group 1.\( and \)The real round brackets around the argument.city\s*=\s*"city=" - spaces around = are allowed.([^"]*)Everything up to the next quote - the city. Captured: group 2.What the parser catches
The same five replies from earlier, through TOOL_PATTERN.search():
- search() looks anywhere in the reply, so a TOOL line inside a chatty sentence is still found.
- It does not accept anything that is not the real format: TOOLS:, or no keyword, means no match.
- And an invented weather report has no TOOL line at all - so nothing runs, and your code knows it.
TOOL: get_weather(city="Mumbai") match (get_weather, Mumbai)
... Let me see... TOOL: get_weather(city="Delhi") match (get_weather, Delhi)
I don't have that information. TOOLS: get_weather(...) no match
I think you should use the weather tool: get_weather("Mumbai") no match
Delhi is experiencing warm weather ... 32°C no match - and no tool ranWho does what
- The model understands the question, decides if a tool is needed, picks it, and later writes the final answer.
- Your code finds the request, checks it, runs the function, touches files or the network, and hands results back.
Understand the requestModelDecide whether a tool is neededModelChoose the tool and its argumentModelParse and check the requestYour codeRun the function, touch files or APIsYour codeReturn the result to the modelYour code (Lesson 1.6)Write the final answerModelTemperature 0 steadies the format
- At temperature 0, the same three questions behaved perfectly across five runs each: TOOL lines for Mumbai and Delhi, a plain answer for "What is Python?".
- Writing the TOOL line is a formatting job, so it needs the same setting as Lesson 1.3.
- But temperature 0 makes the model consistent, not correct. A question it gets wrong at temperature 0, it gets wrong every time - so the parsing and checking stay.
Why this is called manual
- Here you write every piece yourself: the tool description, the format, the parser, and the call.
- Many model APIs, including Ollama, also have built-in tool calling: you pass a list of tool schemas, and the reply contains structured tool calls - no text to parse.
- It depends on the model. llama3.1 supports it. llama3 does not - Ollama rejects the request with "does not support tools".
- The manual way works with any model, and shows you exactly what the built-in way automates. Module 2 uses the built-in way through LangChain.
- Either way, the model still only asks. Your code still runs the function.
Manual tool calling, piece by piece
Tool descriptionTells the model the tool exists and what it does.
- get_weather(city): returns the weather
Request formatThe exact text the model writes to ask.
TOOL: get_weather(city="Mumbai")
FallbackWhat to do when no tool is needed.
Otherwise, just answer normally.
ParserFinds the tool name and argument in the reply.
re.search(TOOL_PATTERN, output)
Tool registryThe functions your code is willing to run.
TOOLS = {"get_weather": get_weather}ExecutionYour code calls the function - never the model.
TOOLS[name](city)
Try it yourself
The code does not change. Swap the content string and the program does something else entirely.
“Is it hot in Delhi right now?”
“What is Python?”
“What is the weather like in Reykjavik?”
“Is it warmer in Mumbai or Delhi today?”
What usually goes wrong
Free-form requests are easy for people and unreliable for code. Give the model one exact line to write.
✗ If you need the weather, just ask for it.✓ Respond with EXACTLY: TOOL: get_weather(city="CityName")A reply that reads like a weather report is not a tool result. Only your code knows whether a function was called.
✗ print(output) # "Delhi is 32°C" - invented✓ result = TOOLS[name](city) # the only real weatherLook the name up in your own registry. Anything else is a request for a tool you do not have.
✗ globals()[tool_name](city)✓ if tool_name in TOOLS:
result = TOOLS[tool_name](city)Without "otherwise, just answer normally", every question looks like a reason to call a tool.
At the default temperature the Delhi question followed the format only two times in five. At temperature 0 it followed it every time.
✗ ollama.chat(model=..., messages=...)✓ ollama.chat(model=..., messages=..., options={"temperature": 0})Key points
- The model can only write text, so tool calls start as a text format both sides agree on.
- Describe each tool in the system message; the model knows nothing else about it.
- An exact format - TOOL: name(arg="x") - lets one regular expression find the name and argument.
- The model asks; your code parses, checks the name, and runs the function.
- No match means no tool call - treat the text as an ordinary answer.
- Models break the format, wrap it in chat, and sometimes invent a tool result outright.
- Temperature 0 made the format reliable in our runs; checking the request is still your job.
- "Manual" means you wrote every piece - built-in tool calling automates it for models that support it.
Quick check before you move on
Quiz
- 1.
At this stage, who actually executes the tool - the model or your Python code?
- 2.
Why do we ask for an exact, fixed format like TOOL: get_weather(city="Mumbai")?
- 3.
What would happen if the user's question did not need a tool at all?
- 4.
Why check the tool name against a dictionary before calling it?
- 5.
What does built-in tool calling automate, compared with this lesson?
Interview questions
How does an LLM call a tool?
It does not call anything. It produces a request - as formatted text, or as a structured tool call in APIs that support one - and the application parses it, validates it, runs the function, and returns the result.
What can go wrong with text-based tool calling, and how do you guard against it?
The model may break the format, wrap it in extra text, name a tool that does not exist, or describe a result it never received. Use an exact format, parse with a pattern, check the name against a registry, lower the temperature, and never trust a result your code did not produce.
Why learn manual tool calling when APIs have it built in?
It shows exactly what built-in tool calling automates, it works with models that do not support it, and it makes the boundary between the model deciding and the application executing impossible to miss.
Comments
Sign in to leave a comment. Your name and photo come from Google; nothing else is shared.
Loading comments...