You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

使用Azure OpenAI初始化OpenAIClient时遇“无法转换”错误求助

问题根源

你同时引用了Azure.AI.OpenAI和OpenAI两个不同的SDK包,代码中实例化的OpenAIClient实际是**OpenAI官方SDK(OpenAI包)**的类,而非Azure OpenAI专属SDK(Azure.AI.OpenAI包)的类,两者构造函数参数要求完全不同,导致类型转换报错。

解决方法

方法一:使用Azure OpenAI专属SDK(推荐)

  1. 移除项目中OpenAI NuGet包的引用,仅保留Azure.AI.OpenAI包
  2. 修正代码,确保使用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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.16 04:01:04