'OpenAi not returning result and exited with code=0

I'm trying to use OpenAi, buat i cant get a result. I'm accessing the API via visual studio code. I have downloaded extension for visual code : Code Runner, and Python. Im also installed Open AI via CMD : pip install openai.

Here's my code :

import os
import openai
openai.api_key = os.getenv("sk-5kyIzSG6wxeCDdf2T3BlbdfJxgdfeet9JWm8cQumrG")
x=openai.Completion.create(
  engine="text-davinci-002",
  prompt="Say this is a test",
  max_tokens=5
)
print(x)

Referenced from the official documentation : https://beta.openai.com/docs/api-reference/completions/create?lang=python

But when i run that code, the output tab is not outputting anything just like this Photos

Anyone know where i possibly go wrong ?



Solution 1:[1]

When I run your code in console/terminal/bash (on Linux) without VSCode then I get some useful error message. So maybe first you should test it on CMD to see if you get error message with explanation.


But main problem is that you use API_KEY in wrong way

You should use it directly in code (without os.getenv())

openai.api_key = "sk-5kyIzSG6wxeCDdf2T3BlbdfJxgdfeet9JWm8cQumrG"

Or in system you should set environment's variable

OPEN_API_KEY=sk-5kyIzSG6wxeCDdf2T3BlbdfJxgdfeet9JWm8cQumrG

and use exactly OPEN_API_KEY

openai.api_key = os.getenv("OPEN_API_KEY")

(and this way you can share code without sharing API_KEY)


Your API_KEY is too short but I tested it with my API_KEY and it works for me.

import openai

openai.api_key = "sk-...my_api_key..."

x = openai.Completion.create(
  engine="text-davinci-002",
  prompt="Say this is a test",
  max_tokens=5
)

print(x)

Result:

{
  "choices": [
    {
      "finish_reason": "length",
      "index": 0,
      "logprobs": null,
      "text": "\n\nThis is a"
    }
  ],
  "created": 1652054180,
  "id": "cmpl-55l36Li5BTrRZWPU38MdQai8yVGEA",
  "model": "text-davinci:002",
  "object": "text_completion"
}

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 furas