using System; using System.Linq; using xAiApi.Models; using System.Threading; using xAiApi.Interfaces; using xAiApi.Extensions; using xCommons.Providers; using xCommons.Extensions; using xAiApi.Configurations; using xExceptions.Constants; using xAiModels.Models.Dtos; using System.Threading.Tasks; using xCommons.Configurations; using Microsoft.AspNetCore.Mvc; using System.Collections.Generic; using Microsoft.AspNetCore.Http; using xIdentityService.Interfaces; using xIdentityService.Controllers; using xAiApi.Interfaces.Extractors; using Microsoft.Extensions.Logging; using Microsoft.AspNetCore.Authorization; namespace xAiApi.Controllers { /// /// Chat With Documents (In-Memory RAG) Controller ... /// Flow: Ingest Files -> SessionId -> Ask / AskStream -> Delete Session /// [Authorize] [Route("[controller]")] public class ChatWithDocumentsController : XBaseIdentityApiV1Controller { /// /// Default AI Service ... /// private readonly IXDefaultAiService aiService; /// /// Text Chunker Service ... /// private readonly IXTextChunker textChunker; /// /// In Memory Vector Store ... /// private readonly IXInMemoryVectorStore vectorStore; /// /// XAiApi Configuration ... /// private readonly XAiApiConfiguration apiConfiguration; /// /// Embedding Service ... /// private readonly IXDefaultEmbeddingService embeddingService; /// /// File Context Extractor Service ... /// private readonly IXFileContentExtractor fileContentExtractor; public ChatWithDocumentsController( IXTextChunker textChunker, IXDefaultAiService aiService, IXInMemoryVectorStore vectorStore, XAppConfiguration appConfiguration, IXIdentityProvider identityProvider, XAiApiConfiguration apiConfiguration, XValidationProvider validationProvider, IXDefaultEmbeddingService embeddingService, ILogger logger, IXFileContentExtractor fileContentExtractor ) : base(logger, appConfiguration, identityProvider, validationProvider) { // this.aiService = aiService; this.textChunker = textChunker; this.vectorStore = vectorStore; this.apiConfiguration = apiConfiguration; this.embeddingService = embeddingService; this.fileContentExtractor = fileContentExtractor; } // #region Ingest ... /// /// Ingest Files into a (new or existing) In-Memory Session: /// Extract -> Chunk -> Embed -> Store ... /// /// /// Optional: Add to an Existing Session /// Optional: Session TTL in Minutes (only for new Session) /// /// [HttpPost("Ingest")] [Consumes("multipart/form-data")] public async Task> Ingest( [FromForm] IFormFileCollection files, [FromForm] Guid? sessionId = null, [FromForm] int? ttlMinutes = null, CancellationToken cancellationToken = default ) { // try { // // Validate ... if (!files.HasChild()) { XException.InvalidArgs.Throw(); } // var userInfo = await GetUserInfo(); var ownerId = userInfo.UserId; // // Resolve Target Session ... Guid targetSessionId; if (sessionId.HasValue && sessionId.Value != Guid.Empty) { // if (!vectorStore.TryGet(sessionId.Value, out _, ownerId)) { XException.NotFound.Throw(); } targetSessionId = sessionId.Value; } else { // var ttl = TimeSpan.FromMinutes( ttlMinutes.HasValue && ttlMinutes.Value > 0 ? ttlMinutes.Value : apiConfiguration.RAGDescriptor.DefaultTtlMinutes ); targetSessionId = vectorStore.CreateSession(ownerId, ttl); } // var result = new XAiDocumentIngestResult { SessionId = targetSessionId }; // // Extract -> Chunk -> Embed ... var vectors = new List(); 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 (string.IsNullOrWhiteSpace(text)) { result.SkippedFiles.Add(file.FileName); continue; } // var chunks = textChunker.Chunk(text, file.FileName); if (!chunks.HasChild()) { result.SkippedFiles.Add(file.FileName); continue; } // // Embed in Batches ... var fileVectors = await EmbedChunks( chunks: chunks, mimeType: mimeType, fileName: file.FileName, cancellationToken: cancellationToken ); // vectors.AddRange(fileVectors); result.FilesCount++; } // // Store ... if (vectors.HasChild() && !vectorStore.Add(targetSessionId, vectors, ownerId)) { XException.ActionFailed.Throw(); } // // Fill Result ... result.ChunksCount = vectors.Count; if (vectorStore.TryGet(targetSessionId, out var session, ownerId)) { lock (session.SyncRoot) { result.TotalVectorsCount = session.Vectors.Count; } result.ExpiresAtUtc = session.LastAccessAtUtc.Add(session.Ttl); } // return Ok(result); } catch (Exception ex) { var result = GetExceptionActionResult(ex); return result; } } #endregion // #region Ask ... /// /// Ask a Question over Ingested Documents ... /// /// /// /// [HttpPost("Ask")] public async Task> Ask( [FromBody] XAiDocumentAskRequest request, CancellationToken cancellationToken = default ) { // try { // // Validate ... if (!request.IsValid()) { XException.InvalidArgs.Throw(); } // var userInfo = await GetUserInfo(); var ownerId = userInfo.UserId; // // Check Session ... if (!vectorStore.TryGet(request.SessionId, out _, ownerId)) { XException.NotFound.Throw(); } // // Retrieve ... var context = await Retrieve(request, ownerId, cancellationToken); // var result = new XAiDocumentAnswer { SessionId = request.SessionId, Sources = ToSources(context) }; // if (!context.HasChild()) { result.NoContextFound = true; return Ok(result); } // // Generate ... result.Answer = await aiService.AskWithContextAsync( prompt: request.Prompt, context: context, cancellationToken: cancellationToken ); // return Ok(result); } catch (Exception ex) { var result = GetExceptionActionResult(ex); return result; } } /// /// Ask a Question over Ingested Documents and Stream Response (SSE) ... /// First Event Carries Sources, Next Events Carry Text Deltas, Last Event has IsFinal = true ... /// /// /// /// [HttpPost("AskStream")] public async Task AskStream( [FromBody] XAiDocumentAskRequest request, CancellationToken cancellationToken = default ) { // try { // // Validate ... if (!request.IsValid()) { XException.InvalidArgs.Throw(); } // var userInfo = await GetUserInfo(); var ownerId = userInfo.UserId; // // Check Session ... if (!vectorStore.TryGet(request.SessionId, out _, ownerId)) { XException.NotFound.Throw(); } // // Retrieve ... var context = await Retrieve(request, ownerId, cancellationToken); // // Configure SSE Response Headers ... Response.Headers["X-Accel-Buffering"] = "no"; Response.Headers["Connection"] = "keep-alive"; Response.Headers["Content-Type"] = "text/event-stream"; Response.Headers["Cache-Control"] = "no-cache, no-store"; // // Disable response buffering ... var responseBodyFeature = HttpContext.Features .Get(); responseBodyFeature?.DisableBuffering(); // // First Event: Sources ... var hasContext = context.HasChild(); await WriteChunk(new XAiDocumentAnswerChunk { Text = string.Empty, IsFinal = !hasContext, NoContextFound = !hasContext, Sources = ToSources(context) }, cancellationToken); // if (!hasContext) { return; } // // Stream Deltas ... var enumerable = aiService.AskWithContextAsEnumerable( prompt: request.Prompt, context: context, cancellationToken: cancellationToken ); await foreach (var delta in enumerable) { // if (delta.IsNullOrEmpty()) { continue; } // await WriteChunk(new XAiDocumentAnswerChunk { Text = delta }, cancellationToken); } // // Final Event ... await WriteChunk(new XAiDocumentAnswerChunk { Text = string.Empty, IsFinal = true }, cancellationToken); } catch (Exception ex) { // Logger.LogError(ex, "ChatWithDocuments: AskStream Failed"); if (!Response.HasStarted) { Response.StatusCode = StatusCodes.Status400BadRequest; } await Response.Body.FlushAsync(); } } #endregion // #region Session ... /// /// Retrieve Session Info (without Embeddings) ... /// /// /// [HttpGet("Session/{id:guid}")] public async Task> GetSession(Guid id) { // try { // var userInfo = await GetUserInfo(); if (!vectorStore.TryGet(id, out var session, userInfo.UserId)) { XException.NotFound.Throw(); } // IList vectors; lock (session.SyncRoot) { vectors = session.Vectors.ToList(); } // var result = new XAiDocumentSessionInfo { Id = session.Id, Ttl = session.Ttl, VectorsCount = vectors.Count, CreatedAtUtc = session.CreatedAtUtc, LastAccessAtUtc = session.LastAccessAtUtc, ExpiresAtUtc = session.LastAccessAtUtc.Add(session.Ttl), Files = vectors .Select(v => GetMetadata(v.Metadata, apiConfiguration.RAGDescriptor.MetadataFileName)) .Where(f => !f.IsNullOrEmpty()) .Distinct() .ToList() }; // return Ok(result); } catch (Exception ex) { var result = GetExceptionActionResult(ex); return result; } } /// /// Remove a Session and Free Memory ... /// /// /// [HttpDelete("Session/{id:guid}")] public async Task> DeleteSession(Guid id) { // try { // var userInfo = await GetUserInfo(); if (!vectorStore.Remove(id, userInfo.UserId)) { XException.NotFound.Throw(); } // return Ok(true); } catch (Exception ex) { var result = GetExceptionActionResult(ex); return result; } } #endregion // #region Private ... /// /// 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, "ChatWithDocuments: Extraction Failed for {FileName}", file.FileName); return null; } } /// /// Embed Chunks in Batches and Build Vectors ... /// private async Task> EmbedChunks( IList chunks, string fileName, string mimeType, CancellationToken cancellationToken ) { // var result = new List(chunks.Count); var batchSize = apiConfiguration.RAGDescriptor.EmbeddingBatchSize; // 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 { [apiConfiguration.RAGDescriptor.MetadataFileName] = fileName, [apiConfiguration.RAGDescriptor.MetadataMimeType] = mimeType, [apiConfiguration.RAGDescriptor.MetadataChunkIndex] = chunk.Index.ToString() } }); } } // return result; } /// /// Embed Prompt and Search Session ... /// private async Task> Retrieve( XAiDocumentAskRequest request, string ownerId, CancellationToken cancellationToken ) { // var topK = Math.Clamp( request.TopK ?? apiConfiguration.RAGDescriptor.DefaultTopK, 1, apiConfiguration.RAGDescriptor.MaxTopK ); var minScore = request.MinScore ?? apiConfiguration.RAGDescriptor.DefaultMinScore; // var queryEmbedding = await embeddingService.Embedding( content: request.Prompt, cancellationToken: cancellationToken ); if (queryEmbedding.IsNullOrDefault() || queryEmbedding.Length == 0) { XException.ActionFailed.Throw(); } // var result = vectorStore.Search( topK: topK, ownerId: ownerId, minScore: minScore, sessionId: request.SessionId, queryEmbedding: queryEmbedding ); // return result ?? []; } /// /// Map Search Results to Public Sources ... /// private IList ToSources( IEnumerable context ) { // var result = (context ?? []) .Select(c => { // var chunkIndexText = GetMetadata(c.Metadata, apiConfiguration.RAGDescriptor.MetadataChunkIndex); var text = c.Text ?? string.Empty; var snippetLength = Math.Min(text.Length, apiConfiguration.RAGDescriptor.SourceSnippetLength); // return new XAiDocumentSource { Score = c.Score, Identifier = c.Identifier, Snippet = text.Substring(0, snippetLength), ChunkIndex = int.TryParse(chunkIndexText, out var idx) ? idx : null, FileName = GetMetadata(c.Metadata, apiConfiguration.RAGDescriptor.MetadataFileName) }; }) .ToList(); // return result; } /// /// Safe Metadata Reader ... /// private string GetMetadata( IDictionary metadata, string key ) { // if (metadata.IsNullOrDefault() || !metadata.TryGetValue(key, out var value)) { return null; } // return value; } /// /// Write a SSE Event ... /// private async Task WriteChunk( XAiDocumentAnswerChunk chunk, CancellationToken cancellationToken ) { // var payload = chunk.ToJSON(camelCase: true); await Response.WriteAsync($"data: {payload}\n\n", cancellationToken); await Response.Body.FlushAsync(cancellationToken); } #endregion } }