2025-06-25 00:30:01 +08:00
|
|
|
|
using System.Collections.Concurrent;
|
|
|
|
|
|
using System.Text;
|
2025-06-21 21:40:51 +08:00
|
|
|
|
using Microsoft.AspNetCore.Authorization;
|
2025-06-21 01:08:14 +08:00
|
|
|
|
using Microsoft.AspNetCore.Http;
|
2025-06-21 21:40:51 +08:00
|
|
|
|
using Microsoft.AspNetCore.Mvc;
|
2025-06-21 01:08:14 +08:00
|
|
|
|
using Microsoft.Extensions.DependencyInjection;
|
2025-07-02 00:28:44 +08:00
|
|
|
|
using Microsoft.Extensions.Logging;
|
2025-06-21 01:08:14 +08:00
|
|
|
|
using Microsoft.Extensions.Options;
|
|
|
|
|
|
using Newtonsoft.Json;
|
|
|
|
|
|
using Newtonsoft.Json.Serialization;
|
|
|
|
|
|
using OpenAI.Chat;
|
2025-06-19 21:24:13 +08:00
|
|
|
|
using Volo.Abp.Application.Services;
|
2025-06-21 13:02:38 +08:00
|
|
|
|
using Volo.Abp.Users;
|
2025-06-19 21:24:13 +08:00
|
|
|
|
using Yi.Framework.AiHub.Application.Contracts.Dtos;
|
2025-06-25 17:12:09 +08:00
|
|
|
|
using Yi.Framework.AiHub.Domain.Entities;
|
2025-06-27 22:13:26 +08:00
|
|
|
|
using Yi.Framework.AiHub.Domain.Entities.Model;
|
2025-06-21 01:08:14 +08:00
|
|
|
|
using Yi.Framework.AiHub.Domain.Managers;
|
2025-06-27 22:13:26 +08:00
|
|
|
|
using Yi.Framework.AiHub.Domain.Shared.Dtos;
|
2025-06-21 21:40:51 +08:00
|
|
|
|
using Yi.Framework.Rbac.Application.Contracts.IServices;
|
|
|
|
|
|
using Yi.Framework.Rbac.Domain.Shared.Dtos;
|
2025-06-25 17:12:09 +08:00
|
|
|
|
using Yi.Framework.SqlSugarCore.Abstractions;
|
2025-06-19 21:24:13 +08:00
|
|
|
|
|
|
|
|
|
|
namespace Yi.Framework.AiHub.Application.Services;
|
|
|
|
|
|
|
2025-06-21 13:02:38 +08:00
|
|
|
|
/// <summary>
|
|
|
|
|
|
/// ai服务
|
|
|
|
|
|
/// </summary>
|
|
|
|
|
|
public class AiChatService : ApplicationService
|
2025-06-19 21:24:13 +08:00
|
|
|
|
{
|
2025-06-21 01:08:14 +08:00
|
|
|
|
private readonly IHttpContextAccessor _httpContextAccessor;
|
2025-06-21 13:02:38 +08:00
|
|
|
|
private readonly AiMessageManager _aiMessageManager;
|
2025-06-25 17:12:09 +08:00
|
|
|
|
private readonly ISqlSugarRepository<AiModelEntity> _aiModelRepository;
|
|
|
|
|
|
private readonly AiBlacklistManager _aiBlacklistManager;
|
2025-06-27 22:13:26 +08:00
|
|
|
|
private readonly UsageStatisticsManager _usageStatisticsManager;
|
2025-07-02 00:28:44 +08:00
|
|
|
|
private readonly ILogger<AiChatService> _logger;
|
2025-06-21 01:08:14 +08:00
|
|
|
|
|
2025-06-25 17:12:09 +08:00
|
|
|
|
public AiChatService(IHttpContextAccessor httpContextAccessor,
|
2025-06-25 22:45:57 +08:00
|
|
|
|
AiMessageManager aiMessageManager, AiBlacklistManager aiBlacklistManager,
|
2025-07-02 00:28:44 +08:00
|
|
|
|
ISqlSugarRepository<AiModelEntity> aiModelRepository, UsageStatisticsManager usageStatisticsManager,
|
|
|
|
|
|
ILogger<AiChatService> logger)
|
2025-06-21 01:08:14 +08:00
|
|
|
|
{
|
|
|
|
|
|
this._httpContextAccessor = httpContextAccessor;
|
2025-06-21 13:02:38 +08:00
|
|
|
|
_aiMessageManager = aiMessageManager;
|
2025-06-25 17:12:09 +08:00
|
|
|
|
_aiBlacklistManager = aiBlacklistManager;
|
2025-06-25 22:45:57 +08:00
|
|
|
|
_aiModelRepository = aiModelRepository;
|
2025-06-27 22:13:26 +08:00
|
|
|
|
_usageStatisticsManager = usageStatisticsManager;
|
2025-07-02 00:28:44 +08:00
|
|
|
|
_logger = logger;
|
2025-06-21 01:08:14 +08:00
|
|
|
|
}
|
2025-06-19 21:24:13 +08:00
|
|
|
|
|
|
|
|
|
|
|
2025-06-21 21:40:51 +08:00
|
|
|
|
/// <summary>
|
|
|
|
|
|
/// 查询已登录的账户信息
|
|
|
|
|
|
/// </summary>
|
|
|
|
|
|
/// <returns></returns>
|
|
|
|
|
|
[Route("ai-chat/account")]
|
|
|
|
|
|
[Authorize]
|
|
|
|
|
|
public async Task<UserRoleMenuDto> GetAsync()
|
|
|
|
|
|
{
|
|
|
|
|
|
var accountService = LazyServiceProvider.GetRequiredService<IAccountService>();
|
|
|
|
|
|
var output = await accountService.GetAsync();
|
|
|
|
|
|
return output;
|
|
|
|
|
|
}
|
|
|
|
|
|
|
2025-06-19 21:24:13 +08:00
|
|
|
|
/// <summary>
|
|
|
|
|
|
/// 获取模型列表
|
|
|
|
|
|
/// </summary>
|
|
|
|
|
|
/// <returns></returns>
|
|
|
|
|
|
public async Task<List<ModelGetListOutput>> GetModelAsync()
|
|
|
|
|
|
{
|
2025-06-25 22:45:57 +08:00
|
|
|
|
var output = await _aiModelRepository._DbQueryable
|
2025-06-27 22:13:26 +08:00
|
|
|
|
.OrderByDescending(x => x.OrderNum)
|
2025-06-25 22:45:57 +08:00
|
|
|
|
.Select(x => new ModelGetListOutput
|
2025-06-27 22:13:26 +08:00
|
|
|
|
{
|
|
|
|
|
|
Id = x.Id,
|
|
|
|
|
|
Category = "chat",
|
|
|
|
|
|
ModelName = x.Name,
|
|
|
|
|
|
ModelDescribe = x.Description,
|
|
|
|
|
|
ModelPrice = 0,
|
|
|
|
|
|
ModelType = "1",
|
|
|
|
|
|
ModelShow = "0",
|
|
|
|
|
|
SystemPrompt = null,
|
|
|
|
|
|
ApiHost = null,
|
|
|
|
|
|
ApiKey = null,
|
|
|
|
|
|
Remark = x.Description
|
|
|
|
|
|
}).ToListAsync();
|
2025-06-21 01:08:14 +08:00
|
|
|
|
return output;
|
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
/// <summary>
|
|
|
|
|
|
/// 发送消息
|
|
|
|
|
|
/// </summary>
|
|
|
|
|
|
/// <param name="input"></param>
|
2025-06-21 01:41:05 +08:00
|
|
|
|
/// <param name="cancellationToken"></param>
|
|
|
|
|
|
public async Task PostSendAsync(SendMessageInput input, CancellationToken cancellationToken)
|
2025-06-21 01:08:14 +08:00
|
|
|
|
{
|
2025-06-25 17:12:09 +08:00
|
|
|
|
//除了免费模型,其他的模型都要校验
|
2025-06-30 22:07:42 +08:00
|
|
|
|
if (!input.Model.Contains("DeepSeek-R1"))
|
2025-06-29 15:41:49 +08:00
|
|
|
|
{
|
|
|
|
|
|
//有token,需要黑名单校验
|
|
|
|
|
|
if (CurrentUser.IsAuthenticated)
|
|
|
|
|
|
{
|
|
|
|
|
|
await _aiBlacklistManager.VerifiyAiBlacklist(CurrentUser.GetId());
|
2025-07-02 00:28:44 +08:00
|
|
|
|
if (!CurrentUser.Roles.Contains("YiXinAi-Vip") && CurrentUser.UserName != "cc")
|
2025-06-29 15:41:49 +08:00
|
|
|
|
{
|
|
|
|
|
|
throw new UserFriendlyException("该模型需要VIP用户才能使用,请购买VIP后重新登录重试");
|
|
|
|
|
|
}
|
|
|
|
|
|
}
|
|
|
|
|
|
else
|
|
|
|
|
|
{
|
|
|
|
|
|
throw new UserFriendlyException("未登录用户,只能使用未加速的DeepSeek-R1,请登录后重试");
|
|
|
|
|
|
}
|
|
|
|
|
|
}
|
2025-06-25 17:12:09 +08:00
|
|
|
|
|
|
|
|
|
|
//前面都是校验,后面才是真正的调用
|
2025-06-21 01:08:14 +08:00
|
|
|
|
var httpContext = this._httpContextAccessor.HttpContext;
|
|
|
|
|
|
var response = httpContext.Response;
|
|
|
|
|
|
// 设置响应头,声明是 SSE 流
|
|
|
|
|
|
response.ContentType = "text/event-stream";
|
|
|
|
|
|
response.Headers.Append("Cache-Control", "no-cache");
|
|
|
|
|
|
response.Headers.Append("Connection", "keep-alive");
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
var history = new List<ChatMessage>();
|
|
|
|
|
|
foreach (var aiChatContextDto in input.Messages)
|
|
|
|
|
|
{
|
2025-06-22 19:09:13 +08:00
|
|
|
|
if (aiChatContextDto.Role == "system")
|
2025-06-19 21:24:13 +08:00
|
|
|
|
{
|
2025-06-21 01:08:14 +08:00
|
|
|
|
history.Add(ChatMessage.CreateAssistantMessage(aiChatContextDto.Content));
|
2025-06-19 21:24:13 +08:00
|
|
|
|
}
|
2025-06-21 01:08:14 +08:00
|
|
|
|
else if (aiChatContextDto.Role == "user")
|
|
|
|
|
|
{
|
|
|
|
|
|
history.Add(ChatMessage.CreateUserMessage(aiChatContextDto.Content));
|
|
|
|
|
|
}
|
|
|
|
|
|
}
|
2025-06-19 21:24:13 +08:00
|
|
|
|
|
2025-06-21 01:08:14 +08:00
|
|
|
|
var gateWay = LazyServiceProvider.GetRequiredService<AiGateWayManager>();
|
2025-06-25 00:30:01 +08:00
|
|
|
|
var completeChatResponse = gateWay.CompleteChatAsync(input.Model, history, cancellationToken);
|
2025-06-27 22:13:26 +08:00
|
|
|
|
var tokenUsage = new TokenUsage();
|
2025-06-25 00:30:01 +08:00
|
|
|
|
await using var writer = new StreamWriter(response.Body, Encoding.UTF8, leaveOpen: true);
|
2025-06-21 13:02:38 +08:00
|
|
|
|
|
2025-06-25 00:30:01 +08:00
|
|
|
|
|
|
|
|
|
|
//缓存队列算法
|
|
|
|
|
|
// 创建一个队列来缓存消息
|
|
|
|
|
|
var messageQueue = new ConcurrentQueue<string>();
|
2025-06-27 22:13:26 +08:00
|
|
|
|
|
|
|
|
|
|
StringBuilder backupSystemContent = new StringBuilder();
|
2025-06-25 00:30:01 +08:00
|
|
|
|
// 设置输出速率(例如每50毫秒输出一次)
|
2025-06-25 00:35:25 +08:00
|
|
|
|
var outputInterval = TimeSpan.FromMilliseconds(100);
|
2025-06-25 00:30:01 +08:00
|
|
|
|
// 标记是否完成接收
|
|
|
|
|
|
var isComplete = false;
|
|
|
|
|
|
// 启动一个后台任务来消费队列
|
|
|
|
|
|
var outputTask = Task.Run(async () =>
|
|
|
|
|
|
{
|
2025-06-25 17:12:09 +08:00
|
|
|
|
while (!(isComplete && messageQueue.IsEmpty))
|
2025-06-25 00:30:01 +08:00
|
|
|
|
{
|
|
|
|
|
|
if (messageQueue.TryDequeue(out var message))
|
|
|
|
|
|
{
|
|
|
|
|
|
await writer.WriteLineAsync(message);
|
|
|
|
|
|
await writer.FlushAsync(cancellationToken);
|
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
|
|
if (!isComplete)
|
|
|
|
|
|
{
|
|
|
|
|
|
// 如果没有完成,才等待,已完成,全部输出
|
|
|
|
|
|
await Task.Delay(outputInterval, cancellationToken);
|
|
|
|
|
|
}
|
|
|
|
|
|
}
|
|
|
|
|
|
}, cancellationToken);
|
|
|
|
|
|
|
|
|
|
|
|
|
2025-07-02 00:28:44 +08:00
|
|
|
|
//IAsyncEnumerable 只能在最外层捕获异常(如果你有其他办法的话...)
|
|
|
|
|
|
try
|
2025-06-25 00:30:01 +08:00
|
|
|
|
{
|
2025-07-02 00:28:44 +08:00
|
|
|
|
await foreach (var data in completeChatResponse)
|
2025-06-27 22:13:26 +08:00
|
|
|
|
{
|
2025-07-02 00:28:44 +08:00
|
|
|
|
if (data.IsFinish)
|
|
|
|
|
|
{
|
|
|
|
|
|
tokenUsage = data.TokenUsage;
|
|
|
|
|
|
}
|
2025-06-27 22:13:26 +08:00
|
|
|
|
|
2025-07-02 00:28:44 +08:00
|
|
|
|
var model = MapToMessage(input.Model, data.Content);
|
|
|
|
|
|
var message = JsonConvert.SerializeObject(model, new JsonSerializerSettings
|
|
|
|
|
|
{
|
|
|
|
|
|
ContractResolver = new CamelCasePropertyNamesContractResolver()
|
|
|
|
|
|
});
|
|
|
|
|
|
backupSystemContent.Append(data.Content);
|
|
|
|
|
|
// 将消息加入队列而不是直接写入
|
|
|
|
|
|
messageQueue.Enqueue($"data: {message}\n");
|
|
|
|
|
|
}
|
|
|
|
|
|
}
|
|
|
|
|
|
catch (Exception e)
|
|
|
|
|
|
{
|
|
|
|
|
|
_logger.LogError(e, $"Ai对话异常");
|
|
|
|
|
|
var errorContent = $"Ai对话异常,异常信息:\n{e.Message}";
|
|
|
|
|
|
var model = MapToMessage(input.Model, errorContent);
|
2025-06-25 00:30:01 +08:00
|
|
|
|
var message = JsonConvert.SerializeObject(model, new JsonSerializerSettings
|
|
|
|
|
|
{
|
|
|
|
|
|
ContractResolver = new CamelCasePropertyNamesContractResolver()
|
|
|
|
|
|
});
|
2025-07-02 00:28:44 +08:00
|
|
|
|
backupSystemContent.Append(errorContent);
|
2025-06-25 00:30:01 +08:00
|
|
|
|
messageQueue.Enqueue($"data: {message}\n");
|
|
|
|
|
|
}
|
|
|
|
|
|
|
2025-06-21 01:41:05 +08:00
|
|
|
|
//断开连接
|
2025-06-27 22:49:08 +08:00
|
|
|
|
messageQueue.Enqueue("data: [DONE]\n");
|
2025-06-27 22:13:26 +08:00
|
|
|
|
// 标记完成并发送结束标记
|
|
|
|
|
|
isComplete = true;
|
2025-06-21 13:02:38 +08:00
|
|
|
|
|
2025-06-25 00:30:01 +08:00
|
|
|
|
await outputTask;
|
2025-06-21 13:02:38 +08:00
|
|
|
|
if (CurrentUser.IsAuthenticated && input.SessionId.HasValue)
|
|
|
|
|
|
{
|
2025-06-27 22:13:26 +08:00
|
|
|
|
await _aiMessageManager.CreateUserMessageAsync(CurrentUser.GetId(), input.SessionId.Value,
|
|
|
|
|
|
new MessageInputDto
|
|
|
|
|
|
{
|
|
|
|
|
|
Content = input.Messages.LastOrDefault()
|
|
|
|
|
|
.Content,
|
|
|
|
|
|
ModelId = input.Model,
|
|
|
|
|
|
TokenUsage = tokenUsage,
|
|
|
|
|
|
});
|
|
|
|
|
|
|
|
|
|
|
|
await _aiMessageManager.CreateSystemMessageAsync(CurrentUser.GetId(), input.SessionId.Value,
|
|
|
|
|
|
new MessageInputDto
|
|
|
|
|
|
{
|
|
|
|
|
|
Content = backupSystemContent.ToString(),
|
|
|
|
|
|
ModelId = input.Model,
|
|
|
|
|
|
TokenUsage = tokenUsage
|
|
|
|
|
|
});
|
|
|
|
|
|
|
|
|
|
|
|
await _usageStatisticsManager.SetUsageAsync(CurrentUser.GetId(), input.Model, tokenUsage.InputTokenCount,
|
|
|
|
|
|
tokenUsage.OutputTokenCount);
|
2025-06-21 13:02:38 +08:00
|
|
|
|
}
|
2025-06-21 01:08:14 +08:00
|
|
|
|
}
|
2025-06-19 21:24:13 +08:00
|
|
|
|
|
|
|
|
|
|
|
2025-06-21 01:08:14 +08:00
|
|
|
|
private SendMessageOutputDto MapToMessage(string modelId, string content)
|
2025-06-19 21:24:13 +08:00
|
|
|
|
{
|
|
|
|
|
|
var output = new SendMessageOutputDto
|
|
|
|
|
|
{
|
2025-07-02 23:30:29 +08:00
|
|
|
|
Id = "chatcmpl-BotYP3BlN5T4g9YPnW0fBSBvKzXdd",
|
2025-06-19 21:24:13 +08:00
|
|
|
|
Object = "chat.completion.chunk",
|
|
|
|
|
|
Created = 1750336171,
|
|
|
|
|
|
Model = modelId,
|
|
|
|
|
|
Choices = new()
|
|
|
|
|
|
{
|
|
|
|
|
|
new Choice
|
|
|
|
|
|
{
|
|
|
|
|
|
Index = 0,
|
|
|
|
|
|
Delta = new Delta
|
|
|
|
|
|
{
|
|
|
|
|
|
Content = content,
|
|
|
|
|
|
Role = "assistant"
|
|
|
|
|
|
},
|
|
|
|
|
|
FinishReason = null,
|
|
|
|
|
|
ContentFilterResults = new()
|
|
|
|
|
|
{
|
|
|
|
|
|
Hate = new()
|
|
|
|
|
|
{
|
|
|
|
|
|
Filtered = false,
|
|
|
|
|
|
Detected = null
|
|
|
|
|
|
},
|
|
|
|
|
|
SelfHarm = new()
|
|
|
|
|
|
{
|
|
|
|
|
|
Filtered = false,
|
|
|
|
|
|
Detected = null
|
|
|
|
|
|
},
|
|
|
|
|
|
Sexual = new()
|
|
|
|
|
|
{
|
|
|
|
|
|
Filtered = false,
|
|
|
|
|
|
Detected = null
|
|
|
|
|
|
},
|
|
|
|
|
|
Violence = new()
|
|
|
|
|
|
{
|
|
|
|
|
|
Filtered = false,
|
|
|
|
|
|
Detected = null
|
|
|
|
|
|
},
|
|
|
|
|
|
Jailbreak = new()
|
|
|
|
|
|
{
|
|
|
|
|
|
Filtered = false,
|
|
|
|
|
|
Detected = false
|
|
|
|
|
|
},
|
|
|
|
|
|
Profanity = new()
|
|
|
|
|
|
{
|
|
|
|
|
|
Filtered = false,
|
|
|
|
|
|
Detected = false
|
|
|
|
|
|
},
|
|
|
|
|
|
}
|
|
|
|
|
|
}
|
|
|
|
|
|
},
|
|
|
|
|
|
SystemFingerprint = "",
|
|
|
|
|
|
Usage = new Usage
|
|
|
|
|
|
{
|
2025-06-27 22:13:26 +08:00
|
|
|
|
PromptTokens = 0,
|
|
|
|
|
|
CompletionTokens = 0,
|
|
|
|
|
|
TotalTokens = 0,
|
2025-06-19 21:24:13 +08:00
|
|
|
|
PromptTokensDetails = new()
|
|
|
|
|
|
{
|
|
|
|
|
|
AudioTokens = 0,
|
|
|
|
|
|
CachedTokens = 0
|
|
|
|
|
|
},
|
|
|
|
|
|
CompletionTokensDetails = new()
|
|
|
|
|
|
{
|
|
|
|
|
|
AudioTokens = 0,
|
|
|
|
|
|
ReasoningTokens = 0,
|
|
|
|
|
|
AcceptedPredictionTokens = 0,
|
|
|
|
|
|
RejectedPredictionTokens = 0
|
|
|
|
|
|
}
|
|
|
|
|
|
}
|
|
|
|
|
|
};
|
|
|
|
|
|
|
|
|
|
|
|
return output;
|
|
|
|
|
|
}
|
|
|
|
|
|
}
|