Calling OpenAI API: chat.completions
Send messages to the OpenAI chat.completions endpoint, set temperature and max_tokens, and parse the response.
Calling OpenAI API: chat.completions is a free AI Agents lesson on CoddyKit — lesson 1 of 4. You can read the complete lesson below for free — then practise it hands-on in the browser with a built-in code editor and a 24/7 AI tutor. It is part of the AI Agents learning path, one of 4 lessons in the course, and your progress syncs across the web and the CoddyKit app.
Why chat.completions?
OpenAI has two APIs:
- chat.completions — the standard, well-supported endpoint
- Responses API / Assistants — managed agents (more advanced)
This lesson covers chat.completions, which is the workhorse for 95% of agents.
Install the SDK
One package, one line:
# pip install openai
from openai import OpenAI
client = OpenAI() # reads OPENAI_API_KEY from envYour First Call
A minimal completion:
response = client.chat.completions.create(
model='gpt-4o-mini',
messages=[
{'role': 'system', 'content': 'You are concise.'},
{'role': 'user', 'content': 'Capital of France?'},
],
)
print(response.choices[0].message.content)
# 'Paris'Response Object Anatomy
The response has more than just text. Useful fields:
response.choices[0].message.content # the text
response.choices[0].finish_reason # 'stop' / 'length' / 'tool_calls'
response.usage.prompt_tokens # input tokens
response.usage.completion_tokens # output tokens
response.usage.total_tokens # sum
response.id # 'chatcmpl-...' for tracingKey Parameters
model— which model to usetemperature— 0.0 deterministic, 1.0 creativemax_tokens— cap on output lengthtop_p— alternative to temperatureseed— reproducible outputs (with caveats)
Temperature: Pick by Task
- 0.0 — extraction, classification, code generation
- 0.2-0.5 — most agent decisions
- 0.7-1.0 — creative writing, brainstorming
Stop Sequences
Cut output at a specific marker:
response = client.chat.completions.create(
model='gpt-4o-mini',
messages=messages,
stop=['\n\n', 'END'],
)
# Stops as soon as a blank line or 'END' appears.Multiple Choices
Generate N candidates in one call:
response = client.chat.completions.create(
model='gpt-4o-mini',
messages=messages,
n=3, # three samples
)
for choice in response.choices:
print(choice.message.content)Error Types to Handle
RateLimitError— 429, back offAPIConnectionError— network problemAPITimeoutError— slow responseAuthenticationError— bad API keyBadRequestError— schema problem
Async Calls
For high-throughput agents, use the async client:
from openai import AsyncOpenAI
import asyncio
client = AsyncOpenAI()
async def ask(q):
r = await client.chat.completions.create(
model='gpt-4o-mini',
messages=[{'role': 'user', 'content': q}],
)
return r.choices[0].message.content
results = asyncio.run(asyncio.gather(*[ask(q) for q in questions]))Timeout and Retries Built-In
The SDK does some retries by default. You can override:
client = OpenAI(
timeout=30.0,
max_retries=3,
)Finish Reasons
What does finish_reason == "length" mean?
Recap
You can now call OpenAI from Python. Next we cover the Anthropic API, which has small but important differences.
Frequently asked questions
Is the “Calling OpenAI API: chat.completions” lesson free?
Yes — the full text of “Calling OpenAI API: chat.completions” is free to read here on the web, and the AI Agents course includes 4 lessons in total. To practise it interactively (a built-in code editor and a 24/7 AI tutor) and unlock the rest of the AI Agents course, upgrade to CoddyKit PRO.
What will I learn in “Calling OpenAI API: chat.completions”?
Send messages to the OpenAI chat.completions endpoint, set temperature and max_tokens, and parse the response. You practise AI Agents with hands-on code you run directly in the browser, and a 24/7 AI tutor answers your questions as you work through the lesson.
Do I need any experience to start AI Agents?
No prior experience is required. AI Agents on CoddyKit is structured for beginners through advanced learners; this is — lesson 1 of 4, so you can start here or from the beginning and move at your own pace.
How long does the “Calling OpenAI API: chat.completions” lesson take?
Most CoddyKit lessons take about 5–10 minutes. Each one is bite-sized and interactive, so you make steady progress and pick up exactly where you left off across the web and the app.
Can I write and run code in this AI Agents lesson?
Yes. Every AI Agents lesson includes a built-in code editor, so you write and run real code right in your browser and get instant AI feedback — no local setup required.
All lessons in this course
- Calling OpenAI API: chat.completions
- Calling Anthropic API: messages
- Streaming Responses (SSE)
- Cost Awareness: Token Counting and Budgets