调用AzureOpenAIModelFactory.StreamingChatCompletions触发NullReferenceException问题
解决AzureOpenAIModelFactory.StreamingChatCompletions()抛出NullReferenceException的问题
问题根源
调用AzureOpenAIModelFactory.StreamingChatCompletions()时立即触发System.NullReferenceException,问题出在StreamingChatCompletions类的内部构造函数:私有只读字段_baseChatCompletions未被初始化,构造函数直接调用其Add()方法,导致空引用异常。相关代码片段如下:
public class StreamingChatCompletions : IDisposable { private readonly IList<ChatCompletions> _baseChatCompletions; //... internal StreamingChatCompletions( ChatCompletions baseChatCompletions = null, List<StreamingChatChoice> streamingChatChoices = null) { _baseChatCompletions.Add(baseChatCompletions); _streamingChatChoices = streamingChatChoices; _streamingTaskComplete = true; } }
解决方案
1. 初始化私有字段_baseChatCompletions
由于_baseChatCompletions是readonly类型,必须在声明时或构造函数内完成初始化。推荐在声明时直接初始化:
private readonly IList<ChatCompletions> _baseChatCompletions = new List<ChatCompletions>();
或者在构造函数开头初始化:
internal StreamingChatCompletions( ChatCompletions baseChatCompletions = null, List<StreamingChatChoice> streamingChatChoices = null) { _baseChatCompletions = new List<ChatCompletions>(); // 后续逻辑... }
2. 处理可选参数的null情况
baseChatCompletions是可选参数,可能传入null,调用Add()前需判断,避免向列表中添加null元素(根据业务需求调整):
if (baseChatCompletions != null) { _baseChatCompletions.Add(baseChatCompletions); }
完整修正后的构造函数示例
public class StreamingChatCompletions : IDisposable { private readonly IList<ChatCompletions> _baseChatCompletions = new List<ChatCompletions>(); private List<StreamingChatChoice> _streamingChatChoices; private bool _streamingTaskComplete; internal StreamingChatCompletions( ChatCompletions baseChatCompletions = null, List<StreamingChatChoice> streamingChatChoices = null) { if (baseChatCompletions != null) { _baseChatCompletions.Add(baseChatCompletions); } _streamingChatChoices = streamingChatChoices; _streamingTaskComplete = true; } // IDisposable接口实现... }
内容的提问来源于stack exchange,提问作者Intelligence6
相关产品推荐
相关产品推荐

