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
toolsparameter and strict mode - Parsing
tool_callsfrom model responses toolrole 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¶
File¶
01_function_calling.py— Define and invoke tools with Pydantic schemas
How to Run¶
Expected Output¶
Structured logging showing the tool call request, local function execution, tool result returned, and the final model response.