Audience: GenAI Developers, Backend Engineers, AI Engineers
Level: Intermediate → Advanced
Language: Python
Focus: Practical usage, production patterns, and mental models
The Chat Completions API is the foundation for building conversational AI systems using :contentReference[oaicite:0]{index=0} models.
It enables:
- Multi-turn conversations
- Role-based prompting (system, user, assistant)
- Tool / function calling
- Structured AI outputs for automation
This document explains:
- How Chat Completions work
- How messages are structured
- What function calling is
- How to implement function calling in Python
- Production best practices
At its core, Chat Completions take a list of messages and return the next assistant message.
Conversation History → LLM → Next Best Response
Each message has:
role: system | user | assistant | toolcontent: text or structured output
from openai import OpenAI
client = OpenAI()
response = client.chat.completions.create(
model="gpt-4.1-mini",
messages=[
{"role": "system", "content": "You are a helpful tutor."},
{"role": "user", "content": "Explain what recursion is in simple terms."}
]
)
print(response.choices[0].message.content)systemsets behavioruserasks the questionassistantis generated by the model- The model is stateless → you must send history every time
Controls personality, tone, rules.
"You are a strict Python code reviewer."
Actual user input.
"Write a recursive factorial function."
Model-generated response.
Used when a tool/function returns output back to the model.
LLMs are great at text, but weak at:
- Performing actions
- Calling APIs
- Returning structured JSON reliably
Function calling bridges this gap.
❌ Unstructured text ❌ Hard to parse ❌ Error-prone automation
✅ Structured JSON ✅ Deterministic schema ✅ Safe automation
User Request
↓
LLM decides: "I should call a function"
↓
LLM returns function name + arguments (JSON)
↓
Your code executes the function
↓
Result sent back to LLM
↓
LLM generates final response
Functions are defined using JSON Schema.
functions = [
{
"name": "get_weather",
"description": "Get current weather for a city",
"parameters": {
"type": "object",
"properties": {
"city": {
"type": "string",
"description": "City name"
}
},
"required": ["city"]
}
}
]response = client.chat.completions.create(
model="gpt-4.1-mini",
messages=[
{"role": "system", "content": "You are a helpful assistant."},
{"role": "user", "content": "What's the weather in Bengaluru?"}
],
functions=functions,
function_call="auto"
)message = response.choices[0].message
if message.function_call:
function_name = message.function_call.name
arguments = message.function_call.argumentsExample output:
{
"name": "get_weather",
"arguments": {
"city": "Bengaluru"
}
}import json
def get_weather(city: str):
# Mocked API call
return {
"city": city,
"temperature": "28°C",
"condition": "Cloudy"
}
args = json.loads(message.function_call.arguments)
result = get_weather(**args)followup_response = client.chat.completions.create(
model="gpt-4.1-mini",
messages=[
{"role": "system", "content": "You are a helpful assistant."},
{"role": "user", "content": "What's the weather in Bengaluru?"},
message,
{
"role": "tool",
"name": "get_weather",
"content": json.dumps(result)
}
]
)
print(followup_response.choices[0].message.content)The current weather in Bengaluru is 28°C with cloudy conditions.
- API orchestration
- Database queries
- RAG pipelines
- Workflow automation
- Agent frameworks
- Admin dashboards
- AI copilots
Always validate function arguments before execution.
Treat LLM outputs as suggestions, not commands.
Avoid side effects where possible.
Store:
- Prompt
- Function name
- Arguments
- Result
| Feature | Chat Completion | Function Calling | Agents |
|---|---|---|---|
| Free-form text | ✅ | ||
| Structured output | ❌ | ✅ | ✅ |
| Automation | ❌ | ✅ | ✅ |
| Multi-step reasoning | ✅ |
-
Chat Completions are the foundation
-
Function calling enables safe automation
-
The model decides, your code executes
-
This pattern is core to:
- RAG
- Agents
- AI workflows
- Enterprise AI systems
- Tool calling vs Function calling
- JSON mode & response schemas
- Agents SDK
- RAG + function calling
- Error recovery strategies