使用Azure OpenAI与.NET Core开发聊天机器人POC时遇DeploymentNotFound错误
问题背景
使用Azure OpenAI免费试用版与.NET Core开发聊天机器人POC,已创建OpenAI资源并部署模型,但调用CompleteChat()时触发404错误:
HTTP 404 (DeploymentNotFound) The API deployment for this resource does not exist. If you created the deployment within the last 5 minutes, please wait a moment and try again.
已尝试两种端点与API密钥组合:
- OpenAI资源「管理密钥」区域的端点(
https://uschatbot.openai.azure.com/)及对应密钥 - 模型部署界面的完整路径端点(
https://aksha-m88bx4tg-eastus2.cognitiveservices.azure.com/openai/deployments/GPT4Model)
核心代码片段:
private readonly string _deploymentName = "GPT4Model"; public HomeController(ILogger<HomeController> logger) { string endpoint = "https://uschatbot.openai.azure.com/"; string apiKey = "<已填入API密钥>"; _aiClient = new AzureOpenAIClient(new Uri(endpoint), new ApiKeyCredential(apiKey)); } [HttpPost] public IActionResult Index(ChatViewModel model) { // ... ChatClient chatClient = _aiClient.GetChatClient(_deploymentName); ChatCompletion completion = chatClient.CompleteChat(model.UserInput); // 此处报错 // ... }
排查与解决步骤
确认部署名称完全匹配
检查Azure门户中模型部署的名称是否与代码中的_deploymentName完全一致(区分大小写、无多余空格)。同时确认部署状态为「成功」,新创建的部署需等待5-10分钟生效。使用正确的端点格式
必须使用OpenAI资源主界面「管理密钥」中的基础端点(无额外路径后缀),SDK会自动拼接部署相关路径。禁止使用模型部署页面的完整路径作为端点。验证资源与部署的区域一致性
确保OpenAI资源所在区域与模型部署的区域完全相同,跨区域部署无法被资源端点访问。切换为异步调用并检查SDK版本
同步调用CompleteChat可能存在潜在问题,建议改用异步方法,并确保Azure.AI.OpenAI和OpenAI.ChatNuGet包为最新稳定版:[HttpPost] public async Task<IActionResult> Index(ChatViewModel model) { var chatHistory = HttpContext.Session.Get<List<string>>("ChatHistory") ?? new List<string>(); if (!string.IsNullOrEmpty(model.UserInput)) { ChatClient chatClient = _aiClient.GetChatClient(_deploymentName); // 改用异步调用 ChatCompletion completion = await chatClient.CompleteChatAsync(model.UserInput); chatHistory.Add($"You: {model.UserInput}"); chatHistory.Add($"E360: {completion.Content[0].Text}"); HttpContext.Session.Set("ChatHistory", chatHistory); model.UserInput = string.Empty; } model.ChatHistory = chatHistory; return View(model); }检查免费试用版限制
确认免费试用额度未耗尽,可在Azure门户「成本管理 + 计费」中查看额度使用情况;部分区域可能对免费试用用户有部署限制,可尝试切换到支持的区域重新部署模型。
内容的提问来源于stack exchange,提问作者Ak C

