Gregorius Alvin
Gregorius Alvin

Reputation: 25

OpenAi not returning result and exited with code=0

I'm trying to use OpenAI, but I can't get a result. I'm accessing the API via Visual Studio Code. I have downloaded these extensions for Visual Studio Code: Code Runner and Python. I've also installed OpenAI via CMD: pip install openai.

Here's my code:

import os
import openai
openai.api_key = os.getenv("sk-xxxxxxxxxxxxxxxxxxxx")
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: Photos

Anyone know where I possibly went wrong?

Upvotes: 2

Views: 7418

Answers (2)

thesirsaurabh
thesirsaurabh

Reputation: 1

import openai

import os

from dotenv import load_dotenv, find_dotenv

_ = load_dotenv(find_dotenv())

os.environ['OPENAI_API_KEY'] = 'sk-qX8fYeuOxPtse7ZXgNgsT3BlbkFJETitXKSk4F32G7bXG5'

or

openai.api_key = 'sk-qX8fYeuOxPtse7ZXgNgsT3BlbkFJETitXKSk4F32G7bXG5'

Note- Find key here https://platform.openai.com/account/api-keys

Upvotes: 0

furas
furas

Reputation: 142681

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"
}

Upvotes: 4

Related Questions