How to use function calling with the OpenAI API in Python

Day 3, 30 minutes · beginner

Goal of this lessonWrite three strict function tools, run the calls the model asks for in your own loop, and send the results back until the model gives a final answer.

Why it matters

Use function calling with the OpenAI API in Python: the model asks for your own functions, your code runs them and sends back the results. A model on its own does not know Otterbrook's lesson times, free places or prices. Ask it anyway and it may guess, politely and wrongly. Function calling fixes that: you describe your own Python functions to the model, the model asks for the one it needs, and your code runs it and sends back the real data.

Today Hedda's helper gets three tools: one for lesson times, one for free places and one for prices. You write them as strict tools, so the model's requests always match the shape you defined, and you write the loop that runs them yourself, with a hard stop. You finish with a helper that answers from data instead of from memory.

Who does what

Function calling (OpenAI also calls it tool calling) is a conversation between your code and the model, in five steps from OpenAI's guide:

  1. You send the question plus a list of tools the model may use.
  2. The model replies with one or more function_call items: a function name and its arguments as JSON text.
  3. Your code runs those functions.
  4. You send the results back as function_call_output items, each with the call_id of the call it answers.
  5. The model writes the answer, or asks for more calls.

The model never runs anything. It only asks. That is why every call passes through run_tool in tools.py. It knows only the three names in its list, and it turns bad arguments into an error message instead of a crash. If you did the Tool Use with the Claude API course, this is the same idea with other field names.

Strict tools

Each tool has a name, a description and parameters, written as JSON Schema (a standard way to describe the shape of data). OpenAI recommends "strict": true. Then the arguments reliably follow your schema, on two conditions from the docs: every object has "additionalProperties": false, and every field is listed in required. A field that may be left empty gets a type that also allows null, as level does in get_lessons. If a strict schema breaks those rules, the API refuses the request and says what is missing.

Good descriptions do most of the work. OpenAI's advice: say what each function does and does not do, use enum (a fixed list of allowed values) where you can, and keep the number of tools small. Tool definitions are sent with every call and billed as input tokens.

The loop

ask_desk.py keeps a list of items. On every round it:

  1. Sends the whole list with the tools.
  2. Adds everything the model returned to the list, including reasoning items. The docs say reasoning items that come with tool calls must be sent back with the results.
  3. Runs every function call in the reply. There can be several at once: the model may ask for free places and a price in the same round.
  4. Adds one function_call_output per call, with the matching call_id.

When a reply has no function calls, that is the final answer. MAX_ROUNDS is the safety stop: a confused model could keep asking, and every round costs tokens.

A worked example

Question: "Is there room in a beginners lesson on Saturday, and what does a block of lessons cost?" A typical run:

  • Round 1: the model calls get_lessons for Saturday, beginners. Your code returns lesson SAT-0900.
  • Round 2: it calls get_spaces_left for SAT-0900 and get_price for lesson_block. Your code returns 0 places and 72 euros.
  • The model answers: the Saturday beginners lesson is full, and a block costs 72 euros.

Your run may take other routes; the model decides. What matters is that each fact in the answer came from a tool result.

The steps

  1. Write the data as plain Python functions.
  2. Describe the tools as strict function definitions.
  3. Build the door that runs only known functions.
  4. Write the loop with a round limit.
  5. Run it with a normal question, a question without data, and one no tool can answer.

Pick your tool below and follow the steps.

Common mistakes

  • Sending the results back without the earlier output items.
  • Running whatever function name the model sends, with eval or getattr.
  • Forgetting a field in required while strict is on.
  • No round limit, so a loop can run and spend without end.
  • Tools that do too much. Small, clear tools are easier for the model to pick.

Deeper dive

Today's actions

Ticks are not saved without an account

Do it in OpenAI API

OpenAI API

  1. Create pool_data.py. It holds made-up pool data and three plain Python functions. A real desk would read its booking system here.
    """Made-up pool data. A real desk would read its booking system here."""
    
    LESSONS = {
        "saturday": [
            {"lesson_id": "SAT-0900", "time": "09:00", "level": "beginners"},
            {"lesson_id": "SAT-1000", "time": "10:00", "level": "improvers"},
        ],
        "wednesday": [{"lesson_id": "WED-1600", "time": "16:00", "level": "beginners"}],
    }
    SPACES = {"SAT-0900": 0, "SAT-1000": 3, "WED-1600": 5}
    PRICES_EUR = {"adult_swim": 6.0, "child_swim": 3.5, "lesson_block": 72.0}
    
    
    def get_lessons(day: str, level: str | None) -> dict:
        lessons = LESSONS.get(day.lower(), [])
        if level:
            lessons = [lesson for lesson in lessons if lesson["level"] == level]
        return {"day": day, "lessons": lessons}
    
    
    def get_spaces_left(lesson_id: str) -> dict:
        if lesson_id not in SPACES:
            return {"error": f"Unknown lesson_id {lesson_id}"}
        return {"lesson_id": lesson_id, "spaces_left": SPACES[lesson_id]}
    
    
    def get_price(ticket_type: str) -> dict:
        if PRICES_EUR.get(ticket_type) is None:
            return {"error": f"No price for {ticket_type}"}
        return {"ticket_type": ticket_type, "price_eur": PRICES_EUR[ticket_type]}
  2. Create tool_specs.py. These are the definitions the model sees. The small helper makes every tool strict: all fields required and no extra fields.
    def function(name, description, properties):
        """Build one strict function tool: every field required, no extra fields."""
        return {
            "type": "function",
            "name": name,
            "description": description,
            "strict": True,
            "parameters": {
                "type": "object",
                "properties": properties,
                "required": list(properties),
                "additionalProperties": False,
            },
        }
    
    
    TOOLS = [
        function(
            "get_lessons",
            "List the swimming lessons on one day. Gives lesson ids, times and levels, not free places.",
            {
                "day": {"type": "string", "description": "Day of the week in lower case, e.g. saturday."},
                "level": {
                    "type": ["string", "null"],
                    "enum": ["beginners", "improvers"],
                    "description": "Only this level, or null for all levels.",
                },
            },
        ),
        function(
            "get_spaces_left",
            "Get the number of free places in one lesson. Needs a lesson id from get_lessons.",
            {"lesson_id": {"type": "string", "description": "A lesson id such as SAT-0900."}},
        ),
        function(
            "get_price",
            "The price in euros for one kind of ticket.",
            {"ticket_type": {"type": "string", "enum": ["adult_swim", "child_swim", "lesson_block"]}},
        ),
    ]
  3. Create tools.py. Every call the model asks for goes through run_tool, which only runs names from its own list.
    from pool_data import get_lessons, get_price, get_spaces_left
    
    FUNCTIONS = {
        "get_lessons": get_lessons,
        "get_spaces_left": get_spaces_left,
        "get_price": get_price,
    }
    
    
    def run_tool(name: str, arguments: dict) -> dict:
        """The model can only reach the functions listed in FUNCTIONS, with checked arguments."""
        chosen = FUNCTIONS.get(name)
        if chosen is None:
            return {"error": f"No such tool: {name}"}
        try:
            return chosen(**arguments)
        except TypeError:
            return {"error": f"Bad arguments for {name}: {arguments}"}
  4. Try run_tool with a tool that is not on the list: python -c "from tools import run_tool; print(run_tool('delete_everything', {}))". It should return a dictionary with an error, and nothing should crash.
  5. Create ask_desk.py. It sends the question with the tools, runs every function call, sends the results back with the earlier output items, and stops after four rounds at most.
    import json
    
    from config import MODEL, client
    from rules import RULES
    from tool_specs import TOOLS
    from tools import run_tool
    
    MAX_ROUNDS = 4  # a hard stop, so a confused model cannot loop and spend
    
    
    def ask(question: str) -> str:
        items = [{"role": "user", "content": question}]
        for round_number in range(1, MAX_ROUNDS + 1):
            response = client.responses.create(
                model=MODEL,
                instructions=RULES + " Answer facts only from tool results.",
                input=items,
                tools=TOOLS,
                reasoning={"effort": "low"},
                max_output_tokens=2000,
            )
            items += response.output  # keep every item, reasoning items too
            calls = [item for item in response.output if item.type == "function_call"]
            if not calls:
                return response.output_text or f"No answer (status {response.status})"
            for call in calls:
                arguments = json.loads(call.arguments)
                result = run_tool(call.name, arguments)
                print(f"round {round_number}: {call.name} {arguments} -> {result}")
                items.append(
                    {"type": "function_call_output", "call_id": call.call_id, "output": json.dumps(result)}
                )
        return f"Stopped after {MAX_ROUNDS} rounds without a final answer."
    
    
    if __name__ == "__main__":
        print(ask("Is there room in a beginners lesson on Saturday, and what does a block of lessons cost?"))
  6. Run python ask_desk.py. You should see one or more round lines with a function name, its arguments and the result, then a short answer that uses those results.
  7. Change the question in the last line to Are there lessons on Monday?, run again, then ask something none of the tools covers, such as the price of a family ticket. Note what the model does each time.

Note: The model never runs anything: it sends a request and your code decides. Strict mode makes the arguments follow your schema; with strict on, an optional field is written as a type that also allows null. Tool definitions count as input tokens, so keep descriptions short. Check every argument before a function changes anything.

Paid planNeeds prepaid API credit. The OpenAI API is billed per use, separately from any ChatGPT plan.

Checked on 4 December 2026 · Source: OpenAI API docs: Function calling (opens in a new tab)

Create a free account to save your progress. Sign in or sign up