C#中Ollama无法保留对话上下文,求启动时仅注入指令方案
解决Ollama C#客户端对话上下文不保留及系统指令单次注入问题
核心解决方案
不要每次将系统指令拼接进用户prompt,而是在初始化对话上下文时一次性注入系统指令,利用Ollama的ConversationContext维护包含系统指令的完整对话历史。
修改后的代码示例
private ConversationContext context; private readonly string _systemInstructions = "你的系统指令内容,比如'你是一个专业的C#开发助手,回答简洁准确'"; // 在类构造函数中初始化上下文并注入系统指令 public YourChatService() { context = new ConversationContext(); // 将系统指令添加为system角色的消息,Ollama会全程遵循该指令 context.AddMessage(MessageRole.System, _systemInstructions); } public async Task SendPrompt(string userPrompt) { var output = string.Empty; // 直接传入用户prompt,上下文会自动携带历史对话和系统指令 context = await ollama.StreamCompletion(userPrompt, context, stream => { output += stream.Response; }); Console.WriteLine(output); }
问题原因说明
- 临时方案的弊端:你之前每次把指令拼到prompt前,相当于每次用户提问都重复发送系统指令,不仅冗余,还可能干扰模型对对话历史的理解。
- context +=无效的原因:
ConversationContext是一个结构化的消息集合(包含角色、内容等信息),不是简单的字符串,直接用+=无法正确向其中添加消息,必须调用AddMessage方法来维护不同角色的对话内容。
额外注意事项
- 确保使用的Ollama C#客户端版本支持
MessageRole.System,部分旧版本可能未实现系统角色的识别逻辑。 - 确认
StreamCompletion方法会正确更新传入的ConversationContext,确保每次对话后上下文都包含最新的用户提问和模型回复。
内容的提问来源于stack exchange,提问作者Heinrich Espach
相关产品推荐
相关产品推荐

