题意:OpenAi 没有返回结果,程序以代码 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
.
你正在尝试使用 OpenAI,但是无法获取结果。你通过 Visual Studio Code 访问 API,并且已经为 Visual Studio Code 下载了这些扩展:Code Runner 和 Python。此外,你还通过 CMD 安装了 OpenAI 的 Python SDK,即使用 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:
但是当我运行那段代码时,输出标签没有输出任何东西:
Anyone know where I possibly went wrong?
有人知道我可能哪里出错了吗?
问题解决:
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.
当我在 Linux 上的控制台/终端/bash 中运行你的代码(不使用 VSCode),我得到了一些有用的错误消息。所以,也许你应该首先在 CMD 中测试一下,看看是否会出现带有说明的错误消息。
But main problem is that you use API_KEY
in wrong way
但是主要问题是你错误地使用了 API_KEY
You should use it directly in code (without os.getenv()
)
你应该直接在代码中使用它(不使用 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
并使用确切的 OPEN_API_KEY
openai.api_key = os.getenv("OPEN_API_KEY")
(and this way you can share code without sharing API_KEY
)
这样你就可以在不共享 API_KEY 的情况下共享代码
Your API_KEY
is too short but I tested it with my API_KEY
and it works for me.
你的 API_KEY 太短了,但我用我自己的 API_KEY 测试过,它对我来说是有效的。
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"
}