React应用调用Azure OpenAI API失败,Python脚本可正常运行
问题分析与解决方案
导致授权错误的三个核心原因:
- API端点路径错误:GPT-35-turbo属于聊天模型,正确的API端点是
/chat/completions,而非你代码中使用的/completions(后者针对文本补全类模型)。 - 认证头格式错误:Azure OpenAI使用API Key认证时,HTTP请求头的格式应为
Authorization: Api-Key {你的密钥},而不是Bearer {密钥}(Bearer是Azure AD令牌的认证方式)。 - 请求体与端点不匹配:只有
/chat/completions端点支持messages请求体结构,/completions端点使用的是prompt字段,原代码的请求体结构和端点不兼容。
修改后的React代码:
import React, { useEffect } from 'react'; const AzureOpenAIComponent: React.FC = () => { useEffect(() => { const fetchCompletion = async () => { const apiKey = process.env.REACT_APP_AZURE_OPENAI_KEY; const azureEndpoint = "https://openai-testbench.openai.azure.com/"; const apiVersion = "2023-05-15"; // 修正端点路径为chat/completions const url = `${azureEndpoint}openai/deployments/gpt-35-turbo/chat/completions?api-version=${apiVersion}`; const requestBody = { model: "gpt-35-turbo", messages: [ { role: "system", content: "Assistant is a large language model trained by OpenAI." }, { role: "user", content: "Who were the founders of Microsoft?" } ], }; try { const response = await fetch(url, { method: 'POST', headers: { 'Content-Type': 'application/json', // 修正认证头格式为Api-Key 'Authorization': `Api-Key ${apiKey}`, }, body: JSON.stringify(requestBody), }); if (!response.ok) { const errorDetails = await response.json(); throw new Error(`Request failed: ${JSON.stringify(errorDetails)}`); } const data = await response.json(); console.log(data); } catch (error) { console.error('Error fetching data: ', error); } }; fetchCompletion(); }, []); return ( <div>Check the console for the response.</div> ); }; export default AzureOpenAIComponent;
额外说明:
- 确认你的Azure OpenAI部署名称确实是
gpt-35-turbo,如果部署名称不同,需要修改URL中的deployments/后的部分。 - 前端直接暴露API Key存在安全风险,建议生产环境通过后端代理请求Azure OpenAI API,避免密钥泄露。
内容的提问来源于stack exchange,提问作者Marc
相关产品推荐
相关产品推荐

