题意:"即使已加载,Langchain 中的 OpenAI 仍然需要 'openai_api_key'"
问题背景:
this is my code: 以下是我的代码:
import os
from dotenv import load_dotenv,find_dotenv
load_dotenv(find_dotenv())
print(os.environ.get("OPEN_AI_KEY"))
from langchain.llms import OpenAI
llm=OpenAI(model_name="text-davinci-003",temperature=0.7,max_tokens=512)
print(llm)
when I execute above code I get this error
"当我执行上述代码时,出现了这个错误。"
ValidationError: 1 validation error for OpenAI
__root__
Did not find openai_api_key, please add an environment variable `OPENAI_API_KEY` which contains it, or pass `openai_api_key` as a named parameter. (type=value_error)
docs say 文档说明
If you'd prefer not to set an environment variable you can pass the key in directly via the openai_api_key named parameter when initiating the OpenAI LLM class:
But already set it and it prints correctly
"但我已经设置了,它也正确打印出来了。"
When I set the llm
by passing named param:
"当我通过传递命名参数设置 `llm` 时:"
llm=OpenAI(openai_api_key="PASSINGCORRECTKEY", model_name="text-davinci-003",temperature=0.7,max_tokens=512)
llm("Tell me a joke")
then I get this error: 然后我得到以下错误
raise ValueError(
"Argument `prompt` is expected to be a string. Instead found "
f"{type(prompt)}. If you want to run the LLM on multiple prompts, use "
"`generate` instead."
)
UPDATE
env variable initially was set as OPEN_AI_KEY
since I copied and pasted from one of my other project which calls chat/completions
api. I changed the env to OPENAI_API_KEY
not I get this error:
"环境变量最初设置为 `OPEN_AI_KEY`,因为我从调用 `chat/completions` API 的另一个项目中复制粘贴了它。我将环境变量更改为 `OPENAI_API_KEY`,现在我遇到了这个错误:"
AuthenticationError: Incorrect API key provided: org-Wz3J****************2XK6. You can find your API key at https://platform.openai.com/account/api-keys.
But same api key works when i call "https://api.openai.com/v1/chat/completions"
endpoint
"但是当我调用 `https://api.openai.com/v1/chat/completions` 端点时,相同的 API 密钥是有效的。"
问题解决:
You may need to store the OpenAI token and then pass it to the llm
variable you have here, or just rename your environment variable to openai_api_key
.
"您可能需要存储 OpenAI 令牌,然后将其传递给您这里的 `llm` 变量,或者只需将环境变量重命名为 `openai_api_key`。"
A possible example of passing a key directly is this:
"直接传递密钥的一个可能示例是:"
import os
from dotenv import load_dotenv,find_dotenv
load_dotenv(find_dotenv())
prompt = "Your Prompt Here"
OpenAI_key = os.environ.get("OPEN_AI_KEY")
print(OpenAI_token)
from langchain.llms import OpenAI
llm=openai.Completion.create(model_name="text-davinci-003",temperature=0.7,max_tokens=512,openai_api_key=OpenAI_key, prompt=prompt, stop=None)
print(llm)
It should work now
"现在应该可以正常工作了。"