Skip to content
AgenticAIWiki
  1. Learn
  2. Part 7
  3. 33. The tool use loop
  4. 33.6

Lesson 33.6 · 6 of 6 · 7 min read · Reviewed 24 Nov 2026

Function calling from first principles

By the end, you can

  • Validate a model's function call against its JSON Schema before running it.
  • Build a function calling loop without an SDK: schema in, call out, result back.

Every provider SDK wraps function callingTool use: Letting a model call functions you define, by returning a structured request your code executes. in helpers, which makes it look like magic. Underneath, it is four plain steps that you can write yourself in about 30 lines. Knowing them makes every SDK easier to debug.

The four steps

  1. Describe. You send the model a list of functions. Each has a name, a description and a JSON Schema for its arguments.
  2. Choose. The model replies either with text, or with a call: a function name and a JSON object of arguments.
  3. Validate and execute. Your code checks the call against the schema, then runs the real function.
  4. Return. You add the result to the conversation and call the model again. It may call another function or answer.

The model never executes anything. Step 2 is just text in a structured shape.

The schema

{
  "name": "convert_currency",
  "description": "Convert an amount between two currencies at today's rate.",
  "parameters": {
    "type": "object",
    "properties": {
      "amount": { "type": "number", "minimum": 0 },
      "from":   { "type": "string", "enum": ["GBP", "EUR", "USD"] },
      "to":     { "type": "string", "enum": ["GBP", "EUR", "USD"] }
    },
    "required": ["amount", "from", "to"]
  }
}

JSON Schema is an open standard, so the same shape works across providers and protocols. Field names differ (parameters, input_schema, inputSchema), but the idea is the same.

The model’s call

The model returns something like this. The id lets you match the result to the call:

{ "id": "call_1", "name": "convert_currency", "arguments": { "amount": 50, "from": "GBP", "to": "EUR" } }

The loop, by hand

for turn in range(5):                       # cap the loop
    reply = model(messages, FUNCTIONS)
    if reply["type"] == "text":
        break                               # the model answered
    call = reply["call"]
    errors = validate(call, FUNCTIONS)      # name known? required fields? types?
    if errors:
        result = {"error": "; ".join(errors)}
    else:
        result = REGISTRY[call["name"]](**call["arguments"])
    messages.append({"role": "assistant", "call": call})
    messages.append({"role": "function", "id": call["id"], "content": json.dumps(result)})

REGISTRY maps names to real Python functions. Only names in it can ever run, which is your allow-list.

What validation must check

  • The name exists. Models occasionally invent a function that sounds right.
  • Required fields are present and no unknown fields slipped in.
  • Types and enums match: "two" is not an integer; "YEN" is not in the enum.
  • Business rules the schema cannot express, such as “amount under 10,000” or “this user may not refund”.

When validation fails, do not crash and do not guess. Return an error result such as {"error": "quantity must be an integer"}. Models are good at fixing a call when told exactly what was wrong.

Common mistakes

  • Running eval or dynamic imports on the name. Always look the name up in a fixed registry.
  • Trusting arguments because they are valid JSON. Valid JSON can still carry a wrong type or a dangerous value.
  • Dropping the call from history. The next request must include both the call and its result, or the model loses track.
  • No turn cap. A model that keeps getting errors can loop forever.

Lessons 33.1 to 33.5 showed this loop through one provider’s API. The lab builds it from scratch with a simulated model.

Key points

  • Function calling is a contract: you describe functions in JSON Schema, the model replies with a name and arguments, and your code does the rest.
  • The model never runs anything. It only writes a request, which may be wrong.
  • Validate the name and the arguments before you execute, and send errors back as results the model can fix.
  • The loop ends when the model answers in text or a turn cap is hit.
Hands-on labRuns in the Playground

Build a function calling loop by hand

Write the whole function calling cycle without an SDK: schema, call, validation, execution and result.

You will have: A 30-line loop with a validate function and a registry that rejects a badly typed call, runs the fixed one and stops on a text answer.

Steps

  1. Run the starter: the simulated model asks for convert_currency with amount as a string, and nothing happens.
  2. Write validate: check the name, required fields, unknown fields, types and enums against the JSON Schema.
  3. In the loop, send an error result if validation fails, otherwise run the function from REGISTRY.
  4. Append the call and its result to messages, matched by id, and remove the early break.
  5. Run it and check that the model fixes its call after the error.

Done when

  • Turn 1 sends back the error amount must be a number.
  • Turn 2 runs convert_currency and the final answer is 50 GBP is 58.00 EUR.
  • The loop stops in 3 turns, under its cap of 5, and never uses eval.

Open in the Playground No API key needed.

Starter code (Python)
# Function calling from first principles: schema in, call out, validate, execute, return.
import json

FUNCTIONS = [{
    "name": "convert_currency",
    "description": "Convert an amount between two currencies at today's rate.",
    "parameters": {
        "type": "object",
        "properties": {
            "amount": {"type": "number"},
            "from": {"type": "string", "enum": ["GBP", "EUR", "USD"]},
            "to": {"type": "string", "enum": ["GBP", "EUR", "USD"]},
        },
        "required": ["amount", "from", "to"],
    },
}]
RATES = {("GBP", "EUR"): 1.16, ("EUR", "GBP"): 0.86}  # illustrative rates


def convert_currency(amount, **kw):
    rate = RATES[(kw["from"], kw["to"])]
    return {"amount": amount, "from": kw["from"], "to": kw["to"], "result": round(amount * rate, 2)}


REGISTRY = {"convert_currency": convert_currency}  # the allow-list: only these can run


def model(messages, functions):
    # A simulated model. It sees only the messages and the function definitions.
    last = messages[-1]
    if last["role"] == "user":
        return {"type": "call", "call": {"id": "call_1", "name": "convert_currency", "arguments": {"amount": "50", "from": "GBP", "to": "EUR"}}}
    result = json.loads(last["content"])
    if "error" in result:  # it fixes the call when told exactly what was wrong
        return {"type": "call", "call": {"id": "call_2", "name": "convert_currency", "arguments": {"amount": 50, "from": "GBP", "to": "EUR"}}}
    return {"type": "text", "text": f"{result['amount']} {result['from']} is {result['result']:.2f} {result['to']}."}


TYPES = {"number": (int, float), "string": str, "integer": int, "boolean": bool}


def validate(call, functions):
    # TODO: return a list of error strings, empty if the call is valid. Check that:
    #   - the name is one of the functions (else "unknown function NAME")
    #   - every required field is present ("KEY is required")
    #   - no unknown fields, each value has the schema type ("KEY must be a number"),
    #     and enum values are allowed. Hint: TYPES maps schema types to Python types.
    return []


messages = [{"role": "user", "content": "Convert 50 pounds to euros."}]
for turn in range(1, 6):  # always cap the loop
    reply = model(messages, FUNCTIONS)
    if reply["type"] == "text":
        break
    call = reply["call"]
    errors = validate(call, FUNCTIONS)
    # TODO: if there are errors, build result = {"error": "; ".join(errors)} and print it.
    #       Otherwise look the function up in REGISTRY (never eval) and run it with the arguments.
    # TODO: append the call and the result to messages, matched by call["id"], e.g.
    #       {"role": "assistant", "call": call} then {"role": "function", "id": ..., "content": json.dumps(result)}
    print(f"turn {turn}: model asked for {call['name']}({call['arguments']}), nothing returned yet")
    break  # TODO: remove once results go back to the model

print("final:", reply.get("text"))
print("turns:", turn)
Show a solution
# Function calling from first principles: schema in, call out, validate, execute, return.
import json

FUNCTIONS = [{
    "name": "convert_currency",
    "description": "Convert an amount between two currencies at today's rate.",
    "parameters": {
        "type": "object",
        "properties": {
            "amount": {"type": "number"},
            "from": {"type": "string", "enum": ["GBP", "EUR", "USD"]},
            "to": {"type": "string", "enum": ["GBP", "EUR", "USD"]},
        },
        "required": ["amount", "from", "to"],
    },
}]
RATES = {("GBP", "EUR"): 1.16, ("EUR", "GBP"): 0.86}  # illustrative rates


def convert_currency(amount, **kw):
    rate = RATES[(kw["from"], kw["to"])]
    return {"amount": amount, "from": kw["from"], "to": kw["to"], "result": round(amount * rate, 2)}


REGISTRY = {"convert_currency": convert_currency}  # the allow-list: only these can run


def model(messages, functions):
    # A simulated model. It sees only the messages and the function definitions.
    last = messages[-1]
    if last["role"] == "user":
        return {"type": "call", "call": {"id": "call_1", "name": "convert_currency", "arguments": {"amount": "50", "from": "GBP", "to": "EUR"}}}
    result = json.loads(last["content"])
    if "error" in result:  # it fixes the call when told exactly what was wrong
        return {"type": "call", "call": {"id": "call_2", "name": "convert_currency", "arguments": {"amount": 50, "from": "GBP", "to": "EUR"}}}
    return {"type": "text", "text": f"{result['amount']} {result['from']} is {result['result']:.2f} {result['to']}."}


TYPES = {"number": (int, float), "string": str, "integer": int, "boolean": bool}


def validate(call, functions):
    spec = next((f for f in functions if f["name"] == call["name"]), None)
    if spec is None:
        return [f"unknown function {call['name']}"]
    schema, args, errors = spec["parameters"], call["arguments"], []
    for key in schema["required"]:
        if key not in args:
            errors.append(f"{key} is required")
    for key, value in args.items():
        prop = schema["properties"].get(key)
        if prop is None:
            errors.append(f"unknown field {key}")
        elif not isinstance(value, TYPES[prop["type"]]) or isinstance(value, bool) and prop["type"] != "boolean":
            errors.append(f"{key} must be a {prop['type']}")
        elif "enum" in prop and value not in prop["enum"]:
            errors.append(f"{key} must be one of {', '.join(prop['enum'])}")
    return errors


messages = [{"role": "user", "content": "Convert 50 pounds to euros."}]
for turn in range(1, 6):  # always cap the loop
    reply = model(messages, FUNCTIONS)
    if reply["type"] == "text":
        break
    call = reply["call"]
    errors = validate(call, FUNCTIONS)
    if errors:
        result = {"error": "; ".join(errors)}
        print(f"turn {turn}: error sent back: {result['error']}")
    else:
        result = REGISTRY[call["name"]](**call["arguments"])
        print(f"turn {turn}: ran {call['name']} -> {result['result']}")
    messages.append({"role": "assistant", "call": call})
    messages.append({"role": "function", "id": call["id"], "content": json.dumps(result)})

print("final:", reply.get("text"))
print("turns:", turn)
Quick checkYour schema says quantity is a required integer. The model calls add_to_cart with {"sku": "B-12", "quantity": "two"}. What should your code do?
How sure are you?
Pick an answer and how sure you are

Finished the chapter? Take the chapter check.