OpenAI API Examples: Chat Completions in Practice
Working curl and Python patterns for auth, chat requests, retries, and streaming—ready to adapt for production.

What you will build
Assuming you finished OpenAI API Application, you will:
- Authenticate with an API key
- Send a chat completion
- Parse the reply and handle common errors
- See a minimal streaming pattern
Docs: https://platform.openai.com/docs/ · Console: https://platform.openai.com/
Model names and paths change—treat samples as structural templates and confirm against current Docs.
1. curl smoke test
curl https://api.openai.com/v1/chat/completions \
-H "Authorization: Bearer $OPENAI_API_KEY" \
-H "Content-Type: application/json" \
-d '{
"model": "gpt-4o-mini",
"messages": [
{"role": "system", "content": "You are a concise assistant."},
{"role": "user", "content": "Explain what an API is in three sentences."}
],
"temperature": 0.4
}'
Look for choices[0].message.content in the JSON response.
2. Minimal Python
import os
from openai import OpenAI
client = OpenAI(api_key=os.environ["OPENAI_API_KEY"])
resp = client.chat.completions.create(
model="gpt-4o-mini",
messages=[
{"role": "system", "content": "You are a careful technical writer."},
{"role": "user", "content": "List five security checks before calling the OpenAI API."},
],
temperature=0.3,
)
print(resp.choices[0].message.content)
Install the official SDK per Docs; watch for breaking changes across majors.
3. Message roles
| role | Use |
|---|---|
| system | Global style, safety rails, output contract |
| user | Current request |
| assistant | Prior replies when continuing a thread |
Trim long histories; summarize when context and cost grow.
4. Retry skeleton
import time
from openai import RateLimitError, APIError
def chat_with_retry(client, **kwargs):
for attempt in range(5):
try:
return client.chat.completions.create(**kwargs)
except RateLimitError:
time.sleep(2 ** attempt)
except APIError:
raise
raise RuntimeError("retries exhausted")
5. Streaming starter
stream = client.chat.completions.create(
model="gpt-4o-mini",
messages=[{"role": "user", "content": "Write a short poem about debugging"}],
stream=True,
)
for chunk in stream:
delta = chunk.choices[0].delta.content or ""
print(delta, end="", flush=True)
6. Production habits
- Keys only in server-side secret stores
- Bound user input length and apply content policies
- Log request id, model, latency, token usage
- Centralize prompt configs—no scattered magic strings
- Budget alerts against runaway loops
Explore interactively on ChatGPT; product home: OpenAI.
7. Error cheatsheet
| Symptom | Likely cause | Fix |
|---|---|---|
| 401 | Bad key | Regenerate; fix env var |
| 429 | Rate/quota | Backoff; lower concurrency |
| Timeouts | Network/proxy | Retry with timeouts; stable path |
| Truncation | Low max tokens | Raise limit or ask for shorter output |
A mirror site entry is a placeholder only—do not route production traffic without review.
Takeaway
Prove auth with curl, wrap a client, then add retries, logging, and streaming. Combine key hygiene from the application guide with these templates, and keep Docs as the living reference.