Python OpenAI

The official SDK, streaming, structured output, and cost control basics.

Intermediate
Key PointsKeep the API key in the environment, set timeouts and max_tokens, and treat the model output as untrusted input.

Install and Configure

The official SDK reads the key from OPENAI_API_KEY. Never hard-code it. Compatible gateways only need a different base_url.

Bash
pip install openai
export OPENAI_API_KEY="sk-..."        # Windows: set OPENAI_API_KEY=sk-...

First Request

Python
from openai import OpenAI

client = OpenAI(timeout=30)

resp = client.chat.completions.create(
    model="gpt-4o-mini",
    messages=[
        {"role": "system", "content": "You are a concise backend tutor."},
        {"role": "user", "content": "用一句话解释 GIL。"},
    ],
    temperature=0.3,
    max_tokens=200,
)
print(resp.choices[0].message.content)
print(resp.usage)          # prompt_tokens / completion_tokens
Output
GIL 是 CPython 的全局解释器锁,同一时刻只允许一个线程执行 Python 字节码,因此多线程无法并行跑纯 Python 计算。
CompletionUsage(prompt_tokens=28, completion_tokens=54, total_tokens=82)

Streaming

Streaming cuts time-to-first-token to a few hundred milliseconds. Guard against delta.content being None.

Python
stream = client.chat.completions.create(
    model="gpt-4o-mini",
    messages=[{"role": "user", "content": "写一个 Python 快速排序"}],
    stream=True,
)
for chunk in stream:
    delta = chunk.choices[0].delta.content
    if delta:
        print(delta, end="", flush=True)

Structured Output

For JSON output, use JSON mode or tool calling with an explicit schema — and still validate the result.

Python
import json

resp = client.chat.completions.create(
    model="gpt-4o-mini",
    response_format={"type": "json_object"},
    messages=[{"role": "user",
               "content": '返回 JSON:{"title": str, "tags": [str]},主题是 Redis 缓存'}],
)
data = json.loads(resp.choices[0].message.content)
print(data["title"], data["tags"])
Output
Redis 缓存入门 ['Redis', '缓存', '后端']
ConcernPractice
CostCap max_tokens, cache repeated prompts
LatencyStream, or use a smaller model
ReliabilityRetry on 429/5xx with backoff
SafetyNever send secrets or PII in prompts
Model output is untrusted input: never eval() it, never interpolate it into SQL, never use it for authorization.

Friends & Partners