Skip to content

Exercise: Function Calling

Objective

Learn how LLMs interact with external tools through function calling — the foundation of agentic behavior.

Concepts Covered

  • Tool definitions with openai.pydantic_function_tool()
  • The tools parameter and strict mode
  • Parsing tool_calls from model responses
  • tool role messages for returning results

How It Works

This script introduces the mechanics of function calling. You define tools as Pydantic models and register them with openai.pydantic_function_tool(). When the model decides it needs a tool, it returns a tool_calls array instead of a text reply. You execute the function locally and send the result back with role: "tool".

sequenceDiagram
    participant Script
    participant LLM
    participant Tools as Local Functions

    Script->>LLM: messages=[system, user]<br/>tools=[get_weather, convert_temp]
    LLM-->>Script: tool_calls: [get_weather(city="Paris")]

    Script->>Tools: get_weather(city="Paris")
    Tools-->>Script: {"temp": 18, "condition": "cloudy"}

    Script->>LLM: messages=[...previous...,<br/>assistant(tool_calls),<br/>tool(result)]
    LLM-->>Script: "It's 18°C and cloudy in Paris"

Context sharing: A single messages list grows across the exchange: system → user → assistant (with tool_calls) → tool result → assistant (final answer).

Interactive Message Flow

You are a helpful weather assistant. Use the provided tools to answer questions.
What's the weather in Berlin? Also convert 18C to Fahrenheit.
get_weather(location='Berlin') + convert_temperature(celsius=18)
{"location": "Berlin", "temperature": 18, "condition": "Partly cloudy"}
{"celsius": 18, "fahrenheit": 64.4}
Berlin is currently 18C (64.4F) and partly cloudy. Great weather for a walk!

File

  • 01_function_calling.py — Define and invoke tools with Pydantic schemas

How to Run

python exercises/02_tool_use/01_function_calling.py

Expected Output

Structured logging showing the tool call request, local function execution, tool result returned, and the final model response.

Next

Exercise: Tool Loop