ExamplescriptbeginnerRunnabletool-agent
Tools
Runnable example (beginner) for script using openai, pydantic.
Key Facts
- Level
- beginner
- Runtime
- Python • OpenAI API
- Pattern
- Inspectable flow with visible system boundaries
- Interaction
- Live sandbox • Script
- Updated
- 14 March 2026
Navigate this example
Library
Browse examplesReopen the wider library to compare adjacent patterns and linked learning paths.Interaction
Run sandbox nowTry the interaction directly in this example’s guided sandbox surface.Source
Open full sourceRead the real implementation, highlighted checkpoints, and runtime requirements.MCP
Call via MCPUse the same resource inside agents, deterministic exports, and MCP setup flows.
Linked principles
3-tools.py
python
import json
import os
import requests
from openai import OpenAI
from pydantic import BaseModel, Field
client = OpenAI(api_key=os.getenv("OPENAI_API_KEY"))
"""
docs: https://platform.openai.com/docs/guides/function-calling
"""
# --------------------------------------------------------------
# Define the tool (function) that we want to call
# --------------------------------------------------------------
def get_weather(latitude, longitude):
"""This is a publically available API that returns the weather for a given location."""
response = requests.get(
f"https://api.open-meteo.com/v1/forecast?latitude={latitude}&longitude={longitude}¤t=temperature_2m,wind_speed_10m&hourly=temperature_2m,relative_humidity_2m,wind_speed_10m"
)
data = response.json()
return data["current"]
# --------------------------------------------------------------
# Step 1: Call model with get_weather tool defined
# --------------------------------------------------------------
tools = [
{
"type": "function",
"function": {
"name": "get_weather",
"description": "Get current temperature for provided coordinates in celsius.",
"parameters": {
"type": "object",
"properties": {
"latitude": {"type": "number"},
"longitude": {"type": "number"},
},
"required": ["latitude", "longitude"],
"additionalProperties": False,
},
"strict": True,
},
}
]
system_prompt = "You are a helpful weather assistant."
messages = [
{"role": "system", "content": system_prompt},
{"role": "user", "content": "What's the weather like in Paris today?"},
]
completion = client.chat.completions.create(
model="gpt-4o",
messages=messages,
tools=tools,
)
# --------------------------------------------------------------
# Step 2: Model decides to call function(s)
# --------------------------------------------------------------
completion.model_dump()
# --------------------------------------------------------------
# Step 3: Execute get_weather function
# --------------------------------------------------------------
def call_function(name, args):
if name == "get_weather":
return get_weather(**args)
for tool_call in completion.choices[0].message.tool_calls:
name = tool_call.function.name
args = json.loads(tool_call.function.arguments)
messages.append(completion.choices[0].message)
result = call_function(name, args)
messages.append(
{"role": "tool", "tool_call_id": tool_call.id, "content": json.dumps(result)}
)
# --------------------------------------------------------------
# Step 4: Supply result and call model again
# --------------------------------------------------------------
class WeatherResponse(BaseModel):
temperature: float = Field(
description="The current temperature in celsius for the given location."
)
response: str = Field(
description="A natural language response to the user's question."
)
completion_2 = client.beta.chat.completions.parse(
model="gpt-4o",
messages=messages,
tools=tools,
response_format=WeatherResponse,
)
# --------------------------------------------------------------
# Step 5: Check model response
# --------------------------------------------------------------
final_response = completion_2.choices[0].message.parsed
final_response.temperature
final_response.response
Related principles
- P1delegationDesign for delegation rather than direct manipulationDesign experiences around the assignment of work, the expression of intent, the setting of constraints, and the review of results, rather than requiring users to execute each step manually.Open principle →
- P8trustMake hand-offs, approvals, and blockers explicitWhen the system cannot proceed, the reason should be immediately visible, along with any action required from the user or another dependency.Open principle →
- P9orchestrationRepresent delegated work as a system, not merely as a conversationWhere work involves multiple steps, agents, dependencies, or concurrent activities, it should be represented as a structured system rather than solely as a message stream.Open principle →
- P10delegationOptimise for steering, not only initiatingThe system should support users not only in starting tasks, but also in guiding, refining, reprioritising, and correcting work while it is underway.Open principle →