Sub topic 5
Giving the agent tools
This chapter assumes you can read basic Python, know what JSON is, and have used a language model through a prompt. It also assumes you know marketing metrics such as impressions, clicks, conversions and spend. By the end you will know what a tool is, how to describe one to a model, how to write tools that are safe to call, and which mistakes to avoid.
Why an agent needs tools
A language model produces text. It cannot read your ad account, query your CRM, or reliably divide 150 by 10 across thousands of rows. A tool is a function that your code runs on the model's behalf. The model asks for the function by name, your code runs it, and the result goes back to the model as text.
This split gives each part a job it does well:
- The model decides what to look up and how to explain the result.
- The tool fetches data or does exact arithmetic.
- Your code sits between them and decides what is allowed to run.
The model never runs anything itself. It only emits a request, and your program chooses whether to honor it. That fact is the basis for most of the safety advice below.
What a tool consists of
Every tool has three parts.
- A name, such as
campaign_metrics. - A description and an argument schema. These are what the model reads to decide when and how to call the tool.
- An implementation, which is ordinary code the model never sees.
Providers differ in the exact format, but most accept a JSON Schema for the arguments. A definition for the metrics tool looks like this:
campaign_metrics_spec = {
"name": "campaign_metrics",
"description": (
"Compute impressions, clicks, spend, conversions, CTR, CPC and CPA "
"from a list of per-campaign rows. Returns null for a ratio whose "
"denominator is zero. Use this instead of doing arithmetic yourself."
),
"input_schema": {
"type": "object",
"properties": {
"rows": {
"type": "array",
"items": {
"type": "object",
"properties": {
"impressions": {"type": "integer"},
"clicks": {"type": "integer"},
"spend": {"type": "number"},
"conversions": {"type": "integer"},
},
"required": ["impressions", "clicks", "spend", "conversions"],
},
}
},
"required": ["rows"],
},
}
print(campaign_metrics_spec["name"])The description is part of your prompt. A vague description such as "does metrics" leads to wrong or missing calls. A good one states what the tool returns, what it does not do, and when to prefer it.
A deterministic tool
The most valuable tools in a reporting agent are the boring ones. This function computes click-through rate (CTR), cost per click (CPC) and cost per acquisition (CPA). The model never does the arithmetic. Zero denominators return None instead of raising an error, so one campaign with no clicks does not stop the whole run.
def campaign_metrics(rows):
"""Compute standard performance metrics from per-campaign rows."""
impressions = sum(r["impressions"] for r in rows)
clicks = sum(r["clicks"] for r in rows)
spend = sum(r["spend"] for r in rows)
conversions = sum(r["conversions"] for r in rows)
return {
"impressions": impressions,
"clicks": clicks,
"spend": round(spend, 2),
"conversions": conversions,
"ctr": round(clicks / impressions, 4) if impressions else None,
"cpc": round(spend / clicks, 2) if clicks else None,
"cpa": round(spend / conversions, 2) if conversions else None,
}
rows = [
{"impressions": 10000, "clicks": 200, "spend": 150.0, "conversions": 10},
{"impressions": 5000, "clicks": 50, "spend": 60.0, "conversions": 2},
]
print(campaign_metrics(rows))Note that the function sums first and divides afterward. Averaging each campaign's CTR would weight a campaign with 100 impressions the same as one with 100,000. Summing the raw counts gives the correct blended rate. The totals here are 15,000 impressions, 250 clicks, 210 spend and 12 conversions, which gives a CTR of 0.0167, a CPC of 0.84 and a CPA of 17.5.
The kinds of tools a reporting agent uses
Tools fall into groups with different risk.
| Kind | Example | Risk | Typical control |
|---|---|---|---|
| Pure computation | `campaign_metrics` | Low. No side effects. | Unit tests |
| Read data | Fetch last week's spend from an ad platform | Medium. Can leak data or burn API quota. | Read-only credentials, row limits |
| Search and fetch | Look up a competitor's public pricing page | Medium. Content may be wrong or hostile. | Allowlist of domains |
| Write or act | Change a bid, send an email, publish a report | High. Hard to undo. | Human approval, dry run |
Start with computation and read tools. Add write tools only after the read-only version works, and put approval in front of them (a later chapter covers where people stay in the loop).
Running tool calls safely
The agent code that receives a request is a trust boundary. The model's arguments are untrusted input, in the same way a web form is. A model can invent a tool name, omit a field, or pass a string where a number belongs. Content the model read earlier, such as a web page, can also try to steer it into calling something harmful.
A dispatcher handles these cases in one place:
import json
def run_tool(name, args, tools, specs):
"""Validate and run one tool call. Always return a JSON-safe dict."""
if name not in tools:
return {"error": "unknown tool: " + name}
required = specs[name]["input_schema"].get("required", [])
missing = [k for k in required if k not in args]
if missing:
return {"error": "missing arguments: " + ", ".join(missing)}
try:
return tools[name](**args)
except Exception as exc:
return {"error": type(exc).__name__ + ": " + str(exc)}
tools = {"campaign_metrics": campaign_metrics}
specs = {"campaign_metrics": campaign_metrics_spec}
print(run_tool("campaign_metrics", {}, tools, specs))
print(run_tool("delete_campaign", {"id": 7}, tools, specs))
print(json.dumps(run_tool(
"campaign_metrics",
{"rows": [{"impressions": 100, "clicks": 0, "spend": 5.0, "conversions": 0}]},
tools, specs,
)))This reuses campaign_metrics and campaign_metrics_spec from the earlier blocks, so run them in the same file or session. Three things matter here.
- An unknown name returns an error. It does not crash and does not run anything.
- Errors are returned as data. The model can read "missing arguments: rows" and try again with a correction.
- Only tools in the
toolsdictionary can run. The model has no way to reach a function you did not register.
A full validator would also check types against the schema, for example with the jsonschema package. The required-field check above is the minimum.
Designing tools the model uses well
Tool design affects accuracy as much as prompt wording does. These guidelines come up repeatedly in practice.
- Keep tools narrow.
get_spend_by_channel(start, end)is easier to call correctly thanquery(sql). A free-form query tool also lets the model read tables you never meant to expose. - Name parameters like a person would. Use
start_dateandend_datein ISO format (2026-11-01) and say so in the description. Ambiguous dates such as03/04cause silent errors. - Return compact, labeled results. Send a summary and a row count rather than 50,000 raw rows. Large results use up the context window (the amount of text the model can consider at once) and raise cost.
- Include units and periods in the output.
{"spend": 210.0, "currency": "USD", "period": "2026-11-01/2026-11-07"}lets the report state them without guessing. - Make errors explain themselves. "Date range exceeds 90 days; request a shorter range" gives the model a way to recover. "Error 400" does not.
- Make read tools idempotent. Calling one twice should give the same answer and change nothing.
Common errors
| Symptom | Likely cause | Fix |
|---|---|---|
| Model calculates a ratio itself and gets it wrong | The tool description does not say to use the tool | State in the description that arithmetic must go through the tool |
| Model calls the wrong tool | Two tools have overlapping descriptions | Merge them or state what each does not cover |
| Run stops on a divide-by-zero | Tool raises on empty data | Return `None` and document it |
| Report cites numbers from an old call | Results from different periods mixed in context | Include the period in every result |
| Cost grows with each step | Tool returns very large payloads | Aggregate inside the tool and return a summary |
| Arguments have the wrong type | No validation at the boundary | Validate against the schema before calling |
Testing tools without a model
A tool is plain code, so test it like plain code. Check the normal case, the empty case and the zero-denominator case before connecting a model. A model failure is then easier to diagnose, because you already know the tool behaves correctly.
def test_campaign_metrics():
rows = [{"impressions": 100, "clicks": 0, "spend": 5.0, "conversions": 0}]
result = campaign_metrics(rows)
assert result["cpc"] is None
assert result["cpa"] is None
assert result["ctr"] == 0.0
assert campaign_metrics([])["ctr"] is None
test_campaign_metrics()
print("ok")Next you will see how these tools are called repeatedly inside the agent loop, which also decides when to stop.
Exercise
A teammate adds a tool run_sql(query) that passes the model's text straight to the marketing database with a read-write account. Name two problems and say how you would redesign it.
Show answer
First, the model controls the whole query, so it can read tables the report never needed (such as customer contact data) and, with write access, can modify or delete data. Second, a query tool gives the model no guidance on correct use, so it can produce wrong joins or huge results that waste context. Redesign: replace it with narrow tools such as get_spend_by_channel(start_date, end_date), use a read-only account limited to the needed tables, cap row counts, and return aggregated results with units and the period.
Exercise
campaign_metrics receives rows for two campaigns. Campaign A has 100 impressions and 10 clicks. Campaign B has 10,000 impressions and 100 clicks. What blended CTR does the tool report, and why is averaging the two campaign CTRs wrong?
Show answer
Total clicks are 110 and total impressions are 10,100, so the blended CTR is 110 / 10,100, which rounds to 0.0109. Averaging the campaign CTRs (0.10 and 0.01) gives 0.055, which gives Campaign A's 100 impressions the same weight as Campaign B's 10,000 and overstates the real rate.
Exercise
Why does the dispatcher return errors as a dictionary instead of letting the exception propagate?
Show answer
A returned error becomes a tool result that the model can read, so it can correct a missing argument or choose another tool and continue. An uncaught exception ends the whole run, and a failure in one tool call would then cost the user the entire report.