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();
|
}
|
}
|
|
}
|
}
|