How to check the validity of the OpenAI key from python?

题意:如何在 Python 中检查 OpenAI 密钥的有效性?

问题背景:

https://pypi.org/project/openai/

  • "The library needs to be configured with your account's secret key which is available on the website. [...] Set it as the OPENAI_API_KEY environment variable"

When I ask Chat GPT to complete a message

当我请求 Chat GPT 完成一条消息时

import openai
response = openai.ChatCompletion.create(
    model="gpt-3.5-turbo",
    messages=[{"role": "user", "content": "What are the trade-offs around deadwood in forests?"}]
)
print(response)

I get a RateLimitError: You exceeded your current quota, please check your plan and billing details.

我收到一个 RateLimitError 错误:您已超出当前配额,请检查您的计划和账单详情

Is there a python method to check that the key is valid?

是否有一种 Python 方法可以检查密钥是否有效?

In [35]: openai.api_key
Out[35]: 'sk-...'

问题解决

The Python codes shown, accesses openai.Model, but this is no longer supported in openai>=1.0.0, see the v1.0.0 Migration Guide or README at https://github.com/openai/openai-python for the API.

显示的 Python 代码访问了 openai.Model,但在 openai>=1.0.0 中不再支持此功能,请参阅 v1.0.0 迁移指南 或 README 以获取 API 信息。

Here is the adapted python code:

这是调整后的 Python 代码:

import openai

def check_openai_api_key(api_key):
    client = openai.OpenAI(api_key=api_key)
    try:
        client.models.list()
    except openai.AuthenticationError:
        return False
    else:
        return True


OPENAI_API_KEY = "sk-7....."

if check_openai_api_key(OPENAI_API_KEY):
    print("Valid OpenAI API key.")
else:
    print("Invalid OpenAI API key.")

  • 13
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

营赢盈英

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值