使用Azure.AI.OpenAI调用时触发400错误(Bad Request)寻求技术支持
解决Azure OpenAI调用带Azure Search数据源时的400错误
常见排查与修复步骤
1. 验证资源配置
- 确认你的Azure OpenAI部署已启用数据检索功能:在Azure门户的OpenAI资源中,进入“数据”选项卡,确保已关联对应的Azure Search资源,且部署的模型支持数据检索(如GPT-4系列)。
- 检查Azure Search索引
test-gpt4是否存在,且索引结构包含可检索的核心字段(如content)。 - 确认Azure Search密钥权限:可尝试将管理密钥替换为查询密钥测试,部分场景下查询密钥的权限适配性更好。
2. 修正数据源参数
- 确保Azure Search的Endpoint格式严格为
https://[search-service-name].search.windows.net,无多余空格或后缀。 - 检查索引名称
test-gpt4拼写完全匹配,注意Azure Search索引名称大小写敏感。
3. 指定兼容的API版本
Azure.AI.OpenAI 2.1.0默认API版本可能不支持数据检索预览功能,初始化客户端时显式指定预览版本:
var client = new AzureOpenAIClient( new Uri("https://[your-url].openai.azure.com/"), new AzureKeyCredential("open-ai-api-key"), new OpenAIClientOptions { ApiVersion = "2024-02-15-preview" } );
4. 调整代码语法与配置
- 若项目使用的C#版本低于12,将消息列表的字面量语法改为传统
List<ChatMessage>构造:
ChatCompletion completion = chatClient.CompleteChat( new List<ChatMessage> { new SystemChatMessage(systemPrompt), new UserChatMessage(query) }, chatOptions );
- 检查
MaxOutputTokenCount设置:若检索返回的内容过长,可适当提高该值,避免输入token超限触发400错误。
5. 捕获详细错误信息
添加异常捕获逻辑,获取更具体的错误详情,精准定位问题:
try { ChatCompletion completion = chatClient.CompleteChat(...); return completion.Content[0].Text; } catch (RequestFailedException ex) { Console.WriteLine($"错误代码:{ex.Status},详情:{ex.Message},请求ID:{ex.RequestId}"); throw; }
替代实现方案
如果SDK方式仍无法解决,可直接调用Azure OpenAI的REST API手动构造请求:
POST https://[your-url].openai.azure.com/openai/deployments/btGPT4/chat/completions?api-version=2024-02-15-preview Authorization: Bearer {open-ai-api-key} Content-Type: application/json { "messages": [ {"role": "system", "content": "You are an AI assistant that helps people find information."}, {"role": "user", "content": "{query}"} ], "max_tokens": 100, "data_sources": [ { "type": "azure_search", "parameters": { "endpoint": "https://[your url].search.windows.net", "index_name": "test-gpt4", "authentication": { "type": "api_key", "key": "[search_admin_key]" } } } ] }
内容的提问来源于stack exchange,提问作者jkyadav
相关产品推荐
相关产品推荐

