Skip to content

API

OpenAI API Examples: Chat Completions in Practice

Working curl and Python patterns for auth, chat requests, retries, and streaming—ready to adapt for production.

·15 min read·Last updated: 2/8/2026

OpenAI API 调用示例:Chat Completions 实战

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

roleUse
systemGlobal style, safety rails, output contract
userCurrent request
assistantPrior 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

  1. Keys only in server-side secret stores
  2. Bound user input length and apply content policies
  3. Log request id, model, latency, token usage
  4. Centralize prompt configs—no scattered magic strings
  5. Budget alerts against runaway loops

Explore interactively on ChatGPT; product home: OpenAI.

7. Error cheatsheet

SymptomLikely causeFix
401Bad keyRegenerate; fix env var
429Rate/quotaBackoff; lower concurrency
TimeoutsNetwork/proxyRetry with timeouts; stable path
TruncationLow max tokensRaise 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.

Related

← All tutorials