using System; using System.Linq; using xAiApi.Models; using System.Threading; using xAiApi.Constants; using xAiApi.Interfaces; using xCommons.Extensions; using xAiModels.Interfaces; using xAiApi.Configurations; using xExceptions.Constants; using xAiModels.Models.Dtos; using System.Threading.Tasks; using xFileService.Interfaces; using Microsoft.AspNetCore.Http; using System.Collections.Generic; using Microsoft.Extensions.Logging; using xAiApi.Interfaces.Extractors; using System.Runtime.CompilerServices; namespace xAiApi.Providers { /// /// Persistent RAG Service over XAiVector Table ... /// Isolation: Identifier = "{ownerId}/{fileName}#{chunkIndex}" ... /// public class XAiRAGService : IXAiRAGService { private readonly IXTextChunker textChunker; private readonly IXFileProvider fileProvider; private readonly IXDefaultAiService aiService; private readonly IXAiDataProvider dataProvider; private readonly ILogger logger; private readonly XAiApiConfiguration configuration; private readonly IXDefaultEmbeddingService embeddingService; private readonly IXFileContentExtractor fileContentExtractor; public XAiRAGService( IXTextChunker textChunker, IXFileProvider fileProvider, IXDefaultAiService aiService, IXAiDataProvider dataProvider, ILogger logger, XAiApiConfiguration configuration, IXDefaultEmbeddingService embeddingService, IXFileContentExtractor fileContentExtractor ) { // this.logger = logger; this.aiService = aiService; this.textChunker = textChunker; this.fileProvider = fileProvider; this.dataProvider = dataProvider; this.configuration = configuration; this.embeddingService = embeddingService; this.fileContentExtractor = fileContentExtractor; } // #region Ingest ... /// /// Ingest Files into Owner's Knowledge Base: /// Extract -> Chunk -> Embed -> Store (XAiVector) ... /// public async Task IngestAsync( IFormFileCollection files, string ownerId, bool replaceExisting = true, CancellationToken cancellationToken = default ) { // // Validate ... if (!files.HasChild() || ownerId.IsNullOrEmpty()) { XException.InvalidArgs.Throw(); } // var result = new XAiKnowledgeIngestResult(); var ingestedAtUtc = DateTime.UtcNow.ToString("O"); // foreach (var file in files) { // cancellationToken.ThrowIfCancellationRequested(); // if (file.IsNull() || file.Length == 0) { result.SkippedFiles.Add(file?.FileName ?? "(null)"); continue; } // var mimeType = file.ContentType?.ToLowerInvariant() ?? string.Empty; if (!fileContentExtractor.CanExtract(mimeType)) { result.SkippedFiles.Add(file.FileName); continue; } // var text = await ExtractText(file, mimeType, cancellationToken); if (text.IsNullOrEmpty()) { result.SkippedFiles.Add(file.FileName); continue; } // // Chunk with Owner Scoped Source => Identifier = "{ownerId}/{fileName}#{index}" ... var documentPrefix = GetDocumentPrefix(ownerId, file.FileName); var chunks = textChunker.Chunk(text, documentPrefix); if (!chunks.HasChild()) { result.SkippedFiles.Add(file.FileName); continue; } // // TODO: Implement File Save ... // // Embed in Batches ... var vectors = await EmbedChunks( chunks: chunks, ownerId: ownerId, mimeType: mimeType, fileName: file.FileName, ingestedAtUtc: ingestedAtUtc, cancellationToken: cancellationToken ); // // Remove Stale Vectors of Same Document ... if (replaceExisting) { // result.ReplacedCount += await dataProvider.RemoveVectorsAsync( identifierPrefix: GetDocumentChunkPrefix(ownerId, file.FileName), cancellationToken: cancellationToken ); } // // Store ... var storedCount = await dataProvider.UpsertVectorsAsync( items: vectors, cancellationToken: cancellationToken ); // result.FilesCount++; result.ChunksCount += storedCount; result.Documents.Add(new XAiKnowledgeDocumentInfo { MimeType = mimeType, FileName = file.FileName, ChunksCount = storedCount, IngestedAtUtc = DateTime.Parse(ingestedAtUtc, null, System.Globalization.DateTimeStyles.RoundtripKind) }); // logger.LogInformation( "Knowledge: Ingested {FileName} for {OwnerId} with {Chunks} Chunks", file.FileName, ownerId, storedCount ); } // return result; } #endregion // #region Ask ... /// /// Embed Prompt and Retrieve Relevant Chunks from Owner's Knowledge Base ... /// public async Task> RetrieveAsync( string prompt, string ownerId, int? topK = null, float? minScore = null, string fileName = null, CancellationToken cancellationToken = default ) { // // Validate ... if (prompt.IsNullOrEmpty() || ownerId.IsNullOrEmpty()) { XException.InvalidArgs.Throw(); } // var rag = configuration.RAGDescriptor; var effectiveTopK = Math.Clamp(topK ?? rag.DefaultTopK, 1, rag.MaxTopK); var effectiveMinScore = minScore ?? rag.DefaultMinScore; // // Embed Question ... var queryEmbedding = await embeddingService.Embedding( content: prompt, cancellationToken: cancellationToken ); if (queryEmbedding.IsNullOrDefault() || queryEmbedding.Length == 0) { XException.ActionFailed.Throw(); } // // Search in DB (Scoped to Owner or Owner + File) ... var prefix = fileName.IsNullOrEmpty() ? GetOwnerPrefix(ownerId) : GetDocumentChunkPrefix(ownerId, fileName); var searchResult = await dataProvider.SearchVectorsAsync( topK: effectiveTopK, identifierPrefix: prefix, minScore: effectiveMinScore, queryEmbedding: queryEmbedding, cancellationToken: cancellationToken ); // var result = searchResult?.ToList() ?? []; return result; } /// /// Ask a Question with RAG (Retrieve from DB then Generate) ... /// public async Task AskWithRAGAsync( XAiKnowledgeAskRequest request, string ownerId, CancellationToken cancellationToken = default ) { // // Validate ... if (request.IsNullOrDefault() || request.Prompt.IsNullOrEmpty()) { XException.InvalidArgs.Throw(); } // // Retrieve ... var context = await RetrieveAsync( ownerId: ownerId, topK: request.TopK, prompt: request.Prompt, minScore: request.MinScore, fileName: request.FileName, cancellationToken: cancellationToken ); // var result = new XAiDocumentAnswer { Sources = ToSources(context) }; if (!context.HasChild()) { // result.NoContextFound = true; return result; } // // Generate ... result.Answer = await aiService.AskWithContextAsync( context: context, prompt: request.Prompt, cancellationToken: cancellationToken ); // return result; } /// /// Ask a Question with RAG and Stream Response ... /// public async IAsyncEnumerable AskWithRAGAsEnumerable( XAiKnowledgeAskRequest request, string ownerId, [EnumeratorCancellation] CancellationToken cancellationToken = default ) { // // Validate ... if (request.IsNullOrDefault() || request.Prompt.IsNullOrEmpty()) { XException.InvalidArgs.Throw(); } // // Retrieve ... var context = await RetrieveAsync( ownerId: ownerId, topK: request.TopK, prompt: request.Prompt, minScore: request.MinScore, fileName: request.FileName, cancellationToken: cancellationToken ); // // First Item: Sources ... var hasContext = context.HasChild(); yield return new XAiDocumentAnswerChunk { Text = string.Empty, IsFinal = !hasContext, NoContextFound = !hasContext, Sources = ToSources(context) }; if (!hasContext) { yield break; } // // Stream Deltas ... var enumerable = aiService.AskWithContextAsEnumerable( context: context, prompt: request.Prompt, cancellationToken: cancellationToken ); await foreach (var delta in enumerable) { // if (cancellationToken.IsCancellationRequested) { yield break; } // if (delta.IsNullOrEmpty()) { continue; } // yield return new XAiDocumentAnswerChunk { Text = delta }; } // // Final Item ... yield return new XAiDocumentAnswerChunk { Text = string.Empty, IsFinal = true }; } #endregion // #region Documents ... /// /// List Ingested Documents of Owner (Grouped by File Name) ... /// public async Task> LoadDocumentsAsync( string ownerId, CancellationToken cancellationToken = default ) { // // Validate ... if (ownerId.IsNullOrEmpty()) { XException.InvalidArgs.Throw(); } // var vectors = await dataProvider.LoadVectorsAsync( includeEmbedding: false, cancellationToken: cancellationToken, identifierPrefix: GetOwnerPrefix(ownerId) ); // var rag = configuration.RAGDescriptor; var result = (vectors ?? []) .GroupBy(v => GetMetadata(v.Metadata, rag.MetadataFileName) ?? v.Identifier) .Select(g => { // var first = g.First(); var ingestedText = GetMetadata(first.Metadata, XAiApiConstants.XAiKnowledgeMetadataIngestedAtUtc); // return new XAiKnowledgeDocumentInfo { FileName = g.Key, ChunksCount = g.Count(), MimeType = GetMetadata(first.Metadata, rag.MetadataMimeType), IngestedAtUtc = DateTime.TryParse( ingestedText, null, System.Globalization.DateTimeStyles.RoundtripKind, out var dt ) ? dt : null }; }) .OrderBy(d => d.FileName) .ToList(); // return result; } /// /// Remove All Vectors of a Document ... /// public async Task RemoveDocumentAsync( string ownerId, string fileName, CancellationToken cancellationToken = default ) { // // Validate ... if (ownerId.IsNullOrEmpty() || fileName.IsNullOrEmpty()) { XException.InvalidArgs.Throw(); } // var result = await dataProvider.RemoveVectorsAsync( cancellationToken: cancellationToken, identifierPrefix: GetDocumentChunkPrefix(ownerId, fileName) ); // return result; } /// /// Map Search Results to Public Sources ... /// public IList ToSources( IEnumerable context ) { // var rag = configuration.RAGDescriptor; var result = (context ?? []) .Select(c => { // var text = c.Text ?? string.Empty; var chunkIndexText = GetMetadata(c.Metadata, rag.MetadataChunkIndex); var snippetLength = Math.Min(text.Length, rag.SourceSnippetLength); // return new XAiDocumentSource { Score = c.Score, Identifier = c.Identifier, Snippet = text.Substring(0, snippetLength), FileName = GetMetadata(c.Metadata, rag.MetadataFileName), ChunkIndex = int.TryParse(chunkIndexText, out var idx) ? idx : null }; }) .ToList(); // return result; } #endregion // #region Private ... /// /// Owner Scope Prefix: "{ownerId}/" ... /// private static string GetOwnerPrefix(string ownerId) { return $"{ownerId}{XAiApiConstants.XAiKnowledgeOwnerSeparator}"; } /// /// Document Prefix (Chunker Source): "{ownerId}/{fileName}" ... /// private static string GetDocumentPrefix(string ownerId, string fileName) { return $"{GetOwnerPrefix(ownerId)}{fileName}"; } /// /// Document Chunk Prefix: "{ownerId}/{fileName}#" ... /// Separator Suffix Prevents "a.pdf" from Matching "a.pdf.bak" ... /// private string GetDocumentChunkPrefix(string ownerId, string fileName) { return $"{GetDocumentPrefix(ownerId, fileName)}{configuration.TextChunker.ChunkIdentifierSeparator}"; } /// /// Extract Plain Text of a File (Text or Audio Transcript) ... /// private async Task ExtractText( IFormFile file, string mimeType, CancellationToken cancellationToken ) { // try { // using var stream = file.OpenReadStream(); var extraction = await fileContentExtractor.ExtractRichAsync( fileStream: stream, mimeType: mimeType, fileName: file.FileName, cancellationToken: cancellationToken ); // var result = extraction?.Text; if (string.IsNullOrWhiteSpace(result)) { result = extraction?.AudioTranscript; } // return result; } catch (OperationCanceledException) { throw; } catch (Exception ex) { logger.LogWarning(ex, "Knowledge: Extraction Failed for {FileName}", file.FileName); return null; } } /// /// Embed Chunks in Batches and Build Vectors ... /// private async Task> EmbedChunks( IList chunks, string ownerId, string fileName, string mimeType, string ingestedAtUtc, CancellationToken cancellationToken ) { // var rag = configuration.RAGDescriptor; var batchSize = Math.Max(1, rag.EmbeddingBatchSize); var result = new List(chunks.Count); // for (var offset = 0; offset < chunks.Count; offset += batchSize) { // cancellationToken.ThrowIfCancellationRequested(); // var batch = chunks.Skip(offset).Take(batchSize).ToList(); var embeddings = await embeddingService.Embeddings( batch: batch.Select(c => c.Text).ToArray(), cancellationToken: cancellationToken ); // if (embeddings.IsNullOrDefault() || embeddings.Count != batch.Count) { XException.ActionFailed.Throw(); } // for (var i = 0; i < batch.Count; i++) { // var chunk = batch[i]; result.Add(new XAiVectorDto { Id = Guid.NewGuid(), Text = chunk.Text, Embedding = embeddings[i], Identifier = chunk.Identifier, Metadata = new Dictionary { [rag.MetadataFileName] = fileName, [rag.MetadataMimeType] = mimeType, [rag.MetadataChunkIndex] = chunk.Index.ToString(), [XAiApiConstants.XAiKnowledgeMetadataOwnerId] = ownerId, [XAiApiConstants.XAiKnowledgeMetadataIngestedAtUtc] = ingestedAtUtc } }); } } // return result; } /// /// Safe Metadata Reader ... /// private static string GetMetadata( IDictionary metadata, string key ) { // if (metadata.IsNullOrDefault() || !metadata.TryGetValue(key, out var value)) { return null; } // return value; } #endregion } }