diff --git a/Controllers/ChatWithDocumentsController.cs b/Controllers/ChatWithDocumentsController.cs index 9c64eee..7cc4ed7 100644 --- a/Controllers/ChatWithDocumentsController.cs +++ b/Controllers/ChatWithDocumentsController.cs @@ -189,8 +189,8 @@ namespace xAiApi.Controllers // Embed in Batches ... var fileVectors = await EmbedChunks( chunks: chunks, - mimeType: mimeType, fileName: file.FileName, + mimeType: mimeType, cancellationToken: cancellationToken ); diff --git a/Controllers/XAiServiceControllerBase.cs b/Controllers/XAiServiceControllerBase.cs index 8aa90ed..f35f3d2 100644 --- a/Controllers/XAiServiceControllerBase.cs +++ b/Controllers/XAiServiceControllerBase.cs @@ -464,7 +464,7 @@ namespace xAiApi.Controllers // var result = await aiService.AskAsync( - files: null, + files: files, topK: request.TopK, userInfo: userInfo, type: request.Type, diff --git a/Extensions/XModelsExtensions.cs b/Extensions/XModelsExtensions.cs index a2225d7..85c0de1 100644 --- a/Extensions/XModelsExtensions.cs +++ b/Extensions/XModelsExtensions.cs @@ -73,9 +73,7 @@ namespace xAiApi.Extensions var result = !source.IsNullOrDefault() && !source.Prompt.IsNullOrEmpty() && - !source.SessionId.IsDefaultGuid() && - source.TopK.HasValue && source.TopK.Value > 0 && - source.MinScore.HasValue && source.MinScore.Value >= -1f && source.MinScore.Value <= 1f; + !source.SessionId.IsDefaultGuid(); // return result; diff --git a/Interfaces/IXAiEmbeddingServiceControllerBase.cs b/Interfaces/IXAiEmbeddingServiceControllerBase.cs deleted file mode 100644 index 5c6b841..0000000 --- a/Interfaces/IXAiEmbeddingServiceControllerBase.cs +++ /dev/null @@ -1,34 +0,0 @@ -using System.Threading; -using System.Threading.Tasks; -using Microsoft.AspNetCore.Mvc; -using System.Collections.Generic; - -namespace xAiApi.Interfaces -{ - public interface IXAiEmbeddingServiceControllerBase - { - /// - /// Request For Embedding Specified String ... - /// - /// - /// - /// - [HttpGet("Embedding")] - Task> Embedding( - [FromQuery] string content, - CancellationToken cancellationToken = default - ); - - /// - /// Request For Embedding Specified Batch ... - /// - /// - /// - /// - [HttpGet("Embeddings")] - Task>> Embeddings( - [FromQuery] string[] batch, - CancellationToken cancellationToken = default - ); - } -} \ No newline at end of file diff --git a/Middlewares/XAiModelProxyMiddleware.cs b/Middlewares/XAiModelProxyMiddleware.cs index ca533bd..f6a2d96 100644 --- a/Middlewares/XAiModelProxyMiddleware.cs +++ b/Middlewares/XAiModelProxyMiddleware.cs @@ -106,7 +106,7 @@ namespace xAiApi.Middlewares var tokenModel = await context.RetrieveTokensAsXTokenResponse(); var isAuthenticated = // - (!apiKey.IsNullOrEmpty()) | + (!apiKey.IsNullOrEmpty()) || // (!tokenModel.IsNull() && !tokenModel.AccessToken.IsNullOrEmpty()) ; diff --git a/Models/XPreparedChatContext.cs b/Models/XPreparedChatContext.cs new file mode 100644 index 0000000..9ad5c49 --- /dev/null +++ b/Models/XPreparedChatContext.cs @@ -0,0 +1,37 @@ +using xAiModels.Models.Dtos; +using Microsoft.Extensions.AI; +using System.Collections.Generic; + +namespace xAiApi.Models +{ + /// + /// a Shared Context Between Actions for Generation ... + /// + public class XPreparedChatContext + { + /// + /// Specified Related Project, if Exists ... + /// + public XAiProjectDto Project { get; set; } = null; + + /// + /// Specified Related Conversation, if Exists ... + /// + public XAiConversationDto Conversation { get; set; } = null; + + /// + /// Specified Message History, if Exists ... + /// + public IList History { get; set; } = []; + + /// + /// Specified Vector Search Conext, if Exists ... + /// + public IList Context { get; set; } = []; + + /// + /// Specified Persisted Prompt, if Exists ... + /// + public XAiMessageDto PersistedPromptMessage { get; set; } = null; + } +} \ No newline at end of file diff --git a/Providers/XAIServiceBase.cs b/Providers/XAIServiceBase.cs index 2b0fa43..3efe183 100644 --- a/Providers/XAIServiceBase.cs +++ b/Providers/XAIServiceBase.cs @@ -285,72 +285,39 @@ namespace xAiApi.Providers ) { // - // Validate Args ... + // Validation ... validationProvider .GroupValidationBuilder() - .AddNotEmpty(prompt) - .AddNotNull(userInfo) - .AddNotEmpty(userInfo.UserId) - .ValidateGroup(); + .AddNotEmpty(prompt) + .AddNotNull(userInfo) + .AddNotEmpty(userInfo.UserId) + .ValidateGroup(); // - // Normalize ... - if (!topK.HasValue || - topK.Value < 1 || - topK.Value > configuration.RAGDescriptor.MaxTopK - ) - { - // - if (!topK.HasValue || - (topK.HasValue && topK.Value < 1)) - { - topK = configuration.RAGDescriptor.DefaultTopK; - } - else if (topK.HasValue && topK.Value > configuration.RAGDescriptor.MaxTopK) - { - topK = configuration.RAGDescriptor.MaxTopK; - } - } - if (!minScore.HasValue || - minScore.Value <= 0 || - minScore.Value > 1 - ) - { - minScore = configuration.RAGDescriptor.DefaultMinScore; - } - if (type.IsNullOrEmpty()) - { - type = XAiModelsConstants.XAiDefaultKnowledgeType; - } - - // - // Prepare Knowledge Request ... - var knowledgeRequest = new XAiKnowledgeAskRequest - { - TopK = topK, - Type = type, - Prompt = prompt, - IncludeUser = true, - MinScore = minScore, - IncludeGlobal = true, - }; - var context = await ragProvider.RetrieveAsync( + // Prepare Requirements ... + var prep = await PrepareChatRequirementsAsync( + topK: topK, + type: type, + files: null, + prompt: prompt, + projectId: null, + minScore: minScore, userInfo: userInfo, - request: knowledgeRequest, + connectionId: null, + conversationId: null, + persistPrompt: false, + resolveConversation: false, cancellationToken: cancellationToken ); // using var client = Descriptor.GetClient(); - var history = GetHistory(prompt, context); - var response = await client.GetResponseAsync( - options: Options, - messages: history, - cancellationToken: cancellationToken - ); - - // - // Validate Response ... + var response = await client + .GetResponseAsync( + options: Options, + messages: prep.History, + cancellationToken: cancellationToken + ); if (!response.IsValid()) { client.Dispose(); @@ -358,10 +325,7 @@ namespace xAiApi.Providers } // - var result = response.Text; - - // - return result; + return response.Text; } /// @@ -385,72 +349,40 @@ namespace xAiApi.Providers ) { // - // Validate Args ... + // Validation ... validationProvider .GroupValidationBuilder() - .AddNotEmpty(prompt) - .AddNotNull(userInfo) - .AddNotEmpty(userInfo.UserId) - .ValidateGroup(); + .AddNotEmpty(prompt) + .AddNotNull(userInfo) + .AddNotEmpty(userInfo.UserId) + .ValidateGroup(); // - // Normalize ... - if (!topK.HasValue || - topK.Value < 1 || - topK.Value > configuration.RAGDescriptor.MaxTopK - ) - { - // - if (!topK.HasValue || - (topK.HasValue && topK.Value < 1)) - { - topK = configuration.RAGDescriptor.DefaultTopK; - } - else if (topK.HasValue && topK.Value > configuration.RAGDescriptor.MaxTopK) - { - topK = configuration.RAGDescriptor.MaxTopK; - } - } - if (!minScore.HasValue || - minScore.Value <= 0 || - minScore.Value > 1 - ) - { - minScore = configuration.RAGDescriptor.DefaultMinScore; - } - if (type.IsNullOrEmpty()) - { - type = XAiModelsConstants.XAiDefaultKnowledgeType; - } - - // - // Prepare Knowledge Request ... - var knowledgeRequest = new XAiKnowledgeAskRequest - { - TopK = topK, - Type = type, - Prompt = prompt, - IncludeUser = true, - MinScore = minScore, - IncludeGlobal = true, - }; - var context = await ragProvider.RetrieveAsync( + // Prepare Requirements ... + var prep = await PrepareChatRequirementsAsync( + topK: topK, + type: type, + files: null, + prompt: prompt, + projectId: null, + minScore: minScore, userInfo: userInfo, - request: knowledgeRequest, + connectionId: null, + conversationId: null, + persistPrompt: false, + resolveConversation: false, cancellationToken: cancellationToken ); // using var client = Descriptor.GetClient(); - var history = GetHistory(prompt, context); - var enumerable = client.GetStreamingResponseAsync( - options: Options, - messages: history, - cancellationToken: cancellationToken - ); - - // - await foreach (var res in enumerable) + var stream = client + .GetStreamingResponseAsync( + options: Options, + messages: prep.History, + cancellationToken: cancellationToken + ); + await foreach (var res in stream) { // if (cancellationToken.IsCancellationRequested) @@ -500,204 +432,48 @@ namespace xAiApi.Providers .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; - } - if (type.IsNullOrEmpty()) - { - type = XAiModelsConstants.XAiDefaultKnowledgeType; - } - - // - // Check Project ... - XAiProjectDto project = null; - if (!projectId.HasValue || projectId.Value.IsDefaultGuid()) - { - // - project = await dataProvider.GetDefaultProject( - ownerId: userInfo.UserId, - 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: userInfo.UserId, - 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 { } - } - - // - // Prepare Knowledge Request ... - var knowledgeRequest = new XAiKnowledgeAskRequest - { - TopK = topK, - Type = type, - Prompt = prompt, - IncludeUser = true, - MinScore = minScore, - IncludeGlobal = true, - ProjectId = projectId, - ConversationId = conversationId - }; - var context = await ragProvider.RetrieveAsync( + var prep = await PrepareChatRequirementsAsync( + type: type, + topK: topK, + files: files, + prompt: prompt, + minScore: minScore, userInfo: userInfo, - request: knowledgeRequest, - 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 - ); - - // - // Prepare and Add Prompt Message ... - var promptMessage = new XAiMessageDto - { - Content = prompt, - Role = XAiChatRole.User, - OwnerId = userInfo.UserId, - CreatedOn = DateTime.UtcNow, - ConversationId = conversationId.Value, - ConversationTitle = conversation.Title - }; - - // - // Save Prompt Message ... - promptMessage = await dataProvider.AddMessage( - item: promptMessage, + persistPrompt: true, + projectId: projectId, + resolveConversation: true, connectionId: connectionId, - conversationId: conversationId.Value, + conversationId: conversationId, cancellationToken: cancellationToken ); // - // Converts to ChatMessage ... - var promptChatMessage = promptMessage - .ToChatMessages(additionalContents: []); - - // - // Ask Questions From LLM ... - var answer = await AskLLMAsync( - history: history, - prompt: promptChatMessage, + using var client = Descriptor.GetClient(); + var response = await client.GetResponseAsync( + options: Options, + messages: prep.History, cancellationToken: cancellationToken ); - - // - // Prepare Answer AI Message ... - var result = new XAiMessageDto + if (!response.IsValid()) { - Content = answer, - OwnerId = userInfo.UserId, - CreatedOn = DateTime.UtcNow, - Role = XAiChatRole.Assistant, - ConversationId = conversationId.Value, - ConversationTitle = conversation.Title - }; - result = await dataProvider.AddMessage( - item: result, + // + client.Dispose(); + XException.ActionFailed.Throw(); + } + + // + var result = await dataProvider.AddMessage( + item: new XAiMessageDto + { + Content = response.Text, + OwnerId = userInfo.UserId, + CreatedOn = DateTime.UtcNow, + Role = XAiChatRole.Assistant, + ConversationId = prep.Conversation.Id, + ConversationTitle = prep.Conversation.Title, + }, connectionId: connectionId, - conversationId: conversationId.Value, + conversationId: prep.Conversation.Id, cancellationToken: cancellationToken ); @@ -743,235 +519,67 @@ namespace xAiApi.Providers .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; - } - if (type.IsNullOrEmpty()) - { - type = XAiModelsConstants.XAiDefaultKnowledgeType; - } - - // - // Check Project ... - XAiProjectDto project = null; - if (!projectId.HasValue || projectId.Value.IsDefaultGuid()) - { - // - project = await dataProvider.GetDefaultProject( - ownerId: userInfo.UserId, - 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: userInfo.UserId, - 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 { } - } - - // - // Prepare Knowledge Request ... - var knowledgeRequest = new XAiKnowledgeAskRequest - { - TopK = topK, - Type = type, - Prompt = prompt, - IncludeUser = true, - MinScore = minScore, - IncludeGlobal = true, - ProjectId = projectId, - ConversationId = conversationId - }; - var context = await ragProvider.RetrieveAsync( + var prep = await PrepareChatRequirementsAsync( + type: type, + topK: topK, + files: files, + prompt: prompt, + minScore: minScore, userInfo: userInfo, - request: knowledgeRequest, - 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 - ); - - // - // Prepare and Add Prompt Message ... - var promptMessage = new XAiMessageDto - { - Content = prompt, - Role = XAiChatRole.User, - OwnerId = userInfo.UserId, - CreatedOn = DateTime.UtcNow, - ConversationId = conversationId.Value, - ConversationTitle = conversation.Title - }; - - // - // Save Prompt Message ... - promptMessage = await dataProvider.AddMessage( - item: promptMessage, + persistPrompt: true, + projectId: projectId, + resolveConversation: true, connectionId: connectionId, - conversationId: conversationId.Value, + conversationId: conversationId, cancellationToken: cancellationToken ); // - // Converts to ChatMessage ... - var promptChatMessage = promptMessage - .ToChatMessages(additionalContents: []); - history.Add(promptChatMessage); - - // - // Ask Questions From LLM ... using var client = Descriptor.GetClient(); - var enumerable = client.GetStreamingResponseAsync( - options: Options, - messages: history - ); + var stream = client + .GetStreamingResponseAsync( + options: Options, + messages: prep.History, + cancellationToken: cancellationToken + ); // + var answer = new System.Text.StringBuilder(); long sequence = 1; - var answer = string.Empty; - await foreach (var res in enumerable) + await foreach (var res in stream) { // - // Cancellation Token ... if (cancellationToken.IsCancellationRequested) { yield break; } // - var resp = new XAiResonseMessage + answer.Append(res.Text); + yield return new XAiResonseMessage { Content = res.Text, - Sequence = sequence, + Sequence = sequence++, OwnerId = userInfo.UserId, - Role = XAiChatRole.System, - RespondTo = promptMessage.Id, + Role = XAiChatRole.Assistant, RespondedOn = DateTime.UtcNow, + RespondTo = prep.PersistedPromptMessage.Id, }; - - // - sequence++; - answer += res.Text; - - // - yield return resp; } // - // Prepare Answer AI Message ... - var result = new XAiMessageDto - { - Content = answer, - OwnerId = userInfo.UserId, - Role = XAiChatRole.System, - CreatedOn = DateTime.UtcNow, - ConversationId = conversationId.Value - }; - result = await dataProvider.AddMessage( - item: result, + // Adding Full Message ... + await dataProvider.AddMessage( + item: new XAiMessageDto + { + OwnerId = userInfo.UserId, + Content = answer.ToString(), + CreatedOn = DateTime.UtcNow, + Role = XAiChatRole.Assistant, + ConversationId = prep.Conversation.Id, + }, connectionId: connectionId, - conversationId: conversationId.Value, + conversationId: prep.Conversation.Id, cancellationToken: cancellationToken ); } @@ -1016,7 +624,7 @@ namespace xAiApi.Providers { // // Here we have to fill Conversations of Default Project ... - var defaultProjectId = result.GetDafualtProject(ownerId); + var defaultProjectId = result.GetDafaultProject(ownerId); var defaultProject = result.FirstOrDefault(x => x.Id == defaultProjectId); result = result.Where(x => x.Id != defaultProjectId); @@ -1462,39 +1070,6 @@ namespace xAiApi.Providers return result; } - /// - /// Prepare a Message History List for LLM Communication based on Prompt ... - /// - /// - /// - /// - private 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; - } - /// /// Build Chat History for RAG: /// [System: Introduction + ChatWithDocuments Prompt + Context Block] + [User: Prompt] ... @@ -1509,7 +1084,7 @@ namespace xAiApi.Providers { // var introductionPrompt = configuration.GetPrompt(); - var ragPrompt = configuration.GetPrompt(configuration.RAGDescriptor.PromptName); + var ragPrompt = configuration.GetPrompt(XAiApiConstants.XAiApiRagPromptName); if (ragPrompt.IsNullOrEmpty()) { XException.InvalidConfiguration.Throw(); @@ -1661,46 +1236,288 @@ namespace xAiApi.Providers } /// - /// Ask Quetion from LLM ... + /// Normalizing Rag Params ... + /// + /// + /// + /// + private void NormalizeRagParams( + ref int? topK, + ref float? minScore, + ref string type + ) + { + // + var rag = configuration.RAGDescriptor; + + // + // TopK ... + if (!topK.HasValue || topK.Value < 1) + { + topK = rag.DefaultTopK; + } + else if (topK.Value > rag.MaxTopK) + { + topK = rag.MaxTopK; + } + + // + // Min Score ... + if (!minScore.HasValue || minScore.Value < 0 || minScore.Value > 1) + { + minScore = rag.DefaultMinScore; + } + + // + // Type ... + if (type.IsNullOrEmpty()) + { + type = XAiModelsConstants.XAiDefaultKnowledgeType; + } + } + + /// + /// Retrieve Prepared Chat Context ... /// /// - /// + /// + /// + /// + /// + /// + /// + /// + /// + /// + /// /// /// - private async Task AskLLMAsync( - ChatMessage prompt, - IList history, + private async Task PrepareChatRequirementsAsync( + int? topK, + string type, + string prompt, + float? minScore, + Guid? projectId, + bool persistPrompt, + string connectionId, + Guid? conversationId, + bool resolveConversation, + IFormFileCollection files, + XUserClaimsInfoDto userInfo, + IList additionalContents = null, CancellationToken cancellationToken = default ) { // - if (prompt.IsNullOrDefault()) - { - XException.InvalidArgs.Throw(); - } + // Validate Args ... + validationProvider + .GroupValidationBuilder() + .AddNotEmpty(prompt) + .AddNotNull(userInfo) + .AddNotEmpty(userInfo.UserId) + .ValidateGroup(); // - history.Add(prompt); - using var client = Descriptor.GetClient(); - var response = await client.GetResponseAsync( - options: Options, - messages: history, - cancellationToken: cancellationToken + // Normalize ... + NormalizeRagParams( + topK: ref topK, + type: ref type, + minScore: ref minScore + ); + + // + // Resolve Project and Conversation ... + XAiProjectDto project = null; + XAiConversationDto conversation = null; + if (resolveConversation) + { + // + // Check Project ... + if (!projectId.HasValue || projectId.Value.IsDefaultGuid()) + { + // + project = await dataProvider.GetDefaultProject( + ownerId: userInfo.UserId, + 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 ... + if (!conversationId.HasValue || conversationId.Value.IsDefaultGuid()) + { + // + conversation = await dataProvider.GetDefaultConversation( + ownerId: userInfo.UserId, + 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 if Provided and also Resolve Conversation Flagged ... + if ( + files.HasChild() && + resolveConversation + ) + { + // + try + { + // + var ingestResult = await ragProvider + .IngestAsync( + files: files, + userInfo: userInfo, + replaceExisting: true, + connectionId: connectionId, + scope: XAiKnowledgeScopeDescriptor + .Conversation( + type: type, + conversationId: conversationId.Value + ), + cancellationToken: cancellationToken + ); + if (ingestResult.SkippedFiles.HasChild()) + { + // + logger.LogWarning( + "Ingest skipped {Count} file(s): {Files}", + ingestResult.SkippedFiles.Count, + string.Join(", ", ingestResult.SkippedFiles)); + } + } + catch (OperationCanceledException) + { + throw; + } + catch (Exception ex) + { + // + logger.LogError(ex, + "Ingest failed for prompt '{Prompt}'. Continuing without attachments.", + prompt + ); + } + } + + // + // Request Knowledge ... + var knowledgeRequest = new XAiKnowledgeAskRequest + { + TopK = topK, + Type = type, + Prompt = prompt, + IncludeUser = true, + MinScore = minScore, + IncludeGlobal = true, + ProjectId = resolveConversation ? projectId : null, + ConversationId = resolveConversation ? conversationId : null, + }; + var context = await ragProvider + .RetrieveAsync( + userInfo: userInfo, + request: knowledgeRequest, + cancellationToken: cancellationToken ); // - // Validate Response ... - if (!response.IsValid()) + // Prepare History and Persisted Prompt Message ... + IList history; + XAiMessageDto persistedPromptMessage = null; + if (persistPrompt) { // - // Dispose Client ... - client.Dispose(); - XException.ActionFailed.Throw(); + // Retrieve Conversation Message ... + var messages = await dataProvider + .LoadMessages( + conversationId: conversationId.Value, + cancellationToken: cancellationToken + ); + + // + // Prepare History based on Memory Strategies ... + history = await PrepareMemory( + context: context, + project: project, + messages: messages, + cancellationToken: cancellationToken + ); + + // + // Persist Prompt Message ... + persistedPromptMessage = await dataProvider.AddMessage( + item: new XAiMessageDto + { + Content = prompt, + Role = XAiChatRole.User, + OwnerId = userInfo.UserId, + CreatedOn = DateTime.UtcNow, + ConversationId = conversationId.Value, + ConversationTitle = conversation.Title, + }, + connectionId: connectionId, + conversationId: conversationId.Value, + cancellationToken: cancellationToken + ); + + // + history + .Add(persistedPromptMessage + .ToChatMessages(additionalContents: additionalContents)); + } + else + { + // + history = GetHistory(prompt, context); } // - // Retrieve Response Text ... - var result = response.Text; + // Prepare Result ... + var result = new XPreparedChatContext + { + Project = project, + Context = context, + History = history, + Conversation = conversation, + PersistedPromptMessage = persistedPromptMessage, + }; // return result; diff --git a/Providers/XAiEmbeddingServiceBase.cs b/Providers/XAiEmbeddingServiceBase.cs index 4bfd753..3cee47e 100644 --- a/Providers/XAiEmbeddingServiceBase.cs +++ b/Providers/XAiEmbeddingServiceBase.cs @@ -84,7 +84,7 @@ namespace xAiApi.Providers } // - using var generator = GetEmbeddingGenerator(); + var generator = GetEmbeddingGenerator(); // GeneratedEmbeddings> response = null; diff --git a/Providers/XAiRAGService.cs b/Providers/XAiRAGService.cs index 7a53118..0ea1635 100644 --- a/Providers/XAiRAGService.cs +++ b/Providers/XAiRAGService.cs @@ -18,6 +18,7 @@ using Microsoft.AspNetCore.Http; using System.Collections.Generic; using Microsoft.Extensions.Logging; using xAiApi.Interfaces.Extractors; +using xFileService.Models.Dtos; namespace xAiApi.Providers { @@ -127,149 +128,181 @@ namespace xAiApi.Providers var existingDocuments = await LoadDocumentNames(scopePrefix, cancellationToken); // + // Loop through Files ... foreach (var file in files) { // - cancellationToken.ThrowIfCancellationRequested(); + XFileDto uploadedFile = null; // - if (file.IsNull() || file.Length == 0) - { - result.SkippedFiles.Add(file?.FileName ?? "(null)"); - continue; - } - - // - // Size Limit ... - if (rag.MaxFileSizeBytes > 0 && file.Length > rag.MaxFileSizeBytes) - { - result.SkippedFiles.Add(file.FileName); - continue; - } - - // - var fileName = NormalizeFileName(file.FileName); - if (fileName.IsNullOrEmpty()) - { - result.SkippedFiles.Add(file.FileName); - continue; - } - - // - // Documents per Scope Limit (Global Unlimited; Re-Ingest of Existing Doc Allowed) ... - var isNewDocument = !existingDocuments.Contains(fileName); - if ( - isNewDocument && - scope.Scope != XAiKnowledgeScope.Global && - rag.MaxDocumentsPerScope > 0 && - existingDocuments.Count >= rag.MaxDocumentsPerScope - ) - { - result.SkippedFiles.Add(file.FileName); - continue; - } - - // - var mimeType = file.ContentType?.ToLowerInvariant() ?? string.Empty; - if (!fileContentExtractor.CanExtract(mimeType)) - { - result.SkippedFiles.Add(file.FileName); - continue; - } - - // - var text = await ExtractText(file, mimeType, cancellationToken); - if (text.IsNullOrEmpty()) - { - result.SkippedFiles.Add(file.FileName); - continue; - } - - // - // Chunk with Scoped Source => Identifier = "{scopePrefix}{fileName}#{index}" ... - var chunks = textChunker.Chunk(text, $"{scopePrefix}{fileName}"); - if (!chunks.HasChild()) - { - result.SkippedFiles.Add(file.FileName); - continue; - } - - // - // Handle File Save ... - var uploadedFile = await fileProvider.Upload( - file: file, - userInfo: userInfo, - connectionId: connectionId, - cancellationToken: cancellationToken - ); - - // - // Add Reference File to Prompt Message ... - if (scope.ScopeId.HasValue) + try { // - await fileProvider.AddReference( + cancellationToken.ThrowIfCancellationRequested(); + + // + if (file.IsNull() || file.Length == 0) + { + result.SkippedFiles.Add(file?.FileName ?? "(null)"); + continue; + } + + // + // Size Limit ... + if (rag.MaxFileSizeBytes > 0 && file.Length > rag.MaxFileSizeBytes) + { + result.SkippedFiles.Add(file.FileName); + continue; + } + + // + var fileName = NormalizeFileName(file.FileName); + if (fileName.IsNullOrEmpty()) + { + result.SkippedFiles.Add(file.FileName); + continue; + } + + // + // Documents per Scope Limit (Global Unlimited; Re-Ingest of Existing Doc Allowed) ... + var isNewDocument = !existingDocuments.Contains(fileName); + if ( + isNewDocument && + scope.Scope != XAiKnowledgeScope.Global && + rag.MaxDocumentsPerScope > 0 && + existingDocuments.Count >= rag.MaxDocumentsPerScope + ) + { + result.SkippedFiles.Add(file.FileName); + continue; + } + + // + var mimeType = file.ContentType?.ToLowerInvariant() ?? string.Empty; + if (!fileContentExtractor.CanExtract(mimeType)) + { + result.SkippedFiles.Add(file.FileName); + continue; + } + + // + var text = await ExtractText(file, mimeType, cancellationToken); + if (text.IsNullOrEmpty()) + { + result.SkippedFiles.Add(file.FileName); + continue; + } + + // + // Chunk with Scoped Source => Identifier = "{scopePrefix}{fileName}#{index}" ... + var chunks = textChunker.Chunk(text, $"{scopePrefix}{fileName}"); + if (!chunks.HasChild()) + { + result.SkippedFiles.Add(file.FileName); + continue; + } + + // + // Handle File Save ... + uploadedFile = await fileProvider.Upload( + file: file, userInfo: userInfo, - id: uploadedFile.Id, connectionId: connectionId, - cancellationToken: cancellationToken, - providedFor: scope.Scope.GetStringValue(), - forProvidedId: scope.ScopeId.Value.ToString() + cancellationToken: cancellationToken + ); + + // + // Add Reference File to Prompt Message ... + if ( + !uploadedFile.IsNullOrDefault() && + scope.ScopeId.HasValue && + !uploadedFile.Id.IsDefaultGuid() + ) + { + // + 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( + scope: scope, + chunks: chunks, + fileName: fileName, + mimeType: mimeType, + type: knowledgeType, + ownerId: userInfo.UserId, + ingestedAtUtc: ingestedAtUtc, + cancellationToken: cancellationToken + ); + + // + // Remove Stale Vectors of Same Document ... + if (replaceExisting) + { + // + result.ReplacedCount += await dataProvider.RemoveVectorsAsync( + cancellationToken: cancellationToken, + identifierPrefix: GetDocumentChunkPrefix(scopePrefix, fileName) + ); + } + + // + // Store ... + var storedCount = await dataProvider.UpsertVectorsAsync( + items: vectors, + cancellationToken: cancellationToken + ); + + // + existingDocuments.Add(fileName); + result.FilesCount++; + result.ChunksCount += storedCount; + result.Documents.Add(new XAiKnowledgeDocumentInfo + { + FileName = fileName, + MimeType = mimeType, + Type = knowledgeType, + Scope = scope.Scope, + ScopeId = scope.ScopeId, + ChunksCount = storedCount, + OwnerId = userInfo.UserId, + IngestedAtUtc = ingestedAt, + }); + + // + logger.LogInformation( + "Knowledge: Ingested {FileName} into {Scope}:{ScopeId} by {OwnerId} with {Chunks} Chunks", + fileName, scope.Scope, scope.ScopeId, userInfo.UserId, storedCount ); } - - // - // Embed in Batches ... - var vectors = await EmbedChunks( - scope: scope, - chunks: chunks, - fileName: fileName, - mimeType: mimeType, - type: knowledgeType, - ownerId: userInfo.UserId, - ingestedAtUtc: ingestedAtUtc, - cancellationToken: cancellationToken - ); - - // - // Remove Stale Vectors of Same Document ... - if (replaceExisting) + catch (Exception ex) { // - result.ReplacedCount += await dataProvider.RemoveVectorsAsync( - cancellationToken: cancellationToken, - identifierPrefix: GetDocumentChunkPrefix(scopePrefix, fileName) - ); + logger.LogError(ex, "Ingesting Failed ..."); + + // + // Removing Uploaded File if Chuncking Failed ... + if (!uploadedFile.IsNullOrDefault() && + !uploadedFile.Id.IsDefaultGuid() + ) + { + // + await fileProvider.Remove( + id: uploadedFile.Id, + userInfo: userInfo, + connectionId: connectionId, + cancellationToken: cancellationToken + ); + } } - - // - // Store ... - var storedCount = await dataProvider.UpsertVectorsAsync( - items: vectors, - cancellationToken: cancellationToken - ); - - // - existingDocuments.Add(fileName); - result.FilesCount++; - result.ChunksCount += storedCount; - result.Documents.Add(new XAiKnowledgeDocumentInfo - { - FileName = fileName, - MimeType = mimeType, - Type = knowledgeType, - Scope = scope.Scope, - ScopeId = scope.ScopeId, - ChunksCount = storedCount, - OwnerId = userInfo.UserId, - IngestedAtUtc = ingestedAt, - }); - - // - logger.LogInformation( - "Knowledge: Ingested {FileName} into {Scope}:{ScopeId} by {OwnerId} with {Chunks} Chunks", - fileName, scope.Scope, scope.ScopeId, userInfo.UserId, storedCount - ); } // @@ -483,11 +516,11 @@ namespace xAiApi.Providers var file = await fileProvider.FindOne( x => x.FileName .Equals( - fileName, + fileName, StringComparison.InvariantCultureIgnoreCase) && x.OwnerId .Equals( - userInfo.UserId, + userInfo.UserId, StringComparison.InvariantCultureIgnoreCase), cancellationToken: cancellationToken ); @@ -736,7 +769,7 @@ namespace xAiApi.Providers // return result; } - + // #region Scope ... /// @@ -953,7 +986,7 @@ namespace xAiApi.Providers /// Separator Suffix Prevents "a.pdf" from Matching "a.pdf.bak" ... /// private string GetDocumentChunkPrefix( - string scopePrefix, + string scopePrefix, string fileName ) { diff --git a/Providers/XInMemoryVectorStore.cs b/Providers/XInMemoryVectorStore.cs index 342cf9f..41da9e9 100644 --- a/Providers/XInMemoryVectorStore.cs +++ b/Providers/XInMemoryVectorStore.cs @@ -174,11 +174,37 @@ namespace xAiApi.Providers // session = null; XAiDocumentSession found; - if (!sessions.TryGetValue(sessionId, out found) || !OwnerMatches(found, ownerId)) return false; - if (found.IsExpired(DateTime.UtcNow)) { sessions.TryRemove(sessionId, out found); return false; } - found.LastAccessAtUtc = DateTime.UtcNow; - session = found; - return true; + if (!sessions.TryGetValue(sessionId, out found)) + { + return false; + } + + // + lock (found.SyncRoot) + { + // + XAiDocumentSession current; + if (!sessions.TryGetValue(sessionId, out current) || + !ReferenceEquals(current, found)) + return false; + + // + if (!OwnerMatches(found, ownerId)) + return false; + + // + if (found.IsExpired(DateTime.UtcNow)) + { + // + sessions.TryRemove(sessionId, out found); + return false; + } + + // + found.LastAccessAtUtc = DateTime.UtcNow; + session = found; + return true; + } } public bool Remove(