namespace ChatRAG.Settings
{
// ============================================================================
// 📁 Configuration/VectorDatabaseSettings.cs
// Settings unificados para todos os providers (MongoDB, Qdrant, etc.)
// ============================================================================
namespace ChatRAG.Configuration
{
///
/// Configurações principais do sistema de Vector Database
///
public class VectorDatabaseSettings
{
///
/// Provider ativo (MongoDB, Qdrant, Pinecone, etc.)
///
public string Provider { get; set; } = "MongoDB";
///
/// Configurações específicas do MongoDB
///
public MongoDbSettings MongoDB { get; set; } = new();
///
/// Configurações específicas do Qdrant
///
public QdrantSettings Qdrant { get; set; } = new();
///
/// Configurações globais de embedding
///
public EmbeddingSettings Embedding { get; set; } = new();
///
/// Configurações de performance e cache
///
public PerformanceSettings Performance { get; set; } = new();
///
/// Configurações de logging e monitoramento
///
public MonitoringSettings Monitoring { get; set; } = new();
///
/// Valida se as configurações estão corretas
///
public bool IsValid()
{
if (string.IsNullOrWhiteSpace(Provider))
return false;
return Provider.ToLower() switch
{
"mongodb" => MongoDB.IsValid(),
"qdrant" => Qdrant.IsValid(),
_ => false
};
}
///
/// Retorna erros de validação
///
public List GetValidationErrors()
{
var errors = new List();
if (string.IsNullOrWhiteSpace(Provider))
errors.Add("Provider é obrigatório");
switch (Provider.ToLower())
{
case "mongodb":
errors.AddRange(MongoDB.GetValidationErrors());
break;
case "qdrant":
errors.AddRange(Qdrant.GetValidationErrors());
break;
default:
errors.Add($"Provider '{Provider}' não é suportado");
break;
}
errors.AddRange(Embedding.GetValidationErrors());
return errors;
}
}
///
/// Configurações específicas do MongoDB
///
public class MongoDbSettings
{
///
/// String de conexão do MongoDB
///
public string ConnectionString { get; set; } = string.Empty;
///
/// Nome do banco de dados
///
public string DatabaseName { get; set; } = string.Empty;
///
/// Nome da coleção de textos/documentos
///
public string TextCollectionName { get; set; } = "texts";
///
/// Nome da coleção de projetos
///
public string ProjectCollectionName { get; set; } = "projects";
///
/// Nome da coleção de dados de usuário
///
public string UserDataName { get; set; } = "users";
///
/// Timeout de conexão em segundos
///
public int ConnectionTimeoutSeconds { get; set; } = 30;
///
/// Timeout de operação em segundos
///
public int OperationTimeoutSeconds { get; set; } = 60;
///
/// Tamanho máximo do pool de conexões
///
public int MaxConnectionPoolSize { get; set; } = 100;
///
/// Habilitar índices de busca vetorial
///
public bool EnableVectorSearch { get; set; } = true;
///
/// Configurações específicas do Atlas Search
///
public MongoAtlasSearchSettings AtlasSearch { get; set; } = new();
public bool IsValid()
{
return !string.IsNullOrWhiteSpace(ConnectionString) &&
!string.IsNullOrWhiteSpace(DatabaseName) &&
!string.IsNullOrWhiteSpace(TextCollectionName);
}
public List GetValidationErrors()
{
var errors = new List();
if (string.IsNullOrWhiteSpace(ConnectionString))
errors.Add("MongoDB ConnectionString é obrigatória");
if (string.IsNullOrWhiteSpace(DatabaseName))
errors.Add("MongoDB DatabaseName é obrigatório");
if (string.IsNullOrWhiteSpace(TextCollectionName))
errors.Add("MongoDB TextCollectionName é obrigatório");
if (ConnectionTimeoutSeconds <= 0)
errors.Add("MongoDB ConnectionTimeoutSeconds deve ser maior que 0");
return errors;
}
}
///
/// Configurações do MongoDB Atlas Search
///
public class MongoAtlasSearchSettings
{
///
/// Nome do índice de busca vetorial
///
public string VectorIndexName { get; set; } = "vector_index";
///
/// Número de candidatos para busca aproximada
///
public int NumCandidates { get; set; } = 200;
///
/// Limite de resultados do Atlas Search
///
public int SearchLimit { get; set; } = 100;
}
///
/// Configurações específicas do Qdrant
///
public class QdrantSettings
{
///
/// Host do servidor Qdrant
///
public string Host { get; set; } = "localhost";
///
/// Porta do servidor Qdrant (REST API)
///
public int Port { get; set; } = 6333;
///
/// Porta gRPC (opcional, para performance)
///
public int? GrpcPort { get; set; } = 6334;
///
/// Chave de API (se autenticação estiver habilitada)
///
public string? ApiKey { get; set; }
///
/// Usar TLS/SSL
///
public bool UseTls { get; set; } = false;
///
/// Nome da coleção principal
///
public string CollectionName { get; set; } = "documents";
///
/// Tamanho do vetor de embedding
///
public int VectorSize { get; set; } = 1536; // OpenAI embedding size
///
/// Métrica de distância (Cosine, Euclid, Dot, Manhattan)
///
public string Distance { get; set; } = "Cosine";
// ========================================
// CONFIGURAÇÕES DE PERFORMANCE
// ========================================
///
/// Parâmetro M do algoritmo HNSW (conectividade)
/// Valores típicos: 16-48, maior = melhor recall, mais memória
///
public int HnswM { get; set; } = 16;
///
/// Parâmetro ef_construct do HNSW (construção do índice)
/// Valores típicos: 100-800, maior = melhor qualidade, mais lento
///
public int HnswEfConstruct { get; set; } = 200;
///
/// Parâmetro ef do HNSW (busca)
/// Valores típicos: igual ou maior que o número de resultados desejados
///
public int HnswEf { get; set; } = 128;
///
/// Armazenar vetores em disco (economiza RAM)
///
public bool OnDisk { get; set; } = false;
///
/// Fator de replicação (para clusters)
///
public int ReplicationFactor { get; set; } = 1;
///
/// Número de shards (para distribuição)
///
public int ShardNumber { get; set; } = 1;
///
/// Usar quantização para reduzir uso de memória
///
public bool UseQuantization { get; set; } = false;
///
/// Configurações de quantização
///
public QuantizationSettings Quantization { get; set; } = new();
///
/// Timeout de conexão em segundos
///
public int ConnectionTimeoutSeconds { get; set; } = 30;
///
/// Timeout de operação em segundos
///
public int OperationTimeoutSeconds { get; set; } = 60;
///
/// URL completa calculada
///
public string GetConnectionUrl()
{
var protocol = UseTls ? "https" : "http";
return $"{protocol}://{Host}:{Port}";
}
public bool IsValid()
{
return !string.IsNullOrWhiteSpace(Host) &&
Port > 0 &&
!string.IsNullOrWhiteSpace(CollectionName) &&
VectorSize > 0;
}
public List GetValidationErrors()
{
var errors = new List();
if (string.IsNullOrWhiteSpace(Host))
errors.Add("Qdrant Host é obrigatório");
if (Port <= 0)
errors.Add("Qdrant Port deve ser maior que 0");
if (string.IsNullOrWhiteSpace(CollectionName))
errors.Add("Qdrant CollectionName é obrigatório");
if (VectorSize <= 0)
errors.Add("Qdrant VectorSize deve ser maior que 0");
if (HnswM <= 0)
errors.Add("Qdrant HnswM deve ser maior que 0");
if (HnswEfConstruct <= 0)
errors.Add("Qdrant HnswEfConstruct deve ser maior que 0");
var validDistances = new[] { "Cosine", "Euclid", "Dot", "Manhattan" };
if (!validDistances.Contains(Distance))
errors.Add($"Qdrant Distance deve ser um de: {string.Join(", ", validDistances)}");
return errors;
}
}
///
/// Configurações de quantização para Qdrant
///
public class QuantizationSettings
{
///
/// Tipo de quantização (scalar, product, binary)
///
public string Type { get; set; } = "scalar";
///
/// Quantil para quantização scalar
///
public double Quantile { get; set; } = 0.99;
///
/// Sempre usar RAM para quantização
///
public bool AlwaysRam { get; set; } = false;
}
///
/// Configurações globais de embedding
///
public class EmbeddingSettings
{
///
/// Provider de embedding (OpenAI, Ollama, Azure, etc.)
///
public string Provider { get; set; } = "OpenAI";
///
/// Modelo de embedding
///
public string Model { get; set; } = "text-embedding-ada-002";
///
/// Tamanho esperado do embedding
///
public int ExpectedSize { get; set; } = 1536;
///
/// Batch size para processamento em lote
///
public int BatchSize { get; set; } = 100;
///
/// Cache de embeddings em memória
///
public bool EnableCache { get; set; } = true;
///
/// TTL do cache em minutos
///
public int CacheTtlMinutes { get; set; } = 60;
public List GetValidationErrors()
{
var errors = new List();
if (ExpectedSize <= 0)
errors.Add("Embedding ExpectedSize deve ser maior que 0");
if (BatchSize <= 0)
errors.Add("Embedding BatchSize deve ser maior que 0");
return errors;
}
}
///
/// Configurações de performance e otimização
///
public class PerformanceSettings
{
///
/// Habilitar paralelização em operações de lote
///
public bool EnableParallelization { get; set; } = true;
///
/// Número máximo de threads paralelas
///
public int MaxParallelism { get; set; } = Environment.ProcessorCount;
///
/// Tamanho do batch para operações em lote
///
public int BatchSize { get; set; } = 100;
///
/// Timeout padrão para operações em segundos
///
public int DefaultTimeoutSeconds { get; set; } = 30;
///
/// Habilitar retry automático
///
public bool EnableRetry { get; set; } = true;
///
/// Número máximo de tentativas
///
public int MaxRetryAttempts { get; set; } = 3;
///
/// Delay entre tentativas em segundos
///
public int RetryDelaySeconds { get; set; } = 2;
}
///
/// Configurações de monitoramento e logging
///
public class MonitoringSettings
{
///
/// Habilitar logging detalhado
///
public bool EnableDetailedLogging { get; set; } = false;
///
/// Logar tempos de operação
///
public bool LogOperationTimes { get; set; } = true;
///
/// Threshold para log de operações lentas (ms)
///
public int SlowOperationThresholdMs { get; set; } = 1000;
///
/// Habilitar métricas de performance
///
public bool EnableMetrics { get; set; } = true;
///
/// Intervalo de coleta de métricas em segundos
///
public int MetricsIntervalSeconds { get; set; } = 60;
///
/// Habilitar health checks
///
public bool EnableHealthChecks { get; set; } = true;
///
/// Intervalo de health check em segundos
///
public int HealthCheckIntervalSeconds { get; set; } = 30;
}
}
}