The Problem: The Agent That Refunded Twice

Here's a failure pattern that's easy to fall into. A support agent can look up orders and open refund requests. In testing it's great. In production, three things go wrong in the first week:

  • A refund tool call times out. The model, seeing an error, calls it again. Both calls actually went through, and the customer gets two refund tickets.
  • A customer types their order ID as ord-1182. The argument schema expects ORD-1182, validation fails, the model retries with the same value, and the agent loops until it hits the step limit.
  • A vague question ("where's my stuff?") sends the agent through fifteen tool calls and a large bill before it asks the customer for an order number.

The model wasn't the problem in any of these. The tools were.

An AI agent is only as good as its tools. Tool calling (also called function calling) is the mechanism behind every agent framework, from LangChain to the Model Context Protocol (MCP). The model doesn't run anything itself. It asks you to run a function with specific arguments, and you send back the result.

In this guide you'll build a tool-calling loop from scratch in Python, then focus on what actually makes agents reliable: tool design, idempotency, loop detection and limits. The patterns apply whether you use a framework, raw SDK calls or MCP servers.

How Tool Calling Works

Every tool-calling exchange follows the same loop:

  1. You send the conversation plus a list of tool definitions (name, description, JSON Schema for arguments).
  2. The model responds with either a final answer or one or more tool calls.
  3. Your code executes each call and appends the results to the conversation.
  4. Repeat until the model answers without calling a tool.
Text
User ──► LLM ──► tool_call(get_order, {"order_id": "ORD-42"})
                      │
           your code runs get_order()
                      │
          tool result ──► LLM ──► final answer ──► User

The model never touches your database or network. That separation is what makes tool calling safe to build on, as long as you respect it.

A Minimal Agent Loop in Python

We'll build a support agent that can look up orders and request refunds. Tools are plain Python functions with Pydantic models for their arguments.

Python
# tools.py
from pydantic import BaseModel, Field

class GetOrderArgs(BaseModel):
    order_id: str = Field(pattern=r"^ORD-\d+$", description="Order ID like ORD-1234")

class RequestRefundArgs(BaseModel):
    order_id: str = Field(pattern=r"^ORD-\d+$")
    reason: str = Field(max_length=500, description="Short reason given by the customer")

async def get_order(args: GetOrderArgs) -> dict:
    order = await orders_repo.find(args.order_id)  # your data access layer
    if order is None:
        return {"error": f"No order found with id {args.order_id}. Ask the customer to check the ID."}
    return {"order_id": order.id, "status": order.status, "total": order.total, "items": order.items}

async def request_refund(args: RequestRefundArgs) -> dict:
    ticket = await refunds.create(order_id=args.order_id, reason=args.reason)
    return {"refund_ticket": ticket.id, "status": "pending_review"}

Register them with their schemas:

Python
from dataclasses import dataclass
from typing import Awaitable, Callable

@dataclass
class Tool:
    name: str
    description: str
    args_model: type[BaseModel]
    fn: Callable[[BaseModel], Awaitable[dict]]

    def spec(self) -> dict:
        return {
            "type": "function",
            "function": {
                "name": self.name,
                "description": self.description,
                "parameters": self.args_model.model_json_schema(),
            },
        }

TOOLS = {
    t.name: t
    for t in [
        Tool(
            "get_order",
            "Look up a single order by ID. Use this before answering any question about an order.",
            GetOrderArgs, get_order,
        ),
        Tool(
            "request_refund",
            "Open a refund request for an order. Only call after confirming the order exists "
            "and the customer explicitly asked for a refund. Does not issue money immediately.",
            RequestRefundArgs, request_refund,
        ),
    ]
}

Now the loop:

Python
# agent.py
import json
import os
from openai import AsyncOpenAI
from pydantic import ValidationError

client = AsyncOpenAI()
MODEL = os.getenv("LLM_MODEL", "gpt-4o")
MAX_STEPS = 8

async def run_tool(name: str, raw_args: str) -> str:
    tool = TOOLS.get(name)
    if tool is None:
        return json.dumps({"error": f"Unknown tool '{name}'. Available: {list(TOOLS)}"})
    try:
        args = tool.args_model.model_validate_json(raw_args)
    except ValidationError as exc:
        return json.dumps({"error": f"Invalid arguments: {exc.errors(include_url=False)}"})
    try:
        return json.dumps(await tool.fn(args))
    except Exception as exc:  # never let a tool crash the loop
        return json.dumps({"error": f"{name} failed: {type(exc).__name__}. Try again or explain to the user."})

async def run_agent(messages: list[dict]) -> str:
    for _ in range(MAX_STEPS):
        response = await client.chat.completions.create(
            model=MODEL,
            messages=messages,
            tools=[t.spec() for t in TOOLS.values()],
        )
        msg = response.choices[0].message
        messages.append(msg.model_dump(exclude_none=True))

        if not msg.tool_calls:
            return msg.content

        for call in msg.tool_calls:
            result = await run_tool(call.function.name, call.function.arguments)
            messages.append({"role": "tool", "tool_call_id": call.id, "content": result})

    return "Sorry, I couldn't finish that request. A human will follow up."

That's a complete agent in about 40 lines. Everything else is about making it behave.

Designing Tools the Model Can Use Correctly

1. Name tools like verbs, describe them like docs

The model chooses tools almost entirely from names and descriptions. Write them for a new teammate who has never seen your codebase.

  • ✅ search_customers — "Search customers by name or email. Returns at most 10 matches with their IDs."
  • ❌ customer_tool — "Customer stuff."

Say when to use a tool and when not to, and mention side effects: "Sends an email immediately. Cannot be undone."

2. Fewer, sharper tools

Every tool you add makes every choice harder. If two tools overlap, the model will pick the wrong one some of the time. Merge get_order_status, get_order_items and get_order_total into one get_order. Split tools only when they have different side effects or permissions.

3. Constrain arguments with schemas

Enums, patterns and bounds turn bad calls into immediate, explainable validation errors instead of weird downstream bugs. This is the same idea as structured outputs with Pydantic, applied to inputs.

4. Return what the model needs, not everything you have

Dumping a 200-field database row wastes tokens and buries the signal. Return the handful of fields that answer likely questions, plus IDs the model might need for a follow-up call. For lists, paginate and say so: {"results": [...], "truncated": true, "hint": "narrow the search with a date range"}.

5. Write errors as instructions

The model reads your error messages and decides what to do next. Make them actionable:

  • ❌ {"error": "404"}
  • ✅ {"error": "No order ORD-981 found. Order IDs look like ORD-1234. Ask the customer to double-check."}

A good error message often turns a failed run into a successful one with zero code changes.

Safety: Permissions, Confirmation and Limits

Tool calling means an LLM can trigger real actions, so treat it with the same care as any public API.

Authorize in the tool, not the prompt

Never rely on "only look up the current user's orders" in the system prompt. Pass the authenticated user into the tool and enforce it in code:

Python
async def get_order(args: GetOrderArgs, user: User) -> dict:
    order = await orders_repo.find(args.order_id)
    if order is None or order.customer_id != user.id:
        return {"error": f"No order {args.order_id} found on this account."}
    ...

Returning the same message for "doesn't exist" and "not yours" avoids leaking which IDs are valid. The JWT authentication guide covers getting a trustworthy user identity into your handlers.

Require confirmation for destructive actions

For anything that moves money, deletes data or contacts people, have the tool return a proposal first and require an explicit user confirmation before executing:

Python
class ProposedAction(BaseModel):
    action: str
    summary: str
    confirmation_token: str

# request_refund returns a ProposedAction; the UI shows "Confirm refund of $42?"
# Only a separate, user-initiated request with the token actually executes it.

Cap everything

  • Steps: a maximum number of loop iterations (the MAX_STEPS above).
  • Cost: a token budget per run.
  • Time: an overall timeout with asyncio.timeout().
  • Rate: per-user limits on expensive tools. See rate limiting in FastAPI.

Agents that hit a cap should stop gracefully with a clear message, not crash.

Treat tool results as untrusted

Content returned by tools (web pages, emails, documents) can contain instructions aimed at your model. That's prompt injection, and it deserves its own article: securing LLM-powered apps.

Parallel Tool Calls

Modern models can request several tool calls in one turn, such as looking up three orders at once. The loop above runs them sequentially. For independent, read-only tools, run them concurrently:

Python
import asyncio

results = await asyncio.gather(
    *(run_tool(c.function.name, c.function.arguments) for c in msg.tool_calls)
)
for call, result in zip(msg.tool_calls, results):
    messages.append({"role": "tool", "tool_call_id": call.id, "content": result})

Keep tools with side effects sequential, so the order of actions stays predictable.

Debugging Agents

When an agent misbehaves, the transcript tells you why. Log every step with the tool name, arguments, result size and latency, and keep full transcripts for failed runs.

The usual fixes, in order of how often they work:

  1. Improve a tool description or error message.
  2. Remove or merge an overlapping tool.
  3. Tighten an argument schema.
  4. Only then, change the system prompt or the model.

Turn the failing transcripts into test cases so fixes stay fixed. How to evaluate LLM applications shows how to build that harness.

Production Gotchas (and What to Do About Them)

Make side-effecting tools idempotent

Models retry, networks time out, and users press the button twice. Any tool that changes state should accept an idempotency key and return the original result when it sees the same key again:

Python
import hashlib, json

def idempotency_key(conversation_id: str, tool: str, args: BaseModel) -> str:
    payload = json.dumps(args.model_dump(), sort_keys=True)
    return hashlib.sha256(f"{conversation_id}:{tool}:{payload}".encode()).hexdigest()

async def request_refund(args: RequestRefundArgs, ctx: RunContext) -> dict:
    key = idempotency_key(ctx.conversation_id, "request_refund", args)
    if existing := await refunds.find_by_key(key):
        return {"refund_ticket": existing.id, "status": existing.status, "note": "already requested"}
    ticket = await refunds.create(order_id=args.order_id, reason=args.reason, idempotency_key=key)
    return {"refund_ticket": ticket.id, "status": "pending_review"}

Normalize before you validate

Strict schemas are good, but rejecting ord-1182 because of letter case just creates loops. Clean up obvious variations first, then validate:

Python
from pydantic import field_validator

class GetOrderArgs(BaseModel):
    order_id: str = Field(pattern=r"^ORD-\d+$")

    @field_validator("order_id", mode="before")
    @classmethod
    def normalize(cls, v: str) -> str:
        v = str(v).strip().upper().replace(" ", "")
        return v if v.startswith("ORD-") else f"ORD-{v.lstrip('#')}"

Detect loops explicitly

If the model calls the same tool with the same arguments twice in one run, it's almost always stuck. Don't execute the call. Return a message that changes the situation:

Python
seen: set[tuple[str, str]] = set()

def check_loop(name: str, raw_args: str) -> str | None:
    key = (name, raw_args)
    if key in seen:
        return json.dumps({"error": "You already called this with the same arguments. "
                                    "Use the earlier result or ask the user for more information."})
    seen.add(key)
    return None

Put timeouts on every tool

A slow dependency shouldn't freeze the whole agent. Wrap each call in asyncio.timeout() and return the timeout as an actionable error ("The order service is slow right now; tell the user you'll follow up"), not an exception.

Tool results bloat the context

Every result stays in the conversation, so long runs get slower, more expensive and less accurate. Keep results small, and for long conversations replace older tool results with short summaries.

Model upgrades change tool behavior

A new model version may pick tools differently or format arguments differently. Keep a set of recorded conversations with the expected tool calls, and re-run it before switching models. How to evaluate LLM applications covers the harness.

Conclusion

Tool calling is a simple protocol: the model asks, your code acts, the model reads the result. Reliability comes from how you design that contract. Write clear names and descriptions, keep the toolset small, validate arguments, return focused results, write actionable errors, and enforce permissions in code.

Get the tools right and you'll find you need far less prompt engineering, and far fewer apologies from your agent.


Resources:

Related Articles: