Skip to content
Visual explainer 3h to learn 4 steps

Function / tool calling

Define tools with JSON schemas and execute model-requested calls safely.

By Invicly Tech, , in AI Engineering with Python. About 11 minutes to read.

Topic 19 of 33

In short

Tool calling lets a model ask your code to run a function, like searching orders or getting the weather. The model only proposes the call; your app validates the arguments, runs it and returns the result.

Explained simply

A language model can only produce text. Tool calling lets it ask your code to do something it cannot do alone: look up an order, check today's weather, search a database. You describe each tool to the model with a name, a short description and the inputs it takes. When the model decides a tool would help, it replies with a structured request instead of a normal answer.

The model never runs anything itself. Your app reads the request, checks the arguments, runs the real function and sends the result back. The model then reads that result and writes its final answer for the user.

Treat the arguments like input typed by a stranger. They can have the wrong type, miss a field, or even be crafted by an attacker who hid instructions in a document the model read. Check them before you run anything.

Good descriptions matter as much as good code. The model chooses tools by reading their names and descriptions, so a vague description leads to the wrong tool or wrong arguments.

Press Play on a diagram to walk through it one step at a time.

SequenceOne tool call round trip
App
LLM API
Tool
  1. 1Messages plus tool schemas
    App to LLM API: Messages plus tool schemas
  2. 2Tool call: get_order(id=42)
    LLM API to App: Tool call: get_order(id=42)
  3. 3Validate arguments
    App to App: Validate arguments
  4. 4Run get_order(42)
    App to Tool: Run get_order(42)
  5. 5Result data
    Tool to App: Result data
  6. 6Send tool result
    App to LLM API: Send tool result
  7. 7Final answer for user
    LLM API to App: Final answer for user
MapAnatomy of a good tool
Tool
  • Name
    • verb_noun, e.g. get_order
    • Unique and specific
  • Description
    • What it does
    • When to use it and when not
    • What it returns
  • Input schema
    • Types and required fields
    • Enums for fixed choices
    • Per-field descriptions
  • Handler
    • Validation and permission checks
    • Timeout and error results
    • Short, structured output

In depth

What the model actually sees and returns

When you pass tools to the API, their names, descriptions and input schemas are added to the model's context. That means tool definitions cost input tokens on every request, and twenty large tools can add thousands of tokens.

The model was trained to produce a special structured block when it wants a tool. The API turns that into a tool call object with three key parts: an ID, the tool name and the arguments as JSON. When you reply, you send the result back tied to that same ID, so the model knows which call it belongs to. Exact field names differ between providers, but this shape is the same everywhere.

Arguments are generated text, so they can occasionally be malformed JSON or break the schema. Many APIs offer a strict mode that constrains the output to your schema. Validate anyway, because a valid shape can still hold a dangerous value.

  • Tool call = ID + name + JSON arguments
  • Tool result must reference the same ID
  • Tool definitions are input tokens on every call

Designing tools the model uses well

Fewer, clearly different tools beat many overlapping ones. If two tools sound alike, the model will mix them up. Use verb_noun names such as search_orders or cancel_order, and write descriptions that say what the tool does, when to use it, when not to, and what it returns.

Make the schema do as much work as possible. Mark required fields, use enums for fixed choices like a status or a unit, and add a description to each field with an example format, such as an ISO date. Narrow inputs mean fewer wrong calls.

Shape results for a reader that pays per token. Return short structured data, not a 5,000-line raw API response. Include IDs the model can pass to the next tool. When something fails, return an error that explains how to fix it, like Order not found. Ask the user for their order number, which starts with ORD-.

  • One job per tool, verb_noun names
  • Enums and required fields shrink mistakes
  • Truncate or summarise big results
  • Errors should say how to recover

Tool choice and parallel calls

Most APIs let you control whether and which tool the model uses. Auto lets the model decide, which is the normal mode for assistants. You can also force a specific tool, a common trick for structured extraction: define one tool whose schema is your output format and require it. Some APIs offer a mode that requires some tool, or none at all. The parameter names differ by provider, so check your SDK docs.

Models can also ask for several tools in a single turn, for example the weather in two cities. Run independent calls at the same time with asyncio.gather, then send all the results back together, each with its own call ID. If one call fails, return an error result for that ID instead of dropping it; most APIs expect a result for every call they issued.

SequenceTwo tool calls in one turn, run in parallel
App
LLM API
Weather tool
Calendar tool
  1. 1Question plus tool schemas
    App to LLM API: Question plus tool schemas
  2. 2Two calls: weather, calendar
    LLM API to App: Two calls: weather, calendar
  3. 3get_weather(Paris)
    App to Weather tool: get_weather(Paris)
  4. 4list_events(tomorrow)
    App to Calendar tool: list_events(tomorrow)
  5. 5Result for call 1
    Weather tool to App: Result for call 1
  6. 6Result for call 2
    Calendar tool to App: Result for call 2
  7. 7Both results with their IDs
    App to LLM API: Both results with their IDs
  8. 8Final answer
    LLM API to App: Final answer

Executing calls safely

Dispatch through an explicit registry: a dictionary from tool name to its schema and function. Never look up functions by a name the model gave you with getattr or eval, or a crafted name could reach code you never meant to expose.

Validate arguments with the tool's Pydantic model. Then check permission using the identity from the user's session, not from the arguments. If get_order receives order_id 42, confirm that order belongs to this user before returning it.

Put a timeout on every tool so one slow API cannot hang the conversation. Catch exceptions and turn them into error results the model can read; a crash helps nobody. For tools with side effects, such as sending email, refunding money or deleting data, ask a human to confirm and use an idempotency key so a retried call does not act twice.

FlowFrom tool call to tool result
  1. 1
    Known tool?

    Look it up in the registry

  2. 2
    Validate args

    Pydantic model for that tool

  3. 3
    Check permission

    Using the session's user

  4. 4
    Confirm if risky

    Human approval for side effects

  5. 5
    Run with timeout

    Catch every exception

  6. 6
    Return result

    Data or a readable error

Learn it in 4 short steps

About 45m each. Track them with a timer in your plan.

  1. 1
    Define tools with JSON schemas~45m
  2. 2
    Handle tool call responses~45m
  3. 3
    Execute calls and return results~45m
  4. 4
    Validate tool arguments safely~45m

Key points

  • Describe each tool with a clear name, description and JSON schema for inputs.
  • The model never runs code itself; your app executes the call.
  • Validate tool arguments like any untrusted input before executing.
  • Return errors to the model as tool results so it can recover.

Key terms

Tap a card to flip it. 0/4 known

Examples

python
from pydantic import BaseModel, Field

class GetOrder(BaseModel):
    order_id: int = Field(gt=0, description='Order number')

TOOLS = [{'name': 'get_order', 'description': 'Look up an order by its number.',
          'input_schema': GetOrder.model_json_schema()}]

def run_tool(name: str, args: dict) -> dict:
    if name == 'get_order':
        params = GetOrder.model_validate(args)  # validate first
        return {'id': params.order_id, 'status': 'shipped'}
    return {'error': f'unknown tool {name}'}

A tool schema from Pydantic and safe dispatch.

A tool registry that never crashes

Your assistant has a get_weather tool. Step 1: describe the input with a Pydantic model, using Literal for the allowed units. Step 2: register the tool name with its model and handler in one dictionary. Step 3: when a call arrives, reject unknown names with a helpful list of valid ones. Step 4: validate the arguments; on failure, return the first error message so the model can fix its call on the next turn. Every path returns a dictionary, so the conversation keeps going.

python
from typing import Literal
from pydantic import BaseModel, ValidationError
class GetWeather(BaseModel):
    city: str
    unit: Literal["c", "f"] = "c"

REGISTRY = {"get_weather": (GetWeather, lambda a: {"city": a.city, "temp": 21, "unit": a.unit})}
def execute(name: str, raw_args: dict) -> dict:
    if name not in REGISTRY:
        return {"error": f"Unknown tool {name}. Valid tools: {list(REGISTRY)}"}
    schema, fn = REGISTRY[name]
    try:
        return fn(schema.model_validate(raw_args))
    except ValidationError as e:
        return {"error": f"Bad arguments: {e.errors()[0]['msg']}"}

Running parallel tool calls

The user asks: Will it rain in Paris and in Rome tomorrow? The model returns two tool calls in one reply, each with its own ID. Step 1: run both at once with asyncio.gather, so the wait is the slowest call, not the sum. Step 2: return_exceptions=True means one failure does not cancel the other. Step 3: build one result per call, matched by ID, turning exceptions into error text. Step 4: send all results back in the next request. The field names here are generic; use your provider's exact format.

python
import asyncio

async def run_calls(calls: list[dict], execute_async) -> list[dict]:
    results = await asyncio.gather(
        *(execute_async(c["name"], c["args"]) for c in calls),
        return_exceptions=True,
    )
    return [
        {"tool_call_id": c["id"],
         "content": f"error: {r}" if isinstance(r, Exception) else str(r)}
        for c, r in zip(calls, results)
    ]

Quick reference

  • The model proposes a call; your code validates, runs it and returns the result
  • Every tool result must reference the ID of the call it answers
  • Name tools verb_noun and say when to use and when not to use each one
  • Use enums and required fields in the schema to narrow what the model can send
  • Dispatch through an explicit registry; never getattr or eval a model-chosen name
  • Check permissions with the session's user, not with IDs from the arguments
  • Return errors as tool results with a hint, instead of raising
  • Force a single tool to get guaranteed structured extraction

Common mistakes

  • Executing model-provided arguments without validation.
  • Writing vague tool descriptions so the model picks the wrong tool.

Quick quiz

Pick an answer to see if you're right and why.

Question 1

1The model asks to call get_order(order_id=42). Which check is most important before returning data?

Question 2

2Why do 30 large tool definitions make every request slower and more expensive?

Question 3

3A tool raises an exception. What should your app do?

Question 4

4What is a common reason to force one specific tool?

Question 5

5The model returns two independent tool calls in one turn. What is the best way to run them?

0/5 answered

Practice exercises

Try each one yourself first. Use the hint if you get stuck, then compare with the solution.

  1. Exercise 1easy

    Write a Pydantic model for a search_orders tool with a required customer_email, an optional status limited to pending, shipped or delivered, and a limit between 1 and 50 (default 10). Print its JSON schema.

  2. Exercise 2medium

    Wrap any tool function with a timeout so a slow tool returns an error result after 5 seconds instead of hanging.

  3. Exercise 3hard

    Add a confirmation gate: tools marked risky are not run directly. Instead, return a pending action with an ID; only when the user approves that ID does the action run.

Check yourself

Answer in your head, reveal, then be honest with yourself.

Feel confident about this topic?

Frequently asked questions

What is the difference between function calling and tool calling?
They are the same idea. Function calling was the earlier name; most providers now say tool calling, and tools can include built-in ones like web search.
Can the model call my API directly?
No. It only returns a request. Your code decides whether to run it, with what checks, and what to send back.
How many tools can I give a model?
There is no single right number, but accuracy drops when tools overlap or the list gets long. Keep a focused set per task, or route to a smaller set first.
Why does the model sometimes ignore my tool?
Usually the description does not make clear when it applies. Rewrite it to say exactly which questions it answers, and test with real prompts.
ShareXLinkedInWhatsApp