Call the OpenAI API from Python: 6 Steps from SDK to Streaming

Blog / Developer tools

Call the OpenAI API from Python: 6 Steps from SDK to Streaming

The shortest way to call the OpenAI API from Python: create a virtual environment, run pip install openai, put your API key in the OPENAI_API_KEY environment variable, then send one request with the official SDK and print the reply. It takes about a dozen lines of code, and you never have to build the HTTP request yourself.

This guide walks through six steps in order: environment, install, key, minimal chat, streaming, and error handling. Model names are written as the placeholder MODEL_NAME; replace it with a model your account can use. Check OpenAI's official docs for exact model names and parameters. Models change fast, and hard-coding one in a tutorial goes stale quickly.

Step 1: Why create a virtual environment first?

A virtual environment isolates this project's dependencies from the system Python, so upgrading or removing the SDK later won't affect other projects. For the minimum required Python version, see the SDK's official documentation.

mkdir openai-demo && cd openai-demo
python3 -m venv .venv
source .venv/bin/activate        # Windows PowerShell: .venv\Scripts\Activate.ps1

Once activated, (.venv) appears at the start of your prompt.

Step 2: How do you install the SDK?

pip install --upgrade openai
python -c "import openai; print(openai.__version__)"

If it prints a version number, the install worked. If pip is slow, switch to a PyPI mirror that works on your network, and use a mirror address from a source you trust.

Step 3: Where should the API key go?

Don't put the key in your code, and never commit it to Git. The official SDK reads the OPENAI_API_KEY environment variable by default, so the key never has to appear in your code.

export OPENAI_API_KEY="sk-你的密钥"      # Windows PowerShell: $env:OPENAI_API_KEY="sk-你的密钥"

This only applies to the current terminal window. For long-term use, add it to your shell config, or load a .env file with python-dotenv and add .env to .gitignore. If you don't have a key yet, start with How to get an OpenAI API key: a step-by-step walkthrough of the Platform dashboard. If a key has already landed in a public repository, see Your OpenAI API key leaked: revoke it, check usage, and prevent a repeat.

Step 4: What does the minimal chat code look like?

Create hello.py:

from openai import OpenAI

client = OpenAI()  # Automatically reads OPENAI_API_KEY

resp = client.chat.completions.create(
    model="MODEL_NAME",
    messages=[
        {"role": "system", "content": "你是一个简洁的助手。"},
        {"role": "user", "content": "用一句话解释什么是 API。"},
    ],
)

print(resp.choices[0].message.content)

Run python hello.py and one reply should appear in the terminal. (The prompts in the code are in Chinese: the system message says "You are a concise assistant," and the user message asks for a one-sentence explanation of what an API is. Use any language you like.) A few key points:

  • model must be a model your account can use. A wrong value gives you a 404 or a permission error.
  • messages is a list, and each item has a role and content. A multi-turn conversation just appends the history in order; the model itself doesn't remember the previous call.
  • The reply text is in resp.choices[0].message.content. Usage information is in resp.usage; print it to get a sense of how many tokens a request used.

OpenAI also offers a newer API (the Responses API) with different syntax. This article uses Chat Completions because it has the widest support among compatible third-party endpoints. For a new project, follow the recommendation in the official docs.

To see what this request actually sends at the HTTP level, compare it with Send your first LLM request with curl: every parameter explained line by line.

Step 5: How do you print the reply token by token, like a chat UI?

Add stream=True and the return value becomes an iterable of chunks:

from openai import OpenAI

client = OpenAI()

stream = client.chat.completions.create(
    model="MODEL_NAME",
    messages=[{"role": "user", "content": "写三行关于夏天的短诗。"}],
    stream=True,
)

for chunk in stream:
    if not chunk.choices:
        continue
    delta = chunk.choices[0].delta.content
    if delta:
        print(delta, end="", flush=True)
print()

Don't skip the if not chunk.choices and if delta checks. Some chunks carry no content, and reading from them directly raises an error or prints None. flush=True makes the text appear immediately; otherwise the terminal may buffer a batch and print it all at once.

Step 6: How do you handle errors?

Network blips, rate limits, and bad parameters all raise exceptions. The SDK splits the common cases into separate exception classes:

import openai
from openai import OpenAI

client = OpenAI(timeout=30.0, max_retries=2)

try:
    resp = client.chat.completions.create(
        model="MODEL_NAME",
        messages=[{"role": "user", "content": "你好"}],
    )
    print(resp.choices[0].message.content)
except openai.APIConnectionError as e:
    print("连不上服务:", e)
except openai.RateLimitError as e:
    print("被限流或额度不足:", e)
except openai.APIStatusError as e:
    print("服务返回错误状态码:", e.status_code, e.response.text)

timeout and max_retries are client parameters. The SDK automatically retries some errors; for the defaults and production recommendations, see How to configure OpenAI SDK timeouts and retries. Note that RateLimitError maps to HTTP 429, which can mean you're sending requests too fast or that you've hit a quota or balance problem. Read the exact wording in the error message. (The print strings above are Chinese: "can't reach the service," "rate limited or out of quota," and "the service returned an error status code.")

Common errors at a glance

SymptomCommon causeWhat to check first
401 / AuthenticationErrorWrong or revoked key, or the environment variable isn't setecho $OPENAI_API_KEY to confirm the current terminal has a value
404 / model not foundmodel is misspelled, or your account lacks access to that modelCompare against the official docs and the models available in your account dashboard
429 / RateLimitErrorRequests too fast, or insufficient quota or balanceRead the error message body; check your account usage and limits
APIConnectionErrorNetwork down, wrong proxy settings, or DNS problemsCheck official status first, then your local network and proxy
TimeoutSlow network, or the request itself takes longIncrease timeout; streaming lets you see output sooner

If you suspect a server-side problem, check cdnping's OpenAI status page, which probes the official API entry point from the Cloudflare edge every 5 minutes. You can also check whether ChatGPT is down right now. For how to judge latency and connection problems when accessing AI APIs from mainland China, see How to read AI API latency from China.

What should you do before going to production?

What if you have no overseas credit card or can't connect directly?

The official OpenAI API requires signing up and paying on OpenAI's platform. Whether it's available depends on your region and account, so follow the terms of service and local regulations. If that step blocks you, an aggregation gateway is another way to connect. For the trade-offs, see How to choose an AI API access path: official API, cloud-hosted, or aggregation gateway.

AGI Plan is one such option, and it is a commercial partner of cdnping. It is a multi-provider LLM aggregation gateway with monthly subscriptions, billed in RMB, with no overseas credit card required. One subscription can switch between multiple capability groups, and it supports both OpenAI-compatible and Anthropic-compatible API formats. For the code in this article, you usually only need to put its endpoint URL and key into OpenAI(base_url=..., api_key=...); the rest stays the same. Check its documentation for the exact URL. The operator states that it is not an officially authorized channel and that some models are available only outside mainland China; see the models page for details. Beginners can start with the AGI Plan getting-started page. To change the endpoint in tools like Claude Code and Codex, see Custom API endpoints for Claude Code, Codex, and OpenCode.

What to do next

  1. Get the Step 4 script running and confirm you receive a reply.
  2. Add the Step 6 error handling, then deliberately break the key once to see what the error looks like.
  3. Set a spending limit in the dashboard before you start building real features.

Related articles

Keep reading