An AI assistant becomes much more useful when it can do something beyond generating text. It can check an order, look up weather conditions, search a database, or retrieve information from another service. The feature that makes this possible is function calling.
But there is one important detail developers often misunderstand: the AI model does not directly execute your application code. It decides when a tool may be useful, generates arguments for that tool, and returns a structured function call. Your application is responsible for validating those arguments, executing the function, and sending the result back to the model.
In this tutorial, we'll build a small weather assistant using Python, the OpenAI Responses API, and Open-Meteo's public weather services. The example will show the complete tool-calling cycle, including an external HTTP request and the model's final response.
Table of Contents
What Function Calling Actually Does
Set Up the Python Project
Define a Tool the Model Can Call
Connect the Tool to an External API
Build the Function-Calling Loop
Security and Reliability Checks
What Function Calling Actually Does
Function calling gives a model access to capabilities that your application controls. You describe available tools using a name, a description, and a parameter schema. When the user asks a question that requires one of those tools, the model can return a function call instead of immediately producing a normal answer.
The application then performs the requested operation and returns its result. The model can use that result to write a response the user can understand.
The basic workflow looks like this:
The user asks a question, such as "What's the weather in Denver?"
The model decides that it needs the weather tool.
The model returns a function call with arguments.
Your application validates the arguments and calls the external service.
Your application sends the tool result back to the model.
The model produces a natural-language answer.

This separation matters. The model chooses a tool, but your application controls what actually happens. That distinction is especially important when tools can access private data, modify records, or trigger payments.
Set Up the Python Project
Start with a small project so the tool-calling logic is easy to understand.
weather-agent/
├── app.py
├── .env
└── requirements.txtInstall the required packages:
pip install openai python-dotenv requestsAdd your API key and a model available to your account in .env:
OPENAI_API_KEY=your_api_key_here
OPENAI_MODEL=your_supported_modelLoad the environment variables in Python:
import os
from dotenv import load_dotenv
from openai import OpenAI
load_dotenv()
client = OpenAI()
MODEL = os.getenv("OPENAI_MODEL")
if not MODEL:
raise RuntimeError("OPENAI_MODEL is not configured")Keep API keys on the server. Never place them in browser JavaScript, commit them to Git, or return them in an API response.
Define a Tool the Model Can Call
Our assistant needs one tool: get_current_weather. It accepts a city name and returns current weather information.
The tool definition tells the model what the function does and what arguments it needs. The schema also makes the expected input more predictable.
weather_tool = {
"type": "function",
"name": "get_current_weather",
"description": (
"Get current weather conditions for a city. "
"Use this when the user asks about current weather."
),
"parameters": {
"type": "object",
"properties": {
"city": {
"type": "string",
"description": "City name, optionally including state or country"
}
},
"required": ["city"],
"additionalProperties": False
},
"strict": True
}The description should explain when the tool is appropriate, not just repeat its name. A vague description makes it harder for the model to select the right function.

Connect the Tool to an External API
Now we need to implement the function. We'll use two Open-Meteo endpoints: its geocoding service to turn a city name into coordinates, and its forecast service to retrieve current weather variables.
First, create a function that looks up a city:
import requests
def get_current_weather(city: str) -> dict:
geo_response = requests.get(
"https://geocoding-api.open-meteo.com/v1/search",
params={
"name": city,
"count": 1,
"language": "en",
"format": "json"
},
timeout=10
)
geo_response.raise_for_status()
locations = geo_response.json().get("results", [])
if not locations:
return {"error": f"No location found for {city}"}
location = locations[0]Next, use the returned coordinates to request weather data:
weather_response = requests.get(
"https://api.open-meteo.com/v1/forecast",
params={
"latitude": location["latitude"],
"longitude": location["longitude"],
"current": "temperature_2m,relative_humidity_2m,wind_speed_10m",
"temperature_unit": "fahrenheit",
"wind_speed_unit": "mph"
},
timeout=10
)
weather_response.raise_for_status()
current = weather_response.json().get("current", {})
return {
"location": location["name"],
"country": location.get("country"),
"temperature_f": current.get("temperature_2m"),
"humidity_percent": current.get("relative_humidity_2m"),
"wind_speed_mph": current.get("wind_speed_10m"),
"observed_at": current.get("time")
}This is a real external API integration, not a simulated response. The function also returns a compact object rather than passing the entire API response to the model. Smaller, purpose-built results are easier to inspect and less likely to introduce irrelevant data.
Build the Function-Calling Loop
The next step connects the tool definition to the model. The Responses API returns function calls as output items. Your code must inspect those items, identify the function, parse its arguments, execute it, and send the result back using the matching call_id.
import json
def run_assistant(user_message: str) -> str:
response = client.responses.create(
model=MODEL,
input=user_message,
tools=[weather_tool]
)
while True:
if response.status != "completed":
raise RuntimeError(
f"Model response ended with status: {response.status}"
)
calls = [
item for item in response.output
if item.type == "function_call"
]
if not calls:
return response.output_text
tool_outputs = []
for call in calls:
if call.name != "get_current_weather":
raise ValueError(f"Unknown tool: {call.name}")
arguments = json.loads(call.arguments)
city = arguments.get("city")
if not isinstance(city, str) or not city.strip():
raise ValueError("A valid city name is required")
result = get_current_weather(city.strip())
tool_outputs.append({
"type": "function_call_output",
"call_id": call.call_id,
"output": json.dumps(result)
})
response = client.responses.create(
model=MODEL,
previous_response_id=response.id,
input=tool_outputs,
tools=[weather_tool]
)
There are two details worth paying attention to.
First, the application checks the function name before executing anything. A model response should never be treated as permission to run an arbitrary function.
Second, each tool result is connected to its original request through call_id. A response can contain multiple function calls, so your application should process every call and return a matching output for each one.
You can now add a simple entry point:
if __name__ == "__main__":
question = input("Ask about the weather: ")
print(run_assistant(question))Run the application:
python app.pyTry asking: "What's the current weather in Boulder, Colorado?" The model should request the weather tool, your Python function should contact Open-Meteo, and the model should use the returned data to answer.
Security and Reliability Checks
A working demonstration is not automatically production-ready. Tool calling creates a boundary between model-generated instructions and real application behavior. Treat that boundary as a security-sensitive part of your system.
Validate every argument. A schema helps constrain model output, but your application should still validate values before using them.
Allowlist functions. Execute only tools that your application explicitly supports.
Set network timeouts. External services can become slow or unavailable.
Handle API failures. Check HTTP status codes and return controlled errors instead of exposing stack traces or credentials.
Limit permissions. A weather lookup needs no access to user accounts, payment methods, or local files.
Require confirmation for consequential actions. Sending an email, deleting a record, or placing an order should not happen merely because the model generated a function call.
Also consider logging the tool name, execution time, and success or failure status. Avoid logging secrets or unnecessary personal data.
What to Build Next
Once the basic loop works, you can add more tools: a database lookup, a product search, or a calendar integration. Keep each function narrow and give it only the permissions it needs.
The central idea is simple: function calling connects a model's reasoning to capabilities your application controls. The model can decide what information it needs, but your code remains responsible for validating requests, executing operations, and protecting users.
Build it. Break it. Understand it. Fix it.
