You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Python调用Azure OpenAI Service与ChatGPT时遇AuthenticationError求助

Azure OpenAI认证错误(No API key provided)解决

你遇到的错误信息:

openai.error.AuthenticationError: No API key provided. You can set your API key in code using 'openai.api_key = ', or you can set the environment variable OPENAI_API_KEY=). If your API key is stored in a file, you can point the openai module at it with 'openai.api_key_path = '. You can generate API keys in the OpenAI web interface. See https://platform.openai.com/account/api-keys for details.

问题核心是代码中环境变量引用错误,或未正确配置环境变量,以下是具体解决步骤:

  • 修正环境变量配置与引用:
    代码里的EndPointHERE和KeyHere是占位符,需替换为实际环境变量名,或确保系统已设置对应变量。推荐用Azure官方约定的变量名:

    • 端点变量名:AZURE_OPENAI_ENDPOINT
    • API密钥变量名:AZURE_OPENAI_API_KEY
      设置方式:
      • Windows命令行:
        set AZURE_OPENAI_API_KEY=你的Azure OpenAI密钥
        set AZURE_OPENAI_ENDPOINT=你的Azure OpenAI端点
        
      • Linux/macOS终端:
        export AZURE_OPENAI_API_KEY=你的Azure OpenAI密钥
        export AZURE_OPENAI_ENDPOINT=你的Azure OpenAI端点
        
  • 调整代码中的环境变量引用:
    将代码里的占位符替换为实际变量名,示例代码如下:

    import os
    import openai
    
    openai.api_type = "azure"
    openai.api_version = "2023-05-15" 
    openai.api_base = os.getenv("AZURE_OPENAI_ENDPOINT")
    openai.api_key = os.getenv("AZURE_OPENAI_API_KEY")
    
    response = openai.ChatCompletion.create(
        engine="KSUAI",  # 确认此部署名称与Azure门户中创建的完全一致
        messages=[
        {"role": "system", "content": "你是由OpenAI训练的大型语言模型助手。"},
        {"role": "user", "content": "微软的创始人是谁?"}
        ]
    )
    
    print(response)
    print(response['choices'][0]['message']['content'])
    
  • 额外验证项:

    • 确认engine参数的KSUAI是你在Azure OpenAI门户中创建的部署名称,大小写和拼写必须完全匹配。
    • 测试阶段可直接硬编码端点和密钥(生产环境不推荐,避免密钥泄露):
      openai.api_base = "https://你的资源名.openai.azure.com/"
      openai.api_key = "你的实际API密钥"
      

内容的提问来源于stack exchange,提问作者Rostislav

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.17 16:05:06