chenzx
2024-12-04 e25af6bdd67188d3049a3e4fca8f3c4e43281b27
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
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();
        /// <summary>
        ///获取聊天记录返回对话
        /// </summary>
        /// <param name="Keyword"></param>
        /// <returns></returns>
        [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();
            }
        }
        /// <summary>
        ///添加聊天记录返回对话
        /// </summary>
        /// <param name="Keyword"></param>
        /// <returns></returns>
        [HttpPost]
        public async Task<ActionResult> AddChat(int UserId, int AgentId, string Chat)
        {
            try
            {
                string Prompt = _acc.GetPromptData(AgentId);
                Prompt = Prompt.Replace("\t", "").Replace("\n", "").Replace("\r", "").Replace("\f", "");
                Prompt = Prompt.Replace(" ", "");
                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<int>(),
                                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();
                            }
                        }
                        bool plus = _acc.UpdataUserNoById(AgentId, UserId);
                        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();
            }
        }
        /// <summary>
        ///删除智能体
        /// </summary>
        /// <param name="Keyword"></param>
        /// <returns></returns>
        [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();
            }
        }
 
    }
}