From ce5db9e34941464adf3a2c91ad471d5b6ac44cd9 Mon Sep 17 00:00:00 2001 From: Hadi Khazaee Asl Date: Sat, 31 Oct 2026 17:19:17 +0330 Subject: [PATCH] last ... --- Controllers/DefaultEmbeddingController.cs | 30 -- Controllers/DefaultThinkingAiController.cs | 26 - .../XAiEmbeddingServiceControllerBase.cs | 113 ----- Controllers/XAiServiceControllerBase.cs | 475 +++++++++++------- Interfaces/IXAiServiceBase.cs | 48 +- Providers/XAIServiceBase.cs | 310 ++++++++++-- 6 files changed, 593 insertions(+), 409 deletions(-) delete mode 100644 Controllers/DefaultEmbeddingController.cs delete mode 100644 Controllers/DefaultThinkingAiController.cs delete mode 100644 Controllers/XAiEmbeddingServiceControllerBase.cs diff --git a/Controllers/DefaultEmbeddingController.cs b/Controllers/DefaultEmbeddingController.cs deleted file mode 100644 index 7ef3879..0000000 --- a/Controllers/DefaultEmbeddingController.cs +++ /dev/null @@ -1,30 +0,0 @@ -using xAiApi.Interfaces; -using xCommons.Providers; -using xCommons.Configurations; -using Microsoft.AspNetCore.Mvc; -using xIdentityService.Interfaces; -using Microsoft.Extensions.Logging; -using Microsoft.AspNetCore.Authorization; - -namespace xAiApi.Controllers -{ - [Authorize] - [Route("[controller]")] - public class DefaultEmbeddingController : XAiEmbeddingServiceControllerBase - { - public DefaultEmbeddingController( - ILogger logger, - IXAiEmbeddingService embeddingService, - XAppConfiguration appConfiguration, - IXIdentityProvider identityProvider, - XValidationProvider validationProvider - ) : base( - logger: logger, - appConfiguration: appConfiguration, - identityProvider: identityProvider, - embeddingService: embeddingService, - validationProvider: validationProvider - ) - { } - } -} \ No newline at end of file diff --git a/Controllers/DefaultThinkingAiController.cs b/Controllers/DefaultThinkingAiController.cs deleted file mode 100644 index ec101a5..0000000 --- a/Controllers/DefaultThinkingAiController.cs +++ /dev/null @@ -1,26 +0,0 @@ -using xAiApi.Interfaces; -using xCommons.Providers; -using xCommons.Configurations; -using xIdentityService.Interfaces; -using Microsoft.Extensions.Logging; - -namespace xAiApi.Controllers -{ - public class DefaultThinkingAiController : XAiServiceControllerBase - { - public DefaultThinkingAiController( - ILogger logger, - IXDefaultThinkingAiService aiService, - XAppConfiguration appConfiguration, - IXIdentityProvider identityProvider, - XValidationProvider validationProvider - ) : base( - logger, - aiService, - appConfiguration, - identityProvider, - validationProvider - ) - { } - } -} \ No newline at end of file diff --git a/Controllers/XAiEmbeddingServiceControllerBase.cs b/Controllers/XAiEmbeddingServiceControllerBase.cs deleted file mode 100644 index 0ad6636..0000000 --- a/Controllers/XAiEmbeddingServiceControllerBase.cs +++ /dev/null @@ -1,113 +0,0 @@ -using System; -using System.Threading; -using xAiApi.Interfaces; -using xCommons.Providers; -using System.Threading.Tasks; -using xCommons.Configurations; -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 : XBaseIdentityApiV1Controller, IXAiEmbeddingServiceControllerBase - where TEmbeddingService : IXAiEmbeddingServiceBase - { - private readonly TEmbeddingService embeddingService; - - protected XAiEmbeddingServiceControllerBase( - ILogger logger, - XAppConfiguration appConfiguration, - IXIdentityProvider identityProvider, - XValidationProvider validationProvider, - TEmbeddingService embeddingService - ) : base( - logger, - appConfiguration, - identityProvider, - validationProvider - ) - { - this.embeddingService = embeddingService; - } - - /// - /// Request For Embedding Specified String ... - /// - /// - /// - /// - [AllowAnonymous] - [HttpGet("Embedding")] - public async Task> Embedding( - [FromQuery] string content, - CancellationToken cancellationToken = default - ) - { - // - try - { - // - // Validate ... - ValidationProvider.NotEmpty(content); - - // - var result = await embeddingService.Embedding( - content: content, - cancellationToken: cancellationToken - ); - - // - return Ok(result); - } - catch (Exception ex) - { - // - var result = GetExceptionActionResult(ex); - return result; - } - } - - /// - /// Request For Embedding Specified Batch ... - /// - /// - /// - /// - [AllowAnonymous] - [HttpGet("Embeddings")] - public async Task>> Embeddings( - [FromQuery] string[] batch, - CancellationToken cancellationToken = default - ) - { - // - try - { - // - // Validate ... - ValidationProvider.NotZeroChilds(batch); - - // - var result = await embeddingService.Embeddings( - batch: batch, - cancellationToken: cancellationToken - ); - - // - return Ok(result); - } - catch (Exception ex) - { - // - var result = GetExceptionActionResult(ex); - return result; - } - } - } -} \ No newline at end of file diff --git a/Controllers/XAiServiceControllerBase.cs b/Controllers/XAiServiceControllerBase.cs index 8a76e2d..0da435c 100644 --- a/Controllers/XAiServiceControllerBase.cs +++ b/Controllers/XAiServiceControllerBase.cs @@ -162,16 +162,282 @@ namespace xAiApi.Controllers } /// - /// Write Validation Error for Streaming Endpoints (before Stream Starts) ... + /// Ask Question and Get Response ... /// + /// + /// /// - [NonAction] - protected async Task WriteStreamValidationError() + [HttpPost("Ask")] + [Authorize(Policy = XPolicies.EnabledUser)] + public async Task> Ask( + [FromBody] XAiResponseRequest request, + CancellationToken cancellationToken = default + ) { // - Response.StatusCode = StatusCodes.Status400BadRequest; - Response.ContentType = "application/json; charset=utf-8"; - await Response.WriteAsync(XException.InvalidArgs.ToXError().ToJSON()); + try + { + // + // Validate ... + if (!request.IsValid()) + { + XException.InvalidArgs.Throw(); + } + + // + var userInfo = await GetUserInfo(); + var connectionId = GetConnectionId(); + + // + var result = await aiService.AskAsync( + files: null, + topK: request.TopK, + userInfo: userInfo, + prompt: request.Prompt, + minScore: request.MinScore, + connectionId: connectionId, + projectId: request.ProjectId, + cancellationToken: cancellationToken, + conversationId: request.ConversationId + ); + + // + return Ok(result); + } + catch (Exception ex) + { + // + var result = GetExceptionActionResult(ex); + return result; + } + } + + /// + /// Ask Question and Get Response Stream ... + /// + /// + /// + /// + [HttpPost("AskStream")] + [Authorize(Policy = XPolicies.EnabledUser)] + public async Task AskStream( + [FromBody] XAiResponseRequest request, + CancellationToken cancellationToken = default + ) + { + // + // Validate (before Stream Starts -> Proper Http Error) ... + if (!request.IsValid()) + { + await WriteStreamValidationError(); + return; + } + + // + try + { + // + var userInfo = await GetUserInfo(); + var connectionId = GetConnectionId(); + + // + // Configure SSE Response ... + Response.PrepareSseResponse(); + + // + var enumerable = aiService.AskAsEnumerable( + files: null, + topK: request.TopK, + userInfo: userInfo, + prompt: request.Prompt, + minScore: request.MinScore, + connectionId: connectionId, + projectId: request.ProjectId, + cancellationToken: cancellationToken, + conversationId: request.ConversationId + ); + + // + // Format: data: {json}\n\n + await foreach (var resp in enumerable) + { + // + // Skip Empty Responses ... + if (resp.IsNullOrDefault()) + { + continue; + } + + // + await Response.WriteSseEventAsync( + data: resp, + cancellationToken: cancellationToken + ); + } + + // + await Response.WriteSseDoneAsync(cancellationToken); + } + catch (Exception ex) when (ex.IsClientCancellation(cancellationToken)) + { + // Client Disconnected ... + } + catch (Exception ex) + { + // + Logger.LogError(ex, "AskStream Failed ..."); + if (!Response.HasStarted) + { + // + var result = GetExceptionActionResult(ex); + await result.ExecuteResultAsync(ControllerContext); + return; + } + + // + await Response.WriteSseErrorAsync(ex.Message); + } + } + + /// + /// Ask Question with Files and Get Response ... + /// + /// + /// + /// + [HttpPost("AskWithFiles")] + [Consumes("multipart/form-data")] + [Authorize(Policy = XPolicies.EnabledUser)] + public async Task> AskWithFiles( + [FromForm] XAiResponseRequest request, + [FromForm] IFormFileCollection files, + CancellationToken cancellationToken = default + ) + { + // + try + { + // + // Validate ... + if (!request.IsValid()) + { + XException.InvalidArgs.Throw(); + } + + // + var userInfo = await GetUserInfo(); + var connectionId = GetConnectionId(); + + // + var result = await aiService.AskAsync( + files: null, + topK: request.TopK, + userInfo: userInfo, + prompt: request.Prompt, + minScore: request.MinScore, + connectionId: connectionId, + projectId: request.ProjectId, + cancellationToken: cancellationToken, + conversationId: request.ConversationId + ); + + // + return Ok(result); + } + catch (Exception ex) + { + var result = GetExceptionActionResult(ex); + return result; + } + } + + /// + /// Ask Question with Files and Get Response Stream ... + /// + /// + /// + /// + [HttpPost("AskWithFilesStream")] + [Consumes("multipart/form-data")] + [Authorize(Policy = XPolicies.EnabledUser)] + public async Task AskWithFilesStream( + [FromForm] XAiResponseRequest request, + [FromForm] IFormFileCollection files, + CancellationToken cancellationToken = default + ) + { + // + // Validate (before Stream Starts -> Proper Http Error) ... + if (!request.IsValid()) + { + await WriteStreamValidationError(); + return; + } + + // + try + { + // + var userInfo = await GetUserInfo(); + var connectionId = GetConnectionId(); + + // + // Configure SSE Response ... + Response.PrepareSseResponse(); + + // + var enumerable = aiService.AskAsEnumerable( + files: files, + topK: request.TopK, + userInfo: userInfo, + prompt: request.Prompt, + minScore: request.MinScore, + connectionId: connectionId, + projectId: request.ProjectId, + cancellationToken: cancellationToken, + conversationId: request.ConversationId + ); + + // + // Format: data: {json}\n\n + await foreach (var resp in enumerable) + { + // + // Skip Empty Responses ... + if (resp.IsNullOrDefault()) + { + continue; + } + + // + await Response.WriteSseEventAsync( + data: resp, + cancellationToken: cancellationToken + ); + } + + // + await Response.WriteSseDoneAsync(cancellationToken); + } + catch (Exception ex) when (ex.IsClientCancellation(cancellationToken)) + { + // Client Disconnected ... + } + catch (Exception ex) + { + // + Logger.LogError(ex, "AskStream Failed ..."); + if (!Response.HasStarted) + { + // + var result = GetExceptionActionResult(ex); + await result.ExecuteResultAsync(ControllerContext); + return; + } + + // + await Response.WriteSseErrorAsync(ex.Message); + } } #endregion @@ -541,7 +807,7 @@ namespace xAiApi.Controllers } } #endregion - + // #region Content Extraction ... /// @@ -556,9 +822,10 @@ namespace xAiApi.Controllers [Authorize(Policy = XPolicies.EnabledUser)] public async Task> ExtractContent( [FromForm] IFormFileCollection files, - [FromForm] string extractors = "*", - CancellationToken cancellationToken = default - ) { + [FromForm] string extractors = null, + CancellationToken cancellationToken = default + ) + { // try { @@ -599,192 +866,18 @@ namespace xAiApi.Controllers #endregion // - #region Data Actions ... + #region Non Actions ... /// - /// Ask Question and Get Response ... + /// Write Validation Error for Streaming Endpoints (before Stream Starts) ... /// - /// - /// /// - [HttpPost("Ask")] - [Authorize(Policy = XPolicies.EnabledUser)] - public async Task> Ask( - [FromBody] XAiResponseRequest request, - CancellationToken cancellationToken = default - ) + [NonAction] + protected async Task WriteStreamValidationError() { // - try - { - // - // Validate ... - if (!request.IsValid()) - { - XException.InvalidArgs.Throw(); - } - - // - var userInfo = await GetUserInfo(); - var connectionId = GetConnectionId(); - - // - // TODO: Reading Fiels Form Collection and Attach it ... - var result = await aiService.AskAsync( - files: null, - prompt: request.Prompt, - ownerId: userInfo.UserId, - connectionId: connectionId, - projectId: request.ProjectId, - cancellationToken: cancellationToken, - conversationId: request.ConversationId - ); - - // - return Ok(result); - } - catch (Exception ex) - { - // - var result = GetExceptionActionResult(ex); - return result; - } - } - - /// - /// Ask Question and Get Response Stream ... - /// - /// - /// - /// - [HttpPost("AskStream")] - [Authorize(Policy = XPolicies.EnabledUser)] - public async Task AskStream( - [FromBody] XAiResponseRequest request, - CancellationToken cancellationToken = default - ) - { - // - // Validate (before Stream Starts -> Proper Http Error) ... - if (!request.IsValid()) - { - await WriteStreamValidationError(); - return; - } - - // - try - { - // - var userInfo = await GetUserInfo(); - var connectionId = GetConnectionId(); - - // - // Configure SSE Response ... - Response.PrepareSseResponse(); - - // - // TODO: Reading Fiels Form Collection and Attach it ... - var enumerable = aiService.AskAsEnumerable( - files: null, - prompt: request.Prompt, - ownerId: userInfo.UserId, - connectionId: connectionId, - projectId: request.ProjectId.Value, - cancellationToken: cancellationToken, - conversationId: request.ConversationId.Value - ); - - // - // Format: data: {json}\n\n - await foreach (var resp in enumerable) - { - // - // Skip Empty Responses ... - if (resp.IsNullOrDefault()) - { - continue; - } - - // - await Response.WriteSseEventAsync( - data: resp, - cancellationToken: cancellationToken - ); - } - - // - await Response.WriteSseDoneAsync(cancellationToken); - } - catch (Exception ex) when (ex.IsClientCancellation(cancellationToken)) - { - // Client Disconnected ... - } - catch (Exception ex) - { - // - Logger.LogError(ex, "AskStream Failed"); - if (!Response.HasStarted) - { - // - var result = GetExceptionActionResult(ex); - await result.ExecuteResultAsync(ControllerContext); - return; - } - - // - await Response.WriteSseErrorAsync(ex.Message); - } - } - - /// - /// Ask Question with Files and Get Response ... - /// - /// - /// - /// - [HttpPost("AskWithFiles")] - [Consumes("multipart/form-data")] - [Authorize(Policy = XPolicies.EnabledUser)] - public async Task> AskWithFiles( - [FromForm] XAiResponseRequest request, - [FromForm] IFormFileCollection files, - CancellationToken cancellationToken = default - ) - { - // - try - { - // - // Validate ... - if (!request.IsValid()) - { - XException.InvalidArgs.Throw(); - } - - // - var userInfo = await GetUserInfo(); - var connectionId = GetConnectionId(); - - // - var result = await aiService.AskAsync( - files: files, - userInfo: userInfo, - prompt: request.Prompt, - ownerId: userInfo.UserId, - connectionId: connectionId, - projectId: request.ProjectId, - cancellationToken: cancellationToken, - conversationId: request.ConversationId - ); - - // - return Ok(result); - } - catch (Exception ex) - { - var result = GetExceptionActionResult(ex); - return result; - } + Response.StatusCode = StatusCodes.Status400BadRequest; + Response.ContentType = "application/json; charset=utf-8"; + await Response.WriteAsync(XException.InvalidArgs.ToXError().ToJSON()); } #endregion } diff --git a/Interfaces/IXAiServiceBase.cs b/Interfaces/IXAiServiceBase.cs index abce7f6..f558c3d 100644 --- a/Interfaces/IXAiServiceBase.cs +++ b/Interfaces/IXAiServiceBase.cs @@ -50,11 +50,38 @@ namespace xAiApi.Interfaces CancellationToken cancellationToken = default ); + /// + /// Ask a Question using Provided Context Chunks (RAG) without Persisting ... + /// + /// + /// + /// + /// + Task AskWithContextAsync( + string prompt, + IEnumerable context, + CancellationToken cancellationToken = default + ); + + /// + /// Ask a Question using Provided Context Chunks (RAG) and Stream Response ... + /// + /// + /// + /// + /// + IAsyncEnumerable AskWithContextAsEnumerable( + string prompt, + IEnumerable context, + CancellationToken cancellationToken = default + ); + /// /// Ask a Question as Prompt and Retrieve Response ... /// /// - /// + /// + /// /// /// /// @@ -64,9 +91,10 @@ namespace xAiApi.Interfaces /// Task AskAsync( string prompt, - string ownerId, - Guid? projectId, - Guid? conversationId, + int? topK = null, + float? minScore = null, + Guid? projectId = null, + Guid? conversationId = null, string connectionId = null, IFormFileCollection files = null, XUserClaimsInfoDto userInfo = null, @@ -77,20 +105,24 @@ namespace xAiApi.Interfaces /// Ask a Question as Prompt and Retrieve Response as Async Enumerable ... /// /// - /// + /// + /// /// /// /// /// + /// /// /// IAsyncEnumerable AskAsEnumerable( string prompt, - string ownerId, - Guid projectId, - Guid conversationId, + int? topK = null, + float? minScore = null, + Guid? projectId = null, + Guid? conversationId = null, string connectionId = null, IFormFileCollection files = null, + XUserClaimsInfoDto userInfo = null, CancellationToken cancellationToken = default ); #endregion diff --git a/Providers/XAIServiceBase.cs b/Providers/XAIServiceBase.cs index 3ee112c..2e174da 100644 --- a/Providers/XAIServiceBase.cs +++ b/Providers/XAIServiceBase.cs @@ -167,12 +167,100 @@ namespace xAiApi.Providers yield return res.Text; } } - + + /// + /// 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 = GetHistory(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 = GetHistory(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; + } + } + /// /// Ask a Question as Prompt and Retrieve Response ... /// /// - /// + /// + /// /// /// /// @@ -182,9 +270,10 @@ namespace xAiApi.Providers /// public virtual async Task AskAsync( string prompt, - string ownerId, - Guid? projectId, - Guid? conversationId, + int? topK = null, + float? minScore = null, + Guid? projectId = null, + Guid? conversationId = null, string connectionId = null, IFormFileCollection files = null, XUserClaimsInfoDto userInfo = null, @@ -196,9 +285,36 @@ namespace xAiApi.Providers validationProvider .GroupValidationBuilder() .AddNotEmpty(prompt) - .AddNotEmpty(ownerId) + .AddNotNull(userInfo) + .AddNotEmpty(userInfo.UserId) .ValidateGroup(); + // + // Normalize ... + if (!topK.HasValue || + topK.Value < 1 || + topK.Value > configuration.RAGDescriptor.MaxTopK + ) + { + // + if (!topK.HasValue || + (topK.HasValue && topK.Value < 1)) + { + topK = configuration.RAGDescriptor.DefaultTopK; + } + else if (topK.HasValue && topK.Value > configuration.RAGDescriptor.MaxTopK) + { + topK = configuration.RAGDescriptor.MaxTopK; + } + } + if (!minScore.HasValue || + minScore.Value <= 0 || + minScore.Value > 1 + ) + { + minScore = configuration.RAGDescriptor.DefaultMinScore; + } + // // Check Project ... XAiProjectDto project = null; @@ -206,7 +322,7 @@ namespace xAiApi.Providers { // project = await dataProvider.GetDefaultProject( - ownerId: ownerId, + ownerId: userInfo.UserId, connectionId: connectionId, cancellationToken: cancellationToken ); @@ -236,7 +352,7 @@ namespace xAiApi.Providers { // conversation = await dataProvider.GetDefaultConversation( - ownerId: ownerId, + ownerId: userInfo.UserId, projectId: projectId.Value, connectionId: connectionId, cancellationToken: cancellationToken @@ -288,8 +404,10 @@ namespace xAiApi.Providers // Prepare Knowledge Request ... var knowledgeRequest = new XAiKnowledgeAskRequest { + TopK = topK, Prompt = prompt, IncludeUser = true, + MinScore = minScore, IncludeGlobal = true, ProjectId = projectId, ConversationId = conversationId @@ -321,8 +439,8 @@ namespace xAiApi.Providers var promptMessage = new XAiMessageDto { Content = prompt, - OwnerId = ownerId, Role = XAiChatRole.User, + OwnerId = userInfo.UserId, CreatedOn = DateTime.UtcNow, ConversationId = conversationId.Value, ConversationTitle = conversation.Title @@ -355,7 +473,7 @@ namespace xAiApi.Providers var result = new XAiMessageDto { Content = answer, - OwnerId = ownerId, + OwnerId = userInfo.UserId, CreatedOn = DateTime.UtcNow, Role = XAiChatRole.Assistant, ConversationId = conversationId.Value, @@ -376,20 +494,24 @@ namespace xAiApi.Providers /// Ask a Question as Prompt and Retrieve Response as Async Enumerable ... /// /// - /// + /// + /// /// /// /// /// + /// /// /// public virtual async IAsyncEnumerable AskAsEnumerable( string prompt, - string ownerId, - Guid projectId, - Guid conversationId, + int? topK = null, + float? minScore = null, + Guid? projectId = null, + Guid? conversationId = null, string connectionId = null, IFormFileCollection files = null, + XUserClaimsInfoDto userInfo = null, [EnumeratorCancellation] CancellationToken cancellationToken = default ) @@ -399,17 +521,44 @@ namespace xAiApi.Providers validationProvider .GroupValidationBuilder() .AddNotEmpty(prompt) - .AddNotEmpty(ownerId) + .AddNotNull(userInfo) + .AddNotEmpty(userInfo.UserId) .ValidateGroup(); + // + // Normalize ... + if (!topK.HasValue || + topK.Value < 1 || + topK.Value > configuration.RAGDescriptor.MaxTopK + ) + { + // + if (!topK.HasValue || + (topK.HasValue && topK.Value < 1)) + { + topK = configuration.RAGDescriptor.DefaultTopK; + } + else if (topK.HasValue && topK.Value > configuration.RAGDescriptor.MaxTopK) + { + topK = configuration.RAGDescriptor.MaxTopK; + } + } + if (!minScore.HasValue || + minScore.Value <= 0 || + minScore.Value > 1 + ) + { + minScore = configuration.RAGDescriptor.DefaultMinScore; + } + // // Check Project ... XAiProjectDto project = null; - if (projectId.IsDefaultGuid()) + if (!projectId.HasValue || projectId.Value.IsDefaultGuid()) { // project = await dataProvider.GetDefaultProject( - ownerId: ownerId, + ownerId: userInfo.UserId, connectionId: connectionId, cancellationToken: cancellationToken ); @@ -421,7 +570,7 @@ namespace xAiApi.Providers { // project = await dataProvider.GetProject( - id: projectId, + id: projectId.Value, fillConversations: false, fillConversationMessages: false, cancellationToken: cancellationToken @@ -435,12 +584,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, + ownerId: userInfo.UserId, + projectId: projectId.Value, connectionId: connectionId, cancellationToken: cancellationToken ); @@ -452,8 +601,8 @@ namespace xAiApi.Providers { // conversation = await dataProvider.GetConversation( - id: conversationId, fillMessages: false, + id: conversationId.Value, cancellationToken: cancellationToken ); } @@ -463,20 +612,60 @@ 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 + { + TopK = topK, + Prompt = prompt, + IncludeUser = true, + MinScore = minScore, + IncludeGlobal = true, + ProjectId = projectId, + ConversationId = conversationId + }; + var context = await ragProvider.RetrieveAsync( + userInfo: userInfo, + request: knowledgeRequest, cancellationToken: cancellationToken ); // - // TODO: Parse Files ... - // for Attached them into Prompt Message ... + // 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 ); @@ -486,33 +675,33 @@ namespace xAiApi.Providers var promptMessage = new XAiMessageDto { Content = prompt, - OwnerId = ownerId, Role = XAiChatRole.User, + OwnerId = userInfo.UserId, CreatedOn = DateTime.UtcNow, - ConversationId = conversationId, + ConversationId = conversationId.Value, + ConversationTitle = conversation.Title }; + + // + // Save Prompt Message ... promptMessage = await dataProvider.AddMessage( item: promptMessage, connectionId: connectionId, - conversationId: conversationId, - cancellationToken: cancellationToken - ); - promptMessage = await dataProvider.Enrich( - source: promptMessage, + conversationId: conversationId.Value, cancellationToken: cancellationToken ); // - // Attach Uploaded Files ... + // Converts to ChatMessage ... var promptChatMessage = promptMessage - .ToChatMessages(); + .ToChatMessages(additionalContents: []); history.Add(promptChatMessage); // // Ask Questions From LLM ... using var client = Descriptor.GetClient(); var enumerable = client.GetStreamingResponseAsync( - options: null, + options: Options, messages: history ); @@ -531,9 +720,9 @@ namespace xAiApi.Providers // var resp = new XAiResonseMessage { - OwnerId = ownerId, Content = res.Text, Sequence = sequence, + OwnerId = userInfo.UserId, Role = XAiChatRole.System, RespondTo = promptMessage.Id, RespondedOn = DateTime.UtcNow, @@ -552,15 +741,15 @@ namespace xAiApi.Providers var result = new XAiMessageDto { Content = answer, - OwnerId = ownerId, + OwnerId = userInfo.UserId, Role = XAiChatRole.System, CreatedOn = DateTime.UtcNow, - ConversationId = conversationId + ConversationId = conversationId.Value }; result = await dataProvider.AddMessage( item: result, connectionId: connectionId, - conversationId: conversationId, + conversationId: conversationId.Value, cancellationToken: cancellationToken ); } @@ -1084,6 +1273,44 @@ namespace xAiApi.Providers return result; } + /// + /// Build Chat History for RAG: + /// [System: Introduction + ChatWithDocuments Prompt + Context Block] + [User: Prompt] ... + /// + /// + /// + /// + protected virtual IList GetHistory( + 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; + } + /// /// Implementing Memory Strategy here ... /// @@ -1222,6 +1449,7 @@ namespace xAiApi.Providers history.Add(prompt); using var client = Descriptor.GetClient(); var response = await client.GetResponseAsync( + options: Options, messages: history, cancellationToken: cancellationToken );