using Microsoft.AspNetCore.Mvc; using ChatRAG.Services.Contracts; using ChatRAG.Services.ResponseService; using ChatRAG.Contracts.VectorSearch; namespace ChatApi.Controllers { [ApiController] [Route("api/[controller]")] public class RAGStrategyController : ControllerBase { private readonly IVectorDatabaseFactory _factory; private readonly IServiceProvider _serviceProvider; private readonly ILogger _logger; public RAGStrategyController( IVectorDatabaseFactory factory, IServiceProvider serviceProvider, ILogger logger) { _factory = factory; _serviceProvider = serviceProvider; _logger = logger; } /// /// Lista as estratégias de RAG disponíveis /// [HttpGet("strategies")] public IActionResult GetAvailableStrategies() { var strategies = new[] { new { name = "Standard", description = "RAG padrão com classificação automática de estratégia", service = "ResponseRAGService", features = new[] { "Busca por similaridade", "Filtros dinâmicos", "Classificação automática" } }, new { name = "Hierarchical", description = "RAG hierárquico com múltiplas etapas de busca", service = "HierarchicalRAGService", features = new[] { "Análise de query", "Busca em múltiplas etapas", "Expansão de contexto", "Identificação de lacunas" } } }; return Ok(new { currentProvider = _factory.GetActiveProvider(), availableStrategies = strategies }); } /// /// Testa uma estratégia específica com uma pergunta /// [HttpPost("test/{strategy}")] public async Task TestStrategy( [FromRoute] string strategy, [FromBody] StrategyTestRequest request) { try { IResponseService responseService = strategy.ToLower() switch { "standard" => _serviceProvider.GetRequiredService(), "hierarchical" => _serviceProvider.GetRequiredService(), _ => throw new ArgumentException($"Estratégia não suportada: {strategy}") }; var stopwatch = System.Diagnostics.Stopwatch.StartNew(); // Usar dados mock se não fornecidos var userData = request.UserData ?? new ChatApi.Models.UserData { Id = "test-user", Name = "Test User" }; var response = await responseService.GetResponse( userData, request.ProjectId, request.SessionId ?? Guid.NewGuid().ToString(), request.Question, request.Language ?? "pt" ); stopwatch.Stop(); return Ok(new { strategy, response, executionTime = stopwatch.ElapsedMilliseconds, provider = _factory.GetActiveProvider() }); } catch (Exception ex) { _logger.LogError(ex, "Erro ao testar estratégia {Strategy}", strategy); return StatusCode(500, new { error = ex.Message }); } } /// /// Compara resultados entre diferentes estratégias /// [HttpPost("compare")] public async Task CompareStrategies([FromBody] StrategyTestRequest request) { try { var userData = request.UserData ?? new ChatApi.Models.UserData { Id = "test-user", Name = "Test User" }; var sessionId = Guid.NewGuid().ToString(); var results = new Dictionary(); // Testar estratégia padrão try { var standardService = _serviceProvider.GetRequiredService(); var stopwatch1 = System.Diagnostics.Stopwatch.StartNew(); var standardResponse = await standardService.GetResponse( userData, request.ProjectId, sessionId + "-standard", request.Question, request.Language ?? "pt"); stopwatch1.Stop(); results["standard"] = new { response = standardResponse, executionTime = stopwatch1.ElapsedMilliseconds, success = true }; } catch (Exception ex) { results["standard"] = new { success = false, error = ex.Message }; } // Testar estratégia hierárquica try { var hierarchicalService = _serviceProvider.GetRequiredService(); var stopwatch2 = System.Diagnostics.Stopwatch.StartNew(); var hierarchicalResponse = await hierarchicalService.GetResponse( userData, request.ProjectId, sessionId + "-hierarchical", request.Question, request.Language ?? "pt"); stopwatch2.Stop(); results["hierarchical"] = new { response = hierarchicalResponse, executionTime = stopwatch2.ElapsedMilliseconds, success = true }; } catch (Exception ex) { results["hierarchical"] = new { success = false, error = ex.Message }; } return Ok(new { question = request.Question, projectId = request.ProjectId, provider = _factory.GetActiveProvider(), results }); } catch (Exception ex) { _logger.LogError(ex, "Erro ao comparar estratégias"); return StatusCode(500, new { error = ex.Message }); } } /// /// Obtém métricas de performance das estratégias /// [HttpGet("metrics")] public IActionResult GetMetrics() { // TODO: Implementar coleta de métricas real var metrics = new { standard = new { avgResponseTime = "1.2s", successRate = "98%", avgContextSize = "3 documentos", usage = "Alto" }, hierarchical = new { avgResponseTime = "2.1s", successRate = "95%", avgContextSize = "5-8 documentos", usage = "Médio" }, recommendations = new[] { "Use Standard para perguntas simples e rápidas", "Use Hierarchical para análises complexas que precisam de contexto profundo", "Hierarchical é melhor para perguntas técnicas detalhadas" } }; return Ok(metrics); } } public class StrategyTestRequest { public string ProjectId { get; set; } = ""; public string Question { get; set; } = ""; public string? Language { get; set; } public string? SessionId { get; set; } public ChatApi.Models.UserData? UserData { get; set; } } }