Tool calling
How tool calling gives an LLM tool access
Say this
An LLM can only produce text, so it can't call anything by itself. Tool calling is a contract. My application sends the model a list of tools, each with a name, a description of when to use it, and a JSON schema for its arguments. The model was fine-tuned to answer, when it needs a tool, not with prose but with a structured call: the tool's name and JSON arguments. My code reads that call, runs the real function, and sends the result back as a tool message with the same call id. The model reads the result and either answers or asks for another tool. So the model decides what to do; my code decides whether and how it's done. In my projects that's ZargarShop on Gemini Live, my railway bot through OpenRouter, an analytics assistant through MCP, and Tez, where a fine-tuned small model writes tool plans under a grammar.
What happens under the hood (how the model "knows" the tools)
The tool list is turned into text by the model's chat template and placed in the prompt. The model was trained on many examples of "tools + request → structured call", so it learned to output the call in a fixed format. Qwen models, for example, use special tags:
system: ... <tools> {"name": "search_trains", "parameters": {...}} </tools>
assistant: <tool_call> {"name": "search_trains", "arguments": {...}} </tool_call>
tool: <tool_response> {"trains": [...]} </tool_response>The API (OpenAI, Anthropic, Gemini, Ollama) hides these tags and gives you clean JSON. Some providers also use constrained decoding, so the arguments always match the schema.
| Provider | You send | Model returns | You reply with |
|---|---|---|---|
| OpenAI-style (also OpenRouter, Ollama) | tools | tool_calls | role tool + tool_call_id |
| Anthropic | tools with input_schema | tool_use block | tool_result block |
| Gemini (and Gemini Live) | functionDeclarations | functionCall / toolCall | functionResponse / toolResponse |
| MCP | a server lists its tools | the client calls tools/call | the server returns the result |
Designing tools the model uses correctly
- The description is a prompt. Say what it does, when to use it, and when not to: "Use when the customer asks what's in stock. Don't use for prices of items already shown."
- Narrow arguments: enums for fixed values (category: uzuk, sirg'a…), required fields marked, units in the description (so'm, YYYY-MM-DD).
- Few, distinct tools. Many similar tools confuse the model and cost prompt tokens; 50 tools × 150 tokens is 7,500 tokens before the question.
- Clear names:
search_products, notdo_query2. - Return compact, labelled results the model can read: only the fields it needs.
Control options
- Tool choice: auto (the model decides), required/any (must call one), none, or one specific tool. Gemini: AUTO / ANY / NONE.
- Parallel calls: the model can request several independent calls in one turn; run them concurrently.
- Multi-step (agent loop / ReAct): call → observe → decide again, with a maximum number of rounds.
- Structured output vs tool calling: structured output means the JSON is the final answer; tool calling means the JSON is a request for an action whose result comes back.
Example project
- ZargarShop: tool declarations set up once in the Gemini Live session; the model sends
toolCallduring the phone call, my backend returnstoolResponse, and the conversation continues. - Railway seat-alert bot: an LLM agent through OpenRouter with tools like
search_trainsandadd_watch. I found that when a tool call stayed in the history without its result, the model invented "the search returned nothing", so the history code drops unpaired tool messages. - Tez: a small local model fine-tuned to write a plan of tool calls (19 tools) as JSON, with a grammar that makes invalid JSON or unknown tool names impossible.
Trap questions
- "Does the model run the tool?" Never. It only writes the request. Execution, permissions and errors are my code's job.
- "How does it know when to call a tool?" From training plus the tool descriptions. Better descriptions → better choices, and I measure tool-selection accuracy on labelled requests.
- "What if it invents a tool or an argument?" The registry rejects unknown names and schema validation rejects bad arguments; the error goes back to the model so it can correct itself.
- "Tool calling vs MCP?" Tool calling is the mechanism between the model and the app. MCP is a standard way to package and serve tools so any app can use them.
How a tool is executed
Say this
When the model's tool call arrives, my backend treats it like untrusted input from the internet. It parses the JSON, checks the tool name against a registry of allowed tools, and validates the arguments against the schema: types, enums, ranges. Then it checks permissions for the real user, not for what the model asks. Anything with side effects, like creating an order, needs a confirmation step first. The function runs with a timeout, retries only on temporary errors, and uses an idempotency key so a retry can't create a duplicate. The result is trimmed to the fields the model needs, with no secrets, and returned with the same call id. Errors come back as clear structured messages, so the model can fix its arguments instead of guessing. Every call is logged, the loop has a maximum number of rounds, and the final answer is checked so its numbers really come from the tool results.
- 1Parse JSONmalformed → "invalid_json" back to the model
- 2Registry lookupunknown name → "unknown_tool" + the allowed tools
- 3Validate argumentswrong type, enum or range → error naming the field and why
- 4Normalizedates, numbers said as words, Latin/Cyrillic spelling
- 5Authorizeis THIS user allowed? never trust the model
- 6Confirm side effectscreate, pay, send → read it back to the user, wait for "yes"
- 7Executetimeout, retry with backoff on transient errors, idempotency key
- 8Shape the resultonly the needed fields, a size cap, no secrets or extra personal data
- 9Returntool_result with the same call id
- 10Logtool, args, user, latency, result size, error
The core in code (simplified)
TOOLS = {"search_products": (SearchArgs, search_products),
"create_order": (OrderArgs, create_order)} # the allowlist
def run_tool(call, user):
if call.name not in TOOLS:
return {"error": "unknown_tool", "allowed": list(TOOLS)}
Args, fn = TOOLS[call.name]
try:
args = Args.model_validate_json(call.arguments) # Pydantic schema
except ValidationError as e:
return {"error": "invalid_arguments", "details": e.errors()}
if not permitted(user, call.name, args):
return {"error": "forbidden"}
try:
result = with_timeout(fn, args, user=user, seconds=5)
except TimeoutError:
return {"error": "timeout", "hint": "try a narrower search"}
log(call, args, user, result)
return shrink(result) # only needed fields
for _ in range(MAX_ROUNDS): # the agent loop
reply = llm(messages, tools=SCHEMAS)
if not reply.tool_calls:
return reply.text
messages.append(reply)
for call in reply.tool_calls: # parallel if independent
messages.append({"role": "tool", "tool_call_id": call.id,
"content": json.dumps(run_tool(call, user))})
return "I couldn't finish this; a staff member will help you."| Situation | What to do |
|---|---|
| Bad arguments | return which field is wrong and why; the model retries; cap the retries |
| Temporary failure (network, 503) | retry with backoff (1 s, 2 s, 4 s), then a clear error |
| Permanent failure (not found, forbidden) | no retry; say it plainly so the model tells the user |
| Empty result | return "nothing found" explicitly, never an empty string the model might fill in |
| Huge result | aggregate, paginate, or return the first N plus the total count |
| Slow tool | start it, return a job id, report when done |
| Side effect (order, payment, message) | confirmation first, idempotency key, least-privilege permission, human review if risky |
| Code-running tool | an isolated sandbox: no network, CPU/memory/time limits, throwaway filesystem |
Example project
- Railway bot: results are filtered in Python by the user's time window and train type, so the model can't present seats outside what was asked.
add_watchrefuses inputs the poller can't use, such as a window that already passed. Seats are double-checked against the API before an alert. History repair drops a tool call that has no result, after I saw the model invent "nothing found". - ZargarShop:
create_orderis the only write. The order is read back and confirmed by the customer, then saved with status "new" for staff review. - Testing: end-to-end tests record every tool call and assert the final database state, and that every train number in the reply appears in that turn's search result.
Trap questions
- "Where does the tool run?" In my backend, never at the model provider. The provider only sees descriptions and results.
- "Why return errors to the model instead of raising?" A specific error ("date must be YYYY-MM-DD") lets the model fix itself; an exception just breaks the conversation.
- "How do you stop infinite loops?" A maximum number of rounds, detecting the same call repeated, and a polite hand-off message when the limit is hit.
- "How do you test tools?" Unit tests per tool (including empty and huge results), end-to-end tests with recorded calls, and tool-selection accuracy on labelled requests.
Questions about this chapter?
The course, homework review and the other five books are in Uzbek. Questions in English are welcome on Telegram.