225 lines
8.2 KiB
Plaintext
225 lines
8.2 KiB
Plaintext
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<RAGStrategyController> _logger;
|
|
|
|
public RAGStrategyController(
|
|
IVectorDatabaseFactory factory,
|
|
IServiceProvider serviceProvider,
|
|
ILogger<RAGStrategyController> logger)
|
|
{
|
|
_factory = factory;
|
|
_serviceProvider = serviceProvider;
|
|
_logger = logger;
|
|
}
|
|
|
|
/// <summary>
|
|
/// Lista as estratégias de RAG disponíveis
|
|
/// </summary>
|
|
[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
|
|
});
|
|
}
|
|
|
|
/// <summary>
|
|
/// Testa uma estratégia específica com uma pergunta
|
|
/// </summary>
|
|
[HttpPost("test/{strategy}")]
|
|
public async Task<IActionResult> TestStrategy(
|
|
[FromRoute] string strategy,
|
|
[FromBody] StrategyTestRequest request)
|
|
{
|
|
try
|
|
{
|
|
IResponseService responseService = strategy.ToLower() switch
|
|
{
|
|
"standard" => _serviceProvider.GetRequiredService<ResponseRAGService>(),
|
|
"hierarchical" => _serviceProvider.GetRequiredService<HierarchicalRAGService>(),
|
|
_ => 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 });
|
|
}
|
|
}
|
|
|
|
/// <summary>
|
|
/// Compara resultados entre diferentes estratégias
|
|
/// </summary>
|
|
[HttpPost("compare")]
|
|
public async Task<IActionResult> 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<string, object>();
|
|
|
|
// Testar estratégia padrão
|
|
try
|
|
{
|
|
var standardService = _serviceProvider.GetRequiredService<ResponseRAGService>();
|
|
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<HierarchicalRAGService>();
|
|
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 });
|
|
}
|
|
}
|
|
|
|
/// <summary>
|
|
/// Obtém métricas de performance das estratégias
|
|
/// </summary>
|
|
[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; }
|
|
}
|
|
} |