import openai
def test_api_key(api_key):
openai.api_key = api_key
try:
# 尝试使用API密钥获取模型列表
models = openai.models.list()
print("您的OpenAI API密钥是有效的。")
print(models)
return True
except Exception as e:
print(f"出现错误,可能是因为API密钥无效:{e}")
return False
# 用您的实际API密钥替换这里的'YOUR_API_KEY'
your_api_key='sk-mb-z……X'
is_valid = test_api_key(your_api_key)
if is_valid:
print("密钥测试通过。")
else:
print("密钥测试失败,请检查您的API密钥。")
your_api_key='sk-mb-z……X'
这里填入你自己的key
然后运行程序
如果结果是下面这样子,就是对的,会列出你能用的模型,如果不是,则出错了。你的key不对(注意如果是tb买的话,只有直连的才可以,过期的也可以显示出有效,但是过期了就不能正式用了)
您的OpenAI API密钥是有效的。
SyncPage[Model](data=[Model(id='dall-e-3', created=1698785189, object='model', owned_by='system'), Model(id='whisper-1', created=1677532384, object='model', owned_by='openai-internal'), Model(id='davinci-002', created=1692634301, object='model', owned_by='system'), Model(id='babbage-002', created=1692634615, object='model', owned_by='system'), Model(id='dall-e-2', created=1698798177, object='model', owned_by='system'), Model(id='gpt-3.5-turbo-16k', created=1683758102, object='model', owned_by='openai-internal'), Model(id='tts-1-hd-1106', created=1699053533, object='model', owned_by='system'), Model(id='tts-1-hd', created=1699046015, object='model', owned_by='system'), Model(id='gpt-3.5-turbo-1106', created=1698959748, object='model', owned_by='system'), Model(id='gpt-3.5-turbo-instruct-0914', created=1694122472, object='model', owned_by='system'), Model(id='gpt-3.5-turbo-instruct', created=1692901427, object='model', owned_by='system'), Model(id='text-embedding-3-small', created=1705948997, object='model', owned_by='system'), Model(id='tts-1', created=1681940951, object='model', owned_by='openai-internal'), Model(id='gpt-3.5-turbo-0125', created=1706048358, object='model', owned_by='system'), Model(id='gpt-3.5-turbo', created=1677610602, object='model', owned_by='openai'), Model(id='gpt-3.5-turbo-0301', created=1677649963, object='model', owned_by='openai'), Model(id='tts-1-1106', created=1699053241, object='model', owned_by='system'), Model(id='text-embedding-3-large', created=1705953180, object='model', owned_by='system'), Model(id='gpt-3.5-turbo-0613', created=1686587434, object='model', owned_by='openai'), Model(id='text-embedding-ada-002', created=1671217299, object='model', owned_by='openai-internal'), Model(id='gpt-3.5-turbo-16k-0613', created=1685474247, object='model', owned_by='openai')], object='list')
密钥测试通过。
如果你等待很长时间,并且出现下面错误,是因为网络问题
出现错误,可能是因为API密钥无效:Request timed out.
密钥测试失败,请检查您的API密钥。