Skip to main content

Function Calling with External APIs

In this lesson, you’ll learn how to use the OpenAI function-calling capability to dynamically fetch real-time weather data using external APIs.

Prerequisites

Make sure you:

  • Have Python 3.8+
  • Installed openai and requests libraries:
pip install openai requests

The Code

from openai import OpenAI
import json
import requests

client = OpenAI()

def get_weather(latitude, longitude):
response = requests.get(
f"https://api.open-meteo.com/v1/forecast?latitude={latitude}&longitude={longitude}&current=temperature_2m,wind_speed_10m&hourly=temperature_2m,relative_humidity_2m,wind_speed_10m"
)
data = response.json()
return data['current']['temperature_2m']

tools = [{
"type": "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
}]

input_messages = [{"role": "user", "content": "What's the weather like in Paris today?"}]

response = client.responses.create(
model="gpt-4.1",
input=input_messages,
tools=tools,
)

tool_call = response.output[0]
print(f"Tool call: {tool_call}")

args = json.loads(tool_call.arguments)
result = get_weather(args["latitude"], args["longitude"])

input_messages.append(tool_call)
input_messages.append({
"type": "function_call_output",
"call_id": tool_call.call_id,
"output": str(result)
})

response_2 = client.responses.create(
model="gpt-4.1",
input=input_messages,
tools=tools,
)

print(response_2.output_text)

Explanation

  • You define a local function get_weather() and describe it for the model.
  • GPT identifies when to call the function, supplies arguments, and waits for the result.
  • You feed the result back into the conversation to continue naturally.

Use Case

This allows GPT to:

  • Call real APIs securely
  • Dynamically fetch external data
  • Integrate seamlessly with live systems like weather, stock, finance, or IoT sensors