llm auth_error ai_generated true

openai.AuthenticationError: Incorrect API key provided: sk-... You can find your API key at https://platform.openai.com/account/api-keys.

ID: llm/invalid-api-key-format

Also available as: JSON · Markdown · 中文
95%Fix Rate
90%Confidence
1Evidence
2023-03-01First Seen

Version Compatibility

VersionStatusIntroducedDeprecatedNotes
openai>=1.0.0 active
openai==0.28.0 active

Root Cause

The API key string is malformed, expired, or belongs to a different organization/project than the one being used for the request.

generic

中文

API密钥字符串格式错误、已过期,或属于与当前请求不同的组织/项目。

Official Documentation

https://platform.openai.com/docs/guides/error-codes/api-errors

Workarounds

  1. 95% success Verify the API key by testing it directly with curl: curl -H 'Authorization: Bearer YOUR_API_KEY' https://api.openai.com/v1/models If this fails, the key is invalid. Check for trailing newlines or spaces in your .env file.
    Verify the API key by testing it directly with curl:
    curl -H 'Authorization: Bearer YOUR_API_KEY' https://api.openai.com/v1/models
    If this fails, the key is invalid. Check for trailing newlines or spaces in your .env file.
  2. 90% success Ensure the API key is loaded correctly from environment variables without quotes: import os import openai openai.api_key = os.getenv('OPENAI_API_KEY').strip() print(repr(openai.api_key)) # Should show 'sk-...' without extra spaces
    Ensure the API key is loaded correctly from environment variables without quotes:
    import os
    import openai
    openai.api_key = os.getenv('OPENAI_API_KEY').strip()
    print(repr(openai.api_key))  # Should show 'sk-...' without extra spaces

中文步骤

  1. 通过curl直接测试API密钥:
    curl -H 'Authorization: Bearer YOUR_API_KEY' https://api.openai.com/v1/models
    如果失败,则密钥无效。检查.env文件中是否有尾随换行符或空格。
  2. 确保从环境变量正确加载API密钥,不带引号:
    import os
    import openai
    openai.api_key = os.getenv('OPENAI_API_KEY').strip()
    print(repr(openai.api_key))  # 应显示'sk-...',无多余空格

Dead Ends

Common approaches that don't work:

  1. 60% fail

    The root cause is often a copy-paste error or whitespace, not the key itself.

  2. 80% fail

    The key may be revoked by the provider after exposure, or the code leaks secrets.