Tool Calls You Can Rely On

When a language model asks for a tool, your program receives a function name and some arguments that the model wrote, and it is your program that runs the function. So tool calling is only as reliable as the code around it. That code checks the arguments before anything runs and tells the model when a call fails. It answers every call the model makes in one reply, and it stops the exchange before it goes on for ever.

The arguments are text the model wrote

A tool call on an assistant message carries an id, a function name and its arguments. The arguments are not a Python dictionary. They are a string of JSON, generated by the model one token at a time, exactly like any other text it writes. The tool definition you sent describes what the arguments should look like, but a description is not a guarantee.

The reference for Chat Completions says this plainly: the model does not always generate valid JSON, and it may invent parameters your function schema does not define, so the arguments should be validated in your code before the function is called.

Some providers offer a strict option that constrains the call to the schema. On Chat Completions it is off unless you ask for it, and not every endpoint offers it. Even when it is on, it governs only the shape of the arguments, not their meaning: an order number with a typo is still a perfectly valid string.

So a tool call can arrive in several broken forms, and each needs a check that catches it:

Arguments the model wroteWhat is wrongWhat catches it
{"order_id": "A-1042"Not valid JSON (the brace is missing)Parsing the JSON
{}A required field is missingThe typed model
{"order_id": "A-1042", "refund": true}A parameter the tool never definedThe typed model, set to forbid extra fields
{"order_id": "1042"}Right type, wrong formA rule on the value, such as a pattern
{"order_id": "A-9999"}Well formed, but no such orderThe tool itself, when the lookup finds nothing
{"order_id": "A-1042"}NothingSafe to run

A Pydantic model describes the arguments one tool accepts, and its model_validate_json() method does the first three checks in one step: it parses the string and validates the result against the fields. Two settings matter here. The first is about unknown keys. By default Pydantic ignores them (extra='ignore'), so an invented parameter would be dropped without a word; extra="forbid" turns it into an error. The second is Field(pattern=...), which checks that a string has the expected form before any lookup runs.

Validate before anything runs
from pydantic import BaseModel, ConfigDict, Field, ValidationError

class OrderLookup(BaseModel):
    model_config = ConfigDict(extra="forbid")
    order_id: str = Field(pattern=r"^A-\d{4}$")

try:
    args = OrderLookup.model_validate_json(call.function.arguments)
except ValidationError as err:
    print(err.errors())   # nothing has run yet
else:
    status = look_up_order(args.order_id)

When validation fails, err.errors() lists every problem. Each one names the field it concerns (loc), gives a readable message (msg) and has an error type, one per kind of failure:

  • json_invalid for text that is not JSON,
  • missing for an absent field,
  • extra_forbidden for an invented one,
  • string_pattern_mismatch for a value of the wrong form.

The function is reached only through the else branch, so it never sees arguments that failed.

True or false?

If the tool definition lists the parameters, the arguments of a call always match them.

False. The definition only describes the arguments to the model. They are still generated text and can be invalid JSON or hold parameters that were never defined.

A Pydantic model with default settings quietly drops a parameter it does not define.

True. The default is extra='ignore'. Setting extra="forbid" makes an unknown key a validation error.

Arguments that pass validation are guaranteed to be correct.

False. Validation proves the shape and the form. A well-formed order number can still name an order that does not exist; only the lookup finds that out.

A failed call goes back as a result

Once a call fails, either at validation or inside the tool, the program has to decide what happens next. Raising an exception and stopping would throw away the conversation over a mistake the model could fix itself. The more useful answer is to send the failure back to the model as the result of the call.

This works because the result of a tool call is just text. On Chat Completions it travels in a tool message with three fields: role set to "tool", the tool_call_id of the call it answers, and the content. There is no separate error field: the format of the content is up to you (JSON, error codes, plain text), and the model reads it like any other result. An error the model can read is an error it can act on.

  • Program
  • Language model
  • Order lookup
  • Language model to Program: call: order_id "1042"
  • Program to Language model: result: error, expected A-1234
  • Language model to Program: call: order_id "A-1042"
  • Program to Order lookup: look_up_order("A-1042")
  • Order lookup to Program: shipped
  • Program to Language model: result: shipped
  • Language model to Program: reply text for the user

With the error in front of it, the model has two sensible moves. If it can see what went wrong, it corrects itself and calls again, as in the exchange above. If it cannot (no order with that number exists), it explains the problem to the user and perhaps asks for the right number. Either way, the program stays in control and never runs a function with arguments it did not accept.

A small function that turns every call into a result string keeps this in one place. Each kind of failure becomes a short JSON object that says what went wrong:

Every outcome becomes a result string
import json

def run_call(call):
    if call.function.name != "look_up_order":
        return json.dumps({"error": f"unknown tool {call.function.name}"})
    try:
        args = OrderLookup.model_validate_json(call.function.arguments)
    except ValidationError as err:
        problems = [{"field": e["loc"], "problem": e["msg"]} for e in err.errors()]
        return json.dumps({"error": "invalid arguments", "details": problems})
    status = ORDERS.get(args.order_id)
    if status is None:
        return json.dumps({"error": f"no order {args.order_id}"})
    return json.dumps({"order_id": args.order_id, "status": status})

The error message is written for the model, so it pays to make it specific. "invalid arguments" with the failing field and the reason gives the model something to correct; a bare "error" does not. Failures that are not the model's fault, such as a database that does not answer, can go back the same way, so the model can tell the user that the lookup is unavailable right now instead of inventing a status.

True or false?

A tool message has a dedicated field for marking a result as an error.

False. It has role, tool_call_id and content only. An error is reported as the content text, in whatever format the program chooses.

Sending a validation error back lets the model retry the call with corrected arguments.

True. The model reads the result like any other text. If the error says which field failed and why, the model can call again with arguments that fit.

Several calls in one turn

A customer writes: Where are my orders A-1042 and A-1077? The model does not need two turns to look both up. One assistant message can carry several tool calls in its tool_calls list, each with its own id. On Chat Completions this is allowed by default. The request parameter that controls it, parallel_tool_calls, is true unless you set it to false, and false limits the model to zero or one call per message.

The word parallel describes the message, not the execution. The API does not run anything: it hands your program a list, and your program runs each call (one after another, or at the same time if it chooses) and answers each one. Each answer is matched to its call by id, never by position. The function name cannot do it either, since both calls here use the same function.

The messages sent with the next request
roletool_calls / tool_call_idcontent
userWhere are my orders A-1042 and A-1077?
assistantcall_a: look_up_order {"order_id": "A-1042"}, call_b: look_up_order {"order_id": "A-1077"}null
toolcall_a{"order_id": "A-1042", "status": "shipped"}
toolcall_b{"error": "no order A-1077"}

Every call gets exactly one tool message, placed after the assistant message that asked, including the calls that failed: the second answer above is an error, and it is still an answer. If one call is left without a reply, the history is incomplete and the endpoint rejects the next request. Answering in the order of the tool_calls list is the simple, safe habit.

A reply that asks for no tool has tool_calls set to None, not an empty list, so the program checks for calls first (the loop in the next section does). Once a reply has asked for tools, it can hold one call or many, so the code that answers it is a loop over the list, even when you expect only one:

Answer every call by its id
message = response.choices[0].message
messages.append(message)
for call in message.tool_calls:
    messages.append({
        "role": "tool",
        "tool_call_id": call.id,
        "content": run_call(call),
    })

True or false?

When one assistant message holds two tool calls, the API runs both functions at the same time.

False. The API never runs your functions. It lists the calls; the program runs each one and sends back each result with its tool_call_id.

A call whose arguments failed validation still needs a tool message in reply.

True. Every call on the assistant message needs exactly one answer. The error is that answer; leaving it out makes the history incomplete.

Repeating the exchange, with a limit

After the results go back, the model may write the final answer, or it may ask for more tools: a corrected call after an error, or a second lookup that depends on the first result. Each assistant message that asks for tools ends with the finish reason tool_calls, and each one needs another round of running calls and sending results. So the exchange is a loop that runs while the model keeps asking.

A loop that waits for the model to stop asking could, in principle, run for ever: a model that keeps making the same invalid call, or keeps looking things up without ever answering, would cost a request and its tokens every round. The fix is a limit on the number of rounds. When it is reached, the program stops and reports a clear failure, the same way it would for any answer that never arrives.

  • Send the messages with the tools, and the model replies
  • Return the answer no tool calls
  • Run every call append one result per id
  • Round limit reached?
  • Stop with a clear failure
  • Send the messages to Return the answer: text
  • Send the messages to Run every call: tool_calls
  • Run every call to Round limit reached?
  • Round limit reached? to Send the messages: no: next round
  • Round limit reached? to Stop with a clear failure: yes

In code, a for loop over a fixed range is the limit. Each pass is one round: one request, one reply. A reply without tool calls ends the loop with the answer; if the loop runs out, the function raises an error the calling code can handle.

The exchange as a loop with a limit
MAX_ROUNDS = 5

def answer(messages):
    for _ in range(MAX_ROUNDS):
        response = client.chat.completions.create(
            model=model, messages=messages, tools=tools,
        )
        message = response.choices[0].message
        if not message.tool_calls:
            return message.content
        messages.append(message)
        for call in message.tool_calls:
            messages.append({
                "role": "tool",
                "tool_call_id": call.id,
                "content": run_call(call),
            })
    raise RuntimeError(f"no answer after {MAX_ROUNDS} rounds")

There is no correct number of rounds. It depends on the task: a single lookup with room for one correction needs two or three, while a task that chains several tools needs more. Choose a limit a little above what a normal conversation takes, so the limit is only ever hit when something has gone wrong. Every round also sends the whole growing history again, so the limit caps the cost of a conversation as well as its length.

True or false?

After the program sends tool results back, the next reply from the model is always the final answer.

False. The model may ask for more tools, for instance to correct a failed call. The program keeps looping while replies hold tool calls.

A limit on rounds also limits how much a single conversation can cost.

True. Each round is one more request that sends the whole history again. Capping the rounds caps the number of requests.