Module 1 · Multi-agent system foundations
Designing a reliable, idempotent tool call
6 min read
In a multi-agent system, tools are the boundary between the model's reasoning and the real world. A badly designed tool produces wrong calls, loops, duplicate actions — or security holes. This lesson details what separates a demo tool from a production tool.
Anatomy of a tool definition
A tool is described by three elements: a name, a description and an input schema. The model sees nothing else; it is your only way of explaining when and how to use it.
{
"name": "search_knowledge",
"description": "Searches the knowledge base. Returns up to k documents (id, title, excerpt). "
"Use it before making any factual claim.",
"strict": True,
"input_schema": {
"type": "object",
"properties": {"query": {"type": "string"}, "k": {"type": "integer"}},
"required": ["query", "k"],
"additionalProperties": False,
},
}
The description is a prompt
The description is the most important and most neglected element. A good description answers three questions:
- What does the tool do? ("Searches the knowledge base")
- What does it return? ("up to k documents: id, title, excerpt")
- When should it be used — and when not? ("before making any factual claim")
If two tools look alike (search_knowledge and read_document), the description must spell out how they fit together: "from an id returned by search_knowledge".
Strict schemas
"strict": True guarantees that the arguments produced by the model match the schema exactly (types, required fields, no extra fields). It requires additionalProperties: false and the required list. Without it, you must validate every call yourself and handle malformed arguments.
The schema describes the shape; business rules (bounds, consistency) are still checked in your execution code.
A word on forcing a tool call
The most recent models reject requests that force a specific tool call (tool_choice of type any or tool). Best practice: leave tool_choice on automatic, explicitly ask in the prompt for the tool, keep strict: True for argument validity — and check in your code that a call actually happened. If you only wanted JSON back, use structured outputs instead (lesson 3.1).
Errors that help the model correct itself
When a tool fails, two bad reactions are common: letting the exception crash the agent, or returning a vague message. The right reaction is to return an actionable error with is_error: True:
def read(doc_id: str) -> str:
for d in CORPUS:
if d["id"] == doc_id:
return d["text"]
return f"Error: document '{doc_id}' not found. Use an id returned by search."
The message says what is wrong and how to fix it. The model then runs another search instead of making up content. Compare with Error 404: technically correct, practically useless.
| Bad message | Good message |
|---|---|
KeyError: 'doc-xyz' | Document 'doc-xyz' not found. Use an id returned by search. |
Invalid date | Date '02/31' is invalid. Expected format: YYYY-MM-DD. |
Rate limited | Service temporarily overloaded. Retry in 30 seconds or use the cache. |
Controlling result size
A tool that returns 200 KB of JSON saturates the context, increases costs and drowns useful information. Design rules:
- Paginate: return
kresults, and a way to get the next ones. - Excerpt: return excerpts (
excerpt) in search, full text only on request (read_document). - Truncate explicitly: if you cut, say so ("… 3,400 more lines, refine the query"), otherwise the model believes it has seen everything.
- Structure: named fields rather than a block of text.
Idempotency: the golden rule of tools that act
Read tools can be replayed safely. Action tools (create a ticket, send an email, charge an account) cannot. Yet in an agentic system, replays are inevitable:
- the SDK automatically retries some network errors;
- a LangGraph node can be re-run by a retry policy;
- after a pause for human approval, the node restarts from the beginning (module 4);
- the model itself may re-request an action whose result it did not see.
The remedy is the idempotency key: a unique identifier per action intent, which the external system (or your tool layer) uses to ignore duplicates.
import hashlib
_done: dict[str, str] = {} # in production: a database table with a uniqueness constraint
def create_ticket(title: str, body: str, run_id: str) -> str:
"""Creates a ticket only once per (run, content), even when replayed."""
key = hashlib.sha256(f"{run_id}|{title}|{body}".encode()).hexdigest()
if key in _done:
return f"Ticket already created: {_done[key]} (no duplicate)."
ticket_id = ticketing_api.create(title=title, body=body, idempotency_key=key)
_done[key] = ticket_id
return f"Ticket created: {ticket_id}"
The run_id (the graph execution identifier, for instance the thread_id) is supplied by your code, never chosen by the model: you don't make the model responsible for avoiding duplicates.
Dedicated tools rather than a universal shell
It is tempting to give an agent an "execute a shell command" tool: it can then do anything. But your harness then only sees an opaque string, identical for every action. A dedicated tool (send_email(to, subject, body)) instead gives you a typed hook to:
- validate (is the recipient allowed?);
- request human approval for irreversible actions;
- log and audit;
- parallelize safely (a read can run in parallel, a
git pushcannot).
Rule of thumb: start broad to explore, then promote to a dedicated tool any action you need to control, audit or parallelize.
Production tool checklist
- Explicit, unique name with an action verb (
search_,read_,create_). - Description: what, what it returns, when to use it (and when not to).
-
strictschema, required fields,additionalProperties: false. - Business validation in the execution code.
- Actionable errors returned with
is_error: True, never an unhandled exception. - Bounded result size (pagination, excerpts, signaled truncation).
- Idempotency for any action with side effects.
- Timeout on external calls.
- Every call logged (module 5).
Key takeaways
- A tool's description is a prompt: it must say what, what it returns, and when.
strict: Trueguarantees argument shape; code guarantees business rules.- A tool error is information for the model: make it actionable.
- Every action with side effects must be idempotent, because replays are inevitable.
Hands-on
- Rewrite the description of a tool from your own project using the three questions of this lesson.
- Add a
max_charsparameter toread_documentwith a truncation that is signaled to the model. - Simulate a replay of
create_ticket(call it twice with the same arguments) and check that no duplicate is created.