🎉 75% of content is free forever — Unlock Premium from $10/mo →
CW
NEWSLIVESearch All Content
đŸ’ŧ Servicesâ„šī¸ Aboutâœ‰ī¸ ContactView Pricing Plansfrom $10

Function Calling: Designing Tools for LLMs

đŸŸĸ Free Lesson

Function Calling: Designing Tools for LLMs

Function Calling FlowUserQueryIntentLLMParse RequestSelect FunctionGenerate ArgsRouterFunction CallParametersExecuteToolsAPI CallsDatabase QueryFile OperationsWeb Search

What the model is really deciding

Function calling does not give the model the ability to run code. The model still only produces text; it produces a specific, structured piece of text — a function name plus a JSON object of arguments — and your runtime decides whether to execute it. That separation is the whole security model, and it is worth stating plainly: the model proposes, your code disposes.

The proposal comes from the schema you send with the request. The model reads each function's name, description, and parameter types, then decides from the conversation whether a call is appropriate and fills in values it can infer. Everything it cannot infer — identifiers, permissions, the current user's role — must be resolved by your code after the call returns, never trusted from the model's output. Treating the argument JSON as a suggestion rather than a command is the single most important habit in tool-using systems.

Schemas the model can fill correctly

Most failed tool calls are bad schemas. A model that has to guess a date format or choose between three similarly described functions will guess, and it will guess inconsistently.

python
TOOLS = [
    {
        "type": "function",
        "function": {
            "name": "search_orders",
            "description": (
                "Look up customer orders by status. Use this when the user asks "
                "about their order history, shipment status, or refunds. "
                "Do not use for product availability."
            ),
            "parameters": {
                "type": "object",
                "properties": {
                    "customer_email": {
                        "type": "string",
                        "description": "Email on the account, lowercase.",
                        "format": "email",
                    },
                    "status": {
                        "type": "string",
                        "enum": ["pending", "shipped", "delivered", "refunded"],
                        "description": "Filter by order status. Omit for all orders.",
                    },
                    "limit": {
                        "type": "integer",
                        "minimum": 1,
                        "maximum": 50,
                        "default": 10,
                        "description": "Maximum orders to return.",
                    },
                },
                "required": ["customer_email"],
                "additionalProperties": False,
            },
        },
    }
]

Four choices do most of the work. The description says when to use the tool and, just as importantly, when not to — models over-call ambiguous tools. Enums replace free strings wherever a closed set exists. Numeric bounds express valid ranges instead of hoping the model respects a prose instruction. And additionalProperties: False blocks invented fields that would otherwise reach your handler as surprises.

The request and response cycle

A call passes through three shapes: your tools array in, a tool-call message back, and a tool result message returned so the model can continue.

python
import json
from openai import OpenAI

client = OpenAI()

def run_turn(question: str, tools, handlers) -> str:
    messages = [{"role": "user", "content": question}]

    while True:
        response = client.chat.completions.create(
            model="gpt-4o-mini",
            messages=messages,
            tools=tools,
            tool_choice="auto",
        )
        message = response.choices[0].message

        if not message.tool_calls:
            return message.content or ""

        messages.append(message)              # assistant turn with tool_calls
        for call in message.tool_calls:
            try:
                args = json.loads(call.function.arguments or "{}")
                handler = handlers.get(call.function.name)
                if handler is None:
                    raise ValueError(f"unknown tool {call.function.name}")
                result = handler(**args)
                payload = json.dumps(result)[:4000]
            except Exception as exc:
                payload = json.dumps({"error": str(exc)})   # feed failure back
            messages.append({
                "role": "tool",
                "tool_call_id": call.id,
                "content": payload,
            })

Notice the error branch returns a message instead of raising. A model that reads {"error": "customer_email is required"} can repair its arguments on the next pass; a raised exception gives it nothing to work with and surfaces as a broken user experience.

One loop, several calls, clear termination

Real tasks need more than one call, so the loop must be bounded and observable.

python
class ToolLoop:
    def __init__(self, client, model, tools, handlers, max_rounds=5, verbose=False):
        self.client, self.model = client, model
        self.tools, self.handlers = tools, handlers
        self.max_rounds, self.verbose = max_rounds, verbose

    def run(self, question: str) -> str:
        messages = [{"role": "user", "content": question}]
        rounds = 0

        while rounds < self.max_rounds:
            rounds += 1
            response = self.client.chat.completions.create(
                model=self.model, messages=messages, tools=self.tools)
            message = response.choices[0].message

            if not message.tool_calls:
                return message.content or ""

            messages.append(message)
            for call in message.tool_calls:
                name = call.function.name
                if self.verbose:
                    print(f"round {rounds}: {name}({call.function.arguments})")
                try:
                    args = json.loads(call.function.arguments or "{}")
                    result = self.handlers[name](**args)
                    content = json.dumps(result, default=str)[:4000]
                except Exception as exc:
                    content = json.dumps({"error": f"{name}: {exc}"})
                messages.append({"role": "tool", "tool_call_id": call.id,
                                 "content": content})

        messages.append({"role": "user",
                         "content": "Stop calling tools and give your best answer now."})
        final = self.client.chat.completions.create(model=self.model, messages=messages)
        return final.choices[0].message.content or ""

Two safeguards matter here. The round cap converts an infinite tool spiral into a bounded cost, and the forced final turn guarantees the user receives an answer even when the model has not decided to stop. Track how often each cap is hit — it is your clearest metric for tool descriptions that confuse the model.

Designing tools for a machine reader

The model is the primary audience for your tool definitions, and humans are secondary.

Design choiceWeak versionStrong version
Scopemanage_orders handles five verbsOne action per tool, verb in the name
Description"Searches orders"Says when to use it and when not to
Time arguments"date" as a stringISO 8601 with an explicit format note
Paginationnonelimit and cursor with stated defaults
Errorsstack traceActionable message the model can act on
Result sizewhole recordsTrimmed fields, truncated to a cap

Tools should also be safe to call twice. If a request can create an order or send an email, make it idempotent with a client-generated key, because retries happen — timeouts, model re-requests, and your own round cap can all replay a call.

Parallel calls, permission and safety

Providers can return several tool calls in one response, and executing independent ones concurrently cuts latency substantially. Sort them by dependency first: reading order status and reading customer profile can run together, while a write that depends on a read cannot.

Permission is the part teams skip. Any tool that writes, spends, or sends should be classified, with high-risk calls requiring confirmation outside the model loop — a human approval, an allow-list of targets, or at minimum an audit record with the actor, the arguments, and the model version that proposed it. The model has no notion of your blast radius; the runtime does.

Knowing which tool is failing

Tool calling is one of the few places where you can measure language-model behaviour with ordinary application metrics, because every step produces a structured event. Log the tool name, the parsed arguments, the outcome, the latency, and the round number at which the call happened. From those events you can derive a per-tool acceptance rate: how often a call for that tool led to a successful result rather than an error, a retry, or an abandoned run.

A falling acceptance rate is the earliest warning you get. It moves before user complaints do, because the model is already struggling to fill the schema correctly while users still receive plausible-looking answers. Pair it with two more ratios — calls per completed task, which detects tools the model is calling repeatedly without effect, and first-call correctness, which measures how often the very first tool call was already right.

SignalHealthyDegradingLikely cause
Acceptance rate per toolstable above 95 percentfalling week over weekdescription drift after a release
Calls per completed taskflatclimbingmissing pagination or filter defaults
First-call correctnesshighdroppingambiguous tool overlap
Argument repair loopsrarefrequentmissing enum or format guidance

Trace one degraded tool end to end before changing anything: read the arguments the model chose, compare them with the schema, and you will usually find a description that no longer matches what the function actually does.

What usually breaks

Failures cluster in predictable places. The model calls a tool for the wrong intent because two descriptions overlap — narrow both. It invents argument values because a required field had no source — make it optional or resolve it server-side. It loops on a failing call because the error message says only "invalid request" — return the specific field and expected format. And it stops early with a plausible answer instead of calling anything at all, which usually means the tool description did not promise enough value for the trouble.

Fix the schema before you add prompt exhortations. Better descriptions beat longer instructions nearly every time.

Common Mistakes

Trusting model-supplied arguments as authoritative

Fix: Re-validate every argument against your own schema and permissions; the model proposes, your code decides.

Returning raw exception text or stack traces to the model

Fix: Return a structured error naming the field, the constraint, and what a valid value looks like.

Giving one tool five responsibilities

Fix: Split by verb; separate tools with narrow descriptions are selected far more reliably.

Leaving the tool loop unbounded

Fix: Cap rounds and force a final answer, then alert when either safeguard triggers.

Best Practices

  • Use enums, bounds, and additionalProperties false on every tool schema.
  • Make write operations idempotent with a client-generated key before exposing them to a loop.
  • Log tool name, arguments, latency, and error rate per call; these are your tool-level SLOs.
  • Prefer returning trimmed fields over whole records to keep context windows small and focused.

Interview Questions

Q1: Where does the actual execution of a tool happen?

In the application runtime, never in the model. The model emits a structured tool call; your code validates it, checks permissions, executes, and returns the result as a message.

Q2: How do you stop an agent from looping on a failing tool?

Return an actionable error as a tool message, cap the number of rounds, and force a final answer once the cap is reached; then alert on how often the cap fires.

Q3: What makes a tool schema reliable?

Closed enums for bounded values, explicit formats and ranges, a description covering both when to use and when not to, and no additional properties.

Key Takeaways

  • The model proposes a structured call; your runtime validates, authorises, and executes it.
  • Schema quality drives success rates: enums, bounds, narrow scope, and a description that names the negative case.
  • Feed errors back as tool messages so the model can self-correct instead of failing silently.
  • Bound the loop with round caps and a forced final answer, and treat cap hits as a monitoring signal.
  • Classify tools by blast radius and require human confirmation for anything that writes, spends, or sends.
CW

ChatWhole Learn Editorial Team

Written by experienced data scientists, software engineers, and educators. All content is reviewed by industry professionals to ensure accuracy and relevance.

Last reviewed: 2026-10-12

—
☆☆☆☆☆
0 ratings

Rate & Feedback

Need Expert Generative AI Help?

Get personalized tutoring, project support, or professional consulting.

Advertisement