From fa1014bf20e2ad4fb8e9823c2221a19799449cd2 Mon Sep 17 00:00:00 2001 From: Hadi Khazaee Asl Date: Sun, 1 Nov 2026 22:36:20 +0330 Subject: [PATCH] Refactoring Services ... --- Controllers/ChatWithDocumentsController.cs | 10 +- Controllers/XAiServiceControllerBase.cs | 140 +++++++++++- Interfaces/IXAiRAGService.cs | 2 + Interfaces/IXAiServiceBase.cs | 50 ++++- Interfaces/IXAiServiceControllerBase.cs | 214 ------------------ Providers/XAIServiceBase.cs | 245 +++++++++++++++++++-- Providers/XAiRAGService.cs | 26 ++- 7 files changed, 434 insertions(+), 253 deletions(-) delete mode 100644 Interfaces/IXAiServiceControllerBase.cs diff --git a/Controllers/ChatWithDocumentsController.cs b/Controllers/ChatWithDocumentsController.cs index c7df8bd..9c64eee 100644 --- a/Controllers/ChatWithDocumentsController.cs +++ b/Controllers/ChatWithDocumentsController.cs @@ -285,9 +285,10 @@ namespace xAiApi.Controllers // // Generate ... - result.Answer = await aiService.AskWithContextAsync( - prompt: request.Prompt, + result.Answer = await aiService.AskTextByContextAsync( context: context, + userInfo: userInfo, + prompt: request.Prompt, cancellationToken: cancellationToken ); @@ -367,9 +368,10 @@ namespace xAiApi.Controllers // // Stream Deltas ... - var enumerable = aiService.AskWithContextAsEnumerable( - prompt: request.Prompt, + var enumerable = aiService.AskTextByContextAsEnumerable( context: context, + userInfo: userInfo, + prompt: request.Prompt, cancellationToken: cancellationToken ); await foreach (var delta in enumerable) diff --git a/Controllers/XAiServiceControllerBase.cs b/Controllers/XAiServiceControllerBase.cs index 0da435c..4f8dc50 100644 --- a/Controllers/XAiServiceControllerBase.cs +++ b/Controllers/XAiServiceControllerBase.cs @@ -25,7 +25,7 @@ namespace xAiApi.Controllers { [Authorize] [Route("[controller]")] - public abstract class XAiServiceControllerBase : XBaseIdentityApiV1Controller, IXAiServiceControllerBase + public abstract class XAiServiceControllerBase : XBaseIdentityApiV1Controller where TAiService : IXAiServiceBase { private readonly TAiService aiService; @@ -161,6 +161,136 @@ namespace xAiApi.Controllers } } + /// + /// Ask a Question By Rag Retrive From Knowledge ... + /// + /// + /// + /// + [HttpGet("AskTextFromKnowledge")] + [Authorize(Policy = XPolicies.EnabledUser)] + public virtual async Task> AskTextFromKnowledge( + [FromQuery] XAiResponseRequest request, + CancellationToken cancellationToken = default + ) + { + // + try + { + // + // Validate ... + if (!request.IsValid()) + { + XException.InvalidArgs.Throw(); + } + + // + var userInfo = await GetUserInfo(); + var connectionId = GetConnectionId(); + + // + var result = await aiService.AskTextFromKnowledgeAsync( + topK: request.TopK, + userInfo: userInfo, + prompt: request.Prompt, + minScore: request.MinScore, + cancellationToken: cancellationToken + ); + + // + return Ok(result); + } + catch (Exception ex) + { + // + var result = GetExceptionActionResult(ex); + return result; + } + } + + /// + /// Ask a Question By Rag Retrive From Knowledge and Stream Response ... + /// + /// + /// + /// + [HttpGet("AskTextFromKnowledgeStream")] + [Authorize(Policy = XPolicies.EnabledUser)] + public virtual async Task AskTextFromKnowledgeStream( + [FromQuery] XAiResponseRequest request, + CancellationToken cancellationToken = default + ) + { + // + // Validate (before Stream Starts -> Proper Http Error) ... + if (!request.IsValid()) + { + await WriteStreamValidationError(); + return; + } + + // + try + { + // + var userInfo = await GetUserInfo(); + var connectionId = GetConnectionId(); + + // + // Configure SSE Response ... + Response.PrepareSseResponse(); + + // + var enumerable = aiService.AskTextFromKnowledgeAsEnumerable( + topK: request.TopK, + userInfo: userInfo, + prompt: request.Prompt, + minScore: request.MinScore, + cancellationToken: cancellationToken + ); + + // + // Format: data: {json}\n\n + await foreach (var resp in enumerable) + { + // + // Skip Empty Responses ... + if (resp.IsNullOrDefault()) + { + continue; + } + + // + await Response.WriteSseEventAsync( + data: resp, + cancellationToken: cancellationToken + ); + } + + // + await Response.WriteSseDoneAsync(cancellationToken); + } + catch (Exception ex) when (ex.IsClientCancellation(cancellationToken)) + { + // Client Disconnected ... + } + catch (Exception ex) + { + // + Logger.LogError(ex, "AskStream Failed ..."); + if (!Response.HasStarted) + { + // + var result = GetExceptionActionResult(ex); + await result.ExecuteResultAsync(ControllerContext); + return; + } + + // + await Response.WriteSseErrorAsync(ex.Message); + } + } + /// /// Ask Question and Get Response ... /// @@ -169,7 +299,7 @@ namespace xAiApi.Controllers /// [HttpPost("Ask")] [Authorize(Policy = XPolicies.EnabledUser)] - public async Task> Ask( + public virtual async Task> Ask( [FromBody] XAiResponseRequest request, CancellationToken cancellationToken = default ) @@ -220,7 +350,7 @@ namespace xAiApi.Controllers /// [HttpPost("AskStream")] [Authorize(Policy = XPolicies.EnabledUser)] - public async Task AskStream( + public virtual async Task AskStream( [FromBody] XAiResponseRequest request, CancellationToken cancellationToken = default ) @@ -308,7 +438,7 @@ namespace xAiApi.Controllers [HttpPost("AskWithFiles")] [Consumes("multipart/form-data")] [Authorize(Policy = XPolicies.EnabledUser)] - public async Task> AskWithFiles( + public virtual async Task> AskWithFiles( [FromForm] XAiResponseRequest request, [FromForm] IFormFileCollection files, CancellationToken cancellationToken = default @@ -360,7 +490,7 @@ namespace xAiApi.Controllers [HttpPost("AskWithFilesStream")] [Consumes("multipart/form-data")] [Authorize(Policy = XPolicies.EnabledUser)] - public async Task AskWithFilesStream( + public virtual async Task AskWithFilesStream( [FromForm] XAiResponseRequest request, [FromForm] IFormFileCollection files, CancellationToken cancellationToken = default diff --git a/Interfaces/IXAiRAGService.cs b/Interfaces/IXAiRAGService.cs index 824f317..d474d0b 100644 --- a/Interfaces/IXAiRAGService.cs +++ b/Interfaces/IXAiRAGService.cs @@ -67,12 +67,14 @@ namespace xAiApi.Interfaces /// /// Target Scope (Null = User Scope) /// + /// /// /// Count of Removed Vectors Task RemoveDocumentAsync( string fileName, XAiKnowledgeScopeDescriptor scope = null, XUserClaimsInfoDto userInfo = null, + string connectionId = null, CancellationToken cancellationToken = default ); diff --git a/Interfaces/IXAiServiceBase.cs b/Interfaces/IXAiServiceBase.cs index f558c3d..1477381 100644 --- a/Interfaces/IXAiServiceBase.cs +++ b/Interfaces/IXAiServiceBase.cs @@ -51,28 +51,66 @@ namespace xAiApi.Interfaces ); /// - /// Ask a Question using Provided Context Chunks (RAG) without Persisting ... + /// Ask a Question By Providing Vector Search Result ... /// /// /// + /// /// /// - Task AskWithContextAsync( + Task AskTextByContextAsync( string prompt, - IEnumerable context, + IList context = null, + XUserClaimsInfoDto userInfo = null, CancellationToken cancellationToken = default ); /// - /// Ask a Question using Provided Context Chunks (RAG) and Stream Response ... + /// Ask a Question By By Providing Vector Search Result and Stream Response ... /// /// /// + /// /// /// - IAsyncEnumerable AskWithContextAsEnumerable( + IAsyncEnumerable AskTextByContextAsEnumerable( string prompt, - IEnumerable context, + IList context = null, + XUserClaimsInfoDto userInfo = null, + CancellationToken cancellationToken = default + ); + + /// + /// Ask a Question By Rag Retrive From Knowledge ... + /// + /// + /// + /// + /// + /// + /// + Task AskTextFromKnowledgeAsync( + string prompt, + int? topK = null, + float? minScore = null, + XUserClaimsInfoDto userInfo = null, + CancellationToken cancellationToken = default + ); + + /// + /// Ask a Question By Rag Retrive From Knowledge and Stream Response ... + /// + /// + /// + /// + /// + /// + /// + IAsyncEnumerable AskTextFromKnowledgeAsEnumerable( + string prompt, + int? topK = null, + float? minScore = null, + XUserClaimsInfoDto userInfo = null, CancellationToken cancellationToken = default ); diff --git a/Interfaces/IXAiServiceControllerBase.cs b/Interfaces/IXAiServiceControllerBase.cs deleted file mode 100644 index 1990353..0000000 --- a/Interfaces/IXAiServiceControllerBase.cs +++ /dev/null @@ -1,214 +0,0 @@ -using System; -using xModels.Dtos; -using System.Threading; -using xAiModels.Models; -using xAiModels.Models.Dtos; -using System.Threading.Tasks; -using Microsoft.AspNetCore.Mvc; -using Microsoft.AspNetCore.Http; -using System.Collections.Generic; - -namespace xAiApi.Interfaces -{ - public interface IXAiServiceControllerBase - { - // - #region Actions ... - /// - /// Ask Question and Get Response ... - /// - /// - /// - /// - [HttpGet("AskText")] - Task> AskText( - [FromQuery] string question, - CancellationToken cancellationToken = default - ); - - /// - /// Ask Question and Get Response Stream ... - /// - /// - /// - /// - [HttpGet("AskTextStream")] - Task AskTextStream( - [FromQuery] string question, - CancellationToken cancellationToken = default - ); - #endregion - - // - #region Loaders ... - /// - /// Retrieve AI Projects ... - /// - /// - /// - /// - [HttpGet("Projects")] - Task>> LoadProjects( - [FromQuery] bool includeDefaults = false, - CancellationToken cancellationToken = default - ); - - /// - /// Retrieve Specified AI Project's Conversations ... - /// - /// - /// - /// - [HttpGet("Projects/{projectId}/Conversations")] - Task>> LoadConversations( - [FromRoute] Guid projectId, - CancellationToken cancellationToken = default - ); - - /// - /// Retrieve Specified AI Conversation's Messages ... - /// - /// - /// - /// - [HttpGet("Conversations/{conversationId}/Messages")] - Task>> LoadMessages( - [FromRoute] Guid conversationId, - CancellationToken cancellationToken = default - ); - #endregion - - // - #region Queries ... - /// - /// Query Projects ... - /// - /// - /// - /// - /// - /// - [HttpGet("Projects/Query")] - Task>> QueryProjects( - [FromQuery] XQuery query, - CancellationToken cancellationToken = default - ); - - /// - /// Query Conversations ... - /// - /// - /// - /// - /// - [HttpGet("Projects/{projectId}/Conversations/Query")] - Task>> QueryConversations( - [FromRoute] Guid projectId, - [FromQuery] XQuery query, - CancellationToken cancellationToken = default - ); - - /// - /// Query Messages ... - /// - /// - /// - /// - /// - [HttpGet("Conversations/{conversationId}/Messages/Query")] - Task>> QueryMessages( - [FromRoute] Guid conversationId, - [FromQuery] XQuery query, - CancellationToken cancellationToken = default - ); - #endregion - - // - #region Creators ... - /// - /// Create an AI Project ... - /// - /// - /// - /// - [HttpPost("Projects")] - Task> CreateProject( - [FromBody] XAiProjectDto item, - CancellationToken cancellationToken = default - ); - - /// - /// Create an AI Conversation ... - /// - /// - /// - /// - /// - [HttpPost("Projects/{projectId}/Conversations")] - Task> CreateConversation( - [FromRoute] Guid projectId, - [FromBody] XAiConversationDto item, - CancellationToken cancellationToken = default - ); - #endregion - - // - #region Content Extraction ... - /// - /// Extract Files Content ... - /// - /// - /// - /// - /// - [HttpPost("ExtractContent")] - [Consumes("multipart/form-data")] - Task> ExtractContent( - [FromForm] IFormFileCollection files, - [FromForm] string extractors = null, - CancellationToken cancellationToken = default - ); - #endregion - - // - #region Data Actions ... - /// - /// Ask Question and Get Response ... - /// - /// - /// - /// - [HttpPost("Ask")] - Task> Ask( - [FromBody] XAiResponseRequest request, - CancellationToken cancellationToken = default - ); - - /// - /// Ask Question and Get Response Stream ... - /// - /// - /// - /// - [HttpPost("AskStream")] - Task AskStream( - [FromBody] XAiResponseRequest request, - CancellationToken cancellationToken = default - ); - - /// - /// Ask Question with Files and Get Response ... - /// - /// - /// - /// - [HttpPost("AskWithFiles")] - [Consumes("multipart/form-data")] - Task> AskWithFiles( - [FromForm] XAiResponseRequest request, - [FromForm] IFormFileCollection files, - CancellationToken cancellationToken = default - ); - #endregion - } -} \ No newline at end of file diff --git a/Providers/XAIServiceBase.cs b/Providers/XAIServiceBase.cs index 1ab04ff..c76bdca 100644 --- a/Providers/XAIServiceBase.cs +++ b/Providers/XAIServiceBase.cs @@ -104,6 +104,7 @@ namespace xAiApi.Providers using var client = Descriptor.GetClient(); var history = GetHistory(prompt); var response = await client.GetResponseAsync( + options: Options, messages: history, cancellationToken: cancellationToken ); @@ -149,7 +150,7 @@ namespace xAiApi.Providers using var client = Descriptor.GetClient(); var history = GetHistory(prompt); var enumerable = client.GetStreamingResponseAsync( - options: null, + options: Options, messages: history ); @@ -169,29 +170,34 @@ namespace xAiApi.Providers } /// - /// Ask a Question using Provided Context Chunks (RAG) without Persisting ... + /// Ask a Question By Providing Vector Search Result ... /// /// /// + /// /// /// - public virtual async Task AskWithContextAsync( + public virtual async Task AskTextByContextAsync( string prompt, - IEnumerable context, + IList context = null, + XUserClaimsInfoDto userInfo = null, CancellationToken cancellationToken = default ) { // // Validate Args ... - if (prompt.IsNullOrEmpty()) - { - XException.InvalidArgs.Throw(); - } + validationProvider + .GroupValidationBuilder() + .AddNotEmpty(prompt) + .AddNotNull(userInfo) + .AddNotEmpty(userInfo.UserId) + .ValidateGroup(); // using var client = Descriptor.GetClient(); var history = GetHistory(prompt, context); var response = await client.GetResponseAsync( + options: Options, messages: history, cancellationToken: cancellationToken ); @@ -212,31 +218,219 @@ namespace xAiApi.Providers } /// - /// Ask a Question using Provided Context Chunks (RAG) and Stream Response ... + /// Ask a Question By By Providing Vector Search Result and Stream Response ... /// /// /// + /// /// /// - public virtual async IAsyncEnumerable AskWithContextAsEnumerable( + public virtual async IAsyncEnumerable AskTextByContextAsEnumerable( string prompt, - IEnumerable context, + IList context = null, + XUserClaimsInfoDto userInfo = null, [EnumeratorCancellation] CancellationToken cancellationToken = default ) { // // Validate Args ... - if (prompt.IsNullOrEmpty()) - { - XException.InvalidArgs.Throw(); - } + validationProvider + .GroupValidationBuilder() + .AddNotEmpty(prompt) + .AddNotNull(userInfo) + .AddNotEmpty(userInfo.UserId) + .ValidateGroup(); // using var client = Descriptor.GetClient(); var history = GetHistory(prompt, context); var enumerable = client.GetStreamingResponseAsync( - options: null, + options: Options, + messages: history, + cancellationToken: cancellationToken + ); + + // + await foreach (var res in enumerable) + { + // + if (cancellationToken.IsCancellationRequested) + { + yield break; + } + + // + yield return res.Text; + } + } + + /// + /// Ask a Question By Rag Retrive From Knowledge ... + /// + /// + /// + /// + /// + /// + /// + public virtual async Task AskTextFromKnowledgeAsync( + string prompt, + int? topK = null, + float? minScore = null, + XUserClaimsInfoDto userInfo = null, + CancellationToken cancellationToken = default + ) + { + // + // Validate Args ... + validationProvider + .GroupValidationBuilder() + .AddNotEmpty(prompt) + .AddNotNull(userInfo) + .AddNotEmpty(userInfo.UserId) + .ValidateGroup(); + + // + // Normalize ... + if (!topK.HasValue || + topK.Value < 1 || + topK.Value > configuration.RAGDescriptor.MaxTopK + ) + { + // + if (!topK.HasValue || + (topK.HasValue && topK.Value < 1)) + { + topK = configuration.RAGDescriptor.DefaultTopK; + } + else if (topK.HasValue && topK.Value > configuration.RAGDescriptor.MaxTopK) + { + topK = configuration.RAGDescriptor.MaxTopK; + } + } + if (!minScore.HasValue || + minScore.Value <= 0 || + minScore.Value > 1 + ) + { + minScore = configuration.RAGDescriptor.DefaultMinScore; + } + + // + // Prepare Knowledge Request ... + var knowledgeRequest = new XAiKnowledgeAskRequest + { + TopK = topK, + Prompt = prompt, + IncludeUser = true, + MinScore = minScore, + IncludeGlobal = true, + }; + var context = await ragProvider.RetrieveAsync( + userInfo: userInfo, + request: knowledgeRequest, + cancellationToken: cancellationToken + ); + + // + using var client = Descriptor.GetClient(); + var history = GetHistory(prompt, context); + var response = await client.GetResponseAsync( + options: Options, + messages: history, + cancellationToken: cancellationToken + ); + + // + // Validate Response ... + if (!response.IsValid()) + { + client.Dispose(); + XException.ActionFailed.Throw(); + } + + // + var result = response.Text; + + // + return result; + } + + /// + /// Ask a Question By Rag Retrive From Knowledge and Stream Response ... + /// + /// + /// + /// + /// + /// + /// + public virtual async IAsyncEnumerable AskTextFromKnowledgeAsEnumerable( + string prompt, + int? topK = null, + float? minScore = null, + XUserClaimsInfoDto userInfo = null, + [EnumeratorCancellation] + CancellationToken cancellationToken = default + ) + { + // + // Validate Args ... + validationProvider + .GroupValidationBuilder() + .AddNotEmpty(prompt) + .AddNotNull(userInfo) + .AddNotEmpty(userInfo.UserId) + .ValidateGroup(); + + // + // Normalize ... + if (!topK.HasValue || + topK.Value < 1 || + topK.Value > configuration.RAGDescriptor.MaxTopK + ) + { + // + if (!topK.HasValue || + (topK.HasValue && topK.Value < 1)) + { + topK = configuration.RAGDescriptor.DefaultTopK; + } + else if (topK.HasValue && topK.Value > configuration.RAGDescriptor.MaxTopK) + { + topK = configuration.RAGDescriptor.MaxTopK; + } + } + if (!minScore.HasValue || + minScore.Value <= 0 || + minScore.Value > 1 + ) + { + minScore = configuration.RAGDescriptor.DefaultMinScore; + } + + // + // Prepare Knowledge Request ... + var knowledgeRequest = new XAiKnowledgeAskRequest + { + TopK = topK, + Prompt = prompt, + IncludeUser = true, + MinScore = minScore, + IncludeGlobal = true, + }; + var context = await ragProvider.RetrieveAsync( + userInfo: userInfo, + request: knowledgeRequest, + cancellationToken: cancellationToken + ); + + // + using var client = Descriptor.GetClient(); + var history = GetHistory(prompt, context); + var enumerable = client.GetStreamingResponseAsync( + options: Options, messages: history, cancellationToken: cancellationToken ); @@ -1280,7 +1474,7 @@ namespace xAiApi.Providers /// /// /// - protected virtual IList GetHistory( + private IList GetHistory( string prompt, IEnumerable context ) @@ -1295,10 +1489,17 @@ namespace xAiApi.Providers // var contextBlock = BuildContextBlock(context); - var systemText = - $"{introductionPrompt}{Environment.NewLine}{Environment.NewLine}" + - $"{ragPrompt}{Environment.NewLine}{Environment.NewLine}" + - $"Context:{Environment.NewLine}{contextBlock}"; + var systemText = introductionPrompt; + if (context.HasChild() && + !contextBlock.IsNullOrEmpty() + ) + { + // + systemText = + $"{introductionPrompt}{Environment.NewLine}{Environment.NewLine}" + + $"{ragPrompt}{Environment.NewLine}{Environment.NewLine}" + + $"Context:{Environment.NewLine}{contextBlock}"; + } // List result = @@ -1347,7 +1548,7 @@ namespace xAiApi.Providers !contextBlock.IsNullOrEmpty()) { // - systemText = + systemText = $"{introductionPrompt}{Environment.NewLine}{Environment.NewLine}" + $"{ragPrompt}{Environment.NewLine}{Environment.NewLine}" + $"Context:{Environment.NewLine}{contextBlock}"; diff --git a/Providers/XAiRAGService.cs b/Providers/XAiRAGService.cs index bd79c6c..7a53118 100644 --- a/Providers/XAiRAGService.cs +++ b/Providers/XAiRAGService.cs @@ -447,12 +447,14 @@ namespace xAiApi.Providers /// /// /// + /// /// /// Count of Removed Vectors public async Task RemoveDocumentAsync( string fileName, XAiKnowledgeScopeDescriptor scope = null, XUserClaimsInfoDto userInfo = null, + string connectionId = null, CancellationToken cancellationToken = default ) { @@ -479,8 +481,28 @@ namespace xAiApi.Providers // // Remove Files using ... var file = await fileProvider.FindOne( - x => x.FileName == - ) + x => x.FileName + .Equals( + fileName, + StringComparison.InvariantCultureIgnoreCase) && + x.OwnerId + .Equals( + userInfo.UserId, + StringComparison.InvariantCultureIgnoreCase), + cancellationToken: cancellationToken + ); + + // + if (!file.IsNullOrDefault()) + { + // + await fileProvider.Remove( + id: file.Id, + userInfo: userInfo, + connectionId: connectionId, + cancellationToken: cancellationToken + ); + } } //