using Microsoft.AspNetCore.Http; using Microsoft.AspNetCore.Mvc; using Microsoft.Extensions.Logging; using Volo.Abp.Application.Services; using Yi.Framework.AiHub.Application.Contracts.Dtos.OpenAi; using Yi.Framework.AiHub.Domain.Entities.Model; using Yi.Framework.AiHub.Domain.Extensions; using Yi.Framework.AiHub.Domain.Managers; using Yi.Framework.SqlSugarCore.Abstractions; namespace Yi.Framework.AiHub.Application.Services; public class OpenApiService : ApplicationService { private readonly IHttpContextAccessor _httpContextAccessor; private readonly ILogger _logger; private readonly TokenManager _tokenManager; private readonly AiGateWayManager _aiGateWayManager; private readonly ISqlSugarRepository _aiModelRepository; public OpenApiService(IHttpContextAccessor httpContextAccessor, ILogger logger, TokenManager tokenManager, AiGateWayManager aiGateWayManager, ISqlSugarRepository aiModelRepository) { _httpContextAccessor = httpContextAccessor; _logger = logger; _tokenManager = tokenManager; _aiGateWayManager = aiGateWayManager; _aiModelRepository = aiModelRepository; } /// /// 对话 /// /// /// [HttpPost("openApi/v1/chat/completions")] public async Task ChatCompletionsAsync([FromBody] ThorChatCompletionsRequest input, CancellationToken cancellationToken) { //前面都是校验,后面才是真正的调用 var httpContext = this._httpContextAccessor.HttpContext; var userId = await _tokenManager.GetUserIdAsync(GetTokenByHttpContext(httpContext)); //ai网关代理httpcontext if (input.Stream == true) { await _aiGateWayManager.CompleteChatStreamForStatisticsAsync(_httpContextAccessor.HttpContext, input, userId, null, cancellationToken); } else { await _aiGateWayManager.CompleteChatForStatisticsAsync(_httpContextAccessor.HttpContext, input, userId, null, cancellationToken); } } /// /// 获取模型列表 /// /// [HttpGet("openApi/v1/models")] public async Task ModelsAsync() { var data = await _aiModelRepository._DbQueryable .OrderByDescending(x => x.OrderNum) .Select(x => new ModelsDataDto { Id = x.ModelId, @object = "model", Created = DateTime.Now.ToUnixTimeSeconds(), OwnedBy = "organization-owner", Type = x.ModelId }).ToListAsync(); return new ModelsListDto() { Data = data }; } private string? GetTokenByHttpContext(HttpContext httpContext) { // 获取Authorization头 string authHeader = httpContext.Request.Headers["Authorization"]; // 检查是否有Bearer token if (authHeader != null && authHeader.StartsWith("Bearer ")) { return authHeader.Substring("Bearer ".Length).Trim(); } return null; } }