Files
Yi.Admin/Yi.Abp.Net8/module/ai-hub/Yi.Framework.AiHub.Domain/Managers/AiGateWayManager.cs

71 lines
2.4 KiB
C#
Raw Normal View History

2025-06-25 17:12:09 +08:00
using System.Runtime.CompilerServices;
2025-06-21 01:08:14 +08:00
using Microsoft.Extensions.DependencyInjection;
using OpenAI.Chat;
using Volo.Abp.Domain.Services;
using Yi.Framework.AiHub.Domain.AiChat;
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-25 17:12:09 +08:00
using Yi.Framework.AiHub.Domain.Shared.Dtos;
using Yi.Framework.SqlSugarCore.Abstractions;
2025-06-21 01:08:14 +08:00
namespace Yi.Framework.AiHub.Domain.Managers;
public class AiGateWayManager : DomainService
{
2025-06-25 17:12:09 +08:00
private readonly ISqlSugarRepository<AiAppAggregateRoot> _aiAppRepository;
2025-06-21 01:08:14 +08:00
2025-06-25 17:12:09 +08:00
public AiGateWayManager(ISqlSugarRepository<AiAppAggregateRoot> aiAppRepository)
2025-06-21 01:08:14 +08:00
{
2025-06-25 17:12:09 +08:00
_aiAppRepository = aiAppRepository;
2025-06-21 01:08:14 +08:00
}
2025-06-25 17:12:09 +08:00
/// <summary>
/// 获取模型
/// </summary>
/// <param name="modelId"></param>
/// <returns></returns>
private async Task<AiModelDescribe> GetModelAsync(string modelId)
2025-06-21 01:08:14 +08:00
{
2025-06-25 17:12:09 +08:00
var allApp = await _aiAppRepository._DbQueryable.Includes(x => x.AiModels).ToListAsync();
foreach (var app in allApp)
2025-06-21 01:08:14 +08:00
{
2025-06-25 17:12:09 +08:00
var model = app.AiModels.FirstOrDefault(x => x.ModelId == modelId);
if (model is not null)
2025-06-21 01:08:14 +08:00
{
2025-06-25 17:12:09 +08:00
return new AiModelDescribe
{
AppId = app.Id,
AppName = app.Name,
Endpoint = app.Endpoint,
ApiKey = app.ApiKey,
OrderNum = model.OrderNum,
HandlerName = model.HandlerName,
ModelId = model.ModelId,
ModelName = model.Name,
Description = model.Description
};
2025-06-21 01:08:14 +08:00
}
}
2025-06-21 01:41:05 +08:00
2025-06-25 17:12:09 +08:00
throw new UserFriendlyException($"{modelId}模型当前版本不支持");
}
/// <summary>
/// 聊天完成
/// </summary>
/// <param name="modelId"></param>
/// <param name="messages"></param>
/// <param name="cancellationToken"></param>
/// <returns></returns>
2025-06-27 22:13:26 +08:00
public async IAsyncEnumerable<CompleteChatResponse> CompleteChatAsync(string modelId, List<ChatMessage> messages,
2025-06-25 17:12:09 +08:00
[EnumeratorCancellation] CancellationToken cancellationToken)
{
var modelDescribe = await GetModelAsync(modelId);
var chatService = LazyServiceProvider.GetRequiredKeyedService<IChatService>(modelDescribe.HandlerName);
await foreach (var result in chatService.CompleteChatAsync(modelDescribe, messages, cancellationToken))
{
yield return result;
}
2025-06-21 01:08:14 +08:00
}
}