Märuf
Märuf

Reputation: 55

Openai api Completion.create not working on my python code

In openai.py the Completion.create is highlighting as alert and also not working.. the error is right down below.. whats the problem with the code

response = openai.Completion.create(
    engine="text-davinci-002",
    prompt="Generate blog topic on: Ethical hacking",
    temperature=0.7,
    max_tokens=256,
    top_p=1,
    frequency_penalty=0,
    presence_penalty=0
)

$ python openai.py
Traceback (most recent call last):
  File "E:\python\openAI\openai.py", line 2, in <module>
    import openai
  File "E:\python\openAI\openai.py", line 9, in <module>
    response = openai.Completion.create(
AttributeError: partially initialized module 'openai' has no attribute 'Completion' (most likely due to a circular import)

Upvotes: 2

Views: 28074

Answers (3)

FabianVal
FabianVal

Reputation: 373

I had the same issue. My problem was that I created a virtual environment with the name openai. That name conflicts with the library. Make sure that openai is not used for a folder or virtual environment.

Upvotes: 0

swyx
swyx

Reputation: 2511

for my fellow doofuses going thru all the above suggestions and wondering why its not working:

make sure your file is NOT named openai.py. because then it will call itself, because python.

wasted 2 hours on this nonsense lol.

relevant link How to fix AttributeError: partially initialized module?

Upvotes: 26

Biranchi
Biranchi

Reputation: 16327

I tried the openai version 0.18.1 and was able to run a sample GPT-3 code.

pip install openai==0.18.1


import openai
import config

openai.api_key = config.OPENAI_API_KEY if 'OPENAI_API_KEY' in dir(config) else ''
print(f'openai.api_key : {openai.api_key}')


def openAIQuery(query):
    response = openai.Completion.create(
      engine="davinci-instruct-beta-v3",
      prompt=query,
      temperature=0.8,
      max_tokens=200,
      top_p=1,
      frequency_penalty=0,
      presence_penalty=0)

    if 'choices' in response:
        if len(response['choices']) > 0:
            answer = response['choices'][0]['text']
        else:
            answer = 'Opps sorry, you beat the AI this time'
    else:
        answer = 'Opps sorry, you beat the AI this time'

    return answer


if __name__ == '__main__':
    if not openai.api_key:
        print(f'api_key is not set')
        exit(0)
        
    query = 'Generate a keras 3 layer neural network python code for classification'
    try:
        response = openAIQuery(query)
        print(f'Response : {response}')
    except Exception as e:
        print(f'Exception : {str(e)}')

Upvotes: 2

Related Questions