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

使用aiohttp+asyncio调用Azure OpenAI ChatGPT遇401未授权错误求助

Azure OpenAI接口401未授权错误排查思路及代码修正

核心排查点:

  • Deployment ID格式错误:你代码里的deployment_id写成了带https的URL,实际Azure OpenAI的部署ID是部署名称(比如你在Azure门户创建的gpt-35-turbo),不是完整URL。这个错误会导致请求路径无效,触发权限验证失败。
  • Authorization头格式验证:Azure OpenAI支持两种鉴权方式,一种是Bearer {api_key},另一种是直接用api-key头传密钥。如果当前方式失败,试试替换头格式。
  • URL拼接正确性:确认endpoint不带https前缀,api版本和openai包使用的完全一致,避免路径拼接错误导致服务端无法识别资源。
  • API Key有效性:检查Key是否对应目标Azure资源,有没有过期或权限变更,可通过Postman直接调接口排除代码外的问题。

修正后的代码:

import aiohttp
import asyncio

async def chatGPT_call():
    # 替换为你的实际配置
    api_key = "你的API Key"
    endpoint = "你的环境名称.openai.azure.com"  # 例:xxx.openai.azure.com,不带https
    deployment_id = "你的部署名称"  # 例:gpt-35-turbo,仅名称

    # 构造正确的请求URL
    url = f"https://{endpoint}/openai/deployments/{deployment_id}/chat/completions?api-version=2024-07-01-preview"
    
    # 方式1:Bearer Token鉴权
    headers = {
        "Content-Type": "application/json",
        "Authorization": f"Bearer {api_key}"
    }
    
    # 方式2:api-key头鉴权(方式1失败时启用)
    # headers = {
    #     "Content-Type": "application/json",
    #     "api-key": api_key
    # }

    payload = {
        "messages": [
            {"role": "system", "content": "你是一个说话像海盗的助手"},
            {"role": "user", "content": "能告诉我怎么照顾鹦鹉吗?"}
        ]
    }

    try:
        async with aiohttp.ClientSession() as session:
            async with session.post(url, headers=headers, json=payload) as response:
                print(f"响应状态码: {response.status}")
                result = await response.json()
                if response.status == 200:
                    return result["choices"][0]["message"]["content"]
                else:
                    return f"请求失败: {result}"
    except Exception as e:
        return f"异常错误: {str(e)}"

async def main():
    response = await chatGPT_call()
    print(response)

asyncio.run(main())

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.18 05:05:00