From 47da04a5946292c9906da860ebd495ec13d0537e Mon Sep 17 00:00:00 2001 From: Hadi Khazaee Asl Date: Sun, 25 Oct 2026 22:24:39 +0330 Subject: [PATCH] Implement Chat With Documents (In-Memory RAG) ... - Add XAiDocumentModels (IngestResult, AskRequest, Answer, AnswerChunk, Source, SessionInfo, RAGDescriptor DTOs); - Add AskWithContextAsync and AskWithContextAsEnumerable (Context Actions) to IXAiServiceBase and XAIServiceBase; - Add GetContextHistory and BuildContextBlock Helpers for Building RAG Chat History without Persisting; - Rewrite ChatWithDocumentsController with Ingest, Ask, AskStream (SSE), Get Session and Delete Session Endpoints; - Add XInMemoryVectorStoreCleanupService (BackgroundService) for Removing Expired Sessions Periodically; - Add AddXAiChatWithDocuments DI Extension, Register Cleanup HostedService and use it in Startup; - Add RAGDescriptor Property to XAiApiConfiguration and its Section to appsettings.Development.json; - Add ChatWithDocuments System Prompt to Prompts in appsettings.Development.json; - Add IsValid Extension Method for XAiDocumentAskRequest; - Optimize XInMemoryVectorStore.Search (Query Embedding Converted once) and Refactor Formatting; - Remove Unused Usings in XAIServiceBase and IXAiServiceBase; - ... --- Configurations/XAiApiConfiguration.cs | 5 + Controllers/ChatWithDocumentsController.cs | 674 +++++++++++++++++- DI/XDIHelperExtension.cs | 11 + Extensions/XModelsExtensions.cs | 21 +- Interfaces/IXAiServiceBase.cs | 34 +- Models/XAiDocumentModels.cs | 181 +++++ Providers/XAIServiceBase.cs | 183 ++++- Providers/XInMemoryVectorStore.cs | 62 +- .../XInMemoryVectorStoreCleanupService.cs | 77 ++ Startup.cs | 6 +- appsettings.Development.json | 266 +++---- 11 files changed, 1349 insertions(+), 171 deletions(-) create mode 100644 Models/XAiDocumentModels.cs create mode 100644 Providers/XInMemoryVectorStoreCleanupService.cs diff --git a/Configurations/XAiApiConfiguration.cs b/Configurations/XAiApiConfiguration.cs index 9507155..480c14a 100644 --- a/Configurations/XAiApiConfiguration.cs +++ b/Configurations/XAiApiConfiguration.cs @@ -40,5 +40,10 @@ namespace xAiApi.Configurations /// Text Chunker Configuration ... /// public XTextChunkerDescriptor TextChunker { get; set; } = new(); + + /// + /// RAG Configuration ... + /// + public XAiDocumentRAGDescriptor RAGDescriptor {get; set;} = new(); } } \ No newline at end of file diff --git a/Controllers/ChatWithDocumentsController.cs b/Controllers/ChatWithDocumentsController.cs index a64f96f..a1f3fb7 100644 --- a/Controllers/ChatWithDocumentsController.cs +++ b/Controllers/ChatWithDocumentsController.cs @@ -1,33 +1,54 @@ using System; -using System.Collections.Generic; using System.Linq; -using System.Threading.Tasks; -using Microsoft.AspNetCore.Authorization; -using Microsoft.AspNetCore.Components; -using Microsoft.Extensions.Logging; +using xAiApi.Models; +using System.Threading; using xAiApi.Interfaces; -using xAiApi.Interfaces.Extractors; -using xAiModels.Models.Dtos; -using xCommons.Configurations; +using xAiApi.Extensions; using xCommons.Providers; -using xIdentityService.Controllers; +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, IDisposable + public class ChatWithDocumentsController : XBaseIdentityApiV1Controller { /// /// Default AI Service ... /// - private IXDefaultAiService aiService; + private readonly IXDefaultAiService aiService; + + /// + /// Text Chunker Service ... + /// + private readonly IXTextChunker textChunker; /// /// In Memory Vector Store ... /// - private IList vectorStore = []; + private readonly IXInMemoryVectorStore vectorStore; + + /// + /// XAiApi Configuration ... + /// + private readonly XAiApiConfiguration apiConfiguration; /// /// Embedding Service ... @@ -40,26 +61,643 @@ namespace xAiApi.Controllers private readonly IXFileContentExtractor fileContentExtractor; public ChatWithDocumentsController( + IXTextChunker textChunker, IXDefaultAiService aiService, - ILogger logger, + IXInMemoryVectorStore vectorStore, XAppConfiguration appConfiguration, IXIdentityProvider identityProvider, - IXDefaultEmbeddingService embeddingService, + 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 ... /// - /// Dispose ... + /// Ingest Files into a (new or existing) In-Memory Session: + /// Extract -> Chunk -> Embed -> Store ... /// - public void Dispose() + /// + /// 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 + ) { - vectorStore.Clear(); + // + 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 } -} \ No newline at end of file +} diff --git a/DI/XDIHelperExtension.cs b/DI/XDIHelperExtension.cs index b5e6020..9bee46a 100644 --- a/DI/XDIHelperExtension.cs +++ b/DI/XDIHelperExtension.cs @@ -134,6 +134,17 @@ namespace xAiApi.DI public static void AddXAiInMemoryVectorStore(this IServiceCollection source) { source.AddSingleton(); + source.AddHostedService(); + } + + /// + /// Register all Services Required for Chat With Documents (In-Memory RAG): + /// Text Chunker + In-Memory Vector Store (+ Cleanup) ... + /// + /// + public static void AddXAiChatWithDocuments(this IServiceCollection source) + { + source.AddXAiInMemoryVectorStore(); } /// diff --git a/Extensions/XModelsExtensions.cs b/Extensions/XModelsExtensions.cs index b88af7a..d7c1351 100644 --- a/Extensions/XModelsExtensions.cs +++ b/Extensions/XModelsExtensions.cs @@ -2,6 +2,7 @@ using System; using OpenAI; using System.Linq; using OllamaSharp; +using xAiApi.Models; using System.Net.Http; using xAiApi.Constants; using xAiModels.Models; @@ -15,7 +16,6 @@ using xExceptions.Constants; using Microsoft.Extensions.AI; using System.Collections.Generic; using System.ClientModel.Primitives; -using xAiApi.Models; namespace xAiApi.Extensions { @@ -62,6 +62,25 @@ namespace xAiApi.Extensions return result; } + /// + /// Check Document Ask Request is Valid or not ... + /// + /// + /// + public static bool IsValid(this XAiDocumentAskRequest source) + { + // + var result = + !source.IsNullOrDefault() && + !source.Prompt.IsNullOrEmpty() && + !source.SessionId.IsDefaultGuid() && + (!source.TopK.HasValue || source.TopK.Value > 0) && + (!source.MinScore.HasValue || (source.MinScore.Value >= -1f && source.MinScore.Value <= 1f)); + + // + return result; + } + /// /// Extract Default Model Descriptor ... /// diff --git a/Interfaces/IXAiServiceBase.cs b/Interfaces/IXAiServiceBase.cs index d7fe355..f61cd4d 100644 --- a/Interfaces/IXAiServiceBase.cs +++ b/Interfaces/IXAiServiceBase.cs @@ -1,6 +1,5 @@ using System; using xModels.Dtos; -using System.Net.Http; using System.Threading; using xAiModels.Models; using xAiModels.Models.Dtos; @@ -74,6 +73,35 @@ namespace xAiApi.Interfaces ); #endregion + // + #region Context Actions ... + /// + /// Ask a Question using Provided Context Chunks (RAG) without Persisting ... + /// + /// + /// + /// + /// + Task AskWithContextAsync( + string prompt, + IEnumerable context, + CancellationToken cancellationToken = default + ); + + /// + /// Ask a Question using Provided Context Chunks (RAG) and Stream Response ... + /// + /// + /// + /// + /// + IAsyncEnumerable AskWithContextAsEnumerable( + string prompt, + IEnumerable context, + CancellationToken cancellationToken = default + ); + #endregion + // #region Loaders ... /// @@ -196,7 +224,7 @@ namespace xAiApi.Interfaces CancellationToken cancellationToken = default ); #endregion - + // #region Content Extraction ... /// @@ -209,7 +237,7 @@ namespace xAiApi.Interfaces Task ExtractContent( IFormFileCollection files, string[] extractors = null, - CancellationToken cancellationToken = default + CancellationToken cancellationToken = default ); #endregion diff --git a/Models/XAiDocumentModels.cs b/Models/XAiDocumentModels.cs new file mode 100644 index 0000000..e15c752 --- /dev/null +++ b/Models/XAiDocumentModels.cs @@ -0,0 +1,181 @@ +using System; +using System.Collections.Generic; + +namespace xAiApi.Models +{ + /// + /// Result of Ingesting Documents into an In-Memory Session ... + /// + public class XAiDocumentIngestResult + { + /// + /// Session Identifier which must be used in Ask Requests ... + /// + public Guid SessionId { get; set; } + + /// + /// Count of Successfully Processed Files ... + /// + public int FilesCount { get; set; } + + /// + /// Count of Chunks (Vectors) Added to Session ... + /// + public int ChunksCount { get; set; } + + /// + /// Total Vectors Count in Session after Ingest ... + /// + public int TotalVectorsCount { get; set; } + + /// + /// Files which Skipped (Unsupported / Empty / Failed) ... + /// + public IList SkippedFiles { get; set; } = new List(); + + /// + /// Session Expiration Time (UTC) based on Last Access ... + /// + public DateTime ExpiresAtUtc { get; set; } + } + + /// + /// Request for Asking a Question over Ingested Documents ... + /// + public class XAiDocumentAskRequest + { + /// + /// Session Identifier ... + /// + public Guid SessionId { get; set; } + + /// + /// User Question ... + /// + public string Prompt { get; set; } + + /// + /// Count of Top Chunks used as Context (Optional) ... + /// + public int? TopK { get; set; } + + /// + /// Minimum Similarity Score of Chunks (Optional) ... + /// + public float? MinScore { get; set; } + } + + /// + /// a Source Chunk which used for Generating Answer ... + /// + public class XAiDocumentSource + { + /// + /// Doc and Chunk Identifier (e.g. "file.pdf#3") ... + /// + public string Identifier { get; set; } + + /// + /// Source File Name ... + /// + public string FileName { get; set; } + + /// + /// Chunk Index in Source File ... + /// + public int? ChunkIndex { get; set; } + + /// + /// Similarity Score ... + /// + public float Score { get; set; } + + /// + /// Short Snippet of Chunk Text ... + /// + public string Snippet { get; set; } + } + + /// + /// Answer of a Chat With Documents Request ... + /// + public class XAiDocumentAnswer + { + /// + /// Session Identifier ... + /// + public Guid SessionId { get; set; } + + /// + /// Generated Answer ... + /// + public string Answer { get; set; } + + /// + /// True when no Relevant Chunk Found in Session ... + /// + public bool NoContextFound { get; set; } + + /// + /// Sources used for Generating Answer ... + /// + public IList Sources { get; set; } = new List(); + } + + /// + /// Streaming Chunk of a Chat With Documents Answer ... + /// + public class XAiDocumentAnswerChunk + { + /// + /// Text Delta ... + /// + public string Text { get; set; } + + /// + /// True for Last Chunk ... + /// + public bool IsFinal { get; set; } + + /// + /// True when no Relevant Chunk Found in Session ... + /// + public bool NoContextFound { get; set; } + + /// + /// Sources (Only Filled in First Chunk) ... + /// + public IList Sources { get; set; } + } + + /// + /// Public Info of a Document Session (without Embeddings) ... + /// + public class XAiDocumentSessionInfo + { + public Guid Id { get; set; } + public TimeSpan Ttl { get; set; } + public int VectorsCount { get; set; } + public DateTime CreatedAtUtc { get; set; } + public DateTime LastAccessAtUtc { get; set; } + public DateTime ExpiresAtUtc { get; set; } + public IList Files { get; set; } = new List(); + } + + /// + /// Document RAG Configuration ... + /// + public class XAiDocumentRAGDescriptor + { + public int MaxTopK { get; set; } = 20; + public int DefaultTopK { get; set; } = 5; + public int DefaultTtlMinutes { get; set; } = 30; + public int EmbeddingBatchSize { get; set; } = 32; + public int SourceSnippetLength { get; set; } = 200; + public float DefaultMinScore { get; set; } = 0.35f; + public string MetadataFileName { get; set; } = "fileName"; + public string MetadataMimeType { get; set; } = "mimeType"; + public string PromptName { get; set; } = "ChatWithDocuments"; + public string MetadataChunkIndex { get; set; } = "chunkIndex"; + } +} diff --git a/Providers/XAIServiceBase.cs b/Providers/XAIServiceBase.cs index 846fbb3..6621139 100644 --- a/Providers/XAIServiceBase.cs +++ b/Providers/XAIServiceBase.cs @@ -1,15 +1,11 @@ using System; -using OpenAI; -using OllamaSharp; using System.Linq; using xModels.Dtos; -using System.Net.Http; using System.Threading; using xAiApi.Constants; using xAiModels.Models; using xAiApi.Interfaces; using xAiApi.Extensions; -using System.ClientModel; using xCommons.Providers; using xCommons.Extensions; using xAiModels.Constants; @@ -28,7 +24,6 @@ using Microsoft.AspNetCore.Http; using System.Collections.Generic; using Microsoft.Extensions.Logging; using xAiApi.Interfaces.Extractors; -using System.ClientModel.Primitives; using System.Runtime.CompilerServices; namespace xAiApi.Providers @@ -256,6 +251,181 @@ namespace xAiApi.Providers } #endregion + // + #region Context Actions ... + /// + /// Ask a Question using Provided Context Chunks (RAG) without Persisting ... + /// + /// + /// + /// + /// + public virtual async Task AskWithContextAsync( + string prompt, + IEnumerable context, + CancellationToken cancellationToken = default + ) + { + // + // Validate Args ... + if (prompt.IsNullOrEmpty()) + { + XException.InvalidArgs.Throw(); + } + + // + using var client = Descriptor.GetClient(); + var history = GetContextHistory(prompt, context); + var response = await client.GetResponseAsync( + messages: history, + cancellationToken: cancellationToken + ); + + // + // Validate Response ... + if (!response.IsValid()) + { + client.Dispose(); + XException.ActionFailed.Throw(); + } + + // + var result = response.Text; + + // + return result; + } + + /// + /// Ask a Question using Provided Context Chunks (RAG) and Stream Response ... + /// + /// + /// + /// + /// + public virtual async IAsyncEnumerable AskWithContextAsEnumerable( + string prompt, + IEnumerable context, + [EnumeratorCancellation] + CancellationToken cancellationToken = default + ) + { + // + // Validate Args ... + if (prompt.IsNullOrEmpty()) + { + XException.InvalidArgs.Throw(); + } + + // + using var client = Descriptor.GetClient(); + var history = GetContextHistory(prompt, context); + var enumerable = client.GetStreamingResponseAsync( + options: null, + messages: history, + cancellationToken: cancellationToken + ); + + // + await foreach (var res in enumerable) + { + // + if (cancellationToken.IsCancellationRequested) + { + yield break; + } + + // + yield return res.Text; + } + } + + /// + /// Build Chat History for RAG: + /// [System: Introduction] + [System: ChatWithDocuments Prompt + Context Block] + [User: Prompt] ... + /// + /// + /// + /// + protected virtual IList GetContextHistory( + string prompt, + IEnumerable context + ) + { + // + var ragPrompt = configuration.GetPrompt(configuration.RAGDescriptor.PromptName); + if (ragPrompt.IsNullOrEmpty()) + { + XException.InvalidConfiguration.Throw(); + } + + // + var contextBlock = BuildContextBlock(context); + var systemText = $"{ragPrompt}{Environment.NewLine}{Environment.NewLine}Context:{Environment.NewLine}{contextBlock}"; + + // + List result = + [ + new ChatMessage(ChatRole.System, configuration.GetPrompt()), + new ChatMessage(ChatRole.System, systemText), + new ChatMessage(ChatRole.User, prompt), + ]; + + // + return result; + } + + /// + /// Convert Context Chunks to a Numbered Text Block ... + /// + /// + /// + protected virtual string BuildContextBlock( + IEnumerable context + ) + { + // + var result = "(no context)"; + + // + var items = context? + .Where(c => + !c.IsNullOrDefault() && + !c.Text.IsNullOrEmpty() + ) + .ToList() ?? []; + if (!items.HasChild()) + { + return result; + } + + // + var index = 1; + var builder = new System.Text.StringBuilder(); + foreach (var item in items) + { + // + var identifier = item.Identifier.IsNullOrEmpty() + ? item.Id.ToString() + : item.Identifier; + + // + builder.AppendLine($"[{index}] Source: [{identifier}] (score: {item.Score:0.000})"); + builder.AppendLine(item.Text.Trim()); + builder.AppendLine("----"); + + // + index++; + } + + // + result = builder.ToString(); + + // + return result; + } + #endregion + // #region Loaders ... /// @@ -663,6 +833,9 @@ namespace xAiApi.Providers { continue; } + + // + // TODO: Implement File Save ... } // diff --git a/Providers/XInMemoryVectorStore.cs b/Providers/XInMemoryVectorStore.cs index 8c58c37..53c9126 100644 --- a/Providers/XInMemoryVectorStore.cs +++ b/Providers/XInMemoryVectorStore.cs @@ -1,8 +1,8 @@ using System; using System.Linq; using xAiApi.Models; -using xAiService.Helpers; using xAiApi.Interfaces; +using xAiService.Helpers; using xAiModels.Models.Dtos; using System.Collections.Generic; using System.Collections.Concurrent; @@ -99,10 +99,10 @@ namespace xAiApi.Providers } public IList Search( - Guid sessionId, - ReadOnlyMemory queryEmbedding, - int topK = 5, - float minScore = 0f, + Guid sessionId, + ReadOnlyMemory queryEmbedding, + int topK = 5, + float minScore = 0f, string ownerId = null ) { @@ -121,6 +121,7 @@ namespace xAiApi.Providers } // + var query = queryEmbedding.ToArray(); lock (session.SyncRoot) { // @@ -135,7 +136,7 @@ namespace xAiApi.Providers // var score = VectorHelper.CosineSimilarity( - queryEmbedding.ToArray(), + query, vector.Embedding.ToArray() ); @@ -143,12 +144,13 @@ namespace xAiApi.Providers if (score >= minScore) { // - result.Add(new XAiVectorSearchResult { + result.Add(new XAiVectorSearchResult + { Score = score, - Id = vector.Id, - Text = vector.Text, - Metadata = vector.Metadata, - Identifier = vector.Identifier, + Id = vector.Id, + Text = vector.Text, + Metadata = vector.Metadata, + Identifier = vector.Identifier, }); } } @@ -161,8 +163,8 @@ namespace xAiApi.Providers } public bool TryGet( - Guid sessionId, - out XAiDocumentSession session, + Guid sessionId, + out XAiDocumentSession session, string ownerId = null ) { @@ -176,8 +178,12 @@ namespace xAiApi.Providers return true; } - public bool Remove(Guid sessionId, string ownerId = null) + public bool Remove( + Guid sessionId, + string ownerId = null + ) { + // XAiDocumentSession session; if (!TryGet(sessionId, out session, ownerId)) return false; return sessions.TryRemove(sessionId, out session); @@ -185,13 +191,35 @@ namespace xAiApi.Providers public int RemoveExpired() { + // var now = DateTime.UtcNow; var removed = 0; foreach (var pair in sessions) { if (pair.Value.IsExpired(now) && sessions.TryRemove(pair.Key, out _)) removed++; } return removed; } - private static bool OwnerMatches(XAiDocumentSession session, string ownerId) { return string.IsNullOrEmpty(session.OwnerId) || string.Equals(session.OwnerId, ownerId, StringComparison.Ordinal); } - private static TimeSpan NormalizeTtl(TimeSpan? ttl) { return !ttl.HasValue || ttl.Value <= TimeSpan.Zero ? TimeSpan.FromMinutes(DefaultTtlMinutes) : ttl.Value; } - private static IList Copy(IEnumerable vectors) { return vectors == null ? new List() : vectors.Where(x => x != null).ToList(); } + // + #region Private ... + private static bool OwnerMatches( + XAiDocumentSession session, + string ownerId + ) + { + return string.IsNullOrEmpty(session.OwnerId) || string.Equals(session.OwnerId, ownerId, StringComparison.Ordinal); + } + + private static TimeSpan NormalizeTtl( + TimeSpan? ttl + ) + { + return !ttl.HasValue || ttl.Value <= TimeSpan.Zero ? TimeSpan.FromMinutes(DefaultTtlMinutes) : ttl.Value; + } + + private static IList Copy( + IEnumerable vectors + ) + { + return vectors == null ? new List() : vectors.Where(x => x != null).ToList(); + } + #endregion } } diff --git a/Providers/XInMemoryVectorStoreCleanupService.cs b/Providers/XInMemoryVectorStoreCleanupService.cs new file mode 100644 index 0000000..8ac96ab --- /dev/null +++ b/Providers/XInMemoryVectorStoreCleanupService.cs @@ -0,0 +1,77 @@ +using System; +using System.Threading; +using xAiApi.Interfaces; +using System.Threading.Tasks; +using Microsoft.Extensions.Hosting; +using Microsoft.Extensions.Logging; + +namespace xAiApi.Providers +{ + /// + /// Periodically Removes Expired Document Sessions from In-Memory Vector Store ... + /// + public class XInMemoryVectorStoreCleanupService : BackgroundService + { + /// + /// Default Cleanup Interval ... + /// + public static readonly TimeSpan DefaultInterval = TimeSpan.FromMinutes(5); + + private readonly TimeSpan interval; + private readonly IXInMemoryVectorStore vectorStore; + private readonly ILogger logger; + + public XInMemoryVectorStoreCleanupService( + IXInMemoryVectorStore vectorStore, + ILogger logger + ) + { + this.logger = logger; + this.vectorStore = vectorStore; + this.interval = DefaultInterval; + } + + /// + /// Cleanup Loop ... + /// + /// + /// + protected override async Task ExecuteAsync(CancellationToken stoppingToken) + { + // + try + { + // + while (!stoppingToken.IsCancellationRequested) + { + // + await Task.Delay(interval, stoppingToken); + + // + try + { + // + var removed = vectorStore.RemoveExpired(); + if (removed > 0) + { + // + logger.LogInformation( + "InMemoryVectorStore Cleanup: {Removed} Expired Session(s) Removed, {Count} Remaining", + removed, + vectorStore.Count + ); + } + } + catch (Exception ex) + { + logger.LogError(ex, "InMemoryVectorStore Cleanup Failed"); + } + } + } + catch (OperationCanceledException) + { + // Shutdown ... + } + } + } +} diff --git a/Startup.cs b/Startup.cs index bffd5cc..d7c70f6 100644 --- a/Startup.cs +++ b/Startup.cs @@ -186,14 +186,14 @@ namespace xAiApi // // Register File Content Extractor Services ... services.AddXAiFileContentExtractors(); - + // // Register Text Chunker Service ... services.AddXAiTextChunker(); // - // Register In-Memory Vector Store Service ... - services.AddXAiInMemoryVectorStore(); + // Register Chat With Documents Services (Text Chunker + In-Memory Vector Store) ... + services.AddXAiChatWithDocuments(); // // Register Default AI Services ... diff --git a/appsettings.Development.json b/appsettings.Development.json index db5104e..c0518b1 100644 --- a/appsettings.Development.json +++ b/appsettings.Development.json @@ -1,125 +1,143 @@ { - "AllowedOrigins": [ - "http://localhost:5000", - "https://localhost:5001", - "http://api.saherelm.ir", - "https://api.saherelm.ir", - "http://api.saherelmhub.ir", - "https://api.saherelmhub.ir" - ], - "IdentityServiceConfiguration": { - "Authority": "https://localhost:4001", - "ApiName": "xSaherElmAPI", - "ApiSecret": "s@H@1694056", - "ClientId": "xSaherElmAPIClient", - "ClientSecret": "s@H@1694056", - "XPoweredValue": "SaherElmITCenter", - "XRevisionSecretKey": "SaherElmITCenter@1694056", - "DefaultClientTimeout": -1 - }, - "StorageConfiguration": { - "Authority": "https://localhost:5001", - "IdentityAuthority": "https://localhost:5001", - "Storage": "Storage", - "Temp": "Temp", - "Thumb": "Thumb", - "Uploads": "Uploads", - "Widgets": "Widgets", - "Image": "Image", - "Audio": "Audio", - "Video": "Video", - "Document": "Document", - "FilePrefix": "xSaherElm_", - "ThumbPrefix": "Thumb_", - "ThumbSize": 512, - "ThumbQuality": 72, - "MaxFileSize": 41943040 - }, - "AiApiConfiguration": { - "Models": [ - { - "ApiKey": "", - "Name": "Gemma", - "LLM": "gemma3:1b", - "Provider": "OpenAI", - "Url": "http://178.131.88.93:1112/v1" - }, - { - "ApiKey": "", - "Name": "Qwen", - "LLM": "qwen-9b", - "Provider": "OpenAI", - "Url": "http://178.131.88.93:1114/v1" - }, - { - "ApiKey": "", - "Name": "Embed", - "LLM": "bge-m3", - "Provider": "OpenAI", - "Url": "http://178.131.88.93:1113/v1" - } - ], - "Prompts": [ - { - "Name": "Introduction", - "Template": "your name is xSaherElmAi, you are a professional ai assistant which develped by SaherElm IT Center, answer each questions by it's language.", - "Description": "", - "Params": [] - }, - { - "Name": "ContentExtraction", - "Template": "You are an Expert Powerful OCR Engine. your job isReading all Contents in Given Document and Retrieve them as Raw Text by following these rules: 1. Converst all tables to Markdown format. 2. extract numbers, date and times and names exactly as is. 3. do not add any extra descriptions, introduction or summarization from yourself and just return extracted Content.", - "Description": "", - "Params": [] - }, - { - "Name": "Embedding", - "Template": "your name is xSaherElmAi, you are a professional ai assistant which develped by SaherElm IT Center specified for Embedding Documents", - "Description": "", - "Params": [] - } - ], - "OCR": { - "DataPath": "Models", - "EngineMode": "LstmOnly", - "EnableOcrFallback": true, - "DefaultLanguage": "fas+eng" - }, - "Transcript": { - "Language": "fa", - "ModelsPath": "Models/ggml-base.bin" - }, - "PDFToImageDescriptor": { - "Dpi": 300, - "Width": 0, - "Height": 0, - "UseTiling": false, - "WithFormFill": false, - "WithAspectRatio": false, - "WithAnnotations": false, - "DpiRelativeToBounds": false, - "MaxImageWidth": 2000, - "MinTextLengthThreshold": 50, - "MaxPagesForImageFallback": 0 - }, - "ProxyConfiguration": { - "Enabled": true, - "RoutePrefix": "/ai-model" - }, - "TextChunker": { - "ChunkSize": 800, - "ChunkOverlap": 150, - "MinChunkSize": 50, - "NormalizeWhitespace": true, - "ChunkIdentifierSeparator": "#" - } - }, - "Logging": { - "LogLevel": { - "Microsoft": "Warning", - "Default": "Information", - "Microsoft.Hosting.Lifetime": "Information" - } - }, - "AllowedHosts": "*" -} \ No newline at end of file + "AllowedOrigins": [ + "http://localhost:5000", + "https://localhost:5001", + "http://api.saherelm.ir", + "https://api.saherelm.ir", + "http://api.saherelmhub.ir", + "https://api.saherelmhub.ir" + ], + "IdentityServiceConfiguration": { + "Authority": "https://localhost:4001", + "ApiName": "xSaherElmAPI", + "ApiSecret": "s@H@1694056", + "ClientId": "xSaherElmAPIClient", + "ClientSecret": "s@H@1694056", + "XPoweredValue": "SaherElmITCenter", + "XRevisionSecretKey": "SaherElmITCenter@1694056", + "DefaultClientTimeout": -1 + }, + "StorageConfiguration": { + "Authority": "https://localhost:5001", + "IdentityAuthority": "https://localhost:5001", + "Storage": "Storage", + "Temp": "Temp", + "Thumb": "Thumb", + "Uploads": "Uploads", + "Widgets": "Widgets", + "Image": "Image", + "Audio": "Audio", + "Video": "Video", + "Document": "Document", + "FilePrefix": "xSaherElm_", + "ThumbPrefix": "Thumb_", + "ThumbSize": 512, + "ThumbQuality": 72, + "MaxFileSize": 41943040 + }, + "AiApiConfiguration": { + "Models": [ + { + "ApiKey": "", + "Name": "Gemma", + "LLM": "gemma3:1b", + "Provider": "OpenAI", + "Url": "http://178.131.88.93:1112/v1" + }, + { + "ApiKey": "", + "Name": "Qwen", + "LLM": "qwen-9b", + "Provider": "OpenAI", + "Url": "http://178.131.88.93:1114/v1" + }, + { + "ApiKey": "", + "Name": "Embed", + "LLM": "bge-m3", + "Provider": "OpenAI", + "Url": "http://178.131.88.93:1113/v1" + } + ], + "Prompts": [ + { + "Name": "Introduction", + "Template": "your name is xSaherElmAi, you are a professional ai assistant which develped by SaherElm IT Center, answer each questions by it's language.", + "Description": "", + "Params": [] + }, + { + "Name": "ContentExtraction", + "Template": "You are an Expert Powerful OCR Engine. your job isReading all Contents in Given Document and Retrieve them as Raw Text by following these rules: 1. Converst all tables to Markdown format. 2. extract numbers, date and times and names exactly as is. 3. do not add any extra descriptions, introduction or summarization from yourself and just return extracted Content.", + "Description": "", + "Params": [] + }, + { + "Name": "Embedding", + "Template": "your name is xSaherElmAi, you are a professional ai assistant which develped by SaherElm IT Center specified for Embedding Documents", + "Description": "", + "Params": [] + }, + { + "Name": "ChatWithDocuments", + "Template": "You are a document question-answering assistant. Answer the user's question ONLY based on the provided Context chunks below. Follow these rules: 1. If the answer is not present in the Context, clearly state that the information was not found in the provided documents and do not make up an answer. 2. When using information from a chunk, cite its source identifier in square brackets (e.g. [file.pdf#3]). 3. Answer in the same language as the user's question. 4. Be concise and precise; do not add unrelated information.", + "Description": "System prompt for RAG based Chat With Documents", + "Params": [] + } + ], + "OCR": { + "DataPath": "Models", + "EngineMode": "LstmOnly", + "EnableOcrFallback": true, + "DefaultLanguage": "fas+eng" + }, + "Transcript": { + "Language": "fa", + "ModelsPath": "Models/ggml-base.bin" + }, + "PDFToImageDescriptor": { + "Dpi": 300, + "Width": 0, + "Height": 0, + "UseTiling": false, + "WithFormFill": false, + "WithAspectRatio": false, + "WithAnnotations": false, + "DpiRelativeToBounds": false, + "MaxImageWidth": 2000, + "MinTextLengthThreshold": 50, + "MaxPagesForImageFallback": 0 + }, + "ProxyConfiguration": { + "Enabled": true, + "RoutePrefix": "/ai-model" + }, + "TextChunker": { + "ChunkSize": 800, + "ChunkOverlap": 150, + "MinChunkSize": 50, + "NormalizeWhitespace": true, + "ChunkIdentifierSeparator": "#" + }, + "RAGDescriptor": { + "MaxTopK": 20, + "DefaultTopK": 5, + "DefaultTtlMinutes": 30, + "EmbeddingBatchSize": 32, + "SourceSnippetLength": 200, + "DefaultMinScore": "0.35f", + "MetadataFileName": "fileName", + "MetadataMimeType": "mimeType", + "PromptName": "ChatWithDocuments", + "MetadataChunkIndex": "chunkIndex" + } + }, + "Logging": { + "LogLevel": { + "Microsoft": "Warning", + "Default": "Information", + "Microsoft.Hosting.Lifetime": "Information" + } + }, + "AllowedHosts": "*" +}