Azure OpenAI C#示例代码无法运行:ChatCompletionsOptions未解析
问题解决:Azure OpenAI C#代码无法解析ChatCompletionsOptions及ChatCompletion类
问题原因
你遇到的问题源于Azure.AI.OpenAI预发行版API的版本更新,生成的示例代码使用了旧版API的属性和类型,与当前包版本不兼容:
ChatCompletion类型已被ChatCompletions替代,且CompleteChat方法返回Response<ChatCompletions>而非直接返回结果对象ChatCompletionsOptions中不存在PastMessages属性,对话历史需通过ChatHistory类维护- 部分参数的初始化方式或名称有变化,比如
StopSequences不能直接用[]初始化
修正后的代码
// 安装预发行版NuGet包: // dotnet add package Azure.AI.OpenAI --prerelease using Azure; using Azure.AI.OpenAI; using Azure.Identity; using static System.Environment; string endpoint = GetEnvironmentVariable("AZURE_OPENAI_ENDPOINT"); string key = GetEnvironmentVariable("AZURE_OPENAI_KEY"); AzureKeyCredential credential = new AzureKeyCredential(key); AzureOpenAIClient azureClient = new AzureOpenAIClient(new Uri(endpoint), credential); ChatClient chatClient = azureClient.GetChatClient("gpt-35-turbo"); // 使用ChatHistory维护对话历史,替代原PastMessages属性 ChatHistory chatHistory = new ChatHistory(); chatHistory.AddSystemMessage("You are an AI assistant that helps people find information."); // 调用CompleteChat并获取响应 Response<ChatCompletions> response = chatClient.CompleteChat( chatHistory, new ChatCompletionsOptions() { Temperature = 0.7f, MaxTokens = 800, StopSequences = Array.Empty<string>(), // 正确初始化空数组 TopP = 0.95f, // 替代原NucleusSamplingFactor FrequencyPenalty = 0f, PresencePenalty = 0f, }); ChatCompletions completion = response.Value; Console.WriteLine($"{completion.Choices[0].Message.Role}: {completion.Choices[0].Message.Content}");
关键改动说明
- 类型与返回值替换:将
ChatCompletion改为ChatCompletions,CompleteChat返回Response<ChatCompletions>,需通过.Value获取实际结果 - 对话历史管理:用
ChatHistory类添加消息,替代原PastMessages属性,这是当前版本维护对话上下文的标准方式 - 参数调整:
NucleusSamplingFactor改名为TopP;StopSequences需用Array.Empty<string>()或new string[] {}初始化,不能直接写[] - 命名空间清理:移除
OpenAI.Chat命名空间,当前Azure.AI.OpenAI包已包含所有必要类型
内容的提问来源于stack exchange,提问作者David Onyango
相关产品推荐
相关产品推荐

