openai.OpenAIError: The api_key client option must be set either by passing api_key to the client or by setting the OPENAI_API_KEY environment variable

Hi, and welcome to the forum. Let’s get right into answering your code’s concerns.

The first problem I can see is that you tried to access openai.Completion, but this is no longer supported in openai>=1.0.0. You can read the page at github openai openai-python to discover those recent changes.

If you already had an existing code base, you can pin your python installation to the old library version, such as by installing an older library module with pip install openai==0.28

Since the AI hasn’t been trained on any of the recent changes to OpenAI models or APIs, you also can run openai migrate from a python interpreter within your code directory to automatically upgrade your codebase to use the 1.0.0 interface.

Your local user installation of Python 3.12 is a bleeding-edge version. I instead would uninstall that and install 3.10 for “all users”, which is not getting feature changes and does not have problems with libraries needed.


But mostly the fault is in letting AI write code you don’t understand, for models you haven’t researched. What if AI-written code called an AI model that cost you several dollars a question? Then you prompted AI into writing other off-base constructions, when you’d likely have intended to use the whisper audio transcription API of OpenAI .

You should absorb the “chat” section of the API documentation, and then also look at the AI models available and their pricing. If you want to just have code to make your first request, which will produce an error if your API account isn’t funded: