Home / AI & GenAI

AI & GenAITroubleshootingBeginner

openai Python SDK upgrade breaks old code: APIRemovedInV1, AzureOpenAI client and response objects

A script or job broke after pip pulled a newer openai package. Map each 0.x error to its 1.x fix, including Azure settings, dict-style access, error classes, streaming and the httpx proxies error.

Deepak Bhardwaj5 min read

Applies toopenai Python package 0.x and 1.x and later; OpenAI API and Azure OpenAI; Python 3.8+

Symptom

An old script, notebook or scheduled job that called OpenAI or Azure OpenAI now fails at the first call. Nobody changed the code. A new container build or pip install -U pulled a newer openai package. Typical messages:

  • APIRemovedInV1: You tried to access openai.ChatCompletion, but this is no longer supported in openai>=1.0.0
  • AttributeError: module 'openai' has no attribute 'error'
  • TypeError: 'ChatCompletion' object is not subscriptable
  • TypeError: Client.__init__() got an unexpected keyword argument 'proxies'

The 1.0 release replaced module-level calls with client objects. Code written for 0.x doesn't run on 1.x without changes.

Check 1: which version is installed

python -c "import openai; print(openai.__version__)"
pip show openai httpx

Run this inside the same virtual environment, container image or job cluster that fails, not on your laptop. If the job has no pinned version, every rebuild can bring in a different one.

Quick map: error to fix

Error Cause Fix
APIRemovedInV1 ... openai.ChatCompletion 0.x call style on 1.x Create a client and call client.chat.completions.create
APIRemovedInV1 ... openai.Embedding Same client.embeddings.create
module 'openai' has no attribute 'error' openai.error.RateLimitError and similar moved Use openai.RateLimitError, openai.APIError and so on
object is not subscriptable Responses are now typed objects, not dicts resp.choices[0].message.content, or resp.model_dump()
unexpected keyword argument 'engine' Azure 0.x used engine= Pass the deployment name as model=
unexpected keyword argument 'request_timeout' Renamed timeout= on the client or per request
Client.__init__() got an unexpected keyword argument 'proxies' Old openai 1.x with httpx 0.28 or later Upgrade openai (fixed in 1.55.3), or pin httpx<0.28
404 DeploymentNotFound on Azure after migrating Model name passed instead of the deployment name, or the wrong endpoint model= must be your deployment name

Fix: rewrite the calls

OpenAI API

Old (0.x):

import openai
openai.api_key = os.environ["OPENAI_API_KEY"]
resp = openai.ChatCompletion.create(
    model="gpt-4o-mini",
    messages=[{"role": "user", "content": "Summarise this alert"}],
    request_timeout=30,
)
print(resp["choices"][0]["message"]["content"])

New (1.x):

from openai import OpenAI

client = OpenAI(timeout=30, max_retries=2)   # reads OPENAI_API_KEY from the environment
resp = client.chat.completions.create(
    model="gpt-4o-mini",
    messages=[{"role": "user", "content": "Summarise this alert"}],
)
print(resp.choices[0].message.content)
print(resp.usage.prompt_tokens, resp.usage.completion_tokens)

Create the client once and reuse it. Building a new client per request wastes connections.

Azure OpenAI

0.x configured Azure through module globals:

openai.api_type = "azure"
openai.api_base = "https://myres.openai.azure.com/"
openai.api_version = "2024-02-01"
openai.api_key = "..."
openai.ChatCompletion.create(engine="chat-prod", messages=[...])

In 1.x, use the AzureOpenAI client. Prefer Entra ID over keys:

from azure.identity import DefaultAzureCredential, get_bearer_token_provider
from openai import AzureOpenAI

token_provider = get_bearer_token_provider(
    DefaultAzureCredential(), "https://cognitiveservices.azure.com/.default"
)
client = AzureOpenAI(
    azure_endpoint="https://myres.openai.azure.com/",
    api_version="2024-10-21",          # use a GA version your resource supports
    azure_ad_token_provider=token_provider,
)
resp = client.chat.completions.create(
    model="chat-prod",                  # the deployment name, not the model name
    messages=[{"role": "user", "content": "ping"}],
)

If you can't change code paths much, AzureOpenAI() with no arguments reads AZURE_OPENAI_ENDPOINT, AZURE_OPENAI_API_KEY and OPENAI_API_VERSION from the environment. Azure OpenAI also offers a /openai/v1/ path that works with the plain OpenAI client and a base_url. Check that your resource and region support it before you switch.

Embeddings

resp = client.embeddings.create(model="text-embedding-3-small", input=["disk full on node-7"])
vector = resp.data[0].embedding

Error handling

The exception classes are now at the top level of the package:

import openai

try:
    resp = client.chat.completions.create(model="chat-prod", messages=msgs)
except openai.RateLimitError as e:          # 429
    log.warning("rate limited: %s", e)
except openai.APITimeoutError:
    log.warning("timed out")
except openai.APIStatusError as e:          # any other non-2xx
    log.error("status %s request-id %s", e.status_code, e.response.headers.get("x-request-id"))
except openai.APIConnectionError:
    log.error("network problem")

APITimeoutError is a subclass of APIConnectionError, so catch it first. The 1.x client also retries some errors itself (max_retries, default 2). If your old code had its own retry loop, lower one of them, or a single failure becomes many calls.

Streaming

stream = client.chat.completions.create(model="chat-prod", messages=msgs, stream=True)
for chunk in stream:
    if not chunk.choices:            # Azure can send chunks with no choices (for example filter results)
        continue
    delta = chunk.choices[0].delta.content
    if delta:
        print(delta, end="", flush=True)

delta.content is None on the role chunk and the final chunk. Code that did chunk["choices"][0]["delta"].get("content") needs both guards.

Code that expects dicts

If downstream code (logging, JSON storage, tests) expects a dict, convert at the boundary instead of rewriting everything:

data = resp.model_dump()            # plain dict
json_text = resp.model_dump_json()  # JSON string

Tip

The openai package ships an openai migrate command that rewrites 0.x code automatically. Check that your installed version still includes it, run it on a branch, and review the diff. It doesn't know your Azure deployment names.

Can't migrate today?

Pin the old version to get the job running, then plan the rewrite:

pip install "openai<1"

Warning

0.x gets no fixes and doesn't support newer API features or parameters. Treat the pin as a short-term workaround. Track it as a ticket with an owner and a date.

Prevent it next time

  • Pin openai (and httpx) to a known version in requirements.txt or a lock file, and upgrade on purpose with a test run.
  • Add a smoke test to CI that makes one real call (or a recorded one) for each client the app uses.
  • Keep the SDK client in one module (llm_client.py) so an SDK change touches one file, not every script.
  • Search the codebase for leftovers after migrating: grep -rnE "openai\.(ChatCompletion|Completion|Embedding|error)|engine=|request_timeout" .
  • Keep scheduled jobs and notebooks on the same pinned environment as the services. Unpinned notebooks are where this breaks first.