From ad8ea9c1dd347f08f0f5966c014770acd0e748de Mon Sep 17 00:00:00 2001 From: Hadi Khazaee Asl Date: Fri, 30 Oct 2026 19:46:20 +0330 Subject: [PATCH] Integrate RAG into Chat Pipeline and Decouple Embedding Service - AskAsync: accept Guid? projectId / conversationId; resolve defaults; - AskAsync: ingest attached files into Conversation scope (replaceExisting) via IXAiRAGService instead of Upload + Extract + raw content attachment; - AskAsync: retrieve context (Conversation -> Project -> User -> Global) and build a single System message: Introduction + ChatWithDocuments prompt + Context block (+ Project prompt); - XAIServiceBase / XDefaultAiService / XDefaultThinkingAiService: inject IXAiRAGService instead of IXFileProvider; - Add IXAiEmbeddingService + XAiEmbeddingService; remove IXDefaultEmbeddingService + XDefaultEmbeddingService; - XAiEmbeddingServiceBase no longer inherits XAIServiceBase; IXAiEmbeddingServiceBase / IXAiEmbeddingServiceControllerBase no longer extend chat interfaces; XAiEmbeddingServiceControllerBase derives from XBaseIdentityApiV1Controller; - XAiRAGService: drop IXDefaultAiService dependency (removes circular dependency); remove AskWithRAGAsync / AskWithRAGAsEnumerable; add file reference (AddReference) for scoped ingests; - KnowledgeController: remove POST Ask and POST AskStream; - DI: add AddXRagService() and call it from Startup before AddXAiServices(); - Add XAiApiRagPromptName = "ChatWithDocuments"; - Knowledge scope factories default Type to XAiDefaultKnowledgeType; - ChatWithDocuments ask request: TopK and MinScore are now required. BREAKING: /Knowledge/Ask and /Knowledge/AskStream removed; IXDefaultEmbeddingService replaced by IXAiEmbeddingService. --- Constants/XAiApiConstants.cs | 1 + Controllers/ChatWithDocumentsController.cs | 4 +- Controllers/DefaultEmbeddingController.cs | 14 +- Controllers/KnowledgeController.cs | 132 ------ .../XAiEmbeddingServiceControllerBase.cs | 18 +- Controllers/XAiServiceControllerBase.cs | 4 +- DI/XDIHelperExtension.cs | 19 +- Extensions/XModelsExtensions.cs | 4 +- Interfaces/IXAiEmbeddingService.cs | 5 + Interfaces/IXAiEmbeddingServiceBase.cs | 5 +- .../IXAiEmbeddingServiceControllerBase.cs | 4 +- Interfaces/IXAiRAGService.cs | 27 -- Interfaces/IXAiServiceBase.cs | 4 +- Interfaces/IXDefaultEmbeddingService.cs | 5 - Models/XAiKnowledgeModels.cs | 9 +- Providers/XAIServiceBase.cs | 312 ++++++-------- ...ddingService.cs => XAiEmbeddingService.cs} | 11 +- Providers/XAiEmbeddingServiceBase.cs | 24 +- Providers/XAiRAGService.cs | 382 +++++++----------- Providers/XDefaultAiService.cs | 5 +- Providers/XDefaultThinkingAiService.cs | 5 +- Startup.cs | 4 + 22 files changed, 343 insertions(+), 655 deletions(-) create mode 100644 Interfaces/IXAiEmbeddingService.cs delete mode 100644 Interfaces/IXDefaultEmbeddingService.cs rename Providers/{XDefaultEmbeddingService.cs => XAiEmbeddingService.cs} (70%) diff --git a/Constants/XAiApiConstants.cs b/Constants/XAiApiConstants.cs index 163fd49..50302f9 100644 --- a/Constants/XAiApiConstants.cs +++ b/Constants/XAiApiConstants.cs @@ -11,6 +11,7 @@ namespace xAiApi.Constants public const string XDILogTag = "XAiApi"; // + public const string XAiApiRagPromptName = "ChatWithDocuments"; public const string XAiApiIntroductionPromptName = "Introduction"; public const string XAiApiContentExtractionPromptName = "ContentExtraction"; diff --git a/Controllers/ChatWithDocumentsController.cs b/Controllers/ChatWithDocumentsController.cs index 6063c11..5f04993 100644 --- a/Controllers/ChatWithDocumentsController.cs +++ b/Controllers/ChatWithDocumentsController.cs @@ -54,7 +54,7 @@ namespace xAiApi.Controllers /// /// Embedding Service ... /// - private readonly IXDefaultEmbeddingService embeddingService; + private readonly IXAiEmbeddingService embeddingService; /// /// File Context Extractor Service ... @@ -68,8 +68,8 @@ namespace xAiApi.Controllers XAppConfiguration appConfiguration, IXIdentityProvider identityProvider, XAiApiConfiguration apiConfiguration, + IXAiEmbeddingService embeddingService, XValidationProvider validationProvider, - IXDefaultEmbeddingService embeddingService, ILogger logger, IXFileContentExtractor fileContentExtractor ) : base(logger, appConfiguration, identityProvider, validationProvider) diff --git a/Controllers/DefaultEmbeddingController.cs b/Controllers/DefaultEmbeddingController.cs index 48d3b5f..7ef3879 100644 --- a/Controllers/DefaultEmbeddingController.cs +++ b/Controllers/DefaultEmbeddingController.cs @@ -10,20 +10,20 @@ namespace xAiApi.Controllers { [Authorize] [Route("[controller]")] - public class DefaultEmbeddingController : XAiEmbeddingServiceControllerBase + public class DefaultEmbeddingController : XAiEmbeddingServiceControllerBase { public DefaultEmbeddingController( ILogger logger, - IXDefaultEmbeddingService aiService, + IXAiEmbeddingService embeddingService, XAppConfiguration appConfiguration, IXIdentityProvider identityProvider, XValidationProvider validationProvider ) : base( - logger, - aiService, - appConfiguration, - identityProvider, - validationProvider + logger: logger, + appConfiguration: appConfiguration, + identityProvider: identityProvider, + embeddingService: embeddingService, + validationProvider: validationProvider ) { } } diff --git a/Controllers/KnowledgeController.cs b/Controllers/KnowledgeController.cs index e49e490..4c8fd07 100644 --- a/Controllers/KnowledgeController.cs +++ b/Controllers/KnowledgeController.cs @@ -40,7 +40,6 @@ namespace xAiApi.Controllers XValidationProvider validationProvider ) : base(logger, appConfiguration, identityProvider, validationProvider) { - // this.ragService = ragService; } @@ -104,137 +103,6 @@ namespace xAiApi.Controllers } #endregion - // - #region Ask ... - /// - /// Ask a Question over Knowledge Base (RAG) ... - /// - /// - /// - /// - [HttpPost("Ask")] - public async Task> Ask( - [FromBody] XAiKnowledgeAskRequest request, - CancellationToken cancellationToken = default - ) - { - // - try - { - // - // Validate ... - if (request.IsNullOrDefault() || request.Prompt.IsNullOrEmpty()) - { - XException.InvalidArgs.Throw(); - } - - // - var userInfo = await GetUserInfo(); - - // - var result = await ragService.AskWithRAGAsync( - request: request, - userInfo: userInfo, - cancellationToken: cancellationToken - ); - - // - return Ok(result); - } - catch (Exception ex) - { - // - var result = GetExceptionActionResult(ex); - return result; - } - } - - /// - /// Ask a Question over Knowledge Base 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] XAiKnowledgeAskRequest request, - CancellationToken cancellationToken = default - ) - { - // - // Validate (before Stream Starts -> Proper Http Error) ... - if (request.IsNullOrDefault() || request.Prompt.IsNullOrEmpty()) - { - Response.StatusCode = StatusCodes.Status400BadRequest; - Response.ContentType = "application/json; charset=utf-8"; - await Response.WriteAsync(XException.InvalidArgs.ToXError().ToJSON()); - return; - } - - // - try - { - // - var userInfo = await GetUserInfo(); - - // - await using var enumerator = ragService - .AskWithRAGAsEnumerable( - request: request, - userInfo: userInfo, - cancellationToken: cancellationToken - ) - .GetAsyncEnumerator(cancellationToken); - - // - // Pull First Item before Starting Stream, so Scope / Ownership / - // Retrieval Errors are Returned as Regular Http Errors ... - var hasItem = await enumerator.MoveNextAsync(); - - // - // Configure SSE Response ... - Response.PrepareSseResponse(); - - // - while (hasItem) - { - // - var chunk = enumerator.Current; - if (!chunk.IsNullOrDefault()) - { - await WriteChunk(chunk, cancellationToken); - } - - // - hasItem = await enumerator.MoveNextAsync(); - } - - // - await Response.WriteSseDoneAsync(cancellationToken); - } - catch (Exception ex) when (ex.IsClientCancellation(cancellationToken)) - { - // Client Disconnected ... - } - catch (Exception ex) - { - // - Logger.LogError(ex, "Knowledge: AskStream Failed"); - if (!Response.HasStarted) - { - // - var result = GetExceptionActionResult(ex); - await result.ExecuteResultAsync(ControllerContext); - return; - } - - // - await Response.WriteSseErrorAsync(ex.Message); - } - } - #endregion - // #region Documents ... /// diff --git a/Controllers/XAiEmbeddingServiceControllerBase.cs b/Controllers/XAiEmbeddingServiceControllerBase.cs index eebea65..0ad6636 100644 --- a/Controllers/XAiEmbeddingServiceControllerBase.cs +++ b/Controllers/XAiEmbeddingServiceControllerBase.cs @@ -8,32 +8,32 @@ using Microsoft.AspNetCore.Mvc; using System.Collections.Generic; using xIdentityService.Interfaces; using Microsoft.Extensions.Logging; +using xIdentityService.Controllers; using Microsoft.AspNetCore.Authorization; namespace xAiApi.Controllers { [Authorize] [Route("[controller]")] - public abstract class XAiEmbeddingServiceControllerBase : XAiServiceControllerBase, IXAiEmbeddingServiceControllerBase - where TAiService : IXAiEmbeddingServiceBase + public abstract class XAiEmbeddingServiceControllerBase : XBaseIdentityApiV1Controller, IXAiEmbeddingServiceControllerBase + where TEmbeddingService : IXAiEmbeddingServiceBase { - private readonly TAiService aiService; + private readonly TEmbeddingService embeddingService; protected XAiEmbeddingServiceControllerBase( ILogger logger, - TAiService aiService, XAppConfiguration appConfiguration, IXIdentityProvider identityProvider, - XValidationProvider validationProvider + XValidationProvider validationProvider, + TEmbeddingService embeddingService ) : base( logger, - aiService, appConfiguration, identityProvider, validationProvider ) { - this.aiService = aiService; + this.embeddingService = embeddingService; } /// @@ -57,7 +57,7 @@ namespace xAiApi.Controllers ValidationProvider.NotEmpty(content); // - var result = await aiService.Embedding( + var result = await embeddingService.Embedding( content: content, cancellationToken: cancellationToken ); @@ -94,7 +94,7 @@ namespace xAiApi.Controllers ValidationProvider.NotZeroChilds(batch); // - var result = await aiService.Embeddings( + var result = await embeddingService.Embeddings( batch: batch, cancellationToken: cancellationToken ); diff --git a/Controllers/XAiServiceControllerBase.cs b/Controllers/XAiServiceControllerBase.cs index 7cde219..8a76e2d 100644 --- a/Controllers/XAiServiceControllerBase.cs +++ b/Controllers/XAiServiceControllerBase.cs @@ -689,9 +689,9 @@ namespace xAiApi.Controllers prompt: request.Prompt, ownerId: userInfo.UserId, connectionId: connectionId, - projectId: request.ProjectId, + projectId: request.ProjectId.Value, cancellationToken: cancellationToken, - conversationId: request.ConversationId + conversationId: request.ConversationId.Value ); // diff --git a/DI/XDIHelperExtension.cs b/DI/XDIHelperExtension.cs index 32ad347..f38c63c 100644 --- a/DI/XDIHelperExtension.cs +++ b/DI/XDIHelperExtension.cs @@ -73,6 +73,20 @@ namespace xAiApi.DI source.AddSingleton(configuration); } + /// + /// Register Rag Service ... + /// + /// + public static void AddXRagService( + this IServiceCollection source + ) + { + // + // Persistent RAG (Knowledge over XAiVector Table) ... + source.AddScoped(); + source.AddScoped(); + } + /// /// Register Ai Services ... /// @@ -83,12 +97,7 @@ namespace xAiApi.DI { // source.AddScoped(); - source.AddScoped(); source.AddScoped(); - - // - // Persistent RAG (Knowledge over XAiVector Table) ... - source.AddScoped(); } /// diff --git a/Extensions/XModelsExtensions.cs b/Extensions/XModelsExtensions.cs index b6a2de5..a2225d7 100644 --- a/Extensions/XModelsExtensions.cs +++ b/Extensions/XModelsExtensions.cs @@ -74,8 +74,8 @@ namespace xAiApi.Extensions !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)); + source.TopK.HasValue && source.TopK.Value > 0 && + source.MinScore.HasValue && source.MinScore.Value >= -1f && source.MinScore.Value <= 1f; // return result; diff --git a/Interfaces/IXAiEmbeddingService.cs b/Interfaces/IXAiEmbeddingService.cs new file mode 100644 index 0000000..4f5781d --- /dev/null +++ b/Interfaces/IXAiEmbeddingService.cs @@ -0,0 +1,5 @@ +namespace xAiApi.Interfaces +{ + public interface IXAiEmbeddingService : IXAiEmbeddingServiceBase + { } +} \ No newline at end of file diff --git a/Interfaces/IXAiEmbeddingServiceBase.cs b/Interfaces/IXAiEmbeddingServiceBase.cs index 14886a5..257bf04 100644 --- a/Interfaces/IXAiEmbeddingServiceBase.cs +++ b/Interfaces/IXAiEmbeddingServiceBase.cs @@ -1,15 +1,14 @@ -using System.Collections.Generic; using System.Threading; using System.Threading.Tasks; using Microsoft.Extensions.AI; -using OllamaSharp; +using System.Collections.Generic; namespace xAiApi.Interfaces { /// /// Base Embedding Provider Service ... /// - public interface IXAiEmbeddingServiceBase : IXAiServiceBase + public interface IXAiEmbeddingServiceBase // : IXAiServiceBase { /// /// Embedding Specified String ... diff --git a/Interfaces/IXAiEmbeddingServiceControllerBase.cs b/Interfaces/IXAiEmbeddingServiceControllerBase.cs index 95b828f..5c6b841 100644 --- a/Interfaces/IXAiEmbeddingServiceControllerBase.cs +++ b/Interfaces/IXAiEmbeddingServiceControllerBase.cs @@ -1,11 +1,11 @@ -using System.Collections.Generic; using System.Threading; using System.Threading.Tasks; using Microsoft.AspNetCore.Mvc; +using System.Collections.Generic; namespace xAiApi.Interfaces { - public interface IXAiEmbeddingServiceControllerBase : IXAiServiceControllerBase + public interface IXAiEmbeddingServiceControllerBase { /// /// Request For Embedding Specified String ... diff --git a/Interfaces/IXAiRAGService.cs b/Interfaces/IXAiRAGService.cs index afef48c..824f317 100644 --- a/Interfaces/IXAiRAGService.cs +++ b/Interfaces/IXAiRAGService.cs @@ -48,33 +48,6 @@ namespace xAiApi.Interfaces CancellationToken cancellationToken = default ); - /// - /// Ask a Question with RAG (Retrieve from DB then Generate) ... - /// - /// - /// - /// - /// - Task AskWithRAGAsync( - XAiKnowledgeAskRequest request, - XUserClaimsInfoDto userInfo = null, - CancellationToken cancellationToken = default - ); - - /// - /// Ask a Question with RAG and Stream Response ... - /// First Item Carries Sources, Next Items Carry Text Deltas, Last Item has IsFinal = true ... - /// - /// - /// - /// - /// - IAsyncEnumerable AskWithRAGAsEnumerable( - XAiKnowledgeAskRequest request, - XUserClaimsInfoDto userInfo = null, - CancellationToken cancellationToken = default - ); - /// /// List Ingested Documents of Specified Scope ... /// diff --git a/Interfaces/IXAiServiceBase.cs b/Interfaces/IXAiServiceBase.cs index f61cd4d..8c3f7f3 100644 --- a/Interfaces/IXAiServiceBase.cs +++ b/Interfaces/IXAiServiceBase.cs @@ -258,8 +258,8 @@ namespace xAiApi.Interfaces Task AskAsync( string prompt, string ownerId, - Guid projectId, - Guid conversationId, + Guid? projectId, + Guid? conversationId, string connectionId = null, IFormFileCollection files = null, XUserClaimsInfoDto userInfo = null, diff --git a/Interfaces/IXDefaultEmbeddingService.cs b/Interfaces/IXDefaultEmbeddingService.cs deleted file mode 100644 index 364273e..0000000 --- a/Interfaces/IXDefaultEmbeddingService.cs +++ /dev/null @@ -1,5 +0,0 @@ -namespace xAiApi.Interfaces -{ - public interface IXDefaultEmbeddingService : IXAiEmbeddingServiceBase - { } -} \ No newline at end of file diff --git a/Models/XAiKnowledgeModels.cs b/Models/XAiKnowledgeModels.cs index 88ee5e1..05d8b0b 100644 --- a/Models/XAiKnowledgeModels.cs +++ b/Models/XAiKnowledgeModels.cs @@ -33,7 +33,8 @@ namespace xAiApi.Models string type = null ) => new() { - Type = type, + // + Type = type ?? XAiModelsConstants.XAiDefaultKnowledgeType, ScopeId = null, Scope = XAiKnowledgeScope.User, }; @@ -47,7 +48,7 @@ namespace xAiApi.Models string type = null ) => new() { - Type = type, + Type = type ?? XAiModelsConstants.XAiDefaultKnowledgeType, ScopeId = null, Scope = XAiKnowledgeScope.Global, }; @@ -63,7 +64,7 @@ namespace xAiApi.Models string type = null ) => new() { - Type = type, + Type = type ?? XAiModelsConstants.XAiDefaultKnowledgeType, ScopeId = projectId, Scope = XAiKnowledgeScope.Project, }; @@ -79,7 +80,7 @@ namespace xAiApi.Models string type = null ) => new() { - Type = type, + Type = type ?? XAiModelsConstants.XAiDefaultKnowledgeType, ScopeId = conversationId, Scope = XAiKnowledgeScope.Conversation, }; diff --git a/Providers/XAIServiceBase.cs b/Providers/XAIServiceBase.cs index 47af7f7..a15b378 100644 --- a/Providers/XAIServiceBase.cs +++ b/Providers/XAIServiceBase.cs @@ -1,6 +1,7 @@ using System; using System.Linq; using xModels.Dtos; +using xAiApi.Models; using System.Threading; using xAiApi.Constants; using xAiModels.Models; @@ -11,14 +12,12 @@ using xCommons.Extensions; using xAiModels.Constants; using xAiModels.Interfaces; using xAiModels.Extensions; -using xAiService.Constants; using xAiApi.Configurations; using xExceptions.Constants; using xAiModels.Models.Dtos; using xAiService.Extensions; using System.Threading.Tasks; using xIdentityModels.Models; -using xFileService.Interfaces; using Microsoft.Extensions.AI; using Microsoft.AspNetCore.Http; using System.Collections.Generic; @@ -43,7 +42,7 @@ namespace xAiApi.Providers /// public XAiModelDescriptor Descriptor { get; } - private readonly IXFileProvider fileProvider; + private readonly IXAiRAGService ragProvider; private readonly IXAiDataProvider dataProvider; private readonly ILogger logger; private readonly XAiApiConfiguration configuration; @@ -51,7 +50,7 @@ namespace xAiApi.Providers private readonly IXFileContentExtractor fileContentExtractor; protected XAIServiceBase( - IXFileProvider fileProvider, + IXAiRAGService ragProvider, IXAiDataProvider dataProvider, ILogger logger, XAiApiConfiguration configuration, @@ -62,7 +61,7 @@ namespace xAiApi.Providers { // this.logger = logger; - this.fileProvider = fileProvider; + this.ragProvider = ragProvider; this.dataProvider = dataProvider; this.configuration = configuration; this.validationProvider = validationProvider; @@ -377,56 +376,6 @@ namespace xAiApi.Providers // 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 // @@ -874,8 +823,8 @@ namespace xAiApi.Providers public virtual async Task AskAsync( string prompt, string ownerId, - Guid projectId, - Guid conversationId, + Guid? projectId, + Guid? conversationId, string connectionId = null, IFormFileCollection files = null, XUserClaimsInfoDto userInfo = null, @@ -893,7 +842,7 @@ namespace xAiApi.Providers // // Check Project ... XAiProjectDto project = null; - if (projectId.IsDefaultGuid()) + if (!projectId.HasValue || projectId.Value.IsDefaultGuid()) { // project = await dataProvider.GetDefaultProject( @@ -909,7 +858,7 @@ namespace xAiApi.Providers { // project = await dataProvider.GetProject( - id: projectId, + id: projectId.Value, fillConversations: false, fillConversationMessages: false, cancellationToken: cancellationToken @@ -923,12 +872,12 @@ namespace xAiApi.Providers // // Check Conversation ... XAiConversationDto conversation = null; - if (conversationId.IsDefaultGuid()) + if (!conversationId.HasValue || conversationId.Value.IsDefaultGuid()) { // conversation = await dataProvider.GetDefaultConversation( ownerId: ownerId, - projectId: projectId, + projectId: projectId.Value, connectionId: connectionId, cancellationToken: cancellationToken ); @@ -940,8 +889,8 @@ namespace xAiApi.Providers { // conversation = await dataProvider.GetConversation( - id: conversationId, fillMessages: false, + id: conversationId.Value, cancellationToken: cancellationToken ); } @@ -951,38 +900,58 @@ namespace xAiApi.Providers } // - // Reading Messages ... - var messages = await dataProvider.LoadMessages( - conversationId: conversationId, + // Ingest Files based on Conversation ... + XAiKnowledgeIngestResult ingestResult; + if (files.HasChild()) + { + // + try + { + // + ingestResult = await ragProvider + .IngestAsync( + files: files, + userInfo: userInfo, + replaceExisting: true, + connectionId: connectionId, + cancellationToken: cancellationToken, + scope: XAiKnowledgeScopeDescriptor.Conversation( + type: null, + conversationId: conversationId.Value + ) + ); + } + catch { } + } + + // + // Prepare Knowledge Request ... + var knowledgeRequest = new XAiKnowledgeAskRequest + { + Prompt = prompt, + IncludeUser = true, + IncludeGlobal = true, + ProjectId = projectId, + ConversationId = conversationId + }; + var context = await ragProvider.RetrieveAsync( + userInfo: userInfo, + request: knowledgeRequest, cancellationToken: cancellationToken ); // - // Upload Files ... - IEnumerable uploadedFiles = null; - if (files.HasChild()) - { - // - // Validate User Info ... - if (userInfo.IsNullOrDefault()) - { - XException.InvalidArgs.Throw(); - } - - // - // Upload Files ... - uploadedFiles = await fileProvider.Upload( - files: files, - userInfo: userInfo, - connectionId: connectionId, - cancellationToken: cancellationToken - ); - } + // Reading Messages ... + var messages = await dataProvider.LoadMessages( + conversationId: conversationId.Value, + cancellationToken: cancellationToken + ); // // Handle Memory ... IList history = await PrepareMemory( project: project, + context: context, messages: messages, cancellationToken: cancellationToken ); @@ -995,102 +964,23 @@ namespace xAiApi.Providers OwnerId = ownerId, Role = XAiChatRole.User, CreatedOn = DateTime.UtcNow, - ConversationId = conversationId, + ConversationId = conversationId.Value, ConversationTitle = conversation.Title }; - // - // Attached Uploaded File Id's as Meta Data ... - if (uploadedFiles.HasChild()) - { - // - var fileIds = uploadedFiles.Select(f => f.Id).ToList(); - promptMessage.MetaDatas = new Dictionary - { - { XAiServiceConstants.XMetaDataFileIdsIdentifier, fileIds } - }.ToJSON(); - } - // // Save Prompt Message ... promptMessage = await dataProvider.AddMessage( item: promptMessage, connectionId: connectionId, - conversationId: conversationId, + conversationId: conversationId.Value, cancellationToken: cancellationToken ); - // - // Since Prompt Message Has Id now, we can Attach Uploaded Files to it ... - IList fileContents = []; - if (uploadedFiles.HasChild()) - { - // - foreach (var uf in uploadedFiles) - { - // - try - { - // - // Add Reference File to Prompt Message ... - await fileProvider.AddReference( - id: uf.Id, - userInfo: userInfo, - connectionId: connectionId, - forProvidedId: promptMessage.Id, - cancellationToken: cancellationToken, - providedFor: XAiServiceConstants.XAiMessageFilesIdentifier - ); - - // - // Handle File Content Extraction and Attach to Prompt Message ... - var fileDescriptor = await fileProvider.GetFileDescriptor( - id: uf.Id, - cancellationToken: cancellationToken - ); - if (fileDescriptor == null || fileDescriptor.Stream == null) - { - continue; - } - - // - var extractionResult = await fileContentExtractor.ExtractRichAsync( - fileStream: fileDescriptor.Stream, - fileName: uf.FileName ?? uf.Name, - mimeType: fileDescriptor.MIMEType, - cancellationToken: cancellationToken - ); - if (extractionResult.IsValid()) - { - // - var contents = extractionResult.ToAIContents(); - fileContents = [.. fileContents, .. contents]; - - // - // ذخیره Metadata برای ردیابی - logger.LogInformation( - "File {FileName} extracted successfully. Text: {HasText}, Images: {ImageCount}, Fallback: {UsedFallback}", - uf.FileName, - !string.IsNullOrEmpty(extractionResult.Text), - extractionResult.Images.Count, - extractionResult.UsedImageFallback - ); - } - - // - fileDescriptor.Stream.Dispose(); - } - catch (Exception ex) - { - logger.LogError(ex, "Failed to extract content from file: {FileName}", uf.FileName); - } - } - } - // // Converts to ChatMessage ... var promptChatMessage = promptMessage - .ToChatMessages(fileContents); + .ToChatMessages(additionalContents: []); // // Ask Questions From LLM ... @@ -1108,13 +998,13 @@ namespace xAiApi.Providers OwnerId = ownerId, CreatedOn = DateTime.UtcNow, Role = XAiChatRole.Assistant, - ConversationId = conversationId, + ConversationId = conversationId.Value, ConversationTitle = conversation.Title }; result = await dataProvider.AddMessage( item: result, connectionId: connectionId, - conversationId: conversationId, + conversationId: conversationId.Value, cancellationToken: cancellationToken ); @@ -1330,11 +1220,13 @@ namespace xAiApi.Providers /// /// /// + /// /// /// private async Task> PrepareMemory( XAiProjectDto project, IEnumerable messages, + IEnumerable context = null, CancellationToken cancellationToken = default ) { @@ -1343,35 +1235,37 @@ namespace xAiApi.Providers // // Retrieve Introduction Prompt ... + var ragPrompt = configuration.GetPrompt(XAiApiConstants.XAiApiRagPromptName); var introductionPrompt = configuration.GetPrompt(XAiApiConstants.XAiApiIntroductionPromptName); - if (introductionPrompt.IsNullOrEmpty()) + if (ragPrompt.IsNullOrEmpty() || + introductionPrompt.IsNullOrEmpty() + ) { XException.InvalidData.Throw(); } // - var introductionMessage = new ChatMessage( - role: ChatRole.System, - content: introductionPrompt - ); - - // - result.Add(introductionMessage); + var contextBlock = BuildContextBlock(context); + var systemText = + $"{introductionPrompt}{Environment.NewLine}{Environment.NewLine}" + + $"{ragPrompt}{Environment.NewLine}{Environment.NewLine}" + + $"Context:{Environment.NewLine}{contextBlock}"; // + // Apply Project Prompt as System Text ... if (!project.IsNullOrDefault() && !project.Prompt.IsNullOrEmpty()) { - // - // TODO: Handle Project Files Here ... - var projectMessage = new ChatMessage( - role: ChatRole.System, - contents: [new TextContent(project.Prompt)] - ); - result.Add(projectMessage); + systemText += $"Project:{Environment.NewLine}{project.Prompt}"; } // + // Add System Message ... + result + .Add(new ChatMessage(ChatRole.System, systemText)); + + // + // Attach Message ... if (messages.HasChild()) { // @@ -1386,6 +1280,56 @@ namespace xAiApi.Providers return result; } + /// + /// Convert Context Chunks to a Numbered Text Block ... + /// + /// + /// + private 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; + } + /// /// Ask Quetion from LLM ... /// diff --git a/Providers/XDefaultEmbeddingService.cs b/Providers/XAiEmbeddingService.cs similarity index 70% rename from Providers/XDefaultEmbeddingService.cs rename to Providers/XAiEmbeddingService.cs index dd5d2dc..d7817ce 100644 --- a/Providers/XDefaultEmbeddingService.cs +++ b/Providers/XAiEmbeddingService.cs @@ -1,25 +1,22 @@ using xAiApi.Constants; using xAiApi.Interfaces; +using xCommons.Providers; using xAiModels.Interfaces; using xAiApi.Configurations; -using xFileService.Interfaces; using Microsoft.Extensions.Logging; using xAiApi.Interfaces.Extractors; -using xCommons.Providers; namespace xAiApi.Providers { - public class XDefaultEmbeddingService : XAiEmbeddingServiceBase, IXDefaultEmbeddingService + public class XAiEmbeddingService : XAiEmbeddingServiceBase, IXAiEmbeddingService { - public XDefaultEmbeddingService( - IXFileProvider fileProvider, + public XAiEmbeddingService( IXAiDataProvider dataProvider, XAiApiConfiguration configuration, + ILogger logger, XValidationProvider validationProvider, - ILogger logger, IXFileContentExtractor fileContentExtractor ) : base( - fileProvider, dataProvider, configuration, validationProvider, diff --git a/Providers/XAiEmbeddingServiceBase.cs b/Providers/XAiEmbeddingServiceBase.cs index 6eab8e3..4bfd753 100644 --- a/Providers/XAiEmbeddingServiceBase.cs +++ b/Providers/XAiEmbeddingServiceBase.cs @@ -17,7 +17,6 @@ using xAiModels.Interfaces; using xAiApi.Configurations; using xExceptions.Constants; using System.Threading.Tasks; -using xFileService.Interfaces; using Microsoft.Extensions.AI; using System.Collections.Generic; using Microsoft.Extensions.Logging; @@ -29,28 +28,23 @@ namespace xAiApi.Providers /// /// Base Embedding Provider Service ... /// - public abstract class XAiEmbeddingServiceBase : XAIServiceBase, IXAiEmbeddingServiceBase + public abstract class XAiEmbeddingServiceBase : IXAiEmbeddingServiceBase { - private readonly IXFileProvider fileProvider; + private readonly string embeddingModelName; private readonly XAiModelDescriptor descriptor; + private readonly IXAiDataProvider dataProvider; + private readonly XAiApiConfiguration configuration; + private readonly XValidationProvider validationProvider; private readonly ILogger logger; + private readonly IXFileContentExtractor fileContentExtractor; protected XAiEmbeddingServiceBase( - IXFileProvider fileProvider, IXAiDataProvider dataProvider, XAiApiConfiguration configuration, XValidationProvider validationProvider, ILogger logger, IXFileContentExtractor fileContentExtractor, string embeddingModelName = XAiApiConstants.XAiEmbeddingModelName - ) : base( - fileProvider, - dataProvider, - logger, - configuration, - validationProvider, - fileContentExtractor, - null ) { // @@ -61,10 +55,14 @@ namespace xAiApi.Providers XException.InvalidConfiguration.Throw(); } - this.fileProvider = fileProvider; + this.dataProvider = dataProvider; + this.configuration = configuration; + this.validationProvider = validationProvider; // this.logger = logger; + this.fileContentExtractor = fileContentExtractor; + this.embeddingModelName = embeddingModelName; } /// diff --git a/Providers/XAiRAGService.cs b/Providers/XAiRAGService.cs index ebe9c5e..d0b5c59 100644 --- a/Providers/XAiRAGService.cs +++ b/Providers/XAiRAGService.cs @@ -2,10 +2,10 @@ using System; using System.IO; using System.Linq; using xAiApi.Models; -using System.Threading; using xIdentityHelper; -using xAiApi.Constants; +using System.Threading; using xAiApi.Interfaces; +using xAiModels.Constants; using xCommons.Extensions; using xAiModels.Interfaces; using xAiApi.Configurations; @@ -18,8 +18,6 @@ using Microsoft.AspNetCore.Http; using System.Collections.Generic; using Microsoft.Extensions.Logging; using xAiApi.Interfaces.Extractors; -using System.Runtime.CompilerServices; -using xAiModels.Constants; namespace xAiApi.Providers { @@ -36,11 +34,10 @@ namespace xAiApi.Providers { 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 IXAiEmbeddingService embeddingService; private readonly IXFileContentExtractor fileContentExtractor; /// @@ -51,17 +48,15 @@ namespace xAiApi.Providers public XAiRAGService( IXTextChunker textChunker, IXFileProvider fileProvider, - IXDefaultAiService aiService, IXAiDataProvider dataProvider, ILogger logger, XAiApiConfiguration configuration, - IXDefaultEmbeddingService embeddingService, + IXAiEmbeddingService embeddingService, IXFileContentExtractor fileContentExtractor ) { // this.logger = logger; - this.aiService = aiService; this.textChunker = textChunker; this.fileProvider = fileProvider; this.dataProvider = dataProvider; @@ -201,13 +196,28 @@ namespace xAiApi.Providers // // Handle File Save ... - await fileProvider.Upload( + var uploadedFile = await fileProvider.Upload( file: file, userInfo: userInfo, connectionId: connectionId, cancellationToken: cancellationToken ); + // + // Add Reference File to Prompt Message ... + if (scope.ScopeId.HasValue) + { + // + await fileProvider.AddReference( + userInfo: userInfo, + id: uploadedFile.Id, + connectionId: connectionId, + cancellationToken: cancellationToken, + providedFor: scope.Scope.GetStringValue(), + forProvidedId: scope.ScopeId.Value.ToString() + ); + } + // // Embed in Batches ... var vectors = await EmbedChunks( @@ -360,123 +370,6 @@ namespace xAiApi.Providers // return result; } - - /// - /// Ask a Question with RAG (Retrieve from DB then Generate) ... - /// - /// - /// - /// - /// - public async Task AskWithRAGAsync( - XAiKnowledgeAskRequest request, - XUserClaimsInfoDto userInfo = null, - CancellationToken cancellationToken = default - ) - { - // - // Retrieve (Validates Request) ... - var context = await RetrieveAsync( - request: request, - userInfo: userInfo, - 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 ... - /// First Item Carries Sources, Next Items Carry Text Deltas, Last Item has IsFinal = true ... - /// - /// - /// - /// - /// - public async IAsyncEnumerable AskWithRAGAsEnumerable( - XAiKnowledgeAskRequest request, - XUserClaimsInfoDto userInfo = null, - [EnumeratorCancellation] - CancellationToken cancellationToken = default - ) - { - // - // Retrieve (Validates Request) ... - var context = await RetrieveAsync( - request: request, - userInfo: userInfo, - 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 // @@ -701,12 +594,125 @@ namespace xAiApi.Providers } #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, "Knowledge: Extraction Failed for {FileName}", file.FileName); + return null; + } + } + + /// + /// Embed Chunks in Batches and Build Vectors (with Scope Metadata) ... + /// + private async Task> EmbedChunks( + XAiKnowledgeScopeDescriptor scope, + IList chunks, + string type, + 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 + { + // + Type = type, + Text = chunk.Text, + Embedding = embeddings[i], + Identifier = chunk.Identifier, + Metadata = new Dictionary + { + [rag.MetadataFileName] = fileName, + [rag.MetadataMimeType] = mimeType, + [rag.MetadataChunkIndex] = chunk.Index.ToString(), + [XAiModelsConstants.XAiKnowledgeMetadataType] = type, + [XAiModelsConstants.XAiKnowledgeMetadataOwnerId] = ownerId, + [XAiModelsConstants.XAiKnowledgeMetadataScope] = scope.Scope.ToString(), + [XAiModelsConstants.XAiKnowledgeMetadataScopeId] = scope.ScopeId?.ToString("D") ?? string.Empty, + [XAiModelsConstants.XAiKnowledgeMetadataIngestedAtUtc] = ingestedAtUtc + } + }); + } + } + + // + return result; + } + // #region Scope ... /// /// Normalize Scope (Null => User, Clear ScopeId for User/Global, Require ScopeId for Project/Conversation) ... /// - private static XAiKnowledgeScopeDescriptor NormalizeScope(XAiKnowledgeScopeDescriptor scope) + private XAiKnowledgeScopeDescriptor NormalizeScope(XAiKnowledgeScopeDescriptor scope) { // var result = scope ?? XAiKnowledgeScopeDescriptor.User(); @@ -916,7 +922,10 @@ namespace xAiApi.Providers /// Document Chunk Prefix: "{scopePrefix}{fileName}#" ... /// Separator Suffix Prevents "a.pdf" from Matching "a.pdf.bak" ... /// - private string GetDocumentChunkPrefix(string scopePrefix, string fileName) + private string GetDocumentChunkPrefix( + string scopePrefix, + string fileName + ) { return $"{scopePrefix}{fileName}{configuration.TextChunker.ChunkIdentifierSeparator}"; } @@ -1005,120 +1014,7 @@ namespace xAiApi.Providers // 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, "Knowledge: Extraction Failed for {FileName}", file.FileName); - return null; - } - } - - /// - /// Embed Chunks in Batches and Build Vectors (with Scope Metadata) ... - /// - private async Task> EmbedChunks( - XAiKnowledgeScopeDescriptor scope, - IList chunks, - string type, - 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 - { - // - Type = type, - Text = chunk.Text, - Embedding = embeddings[i], - Identifier = chunk.Identifier, - Metadata = new Dictionary - { - [rag.MetadataFileName] = fileName, - [rag.MetadataMimeType] = mimeType, - [rag.MetadataChunkIndex] = chunk.Index.ToString(), - [XAiModelsConstants.XAiKnowledgeMetadataType] = type, - [XAiModelsConstants.XAiKnowledgeMetadataOwnerId] = ownerId, - [XAiModelsConstants.XAiKnowledgeMetadataScope] = scope.Scope.ToString(), - [XAiModelsConstants.XAiKnowledgeMetadataScopeId] = scope.ScopeId?.ToString("D") ?? string.Empty, - [XAiModelsConstants.XAiKnowledgeMetadataIngestedAtUtc] = ingestedAtUtc - } - }); - } - } - - // - return result; - } + #endregion #endregion } } diff --git a/Providers/XDefaultAiService.cs b/Providers/XDefaultAiService.cs index dd84fc9..1961cea 100644 --- a/Providers/XDefaultAiService.cs +++ b/Providers/XDefaultAiService.cs @@ -3,7 +3,6 @@ using xAiApi.Interfaces; using xCommons.Providers; using xAiModels.Interfaces; using xAiApi.Configurations; -using xFileService.Interfaces; using Microsoft.Extensions.Logging; using xAiApi.Interfaces.Extractors; @@ -12,14 +11,14 @@ namespace xAiApi.Providers public class XDefaultAiService : XAIServiceBase, IXDefaultAiService { public XDefaultAiService( - IXFileProvider fileProvider, + IXAiRAGService ragProvider, IXAiDataProvider dataProvider, ILogger logger, XAiApiConfiguration configuration, XValidationProvider validationProvider, IXFileContentExtractor fileContentExtractor ) : base( - fileProvider, + ragProvider, dataProvider, logger, configuration, diff --git a/Providers/XDefaultThinkingAiService.cs b/Providers/XDefaultThinkingAiService.cs index 30caada..1f430ed 100644 --- a/Providers/XDefaultThinkingAiService.cs +++ b/Providers/XDefaultThinkingAiService.cs @@ -4,7 +4,6 @@ using xCommons.Providers; using xAiModels.Interfaces; using xAiApi.Configurations; using Microsoft.Extensions.AI; -using xFileService.Interfaces; using Microsoft.Extensions.Logging; using xAiApi.Interfaces.Extractors; @@ -13,7 +12,7 @@ namespace xAiApi.Providers public class XDefaultThinkingAiService : XAIServiceBase, IXDefaultThinkingAiService { public XDefaultThinkingAiService( - IXFileProvider fileProvider, + IXAiRAGService ragProvider, IXAiDataProvider dataProvider, ILogger logger, XAiApiConfiguration configuration, @@ -22,7 +21,7 @@ namespace xAiApi.Providers ReasoningEffort effort = ReasoningEffort.Medium, ReasoningOutput output = ReasoningOutput.Full ) : base( - fileProvider, + ragProvider, dataProvider, logger, configuration, diff --git a/Startup.cs b/Startup.cs index 62e1da5..c094aaf 100644 --- a/Startup.cs +++ b/Startup.cs @@ -196,6 +196,10 @@ namespace xAiApi // Register Chat With Documents Services (Text Chunker + In-Memory Vector Store) ... services.AddXAiChatWithDocuments(); + // + // Persistent RAG (Knowledge over XAiVector Table) ... + services.AddXRagService(); + // // Register Default AI Services ... services.AddXAiServices();