openai function calling
Using OpenAI's Function Calling
OpenAI's function calling feature allows language models like GPT-4 to interact with external code and APIs using structured input and output. This is useful for building intelligent agents, tools, and automation systems.
What Is Function Calling?
Function calling enables the model to:
- Decide when to call a function
- Select which function to call from those you provide
- Generate structured arguments (as JSON)
- Use the function's output in further responses
Basic Workflow
1. Define Functions
You define a function with a name, description, and parameter schema (in JSON format):
{
"name": "get_weather",
"description": "Get the current weather in a city",
"parameters": {
"type": "object",
"properties": {
"location": {
"type": "string",
"description": "The city name, e.g., San Francisco"
}
},
"required": ["location"]
}
}
2. Send Function Metadata with Messages
Call the OpenAI chat/completions
endpoint with the function schema included:
response = openai.ChatCompletion.create(
model="gpt-4",
messages=[
{"role": "user", "content": "What's the weather like in Boston?"}
],
functions=[get_weather_function],
function_call="auto"
)
3. Handle Function Call from Model
Check if the model requested a function call, then parse and execute:
func_call = response["choices"][0]["message"]["function_call"]
func_name = func_call["name"]
arguments = json.loads(func_call["arguments"])
result = get_weather(**arguments)
4. Return the Output Back to the Model
Send a new message that includes the function result so the model can use it in natural language:
response = openai.ChatCompletion.create(
model="gpt-4",
messages=[
{"role": "user", "content": "What's the weather like in Boston?"},
{
"role": "assistant",
"function_call": {
"name": "get_weather",
"arguments": json.dumps(arguments)
}
},
{
"role": "function",
"name": "get_weather",
"content": result
}
]
)
Key Use Cases
- AI agents using tools (e.g., search, APIs)
- Workflow automation (e.g., scheduling, notifications)
- System integration (e.g., databases, smart homes)
- Command-line co-pilots and dev tools
Notes
- You must run the actual function logic yourself—OpenAI only produces structured calls.
- Functions do not expose system access to the model.
- Multiple tools can be used together, including retrieval and code execution.