Reference · API
OpenAI function calling
Last updated
Let the model return **structured tool calls**; your server executes functions and sends results back.
Let the model return **structured tool calls**; your server executes functions and sends results back.
Endpoint
POST https://api.openai.com/v1/chat/completionsTool definition
{
"type": "function",
"function": {
"name": "get_order_status",
"description": "Look up order by ID",
"parameters": {
"type": "object",
"properties": {
"order_id": { "type": "string" }
},
"required": ["order_id"]
}
}
}Flow
1. Send `messages` + `tools` array
2. If `finish_reason` is `tool_calls`, parse `function.name` and `arguments`
3. Run your handler (validate JSON first)
4. Append `role: tool` message with `tool_call_id` and result
5. Call completions again for the final natural-language answer
Python sketch
response = client.chat.completions.create(
model="gpt-4o-mini",
messages=[{"role": "user", "content": "Status for order ORD-42?"}],
tools=tools,
)Safety
- Allowlist function names
- Never execute arbitrary code from the model
- Confirm destructive actions with users
Related
- Lesson: Function calling in code
- Lesson: What are tools?
- Snippet: OpenAI chat with tools