使用OpenAI API密钥定义时遇到问题

我尝试使用langchain openai,但始终无法使其正常工作。

我尝试了openai的快速开始测试:

from openai import OpenAIclient = OpenAI()completion = client.chat.completions.create(  model="gpt-3.5-turbo",  messages=[    {"role": "system", "content": "You are a poetic assistant, skilled in explaining complex programming concepts with creative flair."},    {"role": "user", "content": "Compose a poem that explains the concept of recursion in programming."}  ])print(completion.choices[0].message)

但它会报错:

 line 98, in __init__    raise OpenAIError(openai.OpenAIError: The api_key client option must be set either by passing api_key to the client or by setting the OPENAI_API_KEY environment variable

但在这样设置API密钥后:

import openaiimport osos.environ["OPENAI_API_KEY"] = "myapikey"client = openai.OpenAI()completion = client.chat.completions.create(  model="gpt-3.5-turbo",  messages=[    {"role": "system", "content": "You are a poetic assistant, skilled in explaining complex programming concepts with creative flair."},    {"role": "user", "content": "Compose a poem that explains the concept of recursion in programming."}  ])print(completion.choices[0].messages)

它会显示一大堆错误信息:

    File "C:\Users\jasha\Desktop\code\python\gpt\gpt0\gpt0.py", line 9, in <module>enter code here        completion = client.chat.completions.create(      File "C:\Users\jasha\AppData\Local\Programs\Python\Python311\Lib\site-packages\openai\_utils\_utils.py", line 271, in wrapper        return func(*args, **kwargs)      File "C:\Users\jasha\AppData\Local\Programs\Python\Python311\Lib\site-packages\openai\resources\chat\completions.py", line 659, in create        return self._post(      File "C:\Users\jasha\AppData\Local\Programs\Python\Python311\Lib\site-packages\openai\_base_client.py", line 1180, in post        return cast(ResponseT, self.request(cast_to, opts, stream=stream, stream_cls=stream_cls))      File "C:\Users\jasha\AppData\Local\Programs\Python\Python311\Lib\site-packages\openai\_base_client.py", line 869, in request        return self._request(      File "C:\Users\jasha\AppData\Local\Programs\Python\Python311\Lib\site-packages\openai\_base_client.py", line 945, in _request        return self._retry_request(      File "C:\Users\jasha\AppData\Local\Programs\Python\Python311\Lib\site-packages\openai\_base_client.py", line 993, in _retry_request        return self._request(      File "C:\Users\jasha\AppData\Local\Programs\Python\Python311\Lib\site-packages\openai\_base_client.py", line 945, in _request        return self._retry_request(      File "C:\Users\jasha\AppData\Local\Programs\Python\Python311\Lib\site-packages\openai\_base_client.py", line 993, in _retry_request        return self._request(      File "C:\Users\jasha\AppData\Local\Programs\Python\Python311\Lib\site-packages\openai\_base_client.py", line 960, in _request        raise self._make_status_error_from_response(err.response) from None    openai.RateLimitError: Error code: 429 - {'error': {'message': 'You exceeded your current quota, please check your plan and billing details. For more information on this error, read the docs: https://platform.openai.com/docs/guides/error-codes/api-errors.', 'type': 'insufficient_quota', 'param': None, 'code': 'insufficient_quota'}}

回答:

首先,您需要在项目文件夹中创建一个“.env”文件,像这样

# Once you add your API key below, make sure to not share it with anyone! The API key should remain private.OPENAI_API_KEY=abc123

然后在代码初始化时,它会默认读取该环境变量:

from openai import OpenAI

client = OpenAI()# defaults to getting the key using os.environ.get("OPENAI_API_KEY")# if you saved the key under a different environment variable name, you can do something like:# client = OpenAI(#   api_key=os.environ.get("CUSTOM_ENV_NAME"),# )

还要确保您已正确安装库。或者,您可以直接传递API密钥,但这不推荐,因为这样会暴露在代码中。

!pip install --upgrade pipfrom openai import OpenAIclient = OpenAI(api_key='yourapikey')completion = client.chat.completions.create(  model="gpt-3.5-turbo",  messages=[    {"role": "system", "content": "You are a poetic assistant, skilled in explaining complex programming concepts with creative flair."},    {"role": "user", "content": "Compose a poem that explains the concept of recursion in programming."}  ])print(completion.choices[0].message)

在您发布错误日志后,我终于明白了。错误信息显示您的账户没有余额。您需要一个有效的密钥,或者在您的账户上购买额度。请在这里检查您的账户使用情况 这里

  raise self._make_status_error_from_response(err.response) from None    openai.RateLimitError: Error code: 429 - {'error': {'message': 'You exceeded your current quota, please check your plan and billing details. For more information on this error, read the docs: https://platform.openai.com/docs/guides/error-codes/api-errors.', 'type': 'insufficient_quota', 'param': None, 'code': 'insufficient_quota'}}

来源

Related Posts

使用LSTM在Python中预测未来值

这段代码可以预测指定股票的当前日期之前的值,但不能预测…

如何在gensim的word2vec模型中查找双词组的相似性

我有一个word2vec模型,假设我使用的是googl…

dask_xgboost.predict 可以工作但无法显示 – 数据必须是一维的

我试图使用 XGBoost 创建模型。 看起来我成功地…

ML Tuning – Cross Validation in Spark

我在https://spark.apache.org/…

如何在React JS中使用fetch从REST API获取预测

我正在开发一个应用程序,其中Flask REST AP…

如何分析ML.NET中多类分类预测得分数组?

我在ML.NET中创建了一个多类分类项目。该项目可以对…

发表回复

您的邮箱地址不会被公开。 必填项已用 * 标注