当前位置:   article > 正文

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

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 完成一条消息时

  1. import openai
  2. response = openai.ChatCompletion.create(
  3. model="gpt-3.5-turbo",
  4. messages=[{"role": "user", "content": "What are the trade-offs around deadwood in forests?"}]
  5. )
  6. 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 方法可以检查密钥是否有效?

  1. In [35]: openai.api_key
  2. 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 代码:

  1. import openai
  2. def check_openai_api_key(api_key):
  3. client = openai.OpenAI(api_key=api_key)
  4. try:
  5. client.models.list()
  6. except openai.AuthenticationError:
  7. return False
  8. else:
  9. return True
  10. OPENAI_API_KEY = "sk-7....."
  11. if check_openai_api_key(OPENAI_API_KEY):
  12. print("Valid OpenAI API key.")
  13. else:
  14. print("Invalid OpenAI API key.")

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/盐析白兔/article/detail/1016032
推荐阅读
相关标签
  

闽ICP备14008679号