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

Google Apps Script调用Azure OpenAI API遇401未授权错误求助

解决Google Apps Script调用Azure OpenAI API的401未授权问题

核心错误:认证头格式不符

Azure OpenAI使用API密钥认证时,不需要Bearer前缀,正确的请求头应为api-key字段,而非Authorization: Bearer ...。你当前代码沿用了OpenAI的认证格式,这是触发401错误的主要原因。

其他必须修正的配置

  • 补全完整API端点URL
    Azure OpenAI的API端点需包含部署路径与API版本参数,格式示例:
    https://{你的资源名称}.openai.azure.com/openai/deployments/{你的部署名称}/chat/completions?api-version=2024-02-15-preview
    替换其中的资源名称、部署名称,API版本可参考Azure官方文档选择最新稳定版。

  • 移除Payload中的engine字段
    Azure Chat Completions接口通过URL路径指定部署,请求体中无需engine字段,需删除engine:"gpt-35-turbo"这一行。

  • 修正结果解析字段
    Azure返回的消息内容字段为message.content,原代码中message.text是错误的,会导致即使认证通过也返回"No text generated"。

修改后的完整代码

const api_key = "你的Azure OpenAI API密钥";  
const max_tokens = 500;  
// 替换为完整的Azure OpenAI端点URL
const url = "https://{你的资源名称}.openai.azure.com/openai/deployments/{你的部署名称}/chat/completions?api-version=2024-02-15-preview";

function gpt(userprompt, userrole = "user", temperature = 1) {  
  const gptprompt = [{role: userrole, content: userprompt}];  

  const payload = {  
    messages: gptprompt,
    temperature: temperature,  
    max_tokens: max_tokens,
  };  

  const options = {  
    method: "POST",  
    contentType: "application/json",  
    // 修正认证头格式
    headers: { "api-key": api_key },  
    payload: JSON.stringify(payload),  
    muteHttpExceptions: true  
  };  

  try {  
    const response = UrlFetchApp.fetch(url, options);  
    console.log(response.getContentText());  
    const results = JSON.parse(response.getContentText());  
    console.log(results);  
    // 修正字段为content
    const text = results?.choices?.[0]?.message?.content?.trim() ?? "No text generated";  
    console.log(text);  
    return text;  
  } catch (error) {  
    console.error("Error: ", error);  
    return "Error: Unable to fetch data.";  
  }  
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.19 08:57:20