using System; using System.Linq; using xModels.Dtos; using xAiApi.Models; 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; 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; } } /// /// 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 ... /// /// /// /// /// /// /// /// /// /// /// public virtual async Task AskAsync( string prompt, int? topK = null, float? minScore = null, Guid? projectId = null, Guid? conversationId = null, string connectionId = null, IFormFileCollection files = null, XUserClaimsInfoDto userInfo = null, CancellationToken cancellationToken = default ) { // // Validate Args ... validationProvider .GroupValidationBuilder() .AddNotEmpty(prompt) .AddNotNull(userInfo) .AddNotEmpty(userInfo.UserId) .ValidateGroup(); // // Normalize ... if (!topK.HasValue || topK.Value < 1 || topK.Value > configuration.RAGDescriptor.MaxTopK ) { // if (!topK.HasValue || (topK.HasValue && topK.Value < 1)) { topK = configuration.RAGDescriptor.DefaultTopK; } else if (topK.HasValue && topK.Value > configuration.RAGDescriptor.MaxTopK) { topK = configuration.RAGDescriptor.MaxTopK; } } if (!minScore.HasValue || minScore.Value <= 0 || minScore.Value > 1 ) { minScore = configuration.RAGDescriptor.DefaultMinScore; } // // 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, Prompt = prompt, IncludeUser = true, MinScore = minScore, IncludeGlobal = true, ProjectId = projectId, ConversationId = conversationId }; var context = await ragProvider.RetrieveAsync( 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, connectionId: connectionId, conversationId: conversationId.Value, cancellationToken: cancellationToken ); // // Converts to ChatMessage ... var promptChatMessage = promptMessage .ToChatMessages(additionalContents: []); // // 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 = userInfo.UserId, 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, 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 ) { // // Validate Args ... validationProvider .GroupValidationBuilder() .AddNotEmpty(prompt) .AddNotNull(userInfo) .AddNotEmpty(userInfo.UserId) .ValidateGroup(); // // Normalize ... if (!topK.HasValue || topK.Value < 1 || topK.Value > configuration.RAGDescriptor.MaxTopK ) { // if (!topK.HasValue || (topK.HasValue && topK.Value < 1)) { topK = configuration.RAGDescriptor.DefaultTopK; } else if (topK.HasValue && topK.Value > configuration.RAGDescriptor.MaxTopK) { topK = configuration.RAGDescriptor.MaxTopK; } } if (!minScore.HasValue || minScore.Value <= 0 || minScore.Value > 1 ) { minScore = configuration.RAGDescriptor.DefaultMinScore; } // // 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, Prompt = prompt, IncludeUser = true, MinScore = minScore, IncludeGlobal = true, ProjectId = projectId, ConversationId = conversationId }; var context = await ragProvider.RetrieveAsync( 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, connectionId: connectionId, conversationId: conversationId.Value, 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 ); // long sequence = 1; var answer = string.Empty; await foreach (var res in enumerable) { // // Cancellation Token ... if (cancellationToken.IsCancellationRequested) { yield break; } // var resp = new XAiResonseMessage { Content = res.Text, Sequence = sequence, OwnerId = userInfo.UserId, 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 = userInfo.UserId, Role = XAiChatRole.System, CreatedOn = DateTime.UtcNow, ConversationId = conversationId.Value }; result = await dataProvider.AddMessage( item: result, connectionId: connectionId, conversationId: conversationId.Value, cancellationToken: cancellationToken ); } #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 /// /// Base Dispose Action ... /// /// public virtual void Dispose() { } // #region Private ... /// /// Prepare a Message History List for LLM Communication based on Prompt ... /// /// /// /// private 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 ... /// /// /// /// 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] ... /// /// /// /// 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 ... /// /// /// /// /// /// private async Task> PrepareMemory( XAiProjectDto project, IEnumerable messages, IEnumerable context = null, CancellationToken cancellationToken = default ) { // var result = new List(); // // Retrieve Introduction Prompt ... var ragPrompt = configuration.GetPrompt(XAiApiConstants.XAiApiRagPromptName); var introductionPrompt = configuration.GetPrompt(XAiApiConstants.XAiApiIntroductionPromptName); if (ragPrompt.IsNullOrEmpty() || introductionPrompt.IsNullOrEmpty() ) { XException.InvalidData.Throw(); } // var contextBlock = BuildContextBlock(context); var systemText = introductionPrompt; if (context.HasChild() && !contextBlock.IsNullOrEmpty()) { // 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()) { systemText += $"{project.Prompt}{Environment.NewLine}"; } // // Add System Message ... result.Add(new ChatMessage(ChatRole.System, systemText)); // // Attach Message ... 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; } /// /// 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 ... /// /// /// /// /// 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( options: Options, 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 } }