'OpenAI' object has no attribute 'Completion'

Here is a basic example:

from openai import OpenAI

client = OpenAI()

PROMPT = "give me a random poem"

def call_openai_api():

    response = client.chat.completions.create(
        model="gpt-4",
        messages=[{"role": "user", "content": PROMPT}],
        temperature=1,
        max_tokens=300,
        top_p=1,
        frequency_penalty=0,
        presence_penalty=0
    )

    print(response.choices[0].message.content.strip())

if __name__ == "__main__":
    call_openai_api()

save it as openai_test.py

Then you typically create a virtual env (optional but suggested)

python3 -m venv venv
source venv/bin/activate

And you will need to export the OPENAI_API_KEY - e.g. on ubuntu you do:

export OPENAI_API_KEY=sk....your_key_here

There is no need to explicitly set that for the OpenAI object - it just reads that OPENAI_API_KEY env variable per default.

and then you can install the requirement / openai lib and run the script

pip install openai
python3 openai_test.py

you can deactive the venv by just typing

deactivate