chenzx
2025-01-10 babeb4aa56f623f6ff62554c5becaf2a7d1e187e
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
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
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
            {
                var model = _acc.GetPromptApi(AgentId);
                if (model[0].ModelApi != null && model[0].ModelKey != null) {
                    string apiUrl = model[0].ModelApi;
                    // 设置授权令牌
                    string bearerToken = model[0].ModelKey;
                    string jsonContent = $@"{{
                                  ""inputs"": {{}},
                                  ""query"": ""{Chat}"",
                                  ""response_mode"": ""blocking"",
                                  ""conversation_id"": """",
                                      ""user"": ""{UserId}"",
                                      ""files"": [
                                        {{
                                          ""type"": """",
                                          ""transfer_method"": """",
                                          ""url"": """"
                                        }}
                                  ]
                                  }}";
 
                    using (HttpClient client = new HttpClient())
                    {
                        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);
 
                        // 使用Task.Run来运行异步操作,并使用.Result获取结果
                        HttpResponseMessage response = System.Threading.Tasks.Task.Run(() => client.SendAsync(request)).Result;
 
                        if (response.IsSuccessStatusCode)
                        {
                            string responseContent = System.Threading.Tasks.Task.Run(() => response.Content.ReadAsStringAsync()).Result;
 
                            // 解析JSON字符串
                            var rootObject = 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 = rootObject["answer"].ToString();
                                    ro = "assistant";
                                }
                                ChatHistoryDataPage chatHistoryDataPage = new ChatHistoryDataPage
                                {
 
                                    Content = co,
                                    TotalTokens = 0,
                                    Model = "dify",
                                    Created = "",
                                    Chatid = rootObject["conversation_id"].ToString(),
                                    Object = "",
                                    UserId = UserId,
                                    AgentId = AgentId,
                                    Role = ro
                                };
                                bool plus = _acc.UpdataUserNoById(AgentId, UserId);
                                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 = new JObject();
                            obj.Add("Count", Count);
                            obj.Add("Data", rootObject["answer"].ToString());
                            obj.Add("UserId", RUserId);
                            obj.Add("AssistantId", RAssistantId);
                            return SuccessNoShow(data: obj);
                            //return Content(updatedJson, "application/json");
 
                        }
                        else
                        {
                            Console.WriteLine("请求失败,状态码:" + response.StatusCode);
                            return null;
                        }
                    }
 
                    }
                else
                {
                    string Prompt = _acc.GetPromptData(AgentId);
                    Prompt = Prompt.Replace("\t", "").Replace("\n", "").Replace("\r", "").Replace("\f", "");
                    Prompt = Prompt.Replace(" ", "");
                    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
                                };
                                bool plus = _acc.UpdataUserNoById(AgentId, UserId);
                                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 = new JObject();
                            obj.Add("Count", Count);
                            obj.Add("Data", jsonObject["choices"][0]["message"]["content"].ToString());
                            obj.Add("UserId", RUserId);
                            obj.Add("AssistantId", RAssistantId);
                            return SuccessNoShow(data: obj);
                        }
                        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();
            }
        }
 
    }
}