# Fix "You tried to access openai.ChatCompletion, but this is no longer supported in openai>=1.0.0"

Yes. An agent moves a bot from openai.ChatCompletion to the v1 client, keeps its key and Lambda packaging, and proves the new call offline before opening a PR.

[Run this on Rush](https://cloud.getrush.ai/run/fix-openai-chatcompletion-no-longer-supported/openai/). Opens the console with this prompt ready to send, in a Project that has your repository.

## What the agent does

The message is not a traceback from inside the library. Since openai 1.0.0 the package keeps a stub for every removed symbol, and touching `openai.ChatCompletion`, `openai.Completion` or `openai.Audio` raises `openai.lib._old_api.APIRemovedInV1` with the text in the title, a pointer to the README and two ways out: run `openai migrate`, or pin `openai==0.28`. The current release is 3.46.0 and still raises it, so a requirements file that lists `openai` with no version gets the error on its next clean install, usually a deploy, not a code change.

franalgaba/chatgpt-telegram-bot-serverless is a Telegram bot that runs as one AWS Lambda function behind Chalice. `requirements.txt` lists `openai` unpinned next to `python-telegram-bot==13.11`, `chalice`, `boto3`, `loguru` and `wget`. `app.py` line 21 reads `OPENAI_API_KEY` from the environment, and `ask_chatgpt` on lines 40 to 51 calls `openai.ChatCompletion.create(model="gpt-3.5-turbo", messages=[...])` and returns `message["choices"][0]["message"]["content"]`. Nothing in the file ever assigns `openai.api_key`; the 0.x library read the variable itself. `.chalice/config.json` lists the three environment variables the function needs and sets `lambda_timeout` to 600; `chalicelib/utils.py` transcribes voice notes with AWS Transcribe, not with the OpenAI API, so it is untouched.

The agent starts by making the failure reproducible without Telegram or AWS. It installs the requirements fresh, imports `app` with placeholder environment variables, and calls `ask_chatgpt` with a fake key: the call raises `APIRemovedInV1` before any request leaves the machine. It also installs `openai==0.28.1` in a second environment to show the pin the message suggests still works, so the pull request can say why it chose the port instead: the 0.28 line gets no fixes, and the package it ships beside, python-telegram-bot 13.11, is itself two major versions behind.

Then it ports the three lines that matter. A module-level `client = OpenAI()` replaces the implicit key, and the client reads `OPENAI_API_KEY` from the environment just as the old library did, so Chalice's configuration stays as it is. `openai.ChatCompletion.create(...)` becomes `client.chat.completions.create(...)` with the same `model` and `messages`. The return value is no longer a dict: `completion.choices[0].message.content` replaces the subscripts, because indexing the new `ChatCompletion` object raises `TypeError: 'ChatCompletion' object is not subscriptable`, a second failure that only appears once the first is fixed. The agent pins `openai>=1,<4` in `requirements.txt`, notes that the installed package has no `openai.cli` module so the `openai migrate` command the message names is not available from a plain install, and writes a test that patches the client's `create` with a canned `ChatCompletion` and asserts `ask_chatgpt` returns its text.

## Start it with one API call

`POST https://api.phoenix.so/o/{org}/sessions`

```json
{
  "agent": "claude",
  "input": "Deploys of this Python service fail at runtime with openai.lib._old_api.APIRemovedInV1: You tried to access openai.ChatCompletion, but this is no longer supported in openai>=1.0.0. Read the dependency files and the deployment configuration, and report which openai version a clean install resolves to and whether the package is pinned. Reproduce the error offline: install the requirements in a clean virtual environment, import the application with placeholder environment variables, and call the function that uses openai with a fake key, so the failure is on record without any network call. Also show whether pinning openai==0.28 still installs, and say in the pull request why you did or did not take that route. Port every use of the removed module-level API (ChatCompletion, Completion, Embedding, Audio, Image) to the v1 client: create one OpenAI() client, keep reading the key from the same environment variable the service already uses, and replace dict-style access on responses with attribute access. Keep the model names and prompts exactly as they are. Pin openai to a range that includes the version you tested. Add a test that patches the client's create method with a canned response object and asserts the function returns its text, run it, and include the output. Do not use a real API key and do not call the OpenAI API. Open a pull request that lists each changed call with file and line, the versions installed, and anything you could not verify offline.",
  "resources": [
    {
      "url": "https://github.com/your-org/your-app"
    }
  ]
}
```

1. **Get an API key.** In the console, open Settings, then API keys, and create a key for your org. Send it in the Authorization header as a Bearer token.
2. **Send the request.** POST the body in request.json to https://api.phoenix.so/o/{org}/sessions, with your repository as the resources URL. The run starts in its own cloud sandbox.
3. **Read what came back.** Follow the run on its live stream or wait for the run.completed webhook, then read the result and its trajectory.

## What comes back

A pull request that touches the entry module and the requirements file, plus one new test. The description opens with the reproduction: the command that installed the requirements, the openai version it resolved to, and the `APIRemovedInV1` traceback from calling the handler with a fake key. Below it is the list of ported calls, one line each with the file and line number, and the sentence about the pin: that `openai==0.28.1` still installs on the Python the function uses, and why the port was chosen anyway.

The diff is small enough to read in one sitting. One import, one client, one call, one return expression, and a version range in `requirements.txt`. A reviewer checks three things: that the environment variable name in the deployment configuration is the one the client reads, that the `messages` list and `model` string are byte-for-byte what they were, and that the test's canned object matches the shape a real `ChatCompletion` has, because that is what guards the return expression.

What the run cannot prove is listed last. No request reached the OpenAI API, so a live reply, rate limits and the behaviour of the chosen model name are for the reviewer to try with the real key in a test chat before the deploy.

## Run it on every CloudWatch alarm on Lambda errors

A bot like this has no CI, and the first sign of the break is a CloudWatch alarm on the function's error count after a deploy. Give the repository's Project an automation with the prompt above and a `webhook` trigger. An SNS subscription cannot add the `Authorization: Bearer` header the trigger expects, so a small handler on your side receives the alarm notification, verifies it, and posts the alarm body to the trigger's URL with the trigger's secret. The alarm text then follows the saved prompt as event text, and the agent reads the function's recent log group output from it.

For a team that runs several small services on the same pattern, the port is the same in each. Send the request above once per repository with an API key and read each result from its session, or let the key's webhook report every `run.completed`.

## Why run it on Rush?

The port itself is four lines; the work is proving them. The function only runs inside Lambda with a Telegram token, an OpenAI key and an S3 bucket, so nobody reproduces the error locally and the fix is usually made blind. In a sandbox the agent installs the requirements twice, once as they are and once with the 0.28 pin, imports the handler with placeholder variables, and captures the exact exception without any credential. Those commands and their output stay in the session, so the pull request shows the failure and the fix side by side instead of describing them.

It also keeps the fix honest about its edges. The agent writes the test against a canned `ChatCompletion` object from the installed package, so the return expression is checked against the real response type, not against a dict someone remembered. And because the run never has a real key, the description has to say what was not tried, which is exactly the list a reviewer wants before the next deploy.

## Frequently asked questions

### Can I just pin openai==0.28 and move on?

It still installs, and the check in the run shows that. It is also where the old `ChatCompletion` module lives, so the bot works again at once. The cost is that the 0.28 line receives no fixes and the new endpoints and response types are only in the 1.x and later clients, so the pin buys time rather than ending the work.

### Does the agent need my OpenAI key?

No, and the request tells it not to make any API call. The error is raised inside the library before a request is built, so a fake key reproduces it, and the new code is checked with a patched `create` that returns a canned response object. The first live reply is for you to try after the review.

### Why does my code fail a second time with 'ChatCompletion' object is not subscriptable?

The v1 client returns typed objects, not dicts. `response["choices"][0]["message"]["content"]` must become `response.choices[0].message.content`. The agent changes every such expression it finds and the test covers the one in the handler.

### Will it change my model or prompts?

No. The port keeps the `model` string and the `messages` list exactly as they were, so the pull request is only about the client. Moving to a newer model is a separate request with its own review.

### What about openai migrate, which the error message suggests?

The message names it, but the package installed from a plain `pip install openai` in the run has no `openai.cli` module, so the command is not there to run. The agent makes the same edits by hand, which for a handler this size is a handful of lines, and lists each one in the pull request.

## More OpenAI Python SDK jobs

- [Fix openai.ChatCompletion Errors by Migrating to the v1 Client](https://getrush.ai/run/migrate-to-openai-v1/openai/)

## More jobs like this: Fix a bug from an alert

- [Fix "Option 'testPathPattern' was replaced by '--testPathPatterns'" in Jest 30](https://getrush.ai/run/fix-option-testpathpattern-was-replaced/jest/)
- [Fix "AttributeError: module 'os' has no attribute 'errno'" on Python 3.7 and Later](https://getrush.ai/run/fix-os-errno-attribute-error/os/)
- [Fix "Package subpath './lib/adapters/http' is not defined by \"exports\"" after upgrading axios](https://getrush.ai/run/fix-package-subpath-is-not-defined-by-exports/axios/)
- [Fix "Parameters: { use_label_encoder } are not used" Warning in XGBoost](https://getrush.ai/run/fix-parameters-use-label-encoder-are-not-used-warning/xgboost/)
- [Fix "Passing null to parameter of type string is deprecated" on PHP 8.1 and later](https://getrush.ai/run/fix-passing-null-to-parameter-deprecated/php/)

## Keep reading

- [How a Rush run works on your repository, from request to pull request](https://getrush.ai/cloud/)
- [Compare cloud agents, agent sandboxes and AI code review](https://getrush.ai/compare/)
- [Rush pricing: Free, Pro and Max](https://getrush.ai/pricing/)
