using Antlr.Runtime.Tree; using CommonHelper; using GasolineBlend.BLL; using GasolineBlend.Entity; using Newtonsoft.Json; using Newtonsoft.Json.Linq; using Org.BouncyCastle.Asn1.Pkcs; using SqlSugar.DistributedSystem.Snowflake; using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Net.Http; using System.Runtime.InteropServices; using System.Text; using System.Threading.Tasks; using System.Web; using System.Web.Helpers; using System.Web.Mvc; using System.Web.Razor.Tokenizer.Symbols; using System.Web.UI.WebControls; namespace GasolineBlend.Controllers { public class ChatHistoryController : BaseController { private ChatHistoryBLL _acc = new ChatHistoryBLL(); /// ///获取聊天记录返回对话 /// /// /// [HttpPost] public ActionResult GetChatHistoryList(int UserId, int AgentId, string Keyword, int PageNum, int PageSize) { try { var list = _acc.GetChatHistoryList(UserId, AgentId,Keyword, PageNum, PageSize); return SuccessNoShow(data: list); } catch (Exception e) { LogHelper.Write(Level.Error, "获取地区智能体数据 GetAgentDataList", e, OperatorProvider.Instance.Current == null ? "GuestEx" : OperatorProvider.Instance.Current.LoginName); return Error(); } } /// ///添加聊天记录返回对话 /// /// /// [HttpPost] public async Task AddChat(int UserId, int AgentId, string Prompt, string Chat) { try { Prompt = Prompt.Replace("\t", "").Replace("\n", "").Replace("\r", "").Replace("\f", ""); Prompt = Prompt.Replace(" ", ""); var list = _acc.GetChatHistory6List(AgentId, UserId); string historylist = ""; for (int i = list.Count - 1; i >= 0; i--) { string Role = list.Skip(i).FirstOrDefault()?.Role; string Content = list.Skip(i).FirstOrDefault()?.Content; Content = Content.Replace("\t", "").Replace("\n", "").Replace("\r", "").Replace("\f", ""); Content = Content.Replace(" ", ""); historylist += $@"{{""role"": ""{Role}"", ""content"": ""{Content}""}},"; } // 设置API的URL string apiUrl = "https://api.moonshot.cn/v1/chat/completions"; // 设置授权令牌 string bearerToken = "sk-Lec41LGc7aV8KdFzOCiJQIM9A8bsbBk5KumvqBSyfeW9EXec"; // 设置请求的JSON内容 string jsonContent = $@"{{ ""model"": ""moonshot-v1-128k"", ""messages"": [ {{""role"": ""system"", ""content"": ""{Prompt}""}},"; jsonContent += historylist; jsonContent += $@"{{""role"": ""user"", ""content"": ""{Chat}""}} ], ""temperature"": 0.3 }}"; using (HttpClient client = new HttpClient()) { // 如果响应状态码是200,则文件存在 HttpRequestMessage request = new HttpRequestMessage(HttpMethod.Post, apiUrl) { Content = new StringContent(jsonContent, Encoding.UTF8, "application/json") }; request.Headers.Authorization = new System.Net.Http.Headers.AuthenticationHeaderValue("Bearer", bearerToken); HttpResponseMessage response = await client.SendAsync(request); if (response.IsSuccessStatusCode) { string responseContent = await response.Content.ReadAsStringAsync(); JObject jsonObject = JObject.Parse(responseContent); int RUserId=0; int RAssistantId=0; for (int i = 0; i < 2; i++) { string co = ""; string ro = ""; if (i == 0) { co = Chat; ro = "user"; } else { co = jsonObject["choices"][0]["message"]["content"].ToString(); ro = "assistant"; } ChatHistoryDataPage chatHistoryDataPage = new ChatHistoryDataPage { Content =co , TotalTokens = jsonObject["usage"]["total_tokens"].Value(), Model = jsonObject["model"].ToString(), Created = jsonObject["created"].ToString(), Chatid = jsonObject["id"].ToString(), Object = jsonObject["object"].ToString(), UserId = UserId, AgentId = AgentId, Role = ro }; int chatHistoryId = _acc.AddChatHistoryData(chatHistoryDataPage); if (i == 0) { RUserId= chatHistoryId; } RAssistantId = chatHistoryId; if (chatHistoryId == -1) { return Error(); } } int Count = _acc.GetChatHistoryCountList(UserId, AgentId,null); JObject obj = JObject.Parse(responseContent); obj.Add("Count", Count); obj.Add("UserId", RUserId); obj.Add("AssistantId", RAssistantId); string updatedJson = obj.ToString(); return Content(updatedJson, "application/json"); } else { return Error(); } } } catch (HttpRequestException e) { LogHelper.Write(Level.Error, "添加聊天记录返回对话 AddChat", e, OperatorProvider.Instance.Current == null ? "GuestEx" : OperatorProvider.Instance.Current.LoginName); return Error(); } } /// ///删除智能体 /// /// /// [HttpPost] public ActionResult DelChatHistoryDataById(int Id) { try { bool isDeleted = _acc.DelChatHistoryDataById(Id); return isDeleted ? SuccessNoShow() : Error(); } catch (Exception e) { LogHelper.Write(Level.Error, "删除智能体 DelChatHistoryDataById" + "" + "", e, OperatorProvider.Instance.Current == null ? "GuestEx" : OperatorProvider.Instance.Current.LoginName); return Error(); } } } }