使用Azure OpenAI初始化OpenAIClient时遇“无法转换”错误求助
问题根源
你同时引用了Azure.AI.OpenAI和OpenAI两个不同的SDK包,代码中实例化的OpenAIClient实际是**OpenAI官方SDK(OpenAI包)**的类,而非Azure OpenAI专属SDK(Azure.AI.OpenAI包)的类,两者构造函数参数要求完全不同,导致类型转换报错。
解决方法
方法一:使用Azure OpenAI专属SDK(推荐)
- 移除项目中
OpenAINuGet包的引用,仅保留Azure.AI.OpenAI包 - 修正代码,确保使用
Azure.AI.OpenAI命名空间下的OpenAIClient:
using Azure; using Azure.AI.OpenAI; string endpoint = "https://MYURL.openai.azure.com/"; string key = "MYKEYVALUES"; // 此OpenAIClient来自Azure.AI.OpenAI命名空间,参数匹配要求 OpenAIClient azureClient = new(new Uri(endpoint), new AzureKeyCredential(key));
方法二:用OpenAI官方SDK对接Azure OpenAI
如果需要保留OpenAI包,需调整参数格式,同时指定Azure部署ID:
using OpenAI; using OpenAI.Chat; string apiKey = "MYKEYVALUES"; string azureDeploymentId = "你的Azure部署模型ID"; // 需替换为实际部署ID string endpoint = "https://MYURL.openai.azure.com/"; var client = new OpenAIClient(apiKey, new OpenAIClientOptions { Endpoint = new Uri(endpoint) }); // 调用聊天接口时必须指定Azure部署ID var chatCompletionOptions = new ChatCompletionOptions { DeploymentName = azureDeploymentId };
注意事项
- 禁止同时混用两个SDK,避免命名冲突和参数混淆
- 确认NuGet包版本:
Azure.AI.OpenAI需匹配Azure OpenAI服务的版本,OpenAI包需使用v1.0及以上版本(支持Azure对接)
内容的提问来源于stack exchange,提问作者Proposition Joe
相关产品推荐
相关产品推荐

