2025-12-23 17:08:42 +08:00
|
|
|
|
using System.ClientModel;
|
2025-12-23 17:40:00 +08:00
|
|
|
|
using System.Diagnostics.CodeAnalysis;
|
|
|
|
|
|
using System.Net;
|
2025-12-23 17:08:42 +08:00
|
|
|
|
using System.Reflection;
|
2025-12-24 00:22:46 +08:00
|
|
|
|
using System.Text;
|
2025-12-23 17:29:07 +08:00
|
|
|
|
using System.Text.Json;
|
2025-12-23 17:08:42 +08:00
|
|
|
|
using Dm.util;
|
|
|
|
|
|
using Microsoft.Agents.AI;
|
2025-12-24 00:22:46 +08:00
|
|
|
|
using Microsoft.AspNetCore.Http;
|
2025-12-23 17:08:42 +08:00
|
|
|
|
using Microsoft.Extensions.AI;
|
2025-12-23 00:49:17 +08:00
|
|
|
|
using Microsoft.Extensions.DependencyInjection;
|
|
|
|
|
|
using Microsoft.Extensions.Logging;
|
2025-12-23 17:08:42 +08:00
|
|
|
|
using ModelContextProtocol.Server;
|
|
|
|
|
|
using OpenAI;
|
2025-12-23 17:40:00 +08:00
|
|
|
|
using OpenAI.Chat;
|
|
|
|
|
|
using OpenAI.Responses;
|
2025-12-24 00:22:46 +08:00
|
|
|
|
using Volo.Abp.Domain.Repositories;
|
2025-12-23 00:49:17 +08:00
|
|
|
|
using Volo.Abp.Domain.Services;
|
2025-12-24 00:22:46 +08:00
|
|
|
|
using Yi.Framework.AiHub.Application.Contracts.Dtos.Chat;
|
|
|
|
|
|
using Yi.Framework.AiHub.Domain.AiGateWay;
|
|
|
|
|
|
using Yi.Framework.AiHub.Domain.Entities.Chat;
|
|
|
|
|
|
using Yi.Framework.AiHub.Domain.Entities.OpenApi;
|
|
|
|
|
|
using Yi.Framework.AiHub.Domain.Shared.Dtos.OpenAi;
|
|
|
|
|
|
using Yi.Framework.SqlSugarCore.Abstractions;
|
2025-12-23 00:49:17 +08:00
|
|
|
|
|
|
|
|
|
|
namespace Yi.Framework.AiHub.Domain.Managers;
|
|
|
|
|
|
|
|
|
|
|
|
public class ChatManager : DomainService
|
|
|
|
|
|
{
|
|
|
|
|
|
private readonly AiGateWayManager _aiGateWayManager;
|
2025-12-23 17:08:42 +08:00
|
|
|
|
private readonly ILoggerFactory _loggerFactory;
|
2025-12-24 00:22:46 +08:00
|
|
|
|
private readonly ISqlSugarRepository<MessageAggregateRoot> _messageRepository;
|
|
|
|
|
|
private readonly ISqlSugarRepository<AgentStoreAggregateRoot> _agentStoreRepository;
|
|
|
|
|
|
private readonly ISqlSugarRepository<TokenAggregateRoot> _tokenRepository;
|
2025-12-23 17:29:07 +08:00
|
|
|
|
|
2025-12-24 00:22:46 +08:00
|
|
|
|
public ChatManager(AiGateWayManager aiGateWayManager, ILoggerFactory loggerFactory,
|
|
|
|
|
|
ISqlSugarRepository<MessageAggregateRoot> messageRepository,
|
|
|
|
|
|
ISqlSugarRepository<AgentStoreAggregateRoot> agentStoreRepository,
|
|
|
|
|
|
ISqlSugarRepository<TokenAggregateRoot> tokenRepository)
|
2025-12-23 00:49:17 +08:00
|
|
|
|
{
|
|
|
|
|
|
_aiGateWayManager = aiGateWayManager;
|
2025-12-23 17:08:42 +08:00
|
|
|
|
_loggerFactory = loggerFactory;
|
2025-12-24 00:22:46 +08:00
|
|
|
|
_messageRepository = messageRepository;
|
|
|
|
|
|
_agentStoreRepository = agentStoreRepository;
|
|
|
|
|
|
_tokenRepository = tokenRepository;
|
2025-12-23 00:49:17 +08:00
|
|
|
|
}
|
|
|
|
|
|
|
2025-12-23 17:40:00 +08:00
|
|
|
|
|
2025-12-24 00:22:46 +08:00
|
|
|
|
public async Task AgentCompleteChatStreamAsync(HttpContext httpContext,
|
|
|
|
|
|
Guid sessionId,
|
|
|
|
|
|
string content,
|
|
|
|
|
|
Guid tokenId,
|
|
|
|
|
|
string modelId,
|
|
|
|
|
|
Guid userId,
|
|
|
|
|
|
List<string> tools
|
|
|
|
|
|
, CancellationToken cancellationToken)
|
2025-12-23 00:49:17 +08:00
|
|
|
|
{
|
2025-12-24 00:22:46 +08:00
|
|
|
|
|
|
|
|
|
|
// HttpClient.DefaultProxy = new WebProxy("127.0.0.1:8888");
|
|
|
|
|
|
var response = httpContext.Response;
|
|
|
|
|
|
// 设置响应头,声明是 SSE 流
|
|
|
|
|
|
response.ContentType = "text/event-stream;charset=utf-8;";
|
|
|
|
|
|
response.Headers.TryAdd("Cache-Control", "no-cache");
|
|
|
|
|
|
response.Headers.TryAdd("Connection", "keep-alive");
|
|
|
|
|
|
|
|
|
|
|
|
//token状态检查,在应用层统一处理
|
|
|
|
|
|
var token = await _tokenRepository.GetFirstAsync(x => x.Id == tokenId);
|
|
|
|
|
|
var client = new OpenAIClient(new ApiKeyCredential(token.Token),
|
2025-12-23 17:29:07 +08:00
|
|
|
|
new OpenAIClientOptions
|
|
|
|
|
|
{
|
|
|
|
|
|
Endpoint = new Uri("https://yxai.chat/v1"),
|
|
|
|
|
|
});
|
2025-12-24 00:22:46 +08:00
|
|
|
|
|
2025-12-23 17:08:42 +08:00
|
|
|
|
var agent = client.GetChatClient(modelId)
|
2025-12-24 00:22:46 +08:00
|
|
|
|
.CreateAIAgent("你是一个专业的网页ai助手,擅长解答用户问题");
|
|
|
|
|
|
|
|
|
|
|
|
//线程根据sessionId数据库中获取
|
|
|
|
|
|
var agentStore =
|
|
|
|
|
|
await _agentStoreRepository.GetFirstAsync(x => x.SessionId == sessionId);
|
|
|
|
|
|
if (agentStore is null)
|
|
|
|
|
|
{
|
|
|
|
|
|
agentStore = new AgentStoreAggregateRoot(sessionId);
|
|
|
|
|
|
}
|
2025-12-23 17:29:07 +08:00
|
|
|
|
|
2025-12-24 00:22:46 +08:00
|
|
|
|
//获取当前线程
|
|
|
|
|
|
AgentThread currentThread;
|
|
|
|
|
|
if (!string.IsNullOrWhiteSpace(agentStore.Store))
|
|
|
|
|
|
{
|
|
|
|
|
|
//获取当前存储
|
|
|
|
|
|
JsonElement reloaded = JsonSerializer.Deserialize<JsonElement>(agentStore.Store, JsonSerializerOptions.Web);
|
|
|
|
|
|
currentThread = agent.DeserializeThread(reloaded, JsonSerializerOptions.Web);
|
|
|
|
|
|
}
|
|
|
|
|
|
else
|
|
|
|
|
|
{
|
|
|
|
|
|
currentThread = agent.GetNewThread();
|
|
|
|
|
|
}
|
2025-12-23 00:49:17 +08:00
|
|
|
|
|
|
|
|
|
|
|
2025-12-24 00:22:46 +08:00
|
|
|
|
var toolContents = GetTools();
|
2025-12-23 17:08:42 +08:00
|
|
|
|
var chatOptions = new ChatOptions()
|
2025-12-23 00:49:17 +08:00
|
|
|
|
{
|
2025-12-24 00:22:46 +08:00
|
|
|
|
Tools = toolContents.Select(x => (AITool)x).ToList(),
|
2025-12-23 17:08:42 +08:00
|
|
|
|
ToolMode = ChatToolMode.Auto
|
|
|
|
|
|
};
|
2025-12-23 17:29:07 +08:00
|
|
|
|
|
2025-12-24 00:22:46 +08:00
|
|
|
|
await foreach (var update in agent.RunStreamingAsync(content, currentThread, new ChatClientAgentRunOptions(chatOptions), cancellationToken))
|
2025-12-23 00:49:17 +08:00
|
|
|
|
{
|
2025-12-23 17:08:42 +08:00
|
|
|
|
// 检查每个更新中的内容
|
2025-12-24 00:22:46 +08:00
|
|
|
|
foreach (var updateContent in update.Contents)
|
2025-12-23 00:49:17 +08:00
|
|
|
|
{
|
2025-12-24 00:22:46 +08:00
|
|
|
|
switch (updateContent)
|
2025-12-23 00:49:17 +08:00
|
|
|
|
{
|
2025-12-24 00:22:46 +08:00
|
|
|
|
//工具调用中
|
2025-12-23 17:08:42 +08:00
|
|
|
|
case FunctionCallContent functionCall:
|
2025-12-24 00:22:46 +08:00
|
|
|
|
await SendHttpStreamMessageAsync(httpContext,
|
|
|
|
|
|
new AgentResultOutput
|
|
|
|
|
|
{
|
|
|
|
|
|
TypeEnum = AgentResultTypeEnum.ToolCalling,
|
|
|
|
|
|
Content = functionCall.Name
|
|
|
|
|
|
},
|
|
|
|
|
|
isDone: false, cancellationToken);
|
2025-12-23 17:08:42 +08:00
|
|
|
|
break;
|
2025-12-24 00:22:46 +08:00
|
|
|
|
|
|
|
|
|
|
//工具调用完成
|
2025-12-23 17:08:42 +08:00
|
|
|
|
case FunctionResultContent functionResult:
|
2025-12-24 00:22:46 +08:00
|
|
|
|
await SendHttpStreamMessageAsync(httpContext,
|
|
|
|
|
|
new AgentResultOutput
|
|
|
|
|
|
{
|
|
|
|
|
|
TypeEnum = AgentResultTypeEnum.ToolCalled,
|
|
|
|
|
|
Content = functionResult.Result
|
|
|
|
|
|
},
|
|
|
|
|
|
isDone: false, cancellationToken);
|
2025-12-23 17:08:42 +08:00
|
|
|
|
break;
|
2025-12-24 00:22:46 +08:00
|
|
|
|
|
|
|
|
|
|
//内容输出
|
2025-12-23 17:08:42 +08:00
|
|
|
|
case TextContent textContent:
|
2025-12-24 00:22:46 +08:00
|
|
|
|
//发送消息给前端
|
|
|
|
|
|
await SendHttpStreamMessageAsync(httpContext,
|
|
|
|
|
|
new AgentResultOutput
|
|
|
|
|
|
{
|
|
|
|
|
|
TypeEnum = AgentResultTypeEnum.Text,
|
|
|
|
|
|
Content = textContent.Text
|
|
|
|
|
|
},
|
|
|
|
|
|
isDone: false, cancellationToken);
|
2025-12-23 17:08:42 +08:00
|
|
|
|
break;
|
2025-12-24 00:22:46 +08:00
|
|
|
|
|
|
|
|
|
|
//用量统计
|
2025-12-23 17:08:42 +08:00
|
|
|
|
case UsageContent usageContent:
|
2025-12-24 00:22:46 +08:00
|
|
|
|
//存储message 为了token算费
|
|
|
|
|
|
await SendHttpStreamMessageAsync(httpContext,
|
|
|
|
|
|
new AgentResultOutput
|
|
|
|
|
|
{
|
|
|
|
|
|
TypeEnum = AgentResultTypeEnum.Usage,
|
|
|
|
|
|
Content = new ThorUsageResponse
|
|
|
|
|
|
{
|
|
|
|
|
|
InputTokens = Convert.ToInt32(usageContent.Details.InputTokenCount ?? 0),
|
|
|
|
|
|
OutputTokens = Convert.ToInt32(usageContent.Details.OutputTokenCount ?? 0),
|
|
|
|
|
|
TotalTokens = usageContent.Details.TotalTokenCount ?? 0,
|
|
|
|
|
|
}
|
|
|
|
|
|
},
|
|
|
|
|
|
isDone: false, cancellationToken);
|
2025-12-23 17:08:42 +08:00
|
|
|
|
Console.WriteLine();
|
|
|
|
|
|
Console.WriteLine($"✅ 用量统计: {usageContent.Details.TotalTokenCount}");
|
|
|
|
|
|
break;
|
2025-12-23 00:49:17 +08:00
|
|
|
|
}
|
2025-12-23 17:08:42 +08:00
|
|
|
|
}
|
2025-12-23 00:49:17 +08:00
|
|
|
|
}
|
2025-12-23 17:29:07 +08:00
|
|
|
|
|
2025-12-24 00:22:46 +08:00
|
|
|
|
//断开连接
|
|
|
|
|
|
await SendHttpStreamMessageAsync(httpContext, null, isDone: true, cancellationToken);
|
|
|
|
|
|
|
|
|
|
|
|
//将线程持久化到数据库
|
|
|
|
|
|
string serializedJson = currentThread.Serialize(JsonSerializerOptions.Web).GetRawText();
|
|
|
|
|
|
agentStore.Store = serializedJson;
|
2025-12-23 17:29:07 +08:00
|
|
|
|
|
2025-12-24 00:22:46 +08:00
|
|
|
|
//插入或者更新
|
|
|
|
|
|
await _agentStoreRepository.InsertOrUpdateAsync(agentStore);
|
2025-12-23 00:49:17 +08:00
|
|
|
|
}
|
|
|
|
|
|
|
2025-12-23 17:08:42 +08:00
|
|
|
|
|
|
|
|
|
|
private List<AIFunction> GetTools()
|
2025-12-23 00:49:17 +08:00
|
|
|
|
{
|
2025-12-23 17:08:42 +08:00
|
|
|
|
var toolClasses = typeof(YiFrameworkAiHubDomainModule).Assembly.GetTypes()
|
|
|
|
|
|
.Where(x => x.GetCustomAttribute<McpServerToolTypeAttribute>() is not null)
|
|
|
|
|
|
.ToList();
|
|
|
|
|
|
|
|
|
|
|
|
List<AIFunction> mcpTools = new List<AIFunction>();
|
|
|
|
|
|
foreach (var toolClass in toolClasses)
|
2025-12-23 00:49:17 +08:00
|
|
|
|
{
|
2025-12-23 17:08:42 +08:00
|
|
|
|
var instance = LazyServiceProvider.GetRequiredService(toolClass);
|
|
|
|
|
|
var toolMethods = toolClass.GetMethods()
|
|
|
|
|
|
.Where(y => y.GetCustomAttribute<McpServerToolAttribute>() is not null).ToList();
|
|
|
|
|
|
foreach (var toolMethod in toolMethods)
|
|
|
|
|
|
{
|
|
|
|
|
|
mcpTools.add(AIFunctionFactory.Create(toolMethod, instance));
|
|
|
|
|
|
}
|
2025-12-23 00:49:17 +08:00
|
|
|
|
}
|
|
|
|
|
|
|
2025-12-23 17:08:42 +08:00
|
|
|
|
return mcpTools;
|
2025-12-23 00:49:17 +08:00
|
|
|
|
}
|
2025-12-24 00:22:46 +08:00
|
|
|
|
|
|
|
|
|
|
/// <summary>
|
|
|
|
|
|
/// 发送消息
|
|
|
|
|
|
/// </summary>
|
|
|
|
|
|
/// <param name="httpContext"></param>
|
|
|
|
|
|
/// <param name="content"></param>
|
|
|
|
|
|
/// <param name="isDone"></param>
|
|
|
|
|
|
/// <param name="cancellationToken"></param>
|
|
|
|
|
|
/// <returns></returns>
|
|
|
|
|
|
private async Task SendHttpStreamMessageAsync(HttpContext httpContext,
|
|
|
|
|
|
AgentResultOutput? content,
|
|
|
|
|
|
bool isDone = false,
|
|
|
|
|
|
CancellationToken cancellationToken = default)
|
|
|
|
|
|
{
|
|
|
|
|
|
var response = httpContext.Response;
|
|
|
|
|
|
string output;
|
|
|
|
|
|
if (isDone)
|
|
|
|
|
|
{
|
|
|
|
|
|
output = "[DONE]";
|
|
|
|
|
|
}
|
|
|
|
|
|
else
|
|
|
|
|
|
{
|
|
|
|
|
|
output = JsonSerializer.Serialize(content,ThorJsonSerializer.DefaultOptions);
|
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
|
|
await response.WriteAsync($"data: {output}\n\n", Encoding.UTF8, cancellationToken).ConfigureAwait(false);
|
|
|
|
|
|
await response.Body.FlushAsync(cancellationToken).ConfigureAwait(false);
|
|
|
|
|
|
}
|
2025-12-23 00:49:17 +08:00
|
|
|
|
}
|