Build a multi-tool AI agent in Python: 12 tools, parallel calls, failures and routing
A 12-tool sales-analyst agent on a local Ollama model, with tool-selection accuracy measured at 3 and 12 tools, parallel calls, tool errors and a router.
An agent with two tools is a demo. An agent with twelve is where the engineering starts. The model now has to pick one tool out of a menu where several look alike, it may ask for two at once, some of its calls will fail, and every extra schema costs tokens and attention on every turn.
This post builds a sales-analyst agent with twelve tools over a CSV of orders, runs it on a local model through Ollama, and measures one thing that tutorials skip: how often the model picks the right tool when the menu grows from 3 to 12. Then it tests the standard fix, a router that narrows the menu before each call.
The request and response shapes for tool calls are covered in function calling, end to end. Auth, retries and confirmations for HTTP tools are in connecting an LLM to a REST API. How descriptions steer a single pick is in how AI agents make decisions. This post assumes those and focuses on what changes when the tool count goes up.
The agent and its twelve tools#
The data is 240 synthetic orders across three months (September to November 2026) with category, region, payment method, quantity, unit price and discount. The agent answers questions a sales team asks: revenue last month, which region leads, whether discounts pay off.
All arithmetic happens in Python. The model never adds up rows; it picks a tool, fills in arguments, and writes the answer from the tool's JSON. That split is the main reason to build an agent here at all: summing 240 rows is a job for code, and a language model doing it in its head has no way to show its work.
| Tool | What it returns | Confusable with |
|---|---|---|
sales_summary |
orders, revenue, AOV, overall or one month | compare_months, search_benchmarks |
revenue_by |
revenue split by category, region or payment method | make_chart |
top_products |
best SKUs by revenue | revenue_by |
compare_months |
two months side by side, % change | forecast_revenue |
discount_impact |
orders and AOV per discount level | sales_summary |
customer_history |
one customer's orders and spend | top_products |
stock_level |
units in stock for one SKU | top_products |
convert_currency |
INR to USD, EUR or GBP at fixed demo rates | |
search_benchmarks |
web search for market figures (stubbed offline) | sales_summary |
make_chart |
a chart file of revenue by one dimension | revenue_by |
forecast_revenue |
linear projection for future months | compare_months |
email_report |
sends mail (a write action) |
The third column was designed in on purpose. A twelve-tool menu where every tool is obviously different tells you nothing; real menus have overlap.
Schema design for a big menu#
With three tools, a vague description still works because there is little to confuse it with. With twelve, the description has to say where the tool's job ends. Four rules shaped the schemas here.
Point to the neighbour. sales_summary says "Not for comparing two months: use compare_months." make_chart says "Use only when the user asks for a chart, graph or plot." The model reads the menu as a whole, so a description that names the other tool removes the overlap at the point of choice.
Say whose data it is. search_benchmarks is described as figures "about OTHER companies or the market ... Never for our own data." Without that line, "what is our AOV?" and "what AOV do Indian stores see?" look the same to a small model.
Use enums for closed sets. revenue_by takes dimension as an enum of three values instead of free text. The model cannot invent "city", and if it sends something else anyway, the function rejects it with a message listing the valid values.
Show the format for ids. customer_history says "one customer id like C042", stock_level says "one SKU like ELE-3". A worked example in the description gives the model the format in the same place it reads everything else.
Here is one schema as it sits in tools.py:
MONTH = {"type": "string", "description": "Month as YYYY-MM, e.g. 2026-10. Omit for all months."}
SCHEMAS = {
"sales_summary": _fn("sales_summary", "Our own order count, total revenue and average order value (AOV) in INR, overall or for one month. Not for comparing two months: use compare_months.", {"month": MONTH}),
"revenue_by": _fn("revenue_by", "Our revenue split by one dimension (product_category, region or payment_method), as numbers. For a picture, use make_chart.",
{"dimension": {"type": "string", "enum": ["product_category", "region", "payment_method"]}, "month": MONTH}, ["dimension"]),
_fn wraps the name, description and JSON Schema into the {"type": "function", "function": {...}} shape that Ollama's tool-calling docs use, which is also the OpenAI Chat Completions shape.
The loop#
question
|
v
[router] -- picks k of 12 schemas (optional)
|
v
[model] -- returns text, or 1..n tool calls
| |
text v
| [executor] runs calls in parallel threads
v | each failure -> {"error": "..."}
answer v
append one tool message per call, loop
stop at max_steps or when errors > max_errors
The model client is one function. Everything else is ordinary Python:
def chat(model, messages, tools):
"""The only function that talks to a model. Swap its body for a hosted API call."""
body = {"model": model, "messages": messages, "tools": tools, "stream": False, "think": False,
"options": {"temperature": 0, "seed": 0, "num_predict": 256}}
return _post("/api/chat", body)["message"]
To run the same agent on a hosted model, replace the body of chat with your provider's SDK call and map its tool-call objects into the same {"function": {"name", "arguments"}} dicts. No other code changes. Everything below ran against Ollama 0.40.16 on a MacBook with no API key.
The loop itself:
def run_agent(model, question, tools=None, max_steps=5, max_errors=2, log=print):
tools = tools if tools is not None else list(SCHEMAS.values())
messages = [{"role": "system", "content": SYSTEM}, {"role": "user", "content": question}]
errors = 0
for step in range(1, max_steps + 1):
msg = chat(model, messages, tools)
messages.append(msg)
calls = msg.get("tool_calls") or []
if not calls:
return msg["content"]
results = run_calls(calls)
for c, res in zip(calls, results):
log(f"step {step}: {c['function']['name']}({json.dumps(c['function']['arguments'])}) -> {json.dumps(res)[:110]}")
errors += "error" in res
messages.append({"role": "tool", "tool_name": c["function"]["name"], "content": json.dumps(res)})
if errors > max_errors:
return "Stopped: tools kept failing. Last error: " + results[-1].get("error", "")
return "Stopped: step limit reached."
Two limits keep it from running away. max_steps caps model turns. max_errors counts failed tool results across the whole run, so a model stuck retrying the same bad call stops after three failures instead of burning all five steps. Ollama's docs pair each result with the call through tool_name; on APIs that match by call id, send the id back instead.
Parallel calls#
A question like "revenue by region and by payment method for November" needs two independent calls. A capable model emits both in one turn, and the executor runs them at the same time:
def run_calls(calls):
"""Run all tool calls from one model turn concurrently; keep the model's order."""
with ThreadPoolExecutor(max_workers=4) as pool:
return list(pool.map(lambda c: run_tool(c["function"]["name"], c["function"]["arguments"]), calls))
pool.map returns results in input order even when the threads finish out of order, so result N always pairs with call N. Here is the real run with qwen3:4b-instruct:
step 1: revenue_by({"dimension": "region", "month": "2026-11"}) -> {"South": 763192, "East": 594759, "North": 586014, "West": 499054}
step 1: revenue_by({"dimension": "payment_method", "month": "2026-11"}) -> {"COD": 989175, "UPI": 919016, "Card": 534828}
Here is the revenue breakdown for the month of 2026-11:
**Revenue by Region:**
- South: ₹763,192
- East: ₹594,759
- North: ₹586,014
- West: ₹499,054
**Revenue by Payment Method:**
- COD (Cash on Delivery): ₹989,175
- UPI: ₹919,016
- Card: ₹534,828
Both calls came in step 1, and the answer took one more model turn. Done one at a time, the same question costs three model turns. With local tools the saving is model latency; with network tools (a search API, a database), the threads also overlap the I/O.
Threads are safe here because every tool is a read. Do not run writes in parallel unless they are independent. If the model asks to email_report and to change a record in the same turn, run them in order, or turn parallel calls off for that request. Both major APIs have a switch for that, covered in the function calling post.
When a tool fails#
Tools fail for three ordinary reasons: the model names a tool that does not exist, it sends arguments the function rejects, or the data is missing. run_tool turns all three into a result the model can read, and never lets an exception escape into the loop:
def run_tool(name, args):
"""Never raise into the loop. Every failure becomes a result the model can read."""
if name not in FUNCS:
return {"error": f"no tool named {name!r}; available: {sorted(FUNCS)}"}
try:
return FUNCS[name](**args)
except ToolError as e:
return {"error": str(e)}
except TypeError as e: # wrong or missing arguments
return {"error": f"bad arguments for {name}: {e}"}
Feeding the executor three calls directly, with no model involved, shows each path:
{'South': 2499292, 'East': 2017678, 'West': 1942649, 'North': 1874692}
{'error': "unsupported currency 'JPY'; supported: ['EUR', 'GBP', 'USD']"}
{'error': "no tool named 'refund_order'; available: ['compare_months', 'convert_currency', 'customer_history', 'discount_impact', 'email_report', 'forecast_revenue', 'make_chart', 'revenue_by', 'sales_summary', 'search_benchmarks', 'stock_level', 'top_products']"}
One failing call did not take the other two down with it. That matters more with parallel calls: if one of three threads raises and you let the exception propagate, you lose the two good results and the model sees nothing.
Each error message lists the valid options. Here is what that buys you, from the agent run on "What was our revenue in August 2026?" (the data starts in September):
step 1: sales_summary({"month": "2026-08"}) -> {"error": "no orders for month '2026-08'; available months: ['2026-09', '2026-10', '2026-11']"}
There were no orders in August 2026. The available months with data are September 2026, October 2026, and November 2026.
The model did not retry, did not invent a number, and told the user what data exists. An error that said only "not found" would have invited a guess.
Do not catch everything. A bug in your own tool (a KeyError from a renamed CSV column) should crash in development so you see it. run_tool catches ToolError, which tools raise on purpose for bad input, and TypeError for argument mismatches. In production you would add a catch-all that logs the traceback and returns a generic error, so one bad tool does not kill the session.
Measuring tool selection: 3 tools against 12#
The test set has 29 labelled questions. Ten are "core" questions whose right answer is one of sales_summary, revenue_by or top_products, or no tool at all (a greeting). Nineteen more cover the other nine tools, two per tool, plus "What is a SKU?", which needs no tool. A question scores a point only if the model's first tool call matches the label.
That gives a fair comparison: the same 10 core questions with only the 3 core tools on the menu, and then with all 12. The extra nine tools are pure distraction for those questions. Then all 29 questions go against all 12 tools.
def first_tool(model, q, tools):
msg = chat(model, [{"role": "system", "content": SYSTEM}, {"role": "user", "content": q}], tools)
calls = msg.get("tool_calls") or []
return calls[0]["function"]["name"] if calls else None
Two local models, temperature 0, fixed seed: qwen3:4b-instruct (4B parameters) and llama3.2:1b (1B). The real output:
qwen3:4b-instruct core 10 @ 3 tools 10/10 (100%) 34s
qwen3:4b-instruct core 10 @ 12 tools 10/10 (100%) 34s
qwen3:4b-instruct all 29 @ 12 tools 28/29 (97%) 113s
miss: 'Send a summary mail to ops@example.com with subj' want=email_report got=sales_summary
llama3.2:1b core 10 @ 3 tools 7/10 (70%) 21s
miss: 'Which region brings in the most money?' want=revenue_by got=sales_summary
miss: 'Show the top 10 items by revenue.' want=top_products got=revenue_by
miss: 'Hi, thanks for the help earlier!' want=None got=sales_summary
llama3.2:1b core 10 @ 12 tools 6/10 (60%) 43s
miss: 'Which region brings in the most money?' want=revenue_by got=search_benchmarks
miss: 'How much did each product category earn in Novem' want=revenue_by got=sales_summary
miss: 'Show the top 10 items by revenue.' want=top_products got=sales_summary
miss: 'Hi, thanks for the help earlier!' want=None got=sales_summary
llama3.2:1b all 29 @ 12 tools 17/29 (59%) 245s
The seconds column is wall time on an Ollama install that other jobs were also using, so read it loosely.
The 4B model did not care about menu size at this scale. Ten of ten with 3 tools, ten of ten with 12. Its one miss on the full set is arguably a labelling error on my side: for "send a summary mail with subject 'Nov numbers'", it fetched the summary first, which is a sensible first step before emailing it. A stricter eval would accept either sales_summary or email_report as a valid first call for that question.
The 1B model is a different story. It lost one more core question when nine distractors were added (70% to 60%), and one of the new misses went to a distractor: "Which region brings in the most money?" went to search_benchmarks. Across all 29 questions it scored 59%, and nine of its twelve misses were sales_summary. A small model under a long menu falls back to the most generic tool, and every request starts to look like "get me a number".
Ten questions is one point per 10%, so the 70 to 60 gap is one question and could be noise. The 97% against 59% gap on 29 questions is not. The OpenAI function calling guide puts the threshold for frontier models much higher, suggesting fewer than 20 functions at the start of a turn as "a soft suggestion", and Anthropic's tool search page says Claude's selection accuracy "degrades once you exceed 30–50 available tools". Where your limit sits depends on the model, and the only way to know is to run your own labelled set.
Limiting tool choice per step: a router#
If the model struggles with 12 tools, show it fewer. A router picks a shortlist before the model call. The cheapest version embeds each tool's description once, embeds the question, and keeps the top k by cosine similarity. Here it uses nomic-embed-text through Ollama's embed endpoint, with the search_query: and search_document: prefixes that the model card asks for:
def route(question, k=4, always=()):
"""Return the k tool schemas whose descriptions sit closest to the question."""
if not _TOOL_VECS:
names = list(SCHEMAS)
docs = [f"search_document: {n}: {SCHEMAS[n]['function']['description']}" for n in names]
_TOOL_VECS.update(zip(names, embed(docs)))
if question not in _Q_VECS:
_Q_VECS[question] = embed([f"search_query: {question}"])[0]
q = _Q_VECS[question]
ranked = sorted(_TOOL_VECS, key=lambda n: -_cos(q, _TOOL_VECS[n]))
picked = list(dict.fromkeys([*always, *ranked[:k]]))
return [SCHEMAS[n] for n in picked]
Measure the router on its own first. If the right tool is not in the shortlist, the model cannot pick it, and no prompt fixes that:
router recall@4: 27/27 questions had the right tool in the shortlist
Then the same 29 questions with a 4-tool shortlist per question:
qwen3:4b-instruct all 29 @ router k=4 28/29 (97%) 152s
miss: 'Send a summary mail to ops@example.com with subj' want=email_report got=sales_summary
llama3.2:1b all 29 @ router k=4 26/29 (90%) 65s
miss: 'Hi, thanks for the help earlier!' want=None got=search_benchmarks
miss: 'What AOV do Indian e-commerce stores typically s' want=search_benchmarks got=sales_summary
miss: 'What is a SKU?' want=None got=stock_level
| Model | 12 tools | Router, k=4 |
|---|---|---|
| qwen3:4b-instruct | 28/29 (97%) | 28/29 (97%) |
| llama3.2:1b | 17/29 (59%) | 26/29 (90%) |
For the 1B model, the router moved accuracy from 59% to 90%. Most of the gain came from taking sales_summary off the menu when the question was not about it, so the fallback was not there to fall back to. For the 4B model the router changed nothing, and it added an embedding call per step. Route when your model needs it, not by default.
Two of the 1B model's remaining misses are no-tool questions. The router always returns four tools, even for "Hi", so the model sees a menu and uses it. A similarity floor fixes that: if the best tool scores below a threshold, send no tools at all. Pick the threshold from your labelled set, not by eye.
The always= argument pins tools that should be on every menu. Anthropic's tool search docs suggest keeping your 3 to 5 most-used tools always loaded and deferring the rest, which is the same idea built into the API.
In a multi-step task, route on every step, not once per question. "Email the November summary to ops" needs sales_summary on step 1 and email_report on step 2. Routing on the original question alone can drop the step-2 tool. Route on the question plus the latest tool results, or pin the tools a workflow always ends with.
Failure modes to plan for#
- Generic-tool gravity. The broadest tool (
sales_summaryhere) soaks up misses on small models. Narrow its description, or route it off the menu. - Router recall below 100%. Track recall@k as its own metric. When it drops, raise k or rewrite the description of the tool that went missing.
- Retry loops. A model resending the same failing call burns steps. The
max_errorscap stops it; error messages that list valid values stop it earlier. - Parallel writes. Two writes in one turn, run in threads, can land in either order. Run writes one at a time.
- Label ambiguity. Some questions have two valid first steps. Allow a set of correct answers per case, or your eval will report misses that are not misses.
- Token cost. All twelve schemas ride along on every model call. Ollama does not bill, but a hosted model does, and a router cuts that per call.
Turn it into a test#
The 29 cases are already a regression suite. Keep them in the repo, run them whenever a description changes or the model is swapped, and fail the build if accuracy drops below what you shipped with. Report recall@k for the router as a separate line, so you can tell a routing regression from a model regression. For scoring full trajectories, not only the first call, see evaluating an AI agent in Python.
The full code is four files: make_data.py (seeded synthetic CSV), tools.py (twelve tools and schemas), agent.py (client, executor, router, loop) and eval_select.py (the labelled set). Only the standard library is used, so it runs with python3 and a local Ollama with qwen3:4b-instruct, llama3.2:1b and nomic-embed-text pulled.