C#调用 AI学习从0开始-第1阶段(基础与工具)-第7天多轮对话记忆
什么是AI多轮对话记忆就是让AI记住你之前说过的话能像真人聊天一样连续对话。为什么需要记忆例:无记忆 你什么是List AIList是C#中的动态数组...你它有什么优点 ← AI不知道它是什么 AI请问您说的是什么 ← 回答不出来 有记忆 你什么是List AIList是C#中的动态数组...你它有什么优点 ← AI知道它指的是List AIList的优点有1.大小可变2.有丰富的方法...怎么实现AI多轮对话记忆每次问问题都把之前聊过的所有内容一起发给AI。核心代码//1. 添加保存对话历史privateListChatMessage_historynewListChatMessage();publicasyncTaskstringRequstAI_Message_Multi(stringuserMessage,stringmodelqwen-turbo,float?temperaturenull,int?maxTokensnull){stringresp_answer;// 替换成你的阿里云百炼 API KeyconststringapiKeyConfigCommon.apiKey;//此处写你申请的API KeyconststringurlConfigCommon.url_chat;//https://dashscope.aliyuncs.com/compatible-mode/v1/chat/completions;varclientnewHttpClient();client.DefaultRequestHeaders.Add(Authorization,$Bearer{apiKey});//1 把用户的消息加入历史_history.Add(newChatMessage(user,userMessage));//请求体varrequestBodynew{modelqwen-turbo,messages_history,//MessagesIntemperaturetemperature,// 低温度让输出更稳定 高温度更创新maxTokensmaxTokens,streamfalse};varjsonJsonSerializer.Serialize(requestBody);varcontentnewStringContent(json,Encoding.UTF8,application/json);//使用 response_format: json_object 时必须在 messages 中的某个地方明确提到json这个词,否则会调用报错。//Console.WriteLine(正在调用阿里云百炼 AI...\n);try{varresponseawaitclient.PostAsync(url,content);varresponseStringawaitresponse.Content.ReadAsStringAsync();if(response.IsSuccessStatusCode){vardocJsonDocument.Parse(responseString);varanswerdoc.RootElement.GetProperty(choices)[0].GetProperty(message).GetProperty(content).GetString();Console.WriteLine($AI 回答{answer});resp_answeranswer;// 把AI的回答也加入历史_history.Add(newChatMessage(assistant,answer));}else{Console.WriteLine($HTTP 错误{response.StatusCode});Console.WriteLine($响应内容{responseString});}}catch(Exceptionex){Console.WriteLine($异常{ex.Message});}returnresp_answer;}/// summary/// 2. 设置系统提示词可选放在历史第一位/// /summarypublicvoidSetSystemPrompt(stringsystemPrompt){// 如果已经有system消息先移除if(_history.Count0_history[0].Rolesystem){_history.RemoveAt(0);}// 插入到最前面_history.Insert(0,newChatMessage(system,systemPrompt));}/// summary/// 3. 清空历史记录重新开始对话/// /summarypublicvoidClearHistory(){_history.Clear();}/// summary/// 4. 清空历史但保留system prompt/// /summarypublicvoidClearHistoryKeepSystem(){stringsystemPromptnull;if(_history.Count0_history[0].Rolesystem){systemPrompt_history[0].Content;}_history.Clear();if(!string.IsNullOrEmpty(systemPrompt)){_history.Add(newChatMessage(system,systemPrompt));}}/// summary/// 5. 查看当前历史记录/// /summarypublicIReadOnlyListChatMessageGetHistory(){return_history.AsReadOnly();}/// summary/// 6. 打印历史记录调试用/// /summarypublicvoidPrintHistory(){Console.WriteLine($\n 对话历史共{_history.Count}条);foreach(varmsgin_history){stringpreviewmsg.Content.Length50?msg.Content.Substring(0,50)...:msg.Content;Console.WriteLine($[{msg.Role}]:{preview});}Console.WriteLine(\n);}调用代码publicstaticasyncTaskDay(){try{Console.WriteLine($多轮对话记忆\r\n);CommonClassclientnewCommonClass();client.SetSystemPrompt(你是一个C#编程助手回答要简洁专业);Console.WriteLine(用户什么是C#的ListT);varreply1awaitclient.RequstAI_Message_Multi(什么是C#的ListT);Console.WriteLine($AI{reply1}\n);// 第2轮AI需要知道它指的是什么Console.WriteLine(用户它有什么优点);varreply2awaitclient.RequstAI_Message_Multi(它有什么优点);Console.WriteLine($AI{reply2}\n);// 第3轮Console.WriteLine(用户那它和数组有什么区别);varreply3awaitclient.RequstAI_Message_Multi(那它和数组有什么区别);Console.WriteLine($AI{reply3}\n);// 查看历史client.PrintHistory();// 测试清空Console.WriteLine(--- 清空历史后 ---);client.ClearHistory();Console.WriteLine($清空后历史条数{client.GetHistory().Count});Console.WriteLine(\n用户刚才我们聊了什么);varreply4awaitclient.RequstAI_Message_Multi(刚才我们聊了什么);Console.WriteLine($AI{reply4});}catch(Exceptionex){Console.WriteLine($异常{ex.Message});}}辅助类publicclassChatMessage{/// summary/// 消息角色system / user / assistant/// /summary[JsonPropertyName(role)]publicstringRole{get;set;}string.Empty;/// summary/// 消息内容/// /summary[JsonPropertyName(content)]publicstringContent{get;set;}string.Empty;publicChatMessage(){}publicChatMessage(stringrole,stringcontent){Rolerole;Contentcontent;}publicoverridestringToString(){return${Role}:{Content};}}publicclassChatResponse{[JsonPropertyName(choices)]publicListChoiceChoices{get;set;}newListChoice();}publicclassChoice{[JsonPropertyName(message)]publicChatMessageMessage{get;set;}newChatMessage();}总结多轮对话记忆 用List _history 保存所有对话每次请求都传给API以达到有记忆的效果。