From 888f20ea6390f09a34253ecef320987304c2cbb3 Mon Sep 17 00:00:00 2001 From: Hadi Khazaee Asl Date: Fri, 30 Oct 2026 19:46:42 +0330 Subject: [PATCH] - Update submodule pointers: xAiApi, Modules/xAiModels; - Kanban: move "R&D about MCP Servers" to Test, check "Test Rag Documents by Chat", add "Adding MCP Support ..."; - Authenticate.json: refresh sample tokens/session and add ask samples; - Add Documents/Codes/*.BKP.cs (pre-refactor backups); - Add Documents/Docs/ChangeLogs/1405-08-08-v01.html and this file. --- Documents/Boards/xDashboard.kanban | 29 +- Documents/Codes/1.BKP.cs | 146 ++ Documents/Codes/KnowledgeController.BKP.cs | 369 +++++ Documents/Codes/XAIServiceBase.BKP.cs | 1459 ++++++++++++++++ Documents/Docs/ChangeLogs/1405-08-08-v01.html | 670 ++++++++ .../CommitMessage-1405-08-08-v01.txt | 90 + .../Docs/Developer/1405-08-08.Overview.html | 1466 +++++++++++++++++ ... => xDashboard-xAiApi-20261030_194031.txt} | 1060 +++++------- ... xDashboard-xAiModels-20261030_194032.txt} | 6 +- ...xDashboard-xAiService-20261030_194033.txt} | 0 Documents/Resources/Json/Authenticate.json | 29 +- Modules/xAiModels | 2 +- xAiApi | 2 +- 13 files changed, 4619 insertions(+), 709 deletions(-) create mode 100644 Documents/Codes/1.BKP.cs create mode 100644 Documents/Codes/KnowledgeController.BKP.cs create mode 100644 Documents/Codes/XAIServiceBase.BKP.cs create mode 100644 Documents/Docs/ChangeLogs/1405-08-08-v01.html create mode 100644 Documents/Docs/ChangeLogs/CommitMessage-1405-08-08-v01.txt create mode 100644 Documents/Docs/Developer/1405-08-08.Overview.html rename Documents/GeneratedContext/{xDashboard-xAiApi-20261029_200138.txt => xDashboard-xAiApi-20261030_194031.txt} (95%) rename Documents/GeneratedContext/{xDashboard-xAiModels-20261029_200138.txt => xDashboard-xAiModels-20261030_194032.txt} (99%) rename Documents/GeneratedContext/{xDashboard-xAiService-20261029_200139.txt => xDashboard-xAiService-20261030_194033.txt} (100%) diff --git a/Documents/Boards/xDashboard.kanban b/Documents/Boards/xDashboard.kanban index 8bebf88..ecea421 100644 --- a/Documents/Boards/xDashboard.kanban +++ b/Documents/Boards/xDashboard.kanban @@ -471,15 +471,6 @@ "labels": [], "checkboxes": [], "comments": [] - }, - { - "id": "7785aecc-0b27-4428-a50b-03c046c5a0d6", - "listId": "1706107f-ace2-4240-aa32-3d2031264a41", - "title": "R&D about MCP Servers and how i can Use them ?", - "description": "", - "labels": [], - "checkboxes": [], - "comments": [] } ] }, @@ -562,7 +553,7 @@ { "id": "5814763a-fb4f-45d6-bef4-730d67be00aa", "title": "Test Rag Documents by Chat ...", - "checked": false + "checked": true }, { "id": "51e10834-6ff5-4f29-8bda-70edf9f0206f", @@ -635,6 +626,15 @@ "labels": [], "checkboxes": [], "comments": [] + }, + { + "id": "affe9030-49a3-4937-813a-35f81189039c", + "listId": "171f43f3-ae73-49b7-9239-9f3fb695cc2b", + "title": "Adding MCP Support ...", + "description": "", + "labels": [], + "checkboxes": [], + "comments": [] } ] }, @@ -642,6 +642,15 @@ "id": "8c15334f-3b2e-4eca-999e-4c887cb628e9", "title": "Test", "cards": [ + { + "id": "7785aecc-0b27-4428-a50b-03c046c5a0d6", + "listId": "8c15334f-3b2e-4eca-999e-4c887cb628e9", + "title": "R&D about MCP Servers and how i can Use them ?", + "description": "", + "labels": [], + "checkboxes": [], + "comments": [] + }, { "id": "c4633423-da53-4942-a9b4-d5f23b5759b3", "listId": "8c15334f-3b2e-4eca-999e-4c887cb628e9", diff --git a/Documents/Codes/1.BKP.cs b/Documents/Codes/1.BKP.cs new file mode 100644 index 0000000..b99e3f4 --- /dev/null +++ b/Documents/Codes/1.BKP.cs @@ -0,0 +1,146 @@ + + /// + /// 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 + ); + + /// + /// 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 + }; + } + + diff --git a/Documents/Codes/KnowledgeController.BKP.cs b/Documents/Codes/KnowledgeController.BKP.cs new file mode 100644 index 0000000..80be2b2 --- /dev/null +++ b/Documents/Codes/KnowledgeController.BKP.cs @@ -0,0 +1,369 @@ +using System; +using xAiApi.Models; +using System.Threading; +using xAiApi.Interfaces; +using xCommons.Providers; +using xAiModels.Constants; +using xCommons.Extensions; +using xExceptions.Constants; +using System.Threading.Tasks; +using xHttpService.Extensions; +using xCommons.Configurations; +using Microsoft.AspNetCore.Mvc; +using Microsoft.AspNetCore.Http; +using System.Collections.Generic; +using xIdentityService.Interfaces; +using xIdentityService.Controllers; +using Microsoft.Extensions.Logging; +using Microsoft.AspNetCore.Authorization; + +namespace xAiApi.Controllers +{ + /// + /// Knowledge (Persistent RAG over XAiVector Table) Controller ... + /// Flow: Ingest Files -> Ask / AskStream (Retrieve from DB -> Generate) -> Documents / Delete + /// + [Authorize] + [Route("[controller]")] + public class KnowledgeController : XBaseIdentityApiV1Controller + { + /// + /// Persistent RAG Service ... + /// + private readonly IXAiRAGService ragService; + private readonly IXAiServiceBase aiServiceBase; + + public KnowledgeController( + IXAiRAGService ragService, + IXAiServiceBase aiServiceBase, + XAppConfiguration appConfiguration, + IXIdentityProvider identityProvider, + ILogger logger, + XValidationProvider validationProvider + ) : base(logger, appConfiguration, identityProvider, validationProvider) + { + // + this.ragService = ragService; + this.aiServiceBase = aiServiceBase; + } + + // + #region Ingest ... + /// + /// Ingest Files into a Knowledge Scope: + /// Extract -> Chunk -> Embed -> Store in XAiVector Table ... + /// + /// + /// Target Scope: User (default) / Project / Conversation / Global (Admin) + /// ProjectId or ConversationId (Required for Project / Conversation) + /// Optional Knowledge Type / Domain + /// Replace Previously Stored Vectors of Same File (default true) + /// + /// + [HttpPost("Ingest")] + [Consumes("multipart/form-data")] + public async Task> Ingest( + [FromForm] IFormFileCollection files, + [FromForm] XAiKnowledgeScope scope = XAiKnowledgeScope.Global, + [FromForm] Guid? scopeId = null, + [FromForm] string knowledgeType = null, + [FromForm] bool replaceExisting = true, + CancellationToken cancellationToken = default + ) + { + // + try + { + // + // Validate ... + if (!files.HasChild()) + { + XException.InvalidArgs.Throw(); + } + + // + var userInfo = await GetUserInfo(); + var connectionId = GetConnectionId(); + + // + var result = await ragService.IngestAsync( + files: files, + userInfo: userInfo, + connectionId: connectionId, + replaceExisting: replaceExisting, + cancellationToken: cancellationToken, + scope: BuildScope(scope, scopeId, knowledgeType) + ); + + // + return Ok(result); + } + catch (Exception ex) + { + // + var result = GetExceptionActionResult(ex); + return result; + } + } + #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 aiServiceBase.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 ... + /// + /// List Ingested Documents of a Knowledge Scope ... + /// + /// User (default) / Project / Conversation / Global + /// ProjectId or ConversationId (Required for Project / Conversation) + /// Optional Knowledge Type Filter + /// + /// + [HttpGet("Documents")] + public async Task>> Documents( + [FromQuery] XAiKnowledgeScope scope = XAiKnowledgeScope.User, + [FromQuery] Guid? scopeId = null, + [FromQuery] string knowledgeType = null, + CancellationToken cancellationToken = default + ) + { + // + try + { + // + var userInfo = await GetUserInfo(); + + // + var result = await ragService.LoadDocumentsAsync( + userInfo: userInfo, + cancellationToken: cancellationToken, + scope: BuildScope(scope, scopeId, knowledgeType) + ); + + // + return Ok(result); + } + catch (Exception ex) + { + // + var result = GetExceptionActionResult(ex); + return result; + } + } + + /// + /// Remove All Vectors of a Document in a Knowledge Scope ... + /// + /// + /// User (default) / Project / Conversation / Global (Admin) + /// ProjectId or ConversationId (Required for Project / Conversation) + /// + /// Count of Removed Vectors + [HttpDelete("Documents")] + public async Task> DeleteDocument( + [FromQuery] string fileName, + [FromQuery] XAiKnowledgeScope scope = XAiKnowledgeScope.User, + [FromQuery] Guid? scopeId = null, + CancellationToken cancellationToken = default + ) + { + // + try + { + // + // Validate ... + ValidationProvider.NotEmpty(fileName); + + // + var userInfo = await GetUserInfo(); + + // + var result = await ragService.RemoveDocumentAsync( + fileName: fileName, + userInfo: userInfo, + cancellationToken: cancellationToken, + scope: BuildScope(scope, scopeId, null) + ); + + // + return Ok(result); + } + catch (Exception ex) + { + // + var result = GetExceptionActionResult(ex); + return result; + } + } + #endregion + + // + #region Private ... + /// + /// Build Scope Descriptor from Request Params ... + /// + private XAiKnowledgeScopeDescriptor BuildScope( + XAiKnowledgeScope scope, + Guid? scopeId, + string knowledgeType + ) + { + // + var result = new XAiKnowledgeScopeDescriptor + { + Scope = scope, + ScopeId = scopeId, + Type = knowledgeType, + }; + + // + return result; + } + + /// + /// Write a SSE Event ... + /// + private Task WriteChunk( + XAiDocumentAnswerChunk chunk, + CancellationToken cancellationToken + ) + { + // + return Response.WriteSseEventAsync( + data: chunk, + cancellationToken: cancellationToken + ); + } + #endregion + } +} + diff --git a/Documents/Codes/XAIServiceBase.BKP.cs b/Documents/Codes/XAIServiceBase.BKP.cs new file mode 100644 index 0000000..2c0860b --- /dev/null +++ b/Documents/Codes/XAIServiceBase.BKP.cs @@ -0,0 +1,1459 @@ +using System; +using System.Linq; +using xModels.Dtos; +using System.Threading; +using xAiApi.Constants; +using xAiModels.Models; +using xAiApi.Interfaces; +using xAiApi.Extensions; +using xCommons.Providers; +using xCommons.Extensions; +using xAiModels.Constants; +using xAiModels.Interfaces; +using xAiModels.Extensions; +using xAiApi.Configurations; +using xExceptions.Constants; +using xAiModels.Models.Dtos; +using xAiService.Extensions; +using System.Threading.Tasks; +using xIdentityModels.Models; +using Microsoft.Extensions.AI; +using Microsoft.AspNetCore.Http; +using System.Collections.Generic; +using Microsoft.Extensions.Logging; +using xAiApi.Interfaces.Extractors; +using System.Runtime.CompilerServices; +using xAiApi.Models; + +namespace xAiApi.Providers +{ + /// + /// Base Ai Service ... + /// + public abstract class XAIServiceBase : IXAiServiceBase + { + /// + /// Chat Options ... + /// + public ChatOptions Options { get; } + + /// + /// Descriptor of Models which used in Service ... + /// + public XAiModelDescriptor Descriptor { get; } + + private readonly IXAiRAGService ragProvider; + private readonly IXAiDataProvider dataProvider; + private readonly ILogger logger; + private readonly XAiApiConfiguration configuration; + private readonly XValidationProvider validationProvider; + private readonly IXFileContentExtractor fileContentExtractor; + + protected XAIServiceBase( + IXAiRAGService ragProvider, + IXAiDataProvider dataProvider, + ILogger logger, + XAiApiConfiguration configuration, + XValidationProvider validationProvider, + IXFileContentExtractor fileContentExtractor, + string model = null + ) + { + // + this.logger = logger; + this.ragProvider = ragProvider; + this.dataProvider = dataProvider; + this.configuration = configuration; + this.validationProvider = validationProvider; + this.fileContentExtractor = fileContentExtractor; + + // + // Prepare Embedding Model Descriptor ... + Descriptor = configuration.GetModel(model); + if (!Descriptor.IsValid()) + { + XException.InvalidConfiguration.Throw(); + } + + // + // Prepare Chat Options based On Tools ... + Options = new ChatOptions(); + } + + // + #region Actions ... + /// + /// Base Method for Communicate with LLM ... + /// + /// + /// + /// + public virtual async Task AskTextAsync( + string prompt, + CancellationToken cancellationToken = default + ) + { + // + // Check Prompt Exists ... + if (prompt.IsNullOrEmpty()) + { + XException.InvalidArgs.Throw(); + } + + // + using var client = Descriptor.GetClient(); + var history = GetHistory(prompt); + var response = await client.GetResponseAsync( + messages: history, + cancellationToken: cancellationToken + ); + + // + // Validate Response ... + if (!response.IsValid()) + { + // + // Dispose Client ... + client.Dispose(); + XException.ActionFailed.Throw(); + } + + // + // Retrieve Response Text ... + var result = response.Text; + + // + return result; + } + + /// + /// Base Method for Communicate with LLM ... + /// + /// + /// + /// + public virtual async IAsyncEnumerable AskTextAsEnumerable( + string prompt, + [EnumeratorCancellation] + CancellationToken cancellationToken = default + ) + { + // + // Check Prompt Exists ... + if (prompt.IsNullOrEmpty()) + { + XException.InvalidArgs.Throw(); + } + + // + using var client = Descriptor.GetClient(); + var history = GetHistory(prompt); + var enumerable = client.GetStreamingResponseAsync( + options: null, + messages: history + ); + + // + await foreach (var res in enumerable) + { + // + // Cancellation Token ... + if (cancellationToken.IsCancellationRequested) + { + yield break; + } + + // + yield return res.Text; + } + } + + /// + /// Prepare a Message History List for LLM Communication based on Prompt ... + /// + /// + /// + /// + public virtual IList GetHistory( + string prompt = null, + bool forcePrompt = true + ) + { + // + // Validate Args ... + if (prompt.IsNullOrEmpty()) + { + XException.InvalidArgs.Throw(); + } + + // + // User Prompt ... + var promptMessage = new ChatMessage( + ChatRole.User, + prompt + ); + + // + // Preparing Introduction Prompt ... + var introductionPrompt = new ChatMessage( + ChatRole.System, + configuration.GetPrompt() + ); + + // + List result = + [ + introductionPrompt, + ]; + if (forcePrompt && + prompt is not null && + !string.IsNullOrWhiteSpace(prompt)) + { + result.Add(promptMessage); + } + + // + return result; + } + + /// + /// Prepare a Message History List for LLM Communication based on Prompt ... + /// + /// + /// + /// + public virtual IList GetHistory( + ChatMessage message = null, + bool forceMessage = true + ) + { + // + // Preparing Introduction Prompt ... + var introductionPrompt = new ChatMessage( + ChatRole.System, + configuration.GetPrompt(XAiApiConstants.XAiApiIntroductionPromptName) + ); + + // + List result = + [ + introductionPrompt, + ]; + if (forceMessage && + !message.IsNullOrDefault()) + { + result.Add(message); + } + + // + return result; + } + #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 + ChatWithDocuments Prompt + Context Block] + [User: Prompt] ... + /// + /// + /// + /// + protected virtual IList GetContextHistory( + string prompt, + IEnumerable context + ) + { + // + var introductionPrompt = configuration.GetPrompt(); + var ragPrompt = configuration.GetPrompt(configuration.RAGDescriptor.PromptName); + if (ragPrompt.IsNullOrEmpty()) + { + XException.InvalidConfiguration.Throw(); + } + + // + var contextBlock = BuildContextBlock(context); + var systemText = + $"{introductionPrompt}{Environment.NewLine}{Environment.NewLine}" + + $"{ragPrompt}{Environment.NewLine}{Environment.NewLine}" + + $"Context:{Environment.NewLine}{contextBlock}"; + + // + List result = + [ + 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 ... + /// + /// Load AI Projects ... + /// + /// + /// + /// + /// + /// + public virtual async Task> LoadProjects( + string ownerId, + string connectionId = null, + bool includeDefaults = false, + CancellationToken cancellationToken = default + ) + { + // + // Validate Args ... + if (ownerId.IsNullOrEmpty()) + { + XException.InvalidArgs.Throw(); + } + + // + var result = await dataProvider.LoadProjects( + ownerId: ownerId, + fillConversations: false, + connectionId: connectionId, + fillConversationMessages: false, + cancellationToken: cancellationToken + ); + + // + // Handle Defaults Including ... + if (includeDefaults) + { + // + // Here we have to fill Conversations of Default Project ... + var defaultProjectId = result.GetDafualtProject(ownerId); + var defaultProject = result.FirstOrDefault(x => x.Id == defaultProjectId); + result = result.Where(x => x.Id != defaultProjectId); + + // + // Reading Conversations of Specified Default Project ... + var defaultProjectConversations = await dataProvider.LoadConversations( + fillMessages: false, + connectionId: connectionId, + projectId: defaultProjectId, + cancellationToken: cancellationToken + ); + var defaultConversationId = defaultProjectConversations.GetDefaultConversation( + ownerId: ownerId, + projectId: defaultProjectId + ); + var defaultConversation = defaultProjectConversations.First(x => x.Id == defaultConversationId); + defaultProjectConversations = defaultProjectConversations.Where(x => x.Id != defaultConversationId); + + // + // Reading Default Conversations Messages ... + var defaultConversationMessages = await dataProvider.LoadMessages( + cancellationToken: cancellationToken, + conversationId: defaultConversationId + ); + + // + defaultConversation.Messages = [.. defaultConversationMessages.OrderByDescending(m => m.CreatedOn)]; + defaultProjectConversations = [defaultConversation, .. defaultProjectConversations]; + defaultProject.Conversations = [.. defaultProjectConversations]; + result = [defaultProject, .. result]; + } + + // + return result; + } + + /// + /// Load Conversations of Specified AI Project ... + /// + /// + /// + /// + /// + public virtual async Task> LoadConversations( + Guid projectId, + string connectionId = null, + CancellationToken cancellationToken = default + ) + { + // + // Validate Args ... + if (projectId.IsDefaultGuid()) + { + XException.InvalidArgs.Throw(); + } + + // + var result = await dataProvider.LoadConversations( + fillMessages: false, + projectId: projectId, + connectionId: connectionId, + cancellationToken: cancellationToken + ); + + // + return result; + } + + /// + /// Load Messages of Specified Conversation ... + /// + /// + /// + /// + public virtual async Task> LoadMessages( + Guid conversationId, + CancellationToken cancellationToken = default + ) + { + // + // Validate Args ... + if (conversationId.IsDefaultGuid()) + { + XException.InvalidArgs.Throw(); + } + + // + var result = await dataProvider.LoadMessages( + conversationId: conversationId, + cancellationToken: cancellationToken + ); + + // + return result; + } + #endregion + + // + #region Queries ... + /// + /// Query Projects ... + /// + /// + /// + /// + /// + public virtual async Task> QueryProjects( + string ownerId, + XQuery query, + CancellationToken cancellationToken = default + ) + { + // + // Validate ... + if (ownerId.IsNullOrEmpty()) + { + XException.InvalidArgs.Throw(); + } + + // + var result = await dataProvider.QueryProjects( + query: query, + ownerId: ownerId, + cancellationToken: cancellationToken + ); + + // + return result; + } + + /// + /// Query Conversations ... + /// + /// + /// + /// + /// + /// + public virtual async Task> QueryConversations( + string ownerId, + Guid projectId, + XQuery query, + CancellationToken cancellationToken = default + ) + { + // + // Validate ... + if (ownerId.IsNullOrEmpty() || + projectId.IsDefaultGuid()) + { + XException.InvalidArgs.Throw(); + } + + // + // Retrieve Project ... + var project = await dataProvider.GetProject( + id: projectId, + fillConversations: false, + fillConversationMessages: false, + cancellationToken: cancellationToken + ); + if (project.IsNullOrDefault()) + { + XException.NotFound.Throw(); + } + + // + // Validate Owner ... + if (ownerId != project.OwnerId) + { + XException.NotAllowed.Throw(); + } + + // + var result = await dataProvider.QueryConversations( + query: query, + ownerId: ownerId, + projectId: projectId, + cancellationToken: cancellationToken + ); + + // + return result; + } + + /// + /// Query Messages ... + /// + /// + /// + /// + /// + /// + public virtual async Task> QueryMessages( + string ownerId, + Guid conversationId, + XQuery query, + CancellationToken cancellationToken = default + ) + { + // + // Validate ... + if (ownerId.IsNullOrEmpty() || + conversationId.IsDefaultGuid()) + { + XException.InvalidArgs.Throw(); + } + + // + // Retrieve Conversation ... + var conversation = await dataProvider.GetConversation( + id: conversationId, + fillMessages: false, + cancellationToken: cancellationToken + ); + if (conversation.IsNullOrDefault()) + { + XException.NotFound.Throw(); + } + + // + // Validate Owner ... + if (ownerId != conversation.OwnerId) + { + XException.NotAllowed.Throw(); + } + + // + var result = await dataProvider.QueryMessages( + query: query, + ownerId: ownerId, + conversationId: conversationId, + cancellationToken: cancellationToken + ); + + // + return result; + } + #endregion + + // + #region Creators ... + /// + /// Create an AI Project ... + /// + /// + /// + /// + /// + /// + public virtual async Task CreateProject( + string ownerId, + XAiProjectDto item, + string connectionId = null, + CancellationToken cancellationToken = default + ) + { + // + var result = await dataProvider.CreateProject( + item: item, + ownerId: ownerId, + connectionId: connectionId, + cancellationToken: cancellationToken + ); + + // + return result; + } + + /// + /// Create an AI Conversation ... + /// + /// + /// + /// + /// + /// + /// + public virtual async Task CreateConversation( + string ownerId, + Guid projectId, + XAiConversationDto item, + string connectionId = null, + CancellationToken cancellationToken = default + ) + { + // + var result = await dataProvider.CreateConversation( + item: item, + ownerId: ownerId, + projectId: projectId, + connectionId: connectionId, + cancellationToken: cancellationToken + ); + + // + return result; + } + #endregion + + // + #region Content Extraction ... + /// + /// Try to Extract Files Content ... + /// + /// + /// + /// + /// + public async Task ExtractContent( + IFormFileCollection files, + string[] extractors = null, + CancellationToken cancellationToken = default + ) + { + // + if (!files.HasChild()) + { + XException.InvalidArgs.Throw(); + } + + // + var extractionResults = new List(); + foreach (var file in files) + { + // + if (file.IsNull() || file.Length == 0) + { + continue; + } + + // + var mimeType = file.ContentType?.ToLowerInvariant() ?? string.Empty; + if (!fileContentExtractor.CanExtract(mimeType, extractors)) + { + continue; + } + + // + try + { + // + using var stream = file.OpenReadStream(); + + // + var fr = await fileContentExtractor.ExtractRichAsync( + fileStream: stream, + mimeType: mimeType, + extractors: extractors, + fileName: file.FileName, + cancellationToken: cancellationToken + ); + + // + if (fr.IsValid()) + { + extractionResults.Add(fr); + } + } + catch (OperationCanceledException) + { + throw; + } + catch + { + continue; + } + + // + // TODO: Implement File Save ... + } + + // + var result = string.Empty; + if (extractionResults.HasChild()) + { + // + extractionResults.ForEach(er => + { + result += $"File {er.FileName} Content:{Environment.NewLine}{er.Text ?? er.AudioTranscript}{Environment.NewLine}----"; + }); + } + + // + return result; + } + #endregion + + // + #region Data Actions ... + /// + /// Ask a Question as Prompt and Retrieve Response ... + /// + /// + /// + /// + /// + /// + /// + /// + /// + /// + public virtual async Task AskAsync( + string prompt, + string ownerId, + Guid? projectId, + Guid? conversationId, + string connectionId = null, + IFormFileCollection files = null, + XUserClaimsInfoDto userInfo = null, + CancellationToken cancellationToken = default + ) + { + // + // Validate Args ... + validationProvider + .GroupValidationBuilder() + .AddNotEmpty(prompt) + .AddNotEmpty(ownerId) + .ValidateGroup(); + + // + // Check Project ... + XAiProjectDto project = null; + if (!projectId.HasValue || projectId.Value.IsDefaultGuid()) + { + // + project = await dataProvider.GetDefaultProject( + ownerId: ownerId, + connectionId: connectionId, + cancellationToken: cancellationToken + ); + + // + projectId = project.Id; + } + else + { + // + project = await dataProvider.GetProject( + id: projectId.Value, + fillConversations: false, + fillConversationMessages: false, + cancellationToken: cancellationToken + ); + } + if (project.IsNullOrDefault()) + { + XException.NotFound.Throw(); + } + + // + // Check Conversation ... + XAiConversationDto conversation = null; + if (!conversationId.HasValue || conversationId.Value.IsDefaultGuid()) + { + // + conversation = await dataProvider.GetDefaultConversation( + ownerId: ownerId, + projectId: projectId.Value, + connectionId: connectionId, + cancellationToken: cancellationToken + ); + + // + conversationId = conversation.Id; + } + else + { + // + conversation = await dataProvider.GetConversation( + fillMessages: false, + id: conversationId.Value, + cancellationToken: cancellationToken + ); + } + if (conversation.IsNullOrDefault()) + { + XException.NotFound.Throw(); + } + + // + // 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 { } + } + + // + // Reading Messages ... + var messages = await dataProvider.LoadMessages( + conversationId: conversationId.Value, + 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 + // ); + // } + + // + // Handle Memory ... + IList history = await PrepareMemory( + project: project, + messages: messages, + cancellationToken: cancellationToken + ); + + // + // Prepare and Add Prompt Message ... + var promptMessage = new XAiMessageDto + { + Content = prompt, + OwnerId = ownerId, + Role = XAiChatRole.User, + CreatedOn = DateTime.UtcNow, + 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.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 + + // + // Ask Questions From LLM ... + var answer = await AskLLMAsync( + history: history, + prompt: promptChatMessage, + cancellationToken: cancellationToken + ); + + // + // Prepare Answer AI Message ... + var result = new XAiMessageDto + { + Content = answer, + OwnerId = ownerId, + CreatedOn = DateTime.UtcNow, + Role = XAiChatRole.Assistant, + ConversationId = conversationId.Value, + ConversationTitle = conversation.Title + }; + result = await dataProvider.AddMessage( + item: result, + connectionId: connectionId, + conversationId: conversationId.Value, + cancellationToken: cancellationToken + ); + + // + return result; + } + + /// + /// Ask a Question as Prompt and Retrieve Response as Async Enumerable ... + /// + /// + /// + /// + /// + /// + /// + /// + /// + public virtual async IAsyncEnumerable AskAsEnumerable( + string prompt, + string ownerId, + Guid projectId, + Guid conversationId, + string connectionId = null, + IFormFileCollection files = null, + [EnumeratorCancellation] + CancellationToken cancellationToken = default + ) + { + // + // Validate Args ... + validationProvider + .GroupValidationBuilder() + .AddNotEmpty(prompt) + .AddNotEmpty(ownerId) + .ValidateGroup(); + + // + // Check Project ... + XAiProjectDto project = null; + if (projectId.IsDefaultGuid()) + { + // + project = await dataProvider.GetDefaultProject( + ownerId: ownerId, + connectionId: connectionId, + cancellationToken: cancellationToken + ); + + // + projectId = project.Id; + } + else + { + // + project = await dataProvider.GetProject( + id: projectId, + fillConversations: false, + fillConversationMessages: false, + cancellationToken: cancellationToken + ); + } + if (project.IsNullOrDefault()) + { + XException.NotFound.Throw(); + } + + // + // Check Conversation ... + XAiConversationDto conversation = null; + if (conversationId.IsDefaultGuid()) + { + // + conversation = await dataProvider.GetDefaultConversation( + ownerId: ownerId, + projectId: projectId, + connectionId: connectionId, + cancellationToken: cancellationToken + ); + + // + conversationId = conversation.Id; + } + else + { + // + conversation = await dataProvider.GetConversation( + id: conversationId, + fillMessages: false, + cancellationToken: cancellationToken + ); + } + if (conversation.IsNullOrDefault()) + { + XException.NotFound.Throw(); + } + + // + // Reading Messages ... + var messages = await dataProvider.LoadMessages( + conversationId: conversationId, + cancellationToken: cancellationToken + ); + + // + // TODO: Parse Files ... + // for Attached them into Prompt Message ... + + // + // Handle Memory ... + IList history = await PrepareMemory( + project: project, + messages: messages, + cancellationToken: cancellationToken + ); + + // + // Prepare and Add Prompt Message ... + var promptMessage = new XAiMessageDto + { + Content = prompt, + OwnerId = ownerId, + Role = XAiChatRole.User, + CreatedOn = DateTime.UtcNow, + ConversationId = conversationId, + }; + promptMessage = await dataProvider.AddMessage( + item: promptMessage, + connectionId: connectionId, + conversationId: conversationId, + cancellationToken: cancellationToken + ); + promptMessage = await dataProvider.Enrich( + source: promptMessage, + cancellationToken: cancellationToken + ); + + // + // Attach Uploaded Files ... + var promptChatMessage = promptMessage + .ToChatMessages(); + history.Add(promptChatMessage); + + // + // Ask Questions From LLM ... + using var client = Descriptor.GetClient(); + var enumerable = client.GetStreamingResponseAsync( + options: null, + messages: history + ); + + // + long sequence = 1; + var answer = string.Empty; + await foreach (var res in enumerable) + { + // + // Cancellation Token ... + if (cancellationToken.IsCancellationRequested) + { + yield break; + } + + // + var resp = new XAiResonseMessage + { + OwnerId = ownerId, + Content = res.Text, + Sequence = sequence, + Role = XAiChatRole.System, + RespondTo = promptMessage.Id, + RespondedOn = DateTime.UtcNow, + }; + + // + sequence++; + answer += res.Text; + + // + yield return resp; + } + + // + // Prepare Answer AI Message ... + var result = new XAiMessageDto + { + Content = answer, + OwnerId = ownerId, + Role = XAiChatRole.System, + CreatedOn = DateTime.UtcNow, + ConversationId = conversationId + }; + result = await dataProvider.AddMessage( + item: result, + connectionId: connectionId, + conversationId: conversationId, + cancellationToken: cancellationToken + ); + } + #endregion + + /// + /// Base Dispose Action ... + /// + /// + public virtual void Dispose() + { } + + // + #region Private ... + /// + /// Implementing Memory Strategy here ... + /// + /// + /// + /// + /// + private async Task> PrepareMemory( + XAiProjectDto project, + IEnumerable messages, + CancellationToken cancellationToken = default + ) + { + // + var result = new List(); + + // + // Retrieve Introduction Prompt ... + var introductionPrompt = configuration.GetPrompt(XAiApiConstants.XAiApiIntroductionPromptName); + if (introductionPrompt.IsNullOrEmpty()) + { + XException.InvalidData.Throw(); + } + + // + var introductionMessage = new ChatMessage( + role: ChatRole.System, + content: introductionPrompt + ); + + // + result.Add(introductionMessage); + + // + 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); + } + + // + if (messages.HasChild()) + { + // + // TODO: Here we can Implement Memory Management based on + // Last nth of Messages, or Summarization of Messages, etc ... + result = [..result, ..messages + .OrderBy(m => m.CreatedOn) + .Select(m => m.ToChatMessages())]; + } + + // + return result; + } + + /// + /// Ask Quetion from LLM ... + /// + /// + /// + /// + /// + private async Task AskLLMAsync( + ChatMessage prompt, + IList history, + CancellationToken cancellationToken = default + ) + { + // + if (prompt.IsNullOrDefault()) + { + XException.InvalidArgs.Throw(); + } + + // + history.Add(prompt); + using var client = Descriptor.GetClient(); + var response = await client.GetResponseAsync( + messages: history, + cancellationToken: cancellationToken + ); + + // + // Validate Response ... + if (!response.IsValid()) + { + // + // Dispose Client ... + client.Dispose(); + XException.ActionFailed.Throw(); + } + + // + // Retrieve Response Text ... + var result = response.Text; + + // + return result; + } + #endregion + } +} \ No newline at end of file diff --git a/Documents/Docs/ChangeLogs/1405-08-08-v01.html b/Documents/Docs/ChangeLogs/1405-08-08-v01.html new file mode 100644 index 0000000..2818c1d --- /dev/null +++ b/Documents/Docs/ChangeLogs/1405-08-08-v01.html @@ -0,0 +1,670 @@ + + + + + + ChangeLog ۱۴۰۵/۰۸/۰۸ v01 - RAG in Chat Pipeline + + + +
+
+

گزارش تغییرات ساختار پروژه

+

+ xSaherelmWorkspace | تاریخ: ۱۴۰۵/۰۸/۰۸ (2026-10-30) | نسخه + مستند: v01 +

+

+ موضوع: ادغام RAG در جریان اصلی گفتگو (AskAsync)، جداسازی + سرویس Embedding از سرویس AI، حذف Ask/AskStream از + KnowledgeController و Nullable شدن Project/Conversation در + درخواست پاسخ +

+
+
+ دامنه: xAiApi، + Modules/xAiModels، ریشهٔ Workspace + Build: 0 Error(s) + xAiApi: 21 فایل، +332 / −678 (+۲ فایل جدید) +
+
+
+

۱. خلاصه

+

+ در این مرحله، بازیابی دانش (RAG) که تا قبل فقط از طریق + Endpointهای جداگانهٔ /Knowledge/Ask و + /Knowledge/AskStream در دسترس بود، مستقیماً + وارد جریان اصلی گفتگو (XAIServiceBase.AskAsync) + شد. فایل‌های پیوست یک پیام اکنون به‌جای آپلود ساده و تزریق + محتوای خام در پیام، در Scope همان Conversation + Ingest می‌شوند و Context بازیابی‌شده (Conversation → + Project → User → Global) در System Prompt قرار می‌گیرد. +

+
    +
  • + سرویس Embedding از سلسله‌مراتب سرویس AI جدا شد + (IXAiEmbeddingService / + XAiEmbeddingService جایگزین + IXDefaultEmbeddingService). +
  • +
  • + وابستگی چرخشی XAiRAGService ↔ XDefaultAiService + حذف شد؛ اکنون سرویس AI به RAG وابسته است و نه برعکس. +
  • +
  • + ProjectId و ConversationId در + XAiResponseRequest Nullable شدند. +
  • +
  • + اعتبارسنجی درخواست Chat With Documents سخت‌گیرانه‌تر شد + (TopK و MinScore اجباری). +
  • +
+
+ +
+

۲. تغییرات معماری

+

قبل

+
+XAiEmbeddingServiceBase : XAIServiceBase            (Embedding = نوعی سرویس چت)
+XDefaultEmbeddingService(IXFileProvider, ...)
+XAiRAGService(IXDefaultAiService, IXDefaultEmbeddingService, ...)
+XAIServiceBase(IXFileProvider, ...)  → Upload + Extract + Attach raw contents
+KnowledgeController: Ingest / Retrieve / Ask / AskStream / Documents / ...
+

بعد

+
+XAiEmbeddingServiceBase : IXAiEmbeddingServiceBase  (مستقل، بدون ارث‌بری از XAIServiceBase)
+XAiEmbeddingService(IXAiDataProvider, ...)          (بدون IXFileProvider)
+XAiRAGService(IXAiEmbeddingService, IXFileProvider, ...)   (بدون IXDefaultAiService)
+XAIServiceBase(IXAiRAGService, ...)  → Ingest(Conversation scope) + RetrieveAsync + Context in System Prompt
+KnowledgeController: Ingest / Retrieve / Documents / ...   (Ask/AskStream حذف شد)
+

جریان جدید AskAsync

+
    +
  1. + تعیین Project (پیش‌فرض اگر null/Empty) و + Conversation (پیش‌فرض اگر null/Empty). +
  2. +
  3. + اگر فایل ارسال شده باشد: + ragProvider.IngestAsync با + XAiKnowledgeScopeDescriptor.Conversation(conversationId) + و replaceExisting: true. +
  4. +
  5. + ساخت XAiKnowledgeAskRequest با + IncludeUser = true، + IncludeGlobal = true، ProjectId و + ConversationId و فراخوانی + ragProvider.RetrieveAsync. +
  6. +
  7. + بارگذاری تاریخچهٔ پیام‌ها و ساخت یک پیام System واحد: + Introduction + ChatWithDocuments prompt + Context block + (+ Project prompt). +
  8. +
  9. + ذخیرهٔ پیام کاربر، ارسال به LLM و ذخیرهٔ پاسخ + Assistant. +
  10. +
+
+ +
+

۳. ساب‌ماژول xAiApi

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
وضعیتفایلخطوطشرح
جدیدInterfaces/IXAiEmbeddingService.cs+6 + اینترفیس Embedding پیش‌فرض (جایگزین + IXDefaultEmbeddingService) +
جدیدProviders/XAiEmbeddingService.cs+29 + پیاده‌سازی پیش‌فرض با مدل + XAiApiConstants.XAiEmbeddingModelName؛ + بدون وابستگی به IXFileProvider +
حذفInterfaces/IXDefaultEmbeddingService.cs−5جایگزین با IXAiEmbeddingService
حذفProviders/XDefaultEmbeddingService.cs−32جایگزین با XAiEmbeddingService
تغییرProviders/XAIServiceBase.cs~308 + تزریق IXAiRAGService به‌جای + IXFileProvider؛ AskAsync با + Guid? برای Project/Conversation؛ Ingest + فایل‌ها در Scope گفتگو و RetrieveAsync؛ + حذف منطق Upload/AddReference/Extract و پیوست + fileContents و MetaData شناسهٔ فایل‌ها؛ + PrepareMemory با پارامتر + context و یک پیام System ترکیبی + (Introduction + RAG prompt + Context + Project)؛ + انتقال BuildContextBlock از + protected virtual به private +
تغییرProviders/XAiRAGService.cs~382 + حذف وابستگی IXDefaultAiService؛ استفاده از + IXAiEmbeddingService؛ حذف + AskWithRAGAsync و + AskWithRAGAsEnumerable؛ پس از Upload، اگر + Scope دارای ScopeId باشد، + fileProvider.AddReference با + providedFor = scope.Scope.GetStringValue() + ثبت می‌شود؛ جابه‌جایی region «Private» + (ExtractText, EmbedChunks)؛ + NormalizeScope دیگر static نیست +
تغییرProviders/XAiEmbeddingServiceBase.cs+14 / −10 + دیگر از XAIServiceBase ارث نمی‌برد؛ + فیلدهای خودش (DataProvider، Configuration، + ValidationProvider، Extractor، ModelName) را نگه + می‌دارد؛ حذف IXFileProvider +
تغییر + Providers/XDefaultAiService.cs، + Providers/XDefaultThinkingAiService.cs + ±5 + سازنده: IXAiRAGService ragProvider به‌جای + IXFileProvider +
تغییرControllers/KnowledgeController.cs−132 + حذف Endpointهای POST /Knowledge/Ask و + POST /Knowledge/AskStream +
تغییر + Controllers/XAiEmbeddingServiceControllerBase.cs + ±18 + ارث‌بری مستقیم از + XBaseIdentityApiV1Controller؛ پارامتر + Generic به TEmbeddingService تغییر نام + یافت؛ فیلد embeddingService +
تغییرControllers/DefaultEmbeddingController.cs±14 + استفاده از IXAiEmbeddingService و + آرگومان‌های نام‌دار +
تغییرControllers/ChatWithDocumentsController.cs±4تزریق IXAiEmbeddingService
تغییرControllers/XAiServiceControllerBase.cs±4 + AskStream: ارسال + request.ProjectId.Value / + request.ConversationId.Value (به بخش + هشدارها مراجعه شود) +
تغییر + Interfaces/IXAiEmbeddingServiceBase.cs، + Interfaces/IXAiEmbeddingServiceControllerBase.cs + ±9 + قطع ارث‌بری از IXAiServiceBase / + IXAiServiceControllerBase؛ حذف + using OllamaSharp +
تغییرInterfaces/IXAiRAGService.cs−27 + حذف امضای AskWithRAGAsync و + AskWithRAGAsEnumerable +
تغییرInterfaces/IXAiServiceBase.cs±4 + AskAsync(Guid? projectId, Guid? conversationId, ...) +
تغییرDI/XDIHelperExtension.cs+14 / −5 + متد جدید AddXRagService() (ثبت + IXAiEmbeddingService و + IXAiRAGService)؛ حذف ثبت‌های قدیمی از + AddXAiServices() +
تغییرStartup.cs+4 + فراخوانی services.AddXRagService() قبل از + AddXAiServices() +
تغییرConstants/XAiApiConstants.cs+1 + XAiApiRagPromptName = "ChatWithDocuments" +
تغییرModels/XAiKnowledgeModels.cs±9 + Factoryهای Scope (User/Global/Project/Conversation): + مقدار پیش‌فرض + Type ?? XAiModelsConstants.XAiDefaultKnowledgeType +
تغییرExtensions/XModelsExtensions.cs±4 + IsValid درخواست Chat With Documents: + TopK و MinScore اکنون + اجباری هستند (قبلاً اختیاری) +
+
+ +
+

۴. ساب‌ماژول Modules/xAiModels

+ + + + + + + + + + + + + + + + + + + +
وضعیتفایلخطوطشرح
تغییرModels/XAiResponseRequest.cs±4 + ProjectId و ConversationId از + Guid به Guid? تغییر کردند + (ارسال‌نکردن = استفاده از Project/Conversation پیش‌فرض) +
تغییرExtensions/XAiModelsExtensions.cs±1اصلاح تورفتگی در امضای ToChatMessages
+
+ +
+

۵. مخزن اصلی (Workspace)

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
وضعیتمسیرشرح
ساب‌ماژولxAiApi، Modules/xAiModelsبه‌روزرسانی Pointer پس از Commit ساب‌ماژول‌ها
تغییرDocuments/Boards/xDashboard.kanban + کارت «R&D about MCP Servers» به ستون Test منتقل شد؛ + چک‌باکس «Test Rag Documents by Chat» تیک خورد؛ کارت جدید + «Adding MCP Support ...» اضافه شد +
تغییرDocuments/Resources/Json/Authenticate.json + نمونه‌های تست: توکن/Session جدید و نمونه Body برای + ChatWithDocuments/Ask (topK=6, + minScore=3.5) و Ask بدون Project/Conversation +
جدید + Documents/Codes/1.BKP.cs، + KnowledgeController.BKP.cs، + XAIServiceBase.BKP.cs + نسخهٔ پشتیبان کد پیش از Refactor
جدید + Documents/Docs/ChangeLogs/1405-08-08-v01.html، + CommitMessage-1405-08-08-v01.txt + همین گزارش و پیام Commit
+
+ +
+

۶. تغییرات ناسازگار (Breaking)

+
    +
  • + POST /Knowledge/Ask و + POST /Knowledge/AskStream حذف شدند؛ Frontend + باید از Ask/AskStream کنترلر + سرویس AI استفاده کند (RAG به‌صورت خودکار اعمال می‌شود). +
  • +
  • + IXDefaultEmbeddingService / + XDefaultEmbeddingService حذف شدند؛ هر جای + دیگری که به آن‌ها ارجاع دارد باید به + IXAiEmbeddingService تغییر کند. +
  • +
  • + IXAiEmbeddingServiceBase دیگر متدهای + IXAiServiceBase (چت) را ندارد و + DefaultEmbeddingController دیگر Endpointهای + چت ارث‌بری‌شده را ارائه نمی‌کند. +
  • +
  • + درخواست ChatWithDocuments/Ask بدون + topK یا minScore اکنون + InvalidArgs برمی‌گرداند. +
  • +
+
+ +
+

۷. هشدارها و موارد نیازمند بررسی (کشف‌شده در بازبینی)

+
+ ۱) Ask غیر Stream همیشه با InvalidArgs شکست + می‌خورد: در XAiServiceControllerBase.Ask + (خط ~632) پارامتر userInfo به + aiService.AskAsync ارسال نمی‌شود، اما + ragProvider.RetrieveAsync در + AskAsync با IsValidUser(userInfo) + اعتبارسنجی می‌کند و برای null + XException.InvalidArgs پرتاب می‌کند. پیشنهاد: + افزودن userInfo: userInfo به فراخوانی. +
+
+ ۲) AskStream با Project/Conversation خالی: + پس از Nullable شدن، request.ProjectId.Value و + request.ConversationId.Value در صورت ارسال‌نشدن + InvalidOperationException می‌دهند. همچنین + AskAsEnumerable هنوز Guid می‌گیرد و + جریان RAG در آن اعمال نشده است. +
+
+ ۳) بلعیدن خطای Ingest: در AskAsync بلوک + catch { } خطای Ingest فایل‌ها را بدون لاگ نادیده + می‌گیرد و متغیر ingestResult استفاده نمی‌شود. + پیشنهاد: حداقل logger.LogWarning. +
+
+ ۴) پرامپت ChatWithDocuments: + PrepareMemory اکنون در نبود این پرامپت + InvalidData پرتاب می‌کند؛ این پرامپت فقط در + appsettings.Development.json یافت شد. باید در + تنظیمات Production نیز وجود داشته باشد. +
+
+ ۵) جداکننده Project Prompt: متن + Project: بدون خط جدید به انتهای Context بلوک + چسبانده می‌شود (systemText += $"Project:..."). +
+
+ ۶) نمونه تست: در Authenticate.json مقدار + minScore: 3.5 با اعتبارسنجی جدید (بازهٔ −1 تا 1) + نامعتبر است. همچنین این فایل شامل AccessToken/RefreshToken + است؛ از Commit اطلاعات حساس مطمئن شوید. +
+
+ +
+

۸. اعتبارسنجی

+
+dotnet build xAiApi/xAiApi.csproj --nologo -v q
+    395 Warning(s)   (MSB3277 / NU1900 — از قبل موجود)
+    0 Error(s)
+
+ تست Runtime / End-to-End (Ask با فایل پیوست، Retrieve چندسطحی، + AskStream) در این مرحله انجام نشده است. +
+
+ +
+

۹. ترتیب Commit

+
    +
  1. Modules/xAiModels (وابستگی)
  2. +
  3. xAiApi
  4. +
  5. مخزن اصلی (Pointerها، Kanban، مستندات)
  6. +
+
+ +
+

۱۰. فایل‌های مستند

+

+ گزارش: + Documents/Docs/ChangeLogs/1405-08-08-v01.html +

+

+ Commit message: + Documents/Docs/ChangeLogs/CommitMessage-1405-08-08-v01.txt +

+

+ برای تغییرات بعدی همین تاریخ از پسوند v02 + استفاده شود. +

+
+
+
+ تولیدشده در تاریخ ۱۴۰۵/۰۸/۰۸ (2026-10-30) | xSaherelmWorkspace | + ChangeLog v01 +
+
+ + diff --git a/Documents/Docs/ChangeLogs/CommitMessage-1405-08-08-v01.txt b/Documents/Docs/ChangeLogs/CommitMessage-1405-08-08-v01.txt new file mode 100644 index 0000000..a1e7d19 --- /dev/null +++ b/Documents/Docs/ChangeLogs/CommitMessage-1405-08-08-v01.txt @@ -0,0 +1,90 @@ +=============================================================================== + Commit Message - xSaherelmWorkspace + تاریخ: ۱۴۰۵/۰۸/۰۸ (2026-10-30) + نسخه مستند: v01 + گزارش کامل: Documents/Docs/ChangeLogs/1405-08-08-v01.html +=============================================================================== + +هدف: ادغام RAG در جریان اصلی گفتگو (AskAsync)، جداسازی سرویس Embedding از +سرویس AI، حذف Ask/AskStream از KnowledgeController و Nullable شدن +Project/Conversation در XAiResponseRequest. + +ترتیب Commit: [1] xAiModels -> [2] xAiApi -> [3] Root + +[1] Modules/xAiModels +Make Project and Conversation Optional in XAiResponseRequest +- XAiResponseRequest: ProjectId / ConversationId changed from Guid to Guid? + (omitted => default project / default conversation); +- XAiModelsExtensions: fix indentation of ToChatMessages signature. +Files: M Models/XAiResponseRequest.cs; M Extensions/XAiModelsExtensions.cs + +[2] xAiApi +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. +Files: A Interfaces/IXAiEmbeddingService.cs; A Providers/XAiEmbeddingService.cs; + D Interfaces/IXDefaultEmbeddingService.cs; D Providers/XDefaultEmbeddingService.cs; + M Constants/XAiApiConstants.cs; M Controllers/ChatWithDocumentsController.cs; + M Controllers/DefaultEmbeddingController.cs; M Controllers/KnowledgeController.cs; + M Controllers/XAiEmbeddingServiceControllerBase.cs; + M Controllers/XAiServiceControllerBase.cs; M DI/XDIHelperExtension.cs; + M Extensions/XModelsExtensions.cs; M Interfaces/IXAiEmbeddingServiceBase.cs; + M Interfaces/IXAiEmbeddingServiceControllerBase.cs; M Interfaces/IXAiRAGService.cs; + M Interfaces/IXAiServiceBase.cs; M Models/XAiKnowledgeModels.cs; + M Providers/XAIServiceBase.cs; M Providers/XAiEmbeddingServiceBase.cs; + M Providers/XAiRAGService.cs; M Providers/XDefaultAiService.cs; + M Providers/XDefaultThinkingAiService.cs; M Startup.cs + +[3] Workspace (root) +- Update submodule pointers: xAiApi, Modules/xAiModels; +- Kanban: move "R&D about MCP Servers" to Test, check "Test Rag Documents + by Chat", add "Adding MCP Support ..."; +- Authenticate.json: refresh sample tokens/session and add ask samples; +- Add Documents/Codes/*.BKP.cs (pre-refactor backups); +- Add Documents/Docs/ChangeLogs/1405-08-08-v01.html and this file. + +Validation: +- dotnet build xAiApi/xAiApi.csproj --nologo -v q -> 0 Error(s), + 395 pre-existing warnings (MSB3277/NU1900); +- Runtime / end-to-end tests not performed. + +Known Issues (to fix before release): +- XAiServiceControllerBase.Ask does not pass userInfo to AskAsync -> + RetrieveAsync throws InvalidArgs; +- AskStream uses ProjectId.Value / ConversationId.Value -> throws when + omitted; AskAsEnumerable still takes Guid and has no RAG; +- AskAsync swallows ingest errors with empty catch (no logging); +- "ChatWithDocuments" prompt must exist in production appsettings; +- Project prompt appended without newline separator; +- Authenticate.json sample minScore 3.5 is outside [-1, 1] and the file + contains tokens. + +Suggested root commit title: +Integrate RAG into Chat Pipeline, Decouple Embedding Service, Optional Project/Conversation (۱۴۰۵/۰۸/۰۸ v01) + +For additional documentation use v02: +1405-08-08-v02.html +CommitMessage-1405-08-08-v02.txt +=============================================================================== diff --git a/Documents/Docs/Developer/1405-08-08.Overview.html b/Documents/Docs/Developer/1405-08-08.Overview.html new file mode 100644 index 0000000..8a0f446 --- /dev/null +++ b/Documents/Docs/Developer/1405-08-08.Overview.html @@ -0,0 +1,1466 @@ + + + + + + بازبینی چهارم و تحلیل اصلاحات | سامانه xAiApi + + + +
+
+
+
+ +
+
+
شماره مستند: ARCH-REV-1405-004
+
نسخه: ۴.۰
+
تاریخ تهیه: آبان ۱۴۰۵
+
طبقه‌بندی: محرمانه
+
+
+
+ CHANGES REVIEW & RESULTS +

بازبینی چهارم و تحلیل اصلاحات سامانه xAiApi

+

+ بررسی بازطراحی لایه RAG، تفکیک Embedding و شناسایی + خطاهای جدید +

+
+
+
+
+ خلاصه مدیریتی:
+ در این نسخه، یک بازطراحی جدی در لایه AI انجام شده است: تفکیک + کامل IXAiEmbeddingService از + IXAiServiceBase، انتقال RAG به درون + XAIServiceBase، حذف مسیرهای موازی + AskWithRAG* از XAiRAGService و + بازسازی DI با AddXRagService(). این تغییرات + ساختاری مثبت هستند، اما در کنار آن‌ها چند خطای جدید و یک + بازگشت (Regression) در اعتبارسنجی رخ داده است که باید قبل از + استقرار برطرف شوند. مهم‌ترین مسئله: مسیر + AskAsEnumerable (Streaming) همچنان RAG ندارد. +
+
+
+
۱
+
+

خلاصه اجرایی

+
Executive Summary
+
+
+
+

+ این نسخه شاهد یک بازآرایی معماری مهم است. تفکیک + Embedding از Chat، ادغام جریان RAG در سرویس پایه و + ساده‌سازی KnowledgeController نشان‌دهنده بلوغ در + طراحی است. اما هم‌زمان، سه مورد باز باقی‌مانده از + نسخه قبل (F-10، F-11، F-16) اصلاح نشده‌اند و پنج + خطای جدید - که برخی از آن‌ها مستقیماً از تغییرات این + نسخه ناشی شده‌اند - شناسایی شده است. +

+
+
+
۶
+
اصلاح ساختاری مثبت
+
+
+
۵
+
+ خطای جدید شناسایی‌شده +
+
+
+
۳
+
+ مورد باز از نسخه قبل +
+
+
+
۲
+
+ بازگشت (Regression) +
+
+
+
+ مهم‌ترین مسئله جدید: متد + AskAsEnumerable در + XAIServiceBase هیچ‌گونه فراخوانی به + ragProvider.RetrieveAsync ندارد و سیستم + پیام‌ها را بدون Context به LLM می‌فرستد. بنابراین + پاسخ‌های Streaming به هیچ وجه از دانش ذخیره‌شده + استفاده نمی‌کنند. این دقیقاً همان چیزی است که در + نسخه قبل (F-05) به‌ظاهر برای مسیر + AskAsync حل شده بود، اما برای Streaming + ناقص مانده است. +
+
+ خطاهای بحرانی جدید: +
    +
  • + AskStream در + XAiServiceControllerBase از + request.ProjectId.Value و + request.ConversationId.Value + استفاده می‌کند که در صورت null بودن، + NullReferenceException پرتاب + می‌کند. +
  • +
  • + XAiDocumentAskRequest.IsValid + اکنون TopK و + MinScore را الزامی می‌داند که + باعث شکستن قرارداد با کلاینت‌های فعلی + می‌شود. +
  • +
  • + catch { } در + AskAsync خطاهای Ingest را + بی‌صدا می‌بلعد و کاربر متوجه نمی‌شود که + فایل‌هایش ایندکس نشده‌اند. +
  • +
+
+
+
+
+
+
۲
+
+

فهرست تغییرات سطح کد

+
Applied Code Changes
+
+
+
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
فایل / ماژولتغییر اعمال‌شدهنوع
Startup.cs + فراخوانی جدید + services.AddXRagService() + پیش از + services.AddXAiServices() + برای ثبت Embedding و RAG به‌صورت مستقل. + + ساختاری +
+ DI/XDIHelperExtension.cs + + افزودن AddXRagService() که + IXAiEmbeddingService و + IXAiRAGService را ثبت + می‌کند. حذف + IXDefaultEmbeddingService + از AddXAiServices(). + + DI +
+ XAiEmbeddingService + (جدید) + + جایگزین + XDefaultEmbeddingService، + پیاده‌سازی + IXAiEmbeddingService. + + جدید +
+ XAiEmbeddingServiceBase + + دیگر از XAIServiceBase ارث + نمی‌برد. تنها + IXAiEmbeddingServiceBase را + پیاده‌سازی می‌کند. + Options و + Descriptor از این کلاس حذف + شده‌اند. + + تفکیک +
XAIServiceBase + جایگزینی IXFileProvider با + IXAiRAGService ragProvider. + AskAsync اکنون جریان کامل + RAG (Ingest + Retrieve + Generate) را + انجام می‌دهد. متد + PrepareMemory بازنویسی شد و + Context و RAG Prompt را در System + Message قرار می‌دهد. + + بازطراحی +
XAiRAGService + حذف AskWithRAGAsync و + AskWithRAGAsEnumerable از + این سرویس. تمرکز بر + Retrieve/Ingest/Documents. حذف وابستگی + به IXDefaultAiService. + استفاده از + IXAiEmbeddingService. + افزودن + fileProvider.AddReference + با Scope برای فایل‌های Ingest شده در + Scopeهای Project/Conversation. + + بازنویسی +
+ KnowledgeController + + حذف کامل Endpointهای Ask و + AskStream. تنها Ingest، + Documents و DeleteDocument باقی + مانده‌اند. کاربر باید از طریق + DefaultAi/Ask با + ProjectId/ConversationId از RAG استفاده + کند. + + طراحی جدید +
XAiResponseRequest + ProjectId و + ConversationId از + Guid به + Guid? تغییر کردند تا امکان + استفاده از Default Project/Conversation + فراهم شود. + + اصلاح +
+ XAiKnowledgeScopeDescriptor + + Factory Methodها اکنون مقدار پیش‌فرض + Type = + XAiModelsConstants.XAiDefaultKnowledgeType + را اعمال می‌کنند. + + اصلاح +
XAiApiConstants + افزودن XAiApiRagPromptName. + حذف XOpenAINoKey (که به + XAiModels منتقل شده بود). حذف ثابت‌های + Knowledge منتقل‌شده. + + پاکسازی +
+ XModelsExtensions.IsValid + (XAiDocumentAskRequest) + + اعتبارسنجی سختگیرانه‌تر: اکنون + TopK و + MinScore الزامی هستند + (قبلاً اختیاری بودند). + + Regression +
+ XAiApiConfiguration.IsValid + + حذف اعتبارسنجی Promptها از + XModelsExtensions. اکنون + فقط Models.HasChild() بررسی + می‌شود و وجود Introduction Prompt اجباری + نیست. + + Regression +
+ ChatWithDocumentsController + + استفاده از + IXAiEmbeddingService به جای + IXDefaultEmbeddingService. + + هماهنگ‌سازی +
+ XAiEmbeddingServiceControllerBase + + دیگر از + XAiServiceControllerBase + ارث نمی‌برد. مستقیماً از + XBaseIdentityApiV1Controller + مشتق شده و + IXAiEmbeddingServiceControllerBase + را پیاده می‌کند. اما + [AllowAnonymous] روی + Embedding/Embeddings همچنان برقرار است. + + جزئی +
+
+
+
+
+
۳
+
+

تحلیل تفصیلی اصلاحات مثبت

+
+ Positive Structural Changes +
+
+
+
+

+ ۳-۱. تفکیک کامل Embedding از Chat +

+

+ انتقال IXAiEmbeddingServiceBase از + ارث‌بری IXAiServiceBase و حذف وابستگی + XAiEmbeddingServiceBase به + XAIServiceBase، یک تصمیم درست معماری + است. Embedding و Chat مفاهیم متفاوتی هستند و نباید + در یک سلسله‌مراتب قرار می‌گرفتند. این تفکیک باعث + می‌شود Dependency Injection شفاف‌تر باشد و تست‌پذیری + افزایش یابد. +

+
+ نتیجه: + AddXRagService() صریحاً وابستگی‌های RAG + را ثبت می‌کند و AddXAiServices() تنها + سرویس‌های Chat را. این باعث می‌شود سرویس‌های Chat + بدون RAG هم قابل راه‌اندازی باشند (اگرچه در حال حاضر + همه Chatها به RAG وابسته‌اند). +
+

+ ۳-۲. جریان RAG درون AskAsync +

+

+ متد AskAsync در + XAIServiceBase حالا یک جریان کامل را + اجرا می‌کند: +

+
    +
  • + اگر فایل پیوست شده باشد، ابتدا در Scope گفتگو + Ingest می‌شود. +
  • +
  • + سپس RetrieveAsync با درخواست RAG + (Prompt + ProjectId + ConversationId + + IncludeUser + IncludeGlobal) فراخوانی می‌شود. +
  • +
  • + Context به دست‌آمده به همراه RAG Prompt در + System Message قرار می‌گیرد. +
  • +
  • + پیام‌های قبلی گفتگو به History اضافه می‌شوند. +
  • +
+

+ این طراحی تمیزتر از نسخه قبلی است که در آن + XAiRAGService.AskWithRAGAsync مسئول + Generate نهایی بود. +

+

+ ۳-۳. حذف مسیرهای موازی AskWithRAG* +

+

+ حذف AskWithRAGAsync و + AskWithRAGAsEnumerable از + IXAiRAGService باعث کاهش پیچیدگی + می‌شود. RAG حالا فقط یک لایه بازیابی است و تولید + پاسخ به XAIServiceBase واگذار شده است. + این «جدایی نگرانی‌ها» (Separation of Concerns) را + افزایش می‌دهد. +

+

+ ۳-۴. اتصال فایل‌های Ingest شده به Scope +

+

+ در XAiRAGService.IngestAsync، پس از + Upload فایل، + fileProvider.AddReference با + providedFor = + scope.Scope.GetStringValue() + و + forProvidedId = + scope.ScopeId.Value.ToString() + فراخوانی می‌شود. این باعث می‌شود فایل‌های مرتبط با + هر Project/Conversation قابل ردیابی باشند. +

+
+ نکته: در Scopeهای User و Global که + ScopeId ندارند، این Reference اضافه + نمی‌شود. همچنین uploadedFile بدون بررسی + null استفاده می‌شود که در صورت خطای Provider + می‌تواند NullReferenceException ایجاد کند. +
+

+ ۳-۵. Nullable شدن ProjectId/ConversationId در + XAiResponseRequest +

+

+ تغییر از Guid به + Guid? امکان استفاده از Default + Project/Conversation را برای مشتریانی که این مقادیر + را ارسال نمی‌کنند فراهم می‌کند. این تصمیم درست است، + اما پیاده‌سازی آن در همه مسیرها یکسان نیست (به بخش + خطاها مراجعه کنید). +

+

+ ۳-۶. بازنویسی PrepareMemory با پشتیبانی از + Context +

+

+ PrepareMemory اکنون می‌تواند Context + واکشی‌شده را در System Message جای دهد. همچنین از + ثابت جدید XAiApiRagPromptName استفاده + می‌کند. این باعث می‌شود پرامپت RAG در یک نقطه مشخص + نگهداری شود. +

+
+
+
+
+
۴
+
+

خطاهای جدید و بازگشت‌های شناسایی‌شده

+
+ New Issues & Regressions +
+
+
+
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
شناسهمحلشدتشرح
N-01XAIServiceBase.AskAsEnumerable + بحرانی + + مسیر Streaming هیچ‌گاه + ragProvider.RetrieveAsync + را فراخوانی نمی‌کند و Context را در + System Message قرار نمی‌دهد. کاربرانی که + از AskStream استفاده + می‌کنند پاسخ بدون دانش دریافت می‌کنند. +
N-02XAiServiceControllerBase.AskStream + بحرانی + + استفاده از + request.ProjectId.Value و + request.ConversationId.Value + در حالی که این فیلدها Nullable شده‌اند. + اگر کلاینت مقدار نفرستد، + NullReferenceException رخ + می‌دهد. +
N-03 + XModelsExtensions.IsValid(XAiDocumentAskRequest) + + بالا + + شرط + TopK.HasValue && + MinScore.HasValue + الزامی شده است. کلاینت‌هایی که قبلاً + بدون این فیلدها درخواست می‌فرستادند، + حالا پاسخ 400 دریافت می‌کنند. این یک + Regression و شکستن قرارداد است. +
N-04XAIServiceBase.AskAsync (Ingest) + بالا + + در بلوک Ingest فایل‌ها، خطاها با + catch { } بی‌صدا نادیده + گرفته می‌شوند. اگر Ingest شکست بخورد + (مثلاً فایل رمزدار باشد)، LLM بدون + Context پاسخ می‌دهد و کاربر نمی‌فهمد که + فایل‌ها ایندکس نشده‌اند. متغیر + ingestResult هم بدون + استفاده رها شده است. +
N-05XAiRAGService.IngestAsync + متوسط + + uploadedFile.Id بدون بررسی + null استفاده می‌شود. اگر + fileProvider.Upload مقدار + null برگرداند، NullReferenceException رخ + می‌دهد. +
R-01 + XModelsExtensions.IsValid(XAiApiConfiguration) + + بالا (Regression) + + اعتبارسنجی Promptها حذف شده است. اگر در + تنظیمات، Prompt مربوط به + Introduction یا + ChatWithDocuments وجود + نداشته باشد، Startup موفق می‌شود اما + اولین درخواست Chat با خطا مواجه می‌شود. +
R-02 + IXAiRAGService / KnowledgeController + + متوسط (Regression) + + Endpointهای Ask و + AskStream از + KnowledgeController حذف شده‌اند. کاربران + قبلی که از این مسیرها استفاده می‌کردند، + حالا باید به + DefaultAi/Ask مهاجرت کنند. + این مهاجرت نیاز به مستندسازی و + اطلاع‌رسانی دارد. +
X-01XAiDocumentRAGDescriptor.PromptName + پایین + + فیلد PromptName در + XAiDocumentRAGDescriptor + دیگر استفاده نمی‌شود (به‌جای آن + XAiApiConstants.XAiApiRagPromptName + استفاده می‌شود). Dead code است و باید + حذف یا هماهنگ شود. +
X-02XAIServiceBase.AskAsync + پایین + + فایل‌های پیوست در هر بار ارسال مجدد + Re-Ingest می‌شوند (چون + replaceExisting: true است). + اگر کاربر فایل یکسانی را چند بار پیوست + کند، هزینه Embedding چند برابر می‌شود. + نیاز به هش محتوا یا شناسه فایل دارد. +
+
+ ریسک ترکیبی N-01 و N-02: مسیر + AskStream هم RAG ندارد و هم در صورت + ارسال نکردن ProjectId/ConversationId کرش می‌کند. این + ترکیب باعث می‌شود که عملاً Streaming برای کاربرانی + که فایل پیوست می‌کنند یا می‌خواهند از دانش استفاده + کنند، غیرقابل استفاده باشد. +
+
+
+
+
+
۵
+
+

موارد باز از نسخه‌های قبل

+
+ Still Open from Previous Reviews +
+
+
+
+ + + + + + + + + + + + + + + + + + + + + + + + + +
شناسهمحلوضعیت
F-10 + XImageFileContentExtractor (Constructor) + + باز + — اعتبارسنجی OCR حتی در حالت غیرفعال +
F-11 + XAiEmbeddingServiceBase.GetEmbeddingGenerator + + باز + — عدم ارسال نام مدل به OllamaApiClient +
F-16XAiEmbeddingServiceControllerBase + جزئی + — [AllowAnonymous] هنوز روی + Embedding/Embeddings +
+
+ مشاهده: اگرچه + XAiEmbeddingServiceControllerBase حالا + از XAiServiceControllerBase ارث + نمی‌برد، صفت [AllowAnonymous] روی دو + Endpoint اصلی آن باقی مانده است. اگر این تصمیم + آگاهانه است (مثلاً برای مصرف داخلی توسط سرویس‌های + دیگر)، باید مستندسازی شود. +
+
+
+
+
+
۶
+
+

پیشنهادهای اصلاحی مرحله بعد

+
Recommended Fixes
+
+
+
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
اولویتاقدامشناسه
+ P0 + + افزودن منطق RAG به + AskAsEnumerable: فراخوانی + ragProvider.IngestAsync + (اگر فایل هست) و سپس + ragProvider.RetrieveAsync، + و پاس دادن Context به + PrepareMemory. + N-01
+ P0 + + رفع NullReferenceException در + AskStream: حذف + .Value یا استفاده از + fallback (request.ProjectId ?? + Guid.Empty) و هماهنگ‌سازی امضای + AskAsEnumerable برای پذیرش + Guid?. + N-02
+ P0 + + بازگرداندن اختیاری بودن + TopK و + MinScore در اعتبارسنجی + XAiDocumentAskRequest. + N-03
+ P0 + + حذف catch { } در Ingest و + لاگ کردن خطا. اگر فایل قابل پردازش نیست، + بهتر است در پاسخ Ask گزارش شود. + N-04
+ P1 + + بازگرداندن اعتبارسنجی Promptها در + XAiApiConfiguration.IsValid + یا حداقل اعتبارسنجی Startup برای وجود + Introduction و + ChatWithDocuments. + R-01
+ P1 + + بررسی null برای + uploadedFile پیش از استفاده + از uploadedFile.Id در + XAiRAGService. + N-05
+ P1 + + بررسی هش فایل یا شناسه محتوا قبل از + Re-Ingest در AskAsync برای + جلوگیری از Embedding تکراری. + X-02
+ P2 + + حذف یا هماهنگ‌سازی + XAiDocumentRAGDescriptor.PromptName + با + XAiApiConstants.XAiApiRagPromptName. + X-01
+ P2 + اصلاح فوری F-10، F-11 و F-16.F-*
+ P2 + + مستندسازی تغییر قرارداد (حذف + Ask/AskStream از Knowledge و تغییرات + XAiResponseRequest) برای کلاینت‌های + موجود. + R-02
+
+ پیشنهاد بلندمدت: پیشنهاد می‌شود یک + لایه مشترک به نام + IXAiChatOrchestrator ایجاد شود که جریان + «Ingest → Retrieve → PrepareMemory → Generate» را در + یک نقطه پیاده‌سازی کند و هم AskAsync و + هم AskAsEnumerable از آن استفاده کنند. + این کار از تکرار منطق و اختلاف بین دو مسیر جلوگیری + می‌کند. +
+
+ هشدار درباره AskAsEnumerable: تا + زمانی که N-01 اصلاح نشود، مسیر Streaming Chat عملاً + بدون RAG و بدون دانش است. اگر این Endpoint در حال + حاضر در محیط Production استفاده می‌شود، این یک نقص + عملکردی جدی است که باید در اسرع وقت جبران شود. +
+
+
+
+
+
۷
+
+

جمع‌بندی نهایی

+
Final Conclusion
+
+
+
+

+ بازطراحی این نسخه، مسیر فکری صحیحی را نشان می‌دهد: + تفکیک نگرانی‌ها، انتقال منطق RAG به لایه سرویس پایه + و ساده‌سازی Controllerها. این تغییرات بنیادین، + پایه‌ای مناسب برای توسعه بلندمدت فراهم می‌کند. با + این حال، در جریان اجرای این بازطراحی، چند خطای مشخص + و یک Regression در اعتبارسنجی رخ داده است که باعث + می‌شود وضعیت فعلی از نظر آمادگی Production ضعیف‌تر + از نسخه قبلی به نظر برسد. +

+

+ به‌ویژه این واقعیت که مسیر Streaming حتی به RAG متصل + نشده است، و این‌که AskStream با + ProjectId/ConversationId تهی کرش می‌کند، نشان می‌دهد + که بازطراحی در برخی نقاط بدون اعتبارسنجی کامل + End-to-End انجام شده است. +

+
+

🎯 جمع‌بندی اجرایی بازبینی چهارم

+

+ معماری بهبود یافته است، اما پیاده‌سازی جریان RAG + ناقص و مسیر Streaming دچار کمبود جدی است. +

+
+ اقدامات ضروری قبل از Production:
+ اتصال RAG به AskAsEnumerable + رفع + NullReferenceException در AskStream + بازگرداندن + اعتبارسنجی اختیاری + لاگ‌کردن خطاهای Ingest + + اصلاح F-10/F-11/F-16 +
+
+
+ ارزیابی کلی: علیرغم بهبود ساختاری، + سامانه در وضعیت فعلی برای استفاده Production آماده + نیست. حداقل باید N-01 تا N-04 برطرف شوند. توصیه + می‌شود پیش از ادامه توسعه، یک Suite تست End-to-End + برای مسیرهای Ask و AskStream با و بدون فایل پیوست + نوشته شود. +
+
+
+
+ این مستند محرمانه بوده و صرفاً جهت بررسی فنی داخلی تهیه شده + است. هرگونه کپی‌برداری یا افشا بدون اجازه کتبی ممنوع است. +
+
+
+ + +
+ تاریخ تهیه: آبان ۱۴۰۵  |  نسخه: ۴.۰  |  + طبقه‌بندی: محرمانه +
+
+
+ + diff --git a/Documents/GeneratedContext/xDashboard-xAiApi-20261029_200138.txt b/Documents/GeneratedContext/xDashboard-xAiApi-20261030_194031.txt similarity index 95% rename from Documents/GeneratedContext/xDashboard-xAiApi-20261029_200138.txt rename to Documents/GeneratedContext/xDashboard-xAiApi-20261030_194031.txt index 68deaf2..969e407 100644 --- a/Documents/GeneratedContext/xDashboard-xAiApi-20261029_200138.txt +++ b/Documents/GeneratedContext/xDashboard-xAiApi-20261030_194031.txt @@ -233,6 +233,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(); @@ -417,6 +421,7 @@ namespace xAiApi.Constants public const string XDILogTag = "XAiApi"; // + public const string XAiApiRagPromptName = "ChatWithDocuments"; public const string XAiApiIntroductionPromptName = "Introduction"; public const string XAiApiContentExtractionPromptName = "ContentExtraction"; @@ -517,7 +522,7 @@ namespace xAiApi.Controllers /// /// Embedding Service ... /// - private readonly IXDefaultEmbeddingService embeddingService; + private readonly IXAiEmbeddingService embeddingService; /// /// File Context Extractor Service ... @@ -531,8 +536,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) @@ -1201,20 +1206,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 ) { } } @@ -1293,7 +1298,6 @@ namespace xAiApi.Controllers XValidationProvider validationProvider ) : base(logger, appConfiguration, identityProvider, validationProvider) { - // this.ragService = ragService; } @@ -1357,137 +1361,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 ... /// @@ -1723,32 +1596,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; } /// @@ -1772,7 +1645,7 @@ namespace xAiApi.Controllers ValidationProvider.NotEmpty(content); // - var result = await aiService.Embedding( + var result = await embeddingService.Embedding( content: content, cancellationToken: cancellationToken ); @@ -1809,7 +1682,7 @@ namespace xAiApi.Controllers ValidationProvider.NotZeroChilds(batch); // - var result = await aiService.Embeddings( + var result = await embeddingService.Embeddings( batch: batch, cancellationToken: cancellationToken ); @@ -2520,9 +2393,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 ); // @@ -2785,6 +2658,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 ... /// @@ -2795,12 +2682,7 @@ namespace xAiApi.DI { // source.AddScoped(); - source.AddScoped(); source.AddScoped(); - - // - // Persistent RAG (Knowledge over XAiVector Table) ... - source.AddScoped(); } /// @@ -2972,8 +2854,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; @@ -3317,20 +3199,27 @@ namespace xAiApi.Extensions } } +### FILE: C:\Users\saherelm\Documents\Projects\xSaherelmWorkspace\xAiApi\Interfaces\IXAiEmbeddingService.cs + +namespace xAiApi.Interfaces +{ + public interface IXAiEmbeddingService : IXAiEmbeddingServiceBase + { } +} + ### FILE: C:\Users\saherelm\Documents\Projects\xSaherelmWorkspace\xAiApi\Interfaces\IXAiEmbeddingServiceBase.cs -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 ... @@ -3364,14 +3253,14 @@ namespace xAiApi.Interfaces ### FILE: C:\Users\saherelm\Documents\Projects\xSaherelmWorkspace\xAiApi\Interfaces\IXAiEmbeddingServiceControllerBase.cs -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 ... @@ -3451,33 +3340,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 ... /// @@ -3791,8 +3653,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, @@ -4048,14 +3910,6 @@ namespace xAiApi.Interfaces { } } -### FILE: C:\Users\saherelm\Documents\Projects\xSaherelmWorkspace\xAiApi\Interfaces\IXDefaultEmbeddingService.cs - -namespace xAiApi.Interfaces -{ - public interface IXDefaultEmbeddingService : IXAiEmbeddingServiceBase - { } -} - ### FILE: C:\Users\saherelm\Documents\Projects\xSaherelmWorkspace\xAiApi\Interfaces\IXDefaultThinkingAiService.cs namespace xAiApi.Interfaces @@ -5660,7 +5514,8 @@ namespace xAiApi.Models string type = null ) => new() { - Type = type, + // + Type = type ?? XAiModelsConstants.XAiDefaultKnowledgeType, ScopeId = null, Scope = XAiKnowledgeScope.User, }; @@ -5674,7 +5529,7 @@ namespace xAiApi.Models string type = null ) => new() { - Type = type, + Type = type ?? XAiModelsConstants.XAiDefaultKnowledgeType, ScopeId = null, Scope = XAiKnowledgeScope.Global, }; @@ -5690,7 +5545,7 @@ namespace xAiApi.Models string type = null ) => new() { - Type = type, + Type = type ?? XAiModelsConstants.XAiDefaultKnowledgeType, ScopeId = projectId, Scope = XAiKnowledgeScope.Project, }; @@ -5706,7 +5561,7 @@ namespace xAiApi.Models string type = null ) => new() { - Type = type, + Type = type ?? XAiModelsConstants.XAiDefaultKnowledgeType, ScopeId = conversationId, Scope = XAiKnowledgeScope.Conversation, }; @@ -6039,6 +5894,38 @@ namespace xAiApi.Models } } +### FILE: C:\Users\saherelm\Documents\Projects\xSaherelmWorkspace\xAiApi\Providers\XAiEmbeddingService.cs + +using xAiApi.Constants; +using xAiApi.Interfaces; +using xCommons.Providers; +using xAiModels.Interfaces; +using xAiApi.Configurations; +using Microsoft.Extensions.Logging; +using xAiApi.Interfaces.Extractors; + +namespace xAiApi.Providers +{ + public class XAiEmbeddingService : XAiEmbeddingServiceBase, IXAiEmbeddingService + { + public XAiEmbeddingService( + IXAiDataProvider dataProvider, + XAiApiConfiguration configuration, + ILogger logger, + XValidationProvider validationProvider, + IXFileContentExtractor fileContentExtractor + ) : base( + dataProvider, + configuration, + validationProvider, + logger, + fileContentExtractor, + XAiApiConstants.XAiEmbeddingModelName + ) + { } + } +} + ### FILE: C:\Users\saherelm\Documents\Projects\xSaherelmWorkspace\xAiApi\Providers\XAiEmbeddingServiceBase.cs using System; @@ -6060,7 +5947,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; @@ -6072,28 +5958,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 ) { // @@ -6104,10 +5985,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; } /// @@ -6276,10 +6161,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; @@ -6292,8 +6177,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 { @@ -6310,11 +6193,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; /// @@ -6325,17 +6207,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; @@ -6475,13 +6355,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( @@ -6634,123 +6529,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 // @@ -6975,12 +6753,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(); @@ -7190,7 +7081,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}"; } @@ -7279,120 +7173,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 } } @@ -7402,6 +7183,7 @@ namespace xAiApi.Providers using System; using System.Linq; using xModels.Dtos; +using xAiApi.Models; using System.Threading; using xAiApi.Constants; using xAiModels.Models; @@ -7412,14 +7194,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; @@ -7444,7 +7224,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; @@ -7452,7 +7232,7 @@ namespace xAiApi.Providers private readonly IXFileContentExtractor fileContentExtractor; protected XAIServiceBase( - IXFileProvider fileProvider, + IXAiRAGService ragProvider, IXAiDataProvider dataProvider, ILogger logger, XAiApiConfiguration configuration, @@ -7463,7 +7243,7 @@ namespace xAiApi.Providers { // this.logger = logger; - this.fileProvider = fileProvider; + this.ragProvider = ragProvider; this.dataProvider = dataProvider; this.configuration = configuration; this.validationProvider = validationProvider; @@ -7778,56 +7558,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 // @@ -8275,8 +8005,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, @@ -8294,7 +8024,7 @@ namespace xAiApi.Providers // // Check Project ... XAiProjectDto project = null; - if (projectId.IsDefaultGuid()) + if (!projectId.HasValue || projectId.Value.IsDefaultGuid()) { // project = await dataProvider.GetDefaultProject( @@ -8310,7 +8040,7 @@ namespace xAiApi.Providers { // project = await dataProvider.GetProject( - id: projectId, + id: projectId.Value, fillConversations: false, fillConversationMessages: false, cancellationToken: cancellationToken @@ -8324,12 +8054,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 ); @@ -8341,8 +8071,8 @@ namespace xAiApi.Providers { // conversation = await dataProvider.GetConversation( - id: conversationId, fillMessages: false, + id: conversationId.Value, cancellationToken: cancellationToken ); } @@ -8352,38 +8082,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 ); @@ -8396,102 +8146,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 ... @@ -8509,13 +8180,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 ); @@ -8731,11 +8402,13 @@ namespace xAiApi.Providers /// /// /// + /// /// /// private async Task> PrepareMemory( XAiProjectDto project, IEnumerable messages, + IEnumerable context = null, CancellationToken cancellationToken = default ) { @@ -8744,35 +8417,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()) { // @@ -8787,6 +8462,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 ... /// @@ -8842,7 +8567,6 @@ using xAiApi.Interfaces; using xCommons.Providers; using xAiModels.Interfaces; using xAiApi.Configurations; -using xFileService.Interfaces; using Microsoft.Extensions.Logging; using xAiApi.Interfaces.Extractors; @@ -8851,14 +8575,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, @@ -8870,41 +8594,6 @@ namespace xAiApi.Providers } } -### FILE: C:\Users\saherelm\Documents\Projects\xSaherelmWorkspace\xAiApi\Providers\XDefaultEmbeddingService.cs - -using xAiApi.Constants; -using xAiApi.Interfaces; -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 XDefaultEmbeddingService( - IXFileProvider fileProvider, - IXAiDataProvider dataProvider, - XAiApiConfiguration configuration, - XValidationProvider validationProvider, - ILogger logger, - IXFileContentExtractor fileContentExtractor - ) : base( - fileProvider, - dataProvider, - configuration, - validationProvider, - logger, - fileContentExtractor, - XAiApiConstants.XAiEmbeddingModelName - ) - { } - } -} - ### FILE: C:\Users\saherelm\Documents\Projects\xSaherelmWorkspace\xAiApi\Providers\XDefaultThinkingAiService.cs using xAiApi.Constants; @@ -8913,7 +8602,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; @@ -8922,7 +8610,7 @@ namespace xAiApi.Providers public class XDefaultThinkingAiService : XAIServiceBase, IXDefaultThinkingAiService { public XDefaultThinkingAiService( - IXFileProvider fileProvider, + IXAiRAGService ragProvider, IXAiDataProvider dataProvider, ILogger logger, XAiApiConfiguration configuration, @@ -8931,7 +8619,7 @@ namespace xAiApi.Providers ReasoningEffort effort = ReasoningEffort.Medium, ReasoningOutput output = ReasoningOutput.Full ) : base( - fileProvider, + ragProvider, dataProvider, logger, configuration, diff --git a/Documents/GeneratedContext/xDashboard-xAiModels-20261029_200138.txt b/Documents/GeneratedContext/xDashboard-xAiModels-20261030_194032.txt similarity index 99% rename from Documents/GeneratedContext/xDashboard-xAiModels-20261029_200138.txt rename to Documents/GeneratedContext/xDashboard-xAiModels-20261030_194032.txt index fa34fea..ace86c3 100644 --- a/Documents/GeneratedContext/xDashboard-xAiModels-20261029_200138.txt +++ b/Documents/GeneratedContext/xDashboard-xAiModels-20261030_194032.txt @@ -1636,7 +1636,7 @@ namespace xAiModels.Extensions /// public static ChatMessage ToChatMessages( this XAiMessageDto source, - IList additionalContents = null + IList additionalContents = null ) { // @@ -4409,12 +4409,12 @@ namespace xAiModels.Models /// /// Specified Project Id ... /// - public Guid ProjectId { get; set; } + public Guid? ProjectId { get; set; } /// /// Specified Conversation Id ... /// - public Guid ConversationId { get; set; } + public Guid? ConversationId { get; set; } } } diff --git a/Documents/GeneratedContext/xDashboard-xAiService-20261029_200139.txt b/Documents/GeneratedContext/xDashboard-xAiService-20261030_194033.txt similarity index 100% rename from Documents/GeneratedContext/xDashboard-xAiService-20261029_200139.txt rename to Documents/GeneratedContext/xDashboard-xAiService-20261030_194033.txt diff --git a/Documents/Resources/Json/Authenticate.json b/Documents/Resources/Json/Authenticate.json index 028c69c..74f545d 100644 --- a/Documents/Resources/Json/Authenticate.json +++ b/Documents/Resources/Json/Authenticate.json @@ -4,18 +4,31 @@ } { - "accessToken": "E8C7676F04D16F526B8F3C6F2844BB3101207F4B027DE550AAF5AB697B41E8A7", - "refreshToken": "5EA163B83E3299FDDD13EC3425F9E028EDF8002D92643F255BA120D6E7059B2F", - "expiresAt": 1792996696 + "accessToken": "EE124E2A77328DC1F31421B95A5AE85D9C3A63F4923F9B11AEDABCE1F6FD1FC0", + "refreshToken": "EDD3C6C09C0DA61E18A04B6E77A20F45F161B63B6A544C52461A460BD400F443", + "expiresAt": 1793347477 } { - "sessionId": "1accad72-0c3d-4801-b0d1-07d7c0b65f10", - "filesCount": 12, - "chunksCount": 274, - "totalVectorsCount": 274, + "sessionId": "7f871358-1f00-4444-a10f-d3aed06e5826", + "filesCount": 3, + "chunksCount": 128, + "totalVectorsCount": 128, "skippedFiles": [], - "expiresAtUtc": "2026-10-26T06:10:41.9680924Z" + "expiresAtUtc": "2026-10-30T07:49:41.5926071Z" +} + +{ + "sessionId": "7f871358-1f00-4444-a10f-d3aed06e5826", + "prompt": "what is MCP ?", + "topK": 6, + "minScore": 3.5 +} + +{ + "prompt": "who are you ?", + "projectId": "", + "conversationId": "" } IDS RPK: diff --git a/Modules/xAiModels b/Modules/xAiModels index ef1421d..31a0d09 160000 --- a/Modules/xAiModels +++ b/Modules/xAiModels @@ -1 +1 @@ -Subproject commit ef1421def4c2b03ad2c86ca0adcfe82f900cd89b +Subproject commit 31a0d097c0a5e158d2fa6bbe630c5ac8845137c1 diff --git a/xAiApi b/xAiApi index 37d4e62..ad8ea9c 160000 --- a/xAiApi +++ b/xAiApi @@ -1 +1 @@ -Subproject commit 37d4e622e9cf3b114146128a613d7a0bb5bbfe42 +Subproject commit ad8ea9c1dd347f08f0f5966c014770acd0e748de