One agent, four tools: when a Python AI agent should become a team
A small Python agent with function calling, SQLite and web search, what it can and cannot answer, and how I would split it into a coordinator and specialist agents only when the numbers say it is worth it.
| At a glance | |
|---|---|
| Repo | tanldt/python_ai_agent_v2 |
| Model access | OpenAI Python SDK, Responses API, function calling |
| Default model | gpt-4.1-mini (override with OPENAI_MODEL) |
| Tools | calculator, query_sql, current_utc_time, web_search |
| Data | Local SQLite sample, read-only |
| Interface | Command line |
| Tests | unittest, offline, no API key needed |
A business question is rarely one task. Which product makes the most money, what is the market doing, and what should we do next? is three jobs: read internal data, research outside context, and turn both into a recommendation.
“Multi-agent” is the popular answer to that kind of question. Before I add a coordinator and four specialists, I wanted to see how far one agent with good tools gets. This post walks through a small Python agent I built, what it does well, where it stops, and the multi-agent design I would try next. To be clear up front: the repo is a single agent with several tools, not a multi-agent system. The second half of this post is a design, not shipped code.
What I mean by “agent”
An agent here is a program that lets a language model choose the next step: call a tool, read the result, then either call another tool or answer.
Agent = model + instructions + tools + context + a loop.
A tool does one thing. The agent decides which thing is needed. Asked about revenue, it queries the database instead of guessing a number.
What I built
Two files do the work. agent.py holds the tool schemas and the loop. tools.py holds the local tool implementations.
| Tool | What it does |
|---|---|
calculator | Evaluates arithmetic by walking Python’s AST. No eval(). |
query_sql | Runs a SELECT against a local SQLite sample of sales data |
current_utc_time | Returns the current UTC time |
web_search | Makes a second Responses API call with OpenAI’s hosted web_search tool |
The sales table is deliberately small: id, product, quantity, unit_price, six rows, created on first run.
How it works
flowchart TD
U[User question] --> M[Model reads question<br/>and history]
M --> D{Tool calls<br/>requested?}
D -->|Yes| T[Python runs each tool]
T --> H[Append results<br/>to history]
H --> M
D -->|No| F[Return the answer]
This is plain function calling. The model returns a structured request, Python runs the function, and the result goes back into the history so the model can continue. The core of the loop is about fifteen lines:
for step in range(1, MAX_STEPS + 1):
response = client.responses.create(
model=MODEL, instructions=instructions, input=history, tools=FUNCTION_TOOLS)
history.extend([item.model_dump(exclude_none=True) for item in response.output])
calls = [item for item in response.output if item.type == 'function_call']
if not calls:
return response.output_text
for call in calls:
try:
result = run_tool(client, call.name, json.loads(call.arguments))
except Exception as exc:
result = f'Tool error: {type(exc).__name__}: {exc}'
history.append({'type': 'function_call_output', 'call_id': call.call_id,
'output': str(result)[:15000]})
What I saw on a real run
I ran it end to end with a real API key:
python agent.py "Using the sample sales database, calculate revenue by product and identify the highest revenue product."
The tool log on stderr shows the whole decision:
[Step 1] Tool: query_sql | Args: {"sql":"SELECT product, SUM(quantity * unit_price) AS revenue FROM sales GROUP BY product ORDER BY revenue DESC"}
One round, one tool call, and the SQL is exactly what I would have written by hand. The model knew the table and columns only from the tool description: sales(id, product, quantity, unit_price). It then answered with a table and a verdict:
| Product | Revenue |
|---|---|
| Laptop | $6,000 |
| Monitor | $1,500 |
| Mouse | $750 |
| Keyboard | $750 |
The product with the highest revenue is Laptop, generating $6,000.
Show data
| Revenue | |
|---|---|
| Laptop | 6,000 USD |
| Monitor | 1,500 USD |
| Mouse | 750 USD |
| Keyboard | 750 USD |
The numbers are right; I checked them against the six seed rows in tools.py. Notice one detail, though: Mouse and Keyboard tie at $750, and the answer lists them in the order SQLite happened to return them without saying they are tied. That is harmless for “highest revenue”. Ask for the lowest and the same behaviour would quietly pick one of two equal products. Nothing in a single agent checks for that, and it is exactly the kind of thing a deterministic review step should catch.
The guardrails that matter
The tools are where safety lives, not the prompt:
- SQL is read-only twice. The database opens with
mode=ro, and an SQLite authorizer denies every action exceptSELECT,READandFUNCTION. A progress handler stops runaway queries, and results over 100 rows are rejected. - The calculator cannot run code. It only accepts numbers and arithmetic operators, caps exponents at 10, and rejects results above 1e15.
- Tool output is treated as data. The instructions tell the model that web pages and tool results are untrusted and are not instructions.
- The loop is bounded. Eight model calls, then it stops and says so.
Lesson. Put the limits in code the model cannot talk its way around. A prompt that says “only run SELECT” is a request; an SQLite authorizer is a rule.
Where one agent stops
Reading the code back, these are the limits I would hit first:
- Tools run one after another. If the model asks for a SQL query and a web search in the same round, Python runs them sequentially. Independent work waits.
web_searchis a hidden second model call. It looks like one tool, but it is a full Responses API request with its own cost. A question that searches three times costs noticeably more than one that only queries SQL.- Memory lasts one run. History lives in a Python list. Close the terminal and it is gone.
- The data cannot answer “when”. The
salestable has no date column, so questions about monthly growth or when revenue dropped are out of reach. No prompt fixes a missing column. - One instruction block does everything. The same prompt has to be a careful SQL analyst and a careful web researcher. As the tool list grows, that gets harder to keep sharp.
For “revenue by product”, none of this matters. One agent is the right tool. For “combine our sales with market research and tell me what to do”, the last point starts to bite.
What multi-agent would add
A multi-agent system splits the work between agents with different instructions, tools and permissions. They can share the same model and run in the same Python process; each agent does not need its own server.
| Agent | Job | Tools or inputs |
|---|---|---|
| Coordinator | Break the request into tasks, delegate | Calls to the specialists |
| Data Analyst | Internal numbers | query_sql, calculator |
| Researcher | External context | web_search |
| Reviewer | Check figures and sources | Analyst and Researcher output |
| Writer | Turn findings into a report | Reviewed findings |
flowchart TD
U[User request] --> C[Coordinator]
C --> A[Data Analyst]
C --> R[Researcher]
A --> SQL[(SQLite + calculator)]
R --> WEB[Web search]
A --> V[Reviewer]
R --> V
V --> Q{Enough<br/>evidence?}
Q -->|No, budget left| C
Q -->|Yes, or out of budget| W[Writer]
W --> F[Report to user]
This is a proposed design, not code in the repo.
The Analyst and Researcher do not depend on each other, so they can run in parallel. The Reviewer checks that the numbers reconcile and the sources support the claims; if not, the Coordinator gets another round, inside a time and cost budget. The Writer only sees reviewed findings.
A Reviewer agent does not make the answer correct on its own. Two models can agree on the same wrong assumption. Checks that can be code, such as “do the product totals add up to the grand total” or “is any required field empty”, should be code.
Agents should hand over structured results
Free text between agents loses where a number came from. A typed message keeps it:
{
"task_id": "revenue-analysis",
"status": "completed",
"source": "sample_sales_database",
"findings": [{ "product": "Laptop", "revenue": 6000 }],
"limitations": ["Sample data only", "No date column, so no trend analysis"]
}
The limitations field is the important one. It is how the Writer knows not to claim a trend the data cannot show.
Patterns and tools to look at
LangChain documents several ways to coordinate agents: subagents, handoffs, routers and custom workflows (multi-agent docs). For workflows that branch, keep state, or pause for a human to approve, LangGraph is the one I would evaluate first. Neither is needed for the current repo.
Where this fits in a real business
These are possible uses, not features of the repo:
| Problem | Split of work | What to measure |
|---|---|---|
| Monthly reporting | Retrieve, analyze, validate, write | Prep time, numeric error rate |
| Customer support | Look up the order, check policy, draft a reply | Handling time, how often staff edit the draft |
| Invoice processing | Extract fields, match the PO, flag mismatches | Match accuracy, mismatches caught |
| Technical support | Read the ticket, find docs, suggest a fix | Resolution time, usefulness of suggestions |
The support case is close to what I already run: in the $0 SQL MCP server post the model reads order data through read-only tools. The same principle carries over. One agent gets read access to orders, another searches the return policy, and anything that changes data, such as a refund, needs an explicit permission and a human approval step before it ships.
In many small and mid-size companies, the data already sits in SQL Server behind an older .NET or Access front end. Agents do not need a rewrite of that system. They need a narrow, read-only door into it, and that door is the part worth designing carefully.
What’s next
The experiment I would run, in order:
- Keep the current single agent as the baseline.
- Build a two-specialist version: Data Analyst and Researcher, with a Coordinator that delegates and merges.
- Run both against the same set of questions and compare answer accuracy, wall-clock time and cost per question.
- Add a Reviewer or Writer only if the numbers show the split is paying for itself.
The value of multi-agent AI is in how work is divided, how evidence is passed along, and how quality is checked. The number of agents is just one setting in that design.