
### FILE: C:\Users\saherelm\Documents\Projects\xSaherelmWorkspace\xAiApi\Program.cs

using System.Text;
using xLoggingService.DI;
using Microsoft.AspNetCore.Hosting;
using Microsoft.Extensions.Hosting;

namespace xAiApi
{
    public class Program
    {
        public static void Main(string[] args)
        {
            //
            Encoding.RegisterProvider(CodePagesEncodingProvider.Instance);            
            
            //
            CreateHostBuilder(args).Build().Run();
        }

        public static IHostBuilder CreateHostBuilder(string[] args)
        {
            //            
            var result = Host.CreateDefaultBuilder(args)
                .ConfigureLogging(logging => 
                    logging.AddXTelemetryLogger())
                .ConfigureWebHostDefaults(webBuilder =>
                {
                    webBuilder.UseStartup<Startup>();
                })
                .AddXTelemetry();

            //
            return result;
        }
    }
}

### FILE: C:\Users\saherelm\Documents\Projects\xSaherelmWorkspace\xAiApi\Startup.cs

using System;
using System.IO;
using xAiApi.DI;
using System.Linq;
using xAiModels.DI;
using xAiService.DI;
using xTagService.DI;
using System.Net.Http;
using xAiApi.Database;
using xHttpService.DI;
using xPushService.DI;
using xFileService.DI;
using xDataService.DI;
using Newtonsoft.Json;
using System.Reflection;
using xAiApi.Extensions;
using xStringService.DI;
using xLoggingService.DI;
using xStorageService.DI;
using xIdentityService.DI;
using xDataService.Models;
using xCommons.Extensions;
using xAiModels.Constants;
using xPushService.Helpers;
using xCommons.Configurations;
using System.Collections.Generic;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.Extensions.Hosting;
using Newtonsoft.Json.Serialization;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using IdentityModel.AspNetCore.OAuth2Introspection;

namespace xAiApi
{
    public class Startup
    {
        //
        #region Props ...
        public IConfiguration Configuration { get; }
        private readonly List<XDatabaseDescriptor> databases;
        private readonly XAiApiDatabaseDescriptor apiDatabaseDescriptor;
        #endregion

        //
        #region Constructor(s) ...
        public Startup(IConfiguration configuration)
        {
            //
            Configuration = configuration;

            //
            // Create an Api Descriptor Class Instance ...
            apiDatabaseDescriptor = new XAiApiDatabaseDescriptor();
            databases = new List<XDatabaseDescriptor>
            {
                apiDatabaseDescriptor
            };
        }
        #endregion

        public void ConfigureServices(IServiceCollection services)
        {
            //
            // Register Validation Provider and all XCommons Module Services ...
            services.AddXCommons(Configuration);

            //
            // Register App Configuration ...
            services.AddXAppConfiguration(Configuration);
            var appConfiguration = services.GetRegisteredService<XAppConfiguration>();

            //
            // Register Logging Service ...
            services.AddXLoggingService(Configuration);

            //
            // Register Allowed Origins ...
            services.AddXCors(appConfiguration.AllowedOrigins);

            //
            // Register Swagger ...
            var xmlFile = $"{Assembly.GetExecutingAssembly().GetName().Name}.xml";
            var xmlPath = Path.Combine(AppContext.BaseDirectory, xmlFile);
            services.AddXSwagger(Configuration, xmlFilePath: xmlPath);

            //
            // Register HttpService ...
            services.AddXHttpService(Configuration);

            //
            // Add Api V1 Versioning ...
            services.AddXApiV1Versioning();

            //
            // OAuthIntrospectin Http Client Handler ...
            // this is for handling SSLErrors ...
            services.AddHttpClient(OAuth2IntrospectionDefaults.BackChannelHttpClientName)
                .ConfigurePrimaryHttpMessageHandler(() =>
                {
                    return new HttpClientHandler
                    {
                        ServerCertificateCustomValidationCallback = (sender, certificate, chain, sslPolicyErrors) => true
                    };
                });

            //
            // Register Authorizations ...
            services.AddXAuthorization();

            //
            services.AddControllers()
                .AddNewtonsoftJson(x =>
                {
                    x.SerializerSettings.ReferenceLoopHandling = ReferenceLoopHandling.Ignore;
                    x.SerializerSettings.ContractResolver = new CamelCasePropertyNamesContractResolver();
                });

            //
            var lifeTime = ServiceLifetime.Scoped;
            var repositoryType = xDataService.Constants.XRepositoryType.EF;

            //
            // Register XIdentity Service ...
            services.AddXIdentityService(
                lifeTime: lifeTime,
                configuration: Configuration
            );

            //
            // Storage Service ...
            services.AddXStorageService(Configuration);

            //
            // Push Service ...
            services.AddXPushService(
                lifeTime: lifeTime,
                config: Configuration
            );

            //
            // Preparing DataBases ...
            if (databases.HasChild())
            {
                //
                databases
                    .ToList()
                    .ForEach(database =>
                    {
                        //
                        // Register DataBase ...
                        services.AddXDatabase(
                            lifeTime: lifeTime,
                            descriptor: database,
                            configuration: Configuration
                        );
                    });
            }

            //
            // Register String Service ...
            services.AddXStringService<XAiApiDbContext>(
                lifeTime: lifeTime,
                repositoryType: repositoryType
            );

            //
            // Register Tag Service ...
            services.AddXTagService<XAiApiDbContext>(
                lifeTime: lifeTime,
                repositoryType: repositoryType
            );

            //
            // Register File Service ...
            services.AddXFileService<XAiApiDbContext>(
                lifeTime: lifeTime,
                repositoryType: repositoryType
            );

            //
            // Register AiApi Data Service ...
            services.AddXAiDataService<XAiApiDbContext>(
                lifeTime: lifeTime,
                repositoryType: repositoryType
            );

            //
            // Register XAiApi Configuration ...
            services.AddXAiApiConfiguration(Configuration);

            //
            // Register MCP Server Provider ...
            services.AddXAiMcpServerProvider();

            //
            // Register File Content Extractor Services ...
            services.AddXAiFileContentExtractors();

            //
            // Register Text Chunker Service ...
            services.AddXAiTextChunker();

            //
            // Register Chat With Documents Services (Text Chunker + In-Memory Vector Store) ...
            services.AddXAiChatWithDocuments();

            //
            // Register XAiMcpClient ...
            services.AddXAiMcpClient();

            //
            // Persistent RAG (Knowledge over XAiVector Table) ...
            services.AddXRagService();

            //
            // Register Default AI Services ...
            services.AddXAiServices();
        }

        public void Configure(
            IApplicationBuilder app, 
            IWebHostEnvironment env
        )
        {
            //
            // Configure the HTTP request pipeline.
            // Order: Exception Handling -> Https -> Static Files -> Swagger (Dev) -> Cors
            //        -> Model Proxy (Terminal for /{RoutePrefix}) -> Routing -> AuthN -> AuthZ -> Endpoints ...
            var isDevelopmentEnvironment = env.IsDevelopment();
            if (isDevelopmentEnvironment)
            {
                app.UseDeveloperExceptionPage();
            }
            else
            {
                app.UseExceptionHandler(XAiModelsConstants.XAiErrorRoute);
                app.UseHsts();
            }

            //
            // Setting Environment in App Confiuration ...
            app.AddEnvironmentToXAppConfiguration(env.EnvironmentName);

            //
            // Force Https Redirection ...
            app.UseHttpsRedirection();

            //
            // Use Storage Service (Prepare Folders + Static Files) ...
            // Must be before Routing so Static Files Short Circuit Pipeline ...
            app.UseXStorageService();

            //
            // Use Swagger Middleware (Only in Development) ...
            if (isDevelopmentEnvironment)
            {
                app.UseXSwagger();
            }

            //
            // Using Cors (before Proxy so Browser Requests get CORS Headers) ...
            app.UseXCors();

            //
            // Enable Model Proxy (Handles its own Authentication) ...
            app.UseXAiModelProxy();

            //
            // Using Routing ...
            app.UseRouting();

            //
            // Using Request Logging ...
            if (!isDevelopmentEnvironment)
            {
                app.UseXRequestLogger();
            }

            //
            // Use xIdentityService (Authentication) ...
            app.UseXIdentityService();

            //
            // Use Authorization ...
            app.UseAuthorization();

            //
            app.UseEndpoints(endpoints =>
            {
                endpoints.MapControllers();
            });

            //
            // Use PushService (Legacy UseSignalR -> Registers its own Router) ...
            var pushHelper = new XPushServiceHelper();
            app.UseXPushService(pushHelper);

            //
            // Using DataBase ...
            if (databases.HasChild())
            {
                //
                databases
                    .ToList()
                    .ForEach(database =>
                    {
                        //
                        app.UseXDatabase(
                            descriptor: database,
                            isDevelopmentEnvironment: isDevelopmentEnvironment
                        );
                    });
            }

            //
            // Using String Service ...
            app.UseXStringService(
                isDevelopmentEnvironment: isDevelopmentEnvironment
            );

            //
            // Using XTag Service ...
            app.UseXTagService(
                isDevelopmentEnvironment: isDevelopmentEnvironment
            );

            //
            // Using File Service ...
            app.UseXFileService(
                isDevelopmentEnvironment: isDevelopmentEnvironment
            );
        }
    }
}




### FILE: C:\Users\saherelm\Documents\Projects\xSaherelmWorkspace\xAiApi\Configurations\XAiApiConfiguration.cs

using xAiApi.Models;
using xAiModels.Models;

namespace xAiApi.Configurations
{
    public class XAiApiConfiguration
    {
        /// <summary>
        /// Allowed Models to Use ...
        /// </summary>
        public XAiModelDescriptor[] Models { get; set; } = [];

        /// <summary>
        /// Allowed Prompts to Use ...
        /// </summary>
        public XAiPromptDescriptor[] Prompts { get; set; } = [];

        /// <summary>
        /// OCR Configuration ...
        /// </summary>
        public XAiOCRDescriptor OCR { get; set; } = new();

        /// <summary>
        /// Transcript Configuration ...
        /// </summary>
        public XAiTransciptDescriptor Transcript { get; set; } = new();

        /// <summary>
        /// PDF To Image Configuration ...
        /// </summary>
        public XPDFToImageDescriptor PDFToImageDescriptor { get; set; } = new();

        /// <summary>
        /// Proxy Configuration ...
        /// </summary>
        /// <returns></returns>
        public XAiModelProxyConfiguration ProxyConfiguration { get; set; } = new();

        /// <summary>
        /// Text Chunker Configuration ...
        /// </summary>
        public XTextChunkerDescriptor TextChunker { get; set; } = new();

        /// <summary>
        /// RAG Configuration ...
        /// </summary>
        public XAiDocumentRAGDescriptor RAGDescriptor {get; set;} = new();
        
        /// <summary>
        /// DateTime Configuration ...
        /// </summary>
        /// <returns></returns>
        public XDateTimeDescriptor DateTime { get; set; } = new();
    }
}

### FILE: C:\Users\saherelm\Documents\Projects\xSaherelmWorkspace\xAiApi\Constants\ConfigurationNodeNames.cs

namespace xAiApi.Constants
{
    public partial struct ConfigurationNodeNames
    {
        public const string AI_API_NODE = "AiApiConfiguration";
    }
}

### FILE: C:\Users\saherelm\Documents\Projects\xSaherelmWorkspace\xAiApi\Constants\XAiApiConstants.cs

namespace xAiApi.Constants
{
    public struct XAiApiConstants
    {
        //
        // Database Descriptor ...
        public const string XAiApiDbIdentifier = "xAiApiDb";
        public const string XAiApiMigrationsAssemblyIdentifier = "xAiApi";

        //
        public const string XDILogTag = "XAiApi";

        //
        public const string XAiApiRagPromptName = "ChatWithDocuments";
        public const string XAiApiIntroductionPromptName = "Introduction";
        public const string XAiApiContentExtractionPromptName = "ContentExtraction";

        //
        public const string XAiDefaultModelName = "Arion";
        public const string XAiEmbeddingModelName = "Embed";
        public const string XAiDefaultVisionModelName = "Qwen";
        public const string XAiDefaultThinkingModelName = "Qwen";
        public const string XAiEmbeddingPromptName = "Embedding";
    }
}

### FILE: C:\Users\saherelm\Documents\Projects\xSaherelmWorkspace\xAiApi\Controllers\AccountController.cs

using xCommons.Providers;
using xCommons.Configurations;
using xIdentityHelper.Controllers;
using xIdentityService.Interfaces;
using Microsoft.Extensions.Logging;

namespace xAiApi.Controllers
{
    public partial class AccountController : XAccountControllerBase
    {
        //
        #region Constructor ...
        public AccountController(
            ILogger<AccountController> logger,
            XAppConfiguration appConfiguration,
            IXIdentityProvider identityProvider,
            XValidationProvider validationProvider
        ) : base(
            logger,
            appConfiguration,
            identityProvider,
            validationProvider
        )
        { }
        #endregion
    }
}

### FILE: C:\Users\saherelm\Documents\Projects\xSaherelmWorkspace\xAiApi\Controllers\ChatWithDocumentsController.cs

using System;
using System.Linq;
using xAiApi.Models;
using System.Threading;
using xAiApi.Interfaces;
using xAiApi.Extensions;
using xCommons.Providers;
using xCommons.Extensions;
using xAiApi.Configurations;
using xExceptions.Constants;
using xAiModels.Models.Dtos;
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 xAiApi.Interfaces.Extractors;
using Microsoft.Extensions.Logging;
using Microsoft.AspNetCore.Authorization;

namespace xAiApi.Controllers
{
    /// <summary>
    /// Chat With Documents (In-Memory RAG) Controller ...
    /// Flow: Ingest Files -> SessionId -> Ask / AskStream -> Delete Session
    /// </summary>
    [Authorize]
    public class ChatWithDocumentsController : XBaseIdentityApiV1Controller
    {
        /// <summary>
        /// Default AI Service ...
        /// </summary>
        private readonly IXAiService aiService;

        /// <summary>
        /// Text Chunker Service ...
        /// </summary>
        private readonly IXTextChunker textChunker;

        /// <summary>
        /// In Memory Vector Store ...
        /// </summary>
        private readonly IXInMemoryVectorStore vectorStore;

        /// <summary>
        /// XAiApi Configuration ...
        /// </summary>
        private readonly XAiApiConfiguration apiConfiguration;

        /// <summary>
        /// Embedding Service ...
        /// </summary>
        private readonly IXAiEmbeddingService embeddingService;

        /// <summary>
        /// File Context Extractor Service ...
        /// </summary>
        private readonly IXFileContentExtractor fileContentExtractor;

        public ChatWithDocumentsController(
            IXAiService aiService,
            IXTextChunker textChunker,
            IXInMemoryVectorStore vectorStore,
            XAppConfiguration appConfiguration,
            IXIdentityProvider identityProvider,
            XAiApiConfiguration apiConfiguration,
            IXAiEmbeddingService embeddingService,
            XValidationProvider validationProvider,
            ILogger<ChatWithDocumentsController> logger,
            IXFileContentExtractor fileContentExtractor
        ) : base(logger, appConfiguration, identityProvider, validationProvider)
        {
            //
            this.aiService = aiService;
            this.textChunker = textChunker;
            this.vectorStore = vectorStore;
            this.apiConfiguration = apiConfiguration;
            this.embeddingService = embeddingService;
            this.fileContentExtractor = fileContentExtractor;
        }

        //
        #region Ingest ...
        /// <summary>
        /// Ingest Files into a (new or existing) In-Memory Session:
        /// Extract -> Chunk -> Embed -> Store ...
        /// </summary>
        /// <param name="files"></param>
        /// <param name="sessionId">Optional: Add to an Existing Session</param>
        /// <param name="ttlMinutes">Optional: Session TTL in Minutes (only for new Session)</param>
        /// <param name="cancellationToken"></param>
        /// <returns></returns>
        [HttpPost("Ingest")]
        [Consumes("multipart/form-data")]
        public async Task<ActionResult<XAiDocumentIngestResult>> Ingest(
            [FromForm] IFormFileCollection files,
            [FromForm] Guid? sessionId = null,
            [FromForm] int? ttlMinutes = null,
            CancellationToken cancellationToken = default
        )
        {
            //
            try
            {
                //
                // Validate ...
                if (!files.HasChild())
                {
                    XException.InvalidArgs.Throw();
                }

                //
                var userInfo = await GetUserInfo();
                var ownerId = userInfo.UserId;

                //
                // Resolve Target Session ...
                Guid targetSessionId;
                if (sessionId.HasValue && sessionId.Value != Guid.Empty)
                {
                    //
                    if (!vectorStore.TryGet(sessionId.Value, out _, ownerId))
                    {
                        XException.NotFound.Throw();
                    }
                    targetSessionId = sessionId.Value;
                }
                else
                {
                    //
                    var ttl = TimeSpan.FromMinutes(
                        ttlMinutes.HasValue && ttlMinutes.Value > 0
                            ? ttlMinutes.Value
                            : apiConfiguration.RAGDescriptor.DefaultTtlMinutes
                    );
                    targetSessionId = vectorStore.CreateSession(ownerId, ttl);
                }

                //
                var result = new XAiDocumentIngestResult
                {
                    SessionId = targetSessionId
                };

                //
                // Extract -> Chunk -> Embed ...
                var vectors = new List<XAiVectorDto>();
                foreach (var file in files)
                {
                    //
                    cancellationToken.ThrowIfCancellationRequested();

                    //
                    if (file.IsNull() || file.Length == 0)
                    {
                        result.SkippedFiles.Add(file?.FileName ?? "(null)");
                        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 (string.IsNullOrWhiteSpace(text))
                    {
                        result.SkippedFiles.Add(file.FileName);
                        continue;
                    }

                    //
                    var chunks = textChunker.Chunk(text, file.FileName);
                    if (!chunks.HasChild())
                    {
                        result.SkippedFiles.Add(file.FileName);
                        continue;
                    }

                    //
                    // Embed in Batches ...
                    var fileVectors = await EmbedChunks(
                        chunks: chunks,
                        fileName: file.FileName,
                        mimeType: mimeType,
                        cancellationToken: cancellationToken
                    );

                    //
                    vectors.AddRange(fileVectors);
                    result.FilesCount++;
                }

                //
                // Store ...
                if (vectors.HasChild() &&
                    !vectorStore.Add(targetSessionId, vectors, ownerId))
                {
                    XException.ActionFailed.Throw();
                }

                //
                // Fill Result ...
                result.ChunksCount = vectors.Count;
                if (vectorStore.TryGet(targetSessionId, out var session, ownerId))
                {
                    lock (session.SyncRoot)
                    {
                        result.TotalVectorsCount = session.Vectors.Count;
                    }
                    result.ExpiresAtUtc = session.LastAccessAtUtc.Add(session.Ttl);
                }

                //
                return Ok(result);
            }
            catch (Exception ex)
            {
                var result = GetExceptionActionResult(ex);
                return result;
            }
        }
        #endregion

        //
        #region Ask ...
        /// <summary>
        /// Ask a Question over Ingested Documents ...
        /// </summary>
        /// <param name="request"></param>
        /// <param name="cancellationToken"></param>
        /// <returns></returns>
        [HttpPost("Ask")]
        public async Task<ActionResult<XAiDocumentAnswer>> Ask(
            [FromBody] XAiDocumentAskRequest request,
            CancellationToken cancellationToken = default
        )
        {
            //
            try
            {
                //
                // Validate ...
                if (!request.IsValid())
                {
                    XException.InvalidArgs.Throw();
                }

                //
                var userInfo = await GetUserInfo();
                var ownerId = userInfo.UserId;

                //
                // Check Session ...
                if (!vectorStore.TryGet(request.SessionId, out _, ownerId))
                {
                    XException.NotFound.Throw();
                }

                //
                // Retrieve ...
                var context = await Retrieve(request, ownerId, cancellationToken);

                //
                var result = new XAiDocumentAnswer
                {
                    SessionId = request.SessionId,
                    Sources = ToSources(context)
                };

                //
                if (!context.HasChild())
                {
                    result.NoContextFound = true;
                    return Ok(result);
                }

                //
                // Generate ...
                result.Answer = await aiService.AskTextByContextAsync(
                    context: context,
                    userInfo: userInfo,
                    prompt: request.Prompt,
                    cancellationToken: cancellationToken
                );

                //
                return Ok(result);
            }
            catch (Exception ex)
            {
                var result = GetExceptionActionResult(ex);
                return result;
            }
        }

        /// <summary>
        /// Ask a Question over Ingested Documents and Stream Response (SSE) ...
        /// First Event Carries Sources, Next Events Carry Text Deltas, Last Event has IsFinal = true ...
        /// </summary>
        /// <param name="request"></param>
        /// <param name="cancellationToken"></param>
        /// <returns></returns>
        [HttpPost("AskStream")]
        public async Task AskStream(
            [FromBody] XAiDocumentAskRequest request,
            CancellationToken cancellationToken = default
        )
        {
            //
            // Validate (before Stream Starts -> Proper Http Error) ...
            if (!request.IsValid())
            {
                //
                Response.StatusCode = StatusCodes.Status400BadRequest;
                Response.ContentType = "application/json; charset=utf-8";
                await Response.WriteAsync(XException.InvalidArgs.ToXError().ToJSON());
                return;
            }

            //
            try
            {
                //
                var userInfo = await GetUserInfo();
                var ownerId = userInfo.UserId;

                //
                // Check Session ...
                if (!vectorStore.TryGet(request.SessionId, out _, ownerId))
                {
                    XException.NotFound.Throw();
                }

                //
                // Retrieve ...
                var context = await Retrieve(request, ownerId, cancellationToken);

                //
                // Configure SSE Response ...
                Response.PrepareSseResponse();

                //
                // First Event: Sources ...
                var hasContext = context.HasChild();
                await WriteChunk(new XAiDocumentAnswerChunk
                {
                    Text = string.Empty,
                    IsFinal = !hasContext,
                    NoContextFound = !hasContext,
                    Sources = ToSources(context)
                }, cancellationToken);

                //
                if (!hasContext)
                {
                    await Response.WriteSseDoneAsync(cancellationToken);
                    return;
                }

                //
                // Stream Deltas ...
                var enumerable = aiService.AskTextByContextAsEnumerable(
                    context: context,
                    userInfo: userInfo,
                    prompt: request.Prompt,
                    cancellationToken: cancellationToken
                );
                await foreach (var delta in enumerable)
                {
                    //
                    if (delta.IsNullOrEmpty())
                    {
                        continue;
                    }

                    //
                    await WriteChunk(new XAiDocumentAnswerChunk
                    {
                        Text = delta
                    }, cancellationToken);
                }

                //
                // Final Event ...
                await WriteChunk(new XAiDocumentAnswerChunk
                {
                    Text = string.Empty,
                    IsFinal = true
                }, cancellationToken);
                await Response.WriteSseDoneAsync(cancellationToken);
            }
            catch (Exception ex) when (ex.IsClientCancellation(cancellationToken))
            {
                // Client Disconnected ...
            }
            catch (Exception ex)
            {
                //
                Logger.LogError(ex, "ChatWithDocuments: AskStream Failed");
                if (!Response.HasStarted)
                {
                    //
                    var result = GetExceptionActionResult(ex);
                    await result.ExecuteResultAsync(ControllerContext);
                    return;
                }

                //
                await Response.WriteSseErrorAsync(ex.Message);
            }
        }
        #endregion

        //
        #region Session ...
        /// <summary>
        /// Retrieve Session Info (without Embeddings) ...
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        [HttpGet("Session/{id:guid}")]
        public async Task<ActionResult<XAiDocumentSessionInfo>> GetSession(Guid id)
        {
            //
            try
            {
                //
                var userInfo = await GetUserInfo();
                if (!vectorStore.TryGet(id, out var session, userInfo.UserId))
                {
                    XException.NotFound.Throw();
                }

                //
                IList<XAiVectorDto> vectors;
                lock (session.SyncRoot)
                {
                    vectors = session.Vectors.ToList();
                }

                //
                var result = new XAiDocumentSessionInfo
                {
                    Id = session.Id,
                    Ttl = session.Ttl,
                    VectorsCount = vectors.Count,
                    CreatedAtUtc = session.CreatedAtUtc,
                    LastAccessAtUtc = session.LastAccessAtUtc,
                    ExpiresAtUtc = session.LastAccessAtUtc.Add(session.Ttl),
                    Files = [.. vectors
                        .Select(v => v.Metadata.GetMetadata(apiConfiguration.RAGDescriptor.MetadataFileName))
                        .Where(f => !f.IsNullOrEmpty())
                        .Distinct()]
                };

                //
                return Ok(result);
            }
            catch (Exception ex)
            {
                var result = GetExceptionActionResult(ex);
                return result;
            }
        }

        /// <summary>
        /// Remove a Session and Free Memory ...
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        [HttpDelete("Session/{id:guid}")]
        public async Task<ActionResult<bool>> DeleteSession(Guid id)
        {
            //
            try
            {
                //
                var userInfo = await GetUserInfo();
                if (!vectorStore.Remove(id, userInfo.UserId))
                {
                    XException.NotFound.Throw();
                }

                //
                return Ok(true);
            }
            catch (Exception ex)
            {
                var result = GetExceptionActionResult(ex);
                return result;
            }
        }
        #endregion

        //
        #region Private ...
        /// <summary>
        /// Extract Plain Text of a File (Text or Audio Transcript) ...
        /// </summary>
        private async Task<string> 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, "ChatWithDocuments: Extraction Failed for {FileName}", file.FileName);
                return null;
            }
        }

        /// <summary>
        /// Embed Chunks in Batches and Build Vectors ...
        /// </summary>
        private async Task<IList<XAiVectorDto>> EmbedChunks(
            IList<XTextChunk> chunks,
            string fileName,
            string mimeType,
            CancellationToken cancellationToken
        )
        {
            //
            var result = new List<XAiVectorDto>(chunks.Count);
            var batchSize = apiConfiguration.RAGDescriptor.EmbeddingBatchSize;

            //
            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
                    {
                        Id = Guid.NewGuid(),
                        Text = chunk.Text,
                        Embedding = embeddings[i],
                        Identifier = chunk.Identifier,
                        Metadata = new Dictionary<string, string>
                        {
                            [apiConfiguration.RAGDescriptor.MetadataFileName] = fileName,
                            [apiConfiguration.RAGDescriptor.MetadataMimeType] = mimeType,
                            [apiConfiguration.RAGDescriptor.MetadataChunkIndex] = chunk.Index.ToString()
                        }
                    });
                }
            }

            //
            return result;
        }

        /// <summary>
        /// Embed Prompt and Search Session ...
        /// </summary>
        private async Task<IList<XAiVectorSearchResult>> Retrieve(
            XAiDocumentAskRequest request,
            string ownerId,
            CancellationToken cancellationToken
        )
        {
            //
            var topK = Math.Clamp(
                request.TopK ?? apiConfiguration.RAGDescriptor.DefaultTopK,
                1,
                apiConfiguration.RAGDescriptor.MaxTopK
            );
            var minScore = request.MinScore ?? apiConfiguration.RAGDescriptor.DefaultMinScore;

            //
            var queryEmbedding = await embeddingService.Embedding(
                content: request.Prompt,
                cancellationToken: cancellationToken
            );
            if (queryEmbedding.IsNullOrDefault() || queryEmbedding.Length == 0)
            {
                XException.ActionFailed.Throw();
            }

            //
            var result = vectorStore.Search(
                topK: topK,
                ownerId: ownerId,
                minScore: minScore,
                sessionId: request.SessionId,
                queryEmbedding: queryEmbedding
            );

            //
            return result ?? [];
        }

        /// <summary>
        /// Map Search Results to Public Sources ...
        /// </summary>
        private IList<XAiDocumentSource> ToSources(
            IEnumerable<XAiVectorSearchResult> context
        )
        {
            //
            var result = (context ?? [])
                .Select(c =>
                {
                    //
                    var chunkIndexText = c.Metadata.GetMetadata(apiConfiguration.RAGDescriptor.MetadataChunkIndex);
                    var text = c.Text ?? string.Empty;
                    var snippetLength = Math.Min(text.Length, apiConfiguration.RAGDescriptor.SourceSnippetLength);

                    //
                    return new XAiDocumentSource
                    {
                        Score = c.Score,
                        Identifier = c.Identifier,
                        Snippet = text.Substring(0, snippetLength),
                        ChunkIndex = int.TryParse(chunkIndexText, out var idx) ? idx : null,
                        FileName = c.Metadata.GetMetadata(apiConfiguration.RAGDescriptor.MetadataFileName)
                    };
                })
                .ToList();

            //
            return result;
        }

        /// <summary>
        /// Write a SSE Event ...
        /// </summary>
        private Task WriteChunk(
            XAiDocumentAnswerChunk chunk,
            CancellationToken cancellationToken
        )
        {
            //
            return Response.WriteSseEventAsync(
                data: chunk,
                cancellationToken: cancellationToken
            );
        }
        #endregion
    }
}

### FILE: C:\Users\saherelm\Documents\Projects\xSaherelmWorkspace\xAiApi\Controllers\KnowledgeController.cs

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;
using xIdentityHelper;

namespace xAiApi.Controllers
{
    /// <summary>
    /// Knowledge (Persistent RAG over XAiVector Table) Controller ...
    /// Flow: Ingest Files -> Ask / AskStream (Retrieve from DB -> Generate) -> Documents / Delete
    /// </summary>
    [Authorize]
    public class KnowledgeController : XBaseIdentityApiV1Controller
    {
        /// <summary>
        /// Persistent RAG Service ...
        /// </summary>
        private readonly IXAiRAGService ragService;

        public KnowledgeController(
            IXAiRAGService ragService,
            XAppConfiguration appConfiguration,
            IXIdentityProvider identityProvider,
            ILogger<KnowledgeController> logger,
            XValidationProvider validationProvider
        ) : base(logger, appConfiguration, identityProvider, validationProvider)
        {
            this.ragService = ragService;
        }

        //
        #region Ingest ...
        /// <summary>
        /// Ingest Files into a Knowledge Scope:
        /// Extract -> Chunk -> Embed -> Store in XAiVector Table ...
        /// </summary>
        /// <param name="files"></param>
        /// <param name="scope">Target Scope: User (default) / Project / Conversation / Global (Admin)</param>
        /// <param name="scopeId">ProjectId or ConversationId (Required for Project / Conversation)</param>
        /// <param name="knowledgeType">Optional Knowledge Type / Domain</param>
        /// <param name="replaceExisting">Replace Previously Stored Vectors of Same File (default true)</param>
        /// <param name="cancellationToken"></param>
        /// <returns></returns>
        [HttpPost("Ingest")]
        [Consumes("multipart/form-data")]
        [Authorize(Policy = XPolicies.EnabledAdmin)]
        public async Task<ActionResult<XAiKnowledgeIngestResult>> 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 Documents ...
        /// <summary>
        /// List Ingested Documents of a Knowledge Scope ...
        /// </summary>
        /// <param name="scope">User (default) / Project / Conversation / Global</param>
        /// <param name="scopeId">ProjectId or ConversationId (Required for Project / Conversation)</param>
        /// <param name="knowledgeType">Optional Knowledge Type Filter</param>
        /// <param name="cancellationToken"></param>
        /// <returns></returns>
        [HttpGet("Documents")]
        [Authorize(Policy = XPolicies.EnabledAdmin)]
        public async Task<ActionResult<IList<XAiKnowledgeDocumentInfo>>> Documents(
            [FromQuery] XAiKnowledgeScope? scope = XAiKnowledgeScope.Global,
            [FromQuery] Guid? scopeId = null,
            [FromQuery] string knowledgeType = null,
            CancellationToken cancellationToken = default
        )
        {
            //
            try
            {
                //
                var userInfo = await GetUserInfo();
                var scopeIdentifier = BuildScope(scope, scopeId, knowledgeType);

                //
                var result = await ragService.LoadDocumentsAsync(
                    userInfo: userInfo,
                    scope: scopeIdentifier,
                    cancellationToken: cancellationToken
                );

                //
                return Ok(result);
            }
            catch (Exception ex)
            {
                //
                var result = GetExceptionActionResult(ex);
                return result;
            }
        }

        /// <summary>
        /// Remove All Vectors of a Document in a Knowledge Scope ...
        /// </summary>
        /// <param name="fileName"></param>
        /// <param name="scope">User (default) / Project / Conversation / Global (Admin)</param>
        /// <param name="scopeId">ProjectId or ConversationId (Required for Project / Conversation)</param>
        /// <param name="cancellationToken"></param>
        /// <returns>Count of Removed Vectors</returns>
        [HttpDelete("Documents")]
        [Authorize(Policy = XPolicies.EnabledAdmin)]
        public async Task<ActionResult<int>> DeleteDocument(
            [FromQuery] string fileName,
            [FromQuery] XAiKnowledgeScope? scope = XAiKnowledgeScope.Global,
            [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 ...
        /// <summary>
        /// Build Scope Descriptor from Request Params ...
        /// </summary>
        private XAiKnowledgeScopeDescriptor BuildScope(
            XAiKnowledgeScope? scope,
            Guid? scopeId,
            string knowledgeType
        )
        {
            //
            if (!scope.HasValue)
            {
                scope = XAiKnowledgeScope.Global;
            }

            //
            var result = new XAiKnowledgeScopeDescriptor
            {
                Scope = scope.Value,
                ScopeId = scopeId,
                Type = knowledgeType,
            };

            //
            return result;
        }

        /// <summary>
        /// Write a SSE Event ...
        /// </summary>
        private Task WriteChunk(
            XAiDocumentAnswerChunk chunk,
            CancellationToken cancellationToken
        )
        {
            //
            return Response.WriteSseEventAsync(
                data: chunk,
                cancellationToken: cancellationToken
            );
        }
        #endregion
    }
}


### FILE: C:\Users\saherelm\Documents\Projects\xSaherelmWorkspace\xAiApi\Controllers\McpServersController.cs

using System;
using xModels.Dtos;
using xIdentityHelper;
using System.Threading;
using xAiApi.Interfaces;
using xCommons.Providers;
using xCommons.Extensions;
using xAiModels.Extensions;
using xAiModels.Models.Dtos;
using xExceptions.Constants;
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]
    public class McpServersController : XBaseIdentityApiV1Controller
    {
        private readonly IXAiMcpServerProvider mcpServerProvider;

        public McpServersController(
            XAppConfiguration appConfiguration,
            IXIdentityProvider identityProvider,
            ILogger<McpServersController> logger,
            XValidationProvider validationProvider,
            IXAiMcpServerProvider mcpServerProvider
        ) : base(
            logger,
            appConfiguration,
            identityProvider,
            validationProvider
        )
        {
            this.mcpServerProvider = mcpServerProvider;
        }

        //
        #region Provider ...
        /// <summary>
        /// Retrieve Specified MCP Server ...
        /// </summary>
        /// <param name="id"></param>
        /// <param name="cancellationToken"></param>
        /// <returns></returns>
        [HttpGet("{id}")]
        [Authorize(Policy = XPolicies.EnabledUser)]
        public virtual async Task<ActionResult<XAiMcpServerDto>> GetMcpServer(
            [FromRoute] Guid id,
            CancellationToken cancellationToken = default
        )
        {
            //
            try
            {
                //
                // Validate ...
                if (!ModelState.IsValid || id.IsDefaultGuid())
                {
                    XException.InvalidArgs.Throw();
                }

                //
                var userInfo = await GetUserInfo();
                var connectionId = GetConnectionId();

                //
                var result = await mcpServerProvider.GetMcpServer(
                    id: id,
                    userInfo: userInfo,
                    cancellationToken: cancellationToken
                );

                //
                return Ok(result.ToDynamicObject());
            }
            catch (Exception ex)
            {
                //
                var result = GetExceptionActionResult(ex);
                return result;
            }
        }

        /// <summary>
        /// Add MCP Server ...
        /// </summary>
        /// <param name="item"></param>
        /// <param name="cancellationToken"></param>
        /// <returns></returns>
        [HttpPost]
        [Authorize(Policy = XPolicies.EnabledUser)]
        public virtual async Task<ActionResult<XAiMcpServerDto>> AddMcpServer(
            [FromBody] XAiMcpServerDto item,
            CancellationToken cancellationToken = default
        )
        {
            //
            try
            {
                //
                // Validate ...
                if (!ModelState.IsValid || item.IsNullOrDefault())
                {
                    XException.InvalidArgs.Throw();
                }

                //
                var userInfo = await GetUserInfo();
                var connectionId = GetConnectionId();

                //
                var result = await mcpServerProvider.AddMcpServer(
                    item: item,
                    userInfo: userInfo,
                    connectionId: connectionId,
                    cancellationToken: cancellationToken
                );

                //
                return Ok(result.ToDynamicObject());
            }
            catch (Exception ex)
            {
                //
                var result = GetExceptionActionResult(ex);
                return result;
            }
        }

        /// <summary>
        /// Update Specified MCP Server ...
        /// </summary>
        /// <param name="id"></param>
        /// <param name="item"></param>
        /// <param name="cancellationToken"></param>
        /// <returns></returns>
        [HttpPut("{id}")]
        [Authorize(Policy = XPolicies.EnabledUser)]
        public virtual async Task<ActionResult<XAiMcpServerDto>> UpdateMcpServer(
            [FromRoute] Guid id,
            [FromBody] XAiMcpServerDto item,
            CancellationToken cancellationToken = default
        )
        {
            //
            try
            {
                //
                // Validate ...
                if (id.IsDefaultGuid() ||
                    !ModelState.IsValid || 
                    !item.IsValidForAddOrUpdate())
                {
                    XException.InvalidArgs.Throw();
                }

                //
                var userInfo = await GetUserInfo();
                var connectionId = GetConnectionId();

                //
                var result = await mcpServerProvider.UpdateMcpServer(
                    id: id,
                    item: item,
                    userInfo: userInfo,
                    connectionId: connectionId,
                    cancellationToken: cancellationToken
                );

                //
                return Ok(result.ToDynamicObject());
            }
            catch (Exception ex)
            {
                //
                var result = GetExceptionActionResult(ex);
                return result;
            }
        }

        /// <summary>
        /// Remove Specified MCP Server ...
        /// </summary>
        /// <param name="id"></param>
        /// <param name="cancellationToken"></param>
        /// <returns></returns>
        [HttpDelete("{id}")]
        [Authorize(Policy = XPolicies.EnabledUser)]
        public virtual async Task<ActionResult<XAiMcpServerDto>> RemoveMcpServer(
            [FromRoute] Guid id,
            CancellationToken cancellationToken = default
        )
        {
            //
            try
            {
                //
                // Validate ...
                if (!ModelState.IsValid || id.IsDefaultGuid())
                {
                    XException.InvalidArgs.Throw();
                }

                //
                var userInfo = await GetUserInfo();
                var connectionId = GetConnectionId();

                //
                var result = await mcpServerProvider.RemoveMcpServer(
                    id: id,
                    userInfo: userInfo,
                    connectionId: connectionId,
                    cancellationToken: cancellationToken
                );

                //
                return Ok(result.ToDynamicObject());
            }
            catch (Exception ex)
            {
                //
                var result = GetExceptionActionResult(ex);
                return result;
            }
        }

        /// <summary>
        /// Enable Specified MCP Server ...
        /// </summary>
        /// <param name="id"></param>
        /// <param name="cancellationToken"></param>
        /// <returns></returns>
        [HttpPost("{id}/Enable")]
        [Authorize(Policy = XPolicies.EnabledUser)]
        public virtual async Task<ActionResult<bool>> EnableMcpServer(
            [FromRoute] Guid id,
            CancellationToken cancellationToken = default
        )
        {
            //
            try
            {
                //
                // Validate ...
                if (!ModelState.IsValid || id.IsDefaultGuid())
                {
                    XException.InvalidArgs.Throw();
                }

                //
                var userInfo = await GetUserInfo();
                var connectionId = GetConnectionId();

                //
                var result = await mcpServerProvider.EnableMcpServer(
                    id: id,
                    userInfo: userInfo,
                    connectionId: connectionId,
                    cancellationToken: cancellationToken
                );

                //
                return Ok(result);
            }
            catch (Exception ex)
            {
                //
                var result = GetExceptionActionResult(ex);
                return result;
            }
        }

        /// <summary>
        /// Disable Specified MCP Server ...
        /// </summary>
        /// <param name="id"></param>
        /// <param name="cancellationToken"></param>
        /// <returns></returns>
        [HttpPost("{id}/Disable")]
        [Authorize(Policy = XPolicies.EnabledUser)]
        public virtual async Task<ActionResult<bool>> DisableMcpServer(
            [FromRoute] Guid id,
            CancellationToken cancellationToken = default
        )
        {
            //
            try
            {
                //
                // Validate ...
                if (!ModelState.IsValid || id.IsDefaultGuid())
                {
                    XException.InvalidArgs.Throw();
                }

                //
                var userInfo = await GetUserInfo();
                var connectionId = GetConnectionId();

                //
                var result = await mcpServerProvider.DisableMcpServer(
                    id: id,
                    userInfo: userInfo,
                    connectionId: connectionId,
                    cancellationToken: cancellationToken
                );

                //
                return Ok(result);
            }
            catch (Exception ex)
            {
                //
                var result = GetExceptionActionResult(ex);
                return result;
            }
        }

        /// <summary>
        /// Toggle Specified MCP Server ...
        /// </summary>
        /// <param name="id"></param>
        /// <param name="cancellationToken"></param>
        /// <returns></returns>
        [HttpPost("{id}/Toggle")]
        [Authorize(Policy = XPolicies.EnabledUser)]
        public virtual async Task<ActionResult<bool>> ToggleMcpServer(
            [FromRoute] Guid id,
            CancellationToken cancellationToken = default
        )
        {
            //
            try
            {
                //
                // Validate ...
                if (!ModelState.IsValid || id.IsDefaultGuid())
                {
                    XException.InvalidArgs.Throw();
                }

                //
                var userInfo = await GetUserInfo();
                var connectionId = GetConnectionId();

                //
                var result = await mcpServerProvider.ToggleMcpServer(
                    id: id,
                    userInfo: userInfo,
                    connectionId: connectionId,
                    cancellationToken: cancellationToken
                );

                //
                return Ok(result);
            }
            catch (Exception ex)
            {
                //
                var result = GetExceptionActionResult(ex);
                return result;
            }
        }

        /// <summary>
        /// Get all Registered MCP Servers by handling Ownership ...
        /// </summary>
        /// <param name="cancellationToken"></param>
        /// <returns></returns>
        [HttpGet]
        [Authorize(Policy = XPolicies.EnabledUser)]
        public virtual async Task<ActionResult<IEnumerable<XAiMcpServerDto>>> GetMcpServers(
            [FromQuery] bool forceOwner = true,
            CancellationToken cancellationToken = default
        )
        {
            //
            try
            {
                //
                // Validate ...
                if (!ModelState.IsValid)
                {
                    XException.InvalidArgs.Throw();
                }

                //
                var userInfo = await GetUserInfo();
                var connectionId = GetConnectionId();

                //
                var result = await mcpServerProvider.GetAll(
                    userInfo: userInfo,
                    forceOwner: forceOwner,
                    cancellationToken: cancellationToken
                );

                //
                return Ok(result.ToDynamicObject());
            }
            catch (Exception ex)
            {
                //
                var result = GetExceptionActionResult(ex);
                return result;
            }
        }

        /// <summary>
        /// Query Registered MCP Servers by handling Ownership ...
        /// </summary>
        /// <param name="query"></param>
        /// <param name="forceOwner"></param>
        /// <param name="cancellationToken"></param>
        /// <returns></returns>
        [HttpGet("Query")]
        [Authorize(Policy = XPolicies.EnabledUser)]
        public virtual async Task<ActionResult<XQueryResult<XAiMcpServerDto>>> QueryMcpServers(
            [FromQuery] XQuery query,
            [FromQuery] bool forceOwner = true,
            CancellationToken cancellationToken = default
        )
        {
            //
            try
            {
                //
                // Validate ...
                if (!ModelState.IsValid)
                {
                    XException.InvalidArgs.Throw();
                }
                await ValidationProvider
                    .GroupValidationBuilder()
                    .AddNotNull(query)
                    .ValidateGroupAsync();

                //
                var userInfo = await GetUserInfo();
                var connectionId = GetConnectionId();

                //
                var result = await mcpServerProvider.Query(
                    query: query,
                    userInfo: userInfo,
                    forceOwner: forceOwner,
                    cancellationToken: cancellationToken
                );

                //
                return Ok(result.ToDynamicObject());
            }
            catch (Exception ex)
            {
                //
                var result = GetExceptionActionResult(ex);
                return result;
            }
        }
        #endregion

        /// <summary>
        /// Refresh MCP Servers ...
        /// </summary>
        /// <param name="cancellationToken"></param>
        /// <returns></returns>
        [HttpPost("Refresh")]
        [Authorize(Policy = XPolicies.EnabledAdmin)]
        public async Task<ActionResult> RefreshMcpServers(
            CancellationToken cancellationToken = default
        )
        {
            //
            try
            {
                //
                var userInfo = await GetUserInfo();

                //
                await mcpServerProvider.RefreshAsync(
                    userInfo: userInfo,
                    cancellationToken: cancellationToken
                );

                //
                return Ok();                
            } catch(Exception ex)
            {
                //
                var result = GetExceptionActionResult(ex);
                return result;
            }
        }
    }
}

### FILE: C:\Users\saherelm\Documents\Projects\xSaherelmWorkspace\xAiApi\Controllers\StartupController.cs

using xCommons.Providers;
using xCommons.Extensions;
using xCommons.Controllers;
using xExceptions.Constants;
using xCommons.Configurations;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Http;
using Microsoft.Extensions.Logging;
using Microsoft.AspNetCore.Authorization;

namespace xAiApi.Controllers
{
    /// <summary>
    /// Runing when application start ...
    /// </summary>
    [Route("")]
    [AllowAnonymous]
    public class StartupController : XBaseController
    {

        public StartupController(
            ILogger<StartupController> logger,
            XAppConfiguration appConfiguration,
            XValidationProvider validationProvider
        ) : base(
            logger,
            appConfiguration,
            validationProvider
        )
        { }

        /// <summary>
        /// Show Configured Welcome Message 
        /// </summary>
        /// <returns></returns>
        [HttpGet("")]
        [AllowAnonymous]
        public virtual ActionResult<string> Index()
        {
            //
            var controllerName = GetControllerName();
            var message = $"{AppConfiguration.WelcomeMessage}";

            //
            return Ok(message);
        }

        /// <summary>
        /// Global Exception Handler Endpoint (Production) ...
        /// Returns a Generic Error without Leaking Exception Details ...
        /// </summary>
        /// <returns></returns>
        [AllowAnonymous]
        [Route("error")]
        [ApiExplorerSettings(IgnoreApi = true)]
        public virtual ActionResult Error()
        {
            //
            var error = XException.ActionFailed.ToXError();
            return StatusCode(StatusCodes.Status500InternalServerError, error);
        }
    }
}

### FILE: C:\Users\saherelm\Documents\Projects\xSaherelmWorkspace\xAiApi\Controllers\TestIdentity.cs

using xCommons.Providers;
using xCommons.Configurations;
using xIdentityService.Interfaces;
using xIdentityHelper.Controllers;
using Microsoft.Extensions.Logging;

namespace xAiApi.Controllers {
    /// <summary>
    /// Test all Authentication Policies ...
    /// </summary>
    public class TestIdentity : XTestIdentityControllerBase {
        public TestIdentity (
            ILogger<TestIdentity> logger,
            XAppConfiguration appConfiguration,
            IXIdentityProvider identityProvider,
            XValidationProvider validationProvider
        ) : base (
            logger,
            appConfiguration,
            identityProvider,
            validationProvider
        ) { }
    }
}

### FILE: C:\Users\saherelm\Documents\Projects\xSaherelmWorkspace\xAiApi\Controllers\XAiController.cs

using xAiApi.Interfaces;
using xCommons.Providers;
using xCommons.Configurations;
using xIdentityService.Interfaces;
using Microsoft.Extensions.Logging;
using Microsoft.AspNetCore.Authorization;

namespace xAiApi.Controllers
{
    [Authorize]
    public class XAiController : XAiServiceControllerBase<IXAiService>
    {
        public XAiController(
            ILogger<XAiController> logger,
            IXAiService aiService,
            XAppConfiguration appConfiguration,
            IXIdentityProvider identityProvider,
            XValidationProvider validationProvider
        ) : base(
            logger,
            aiService,
            appConfiguration,
            identityProvider,
            validationProvider
        )
        { }
    }
}

### FILE: C:\Users\saherelm\Documents\Projects\xSaherelmWorkspace\xAiApi\Controllers\XAiServiceControllerBase.cs

using System;
using xModels.Dtos;
using xIdentityHelper;
using System.Threading;
using xAiModels.Models;
using xAiApi.Extensions;
using xAiApi.Interfaces;
using xCommons.Providers;
using xCommons.Extensions;
using xAiModels.Extensions;
using xAiModels.Models.Dtos;
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 Microsoft.Extensions.Logging;
using xIdentityService.Controllers;
using Microsoft.AspNetCore.Authorization;

namespace xAiApi.Controllers
{
    [Authorize]
    public abstract class XAiServiceControllerBase<TAiService> : XBaseIdentityApiV1Controller
    where TAiService : IXAiServiceBase
    {
        private readonly TAiService aiService;

        protected XAiServiceControllerBase(
            ILogger logger,
            TAiService aiService,
            XAppConfiguration appConfiguration,
            IXIdentityProvider identityProvider,
            XValidationProvider validationProvider
        ) : base(
            logger,
            appConfiguration,
            identityProvider,
            validationProvider
        )
        {
            this.aiService = aiService;
        }

        //
        #region Actions ...
        /// <summary>
        /// Ask Question and Get Response ...
        /// </summary>
        /// <param name="question"></param>
        /// <param name="cancellationToken"></param>
        /// <returns></returns>
        [HttpGet("AskText")]
        [Authorize(Policy = XPolicies.EnabledUser)]
        public virtual async Task<ActionResult<string>> AskText(
            [FromQuery] string question,
            CancellationToken cancellationToken = default
        )
        {
            //
            try
            {
                //
                // Validate ...
                ValidationProvider.NotEmpty(question);

                //
                var userInfo = await GetUserInfo();

                //
                var result = await aiService.AskTextAsync(
                    prompt: question,
                    userInfo: userInfo,
                    cancellationToken: cancellationToken
                );

                //
                return Ok(result);
            }
            catch (Exception ex)
            {
                //
                var result = GetExceptionActionResult(ex);
                return result;
            }
        }

        /// <summary>
        /// Ask Question and Get Response Stream ...
        /// </summary>
        /// <param name="question"></param>
        /// <param name="cancellationToken"></param>
        /// <returns></returns>
        [HttpGet("AskTextStream")]
        [Authorize(Policy = XPolicies.EnabledUser)]
        public virtual async Task AskTextStream(
            [FromQuery] string question,
            CancellationToken cancellationToken = default
        )
        {
            //
            // Validate (before Stream Starts -> Proper Http Error) ...
            if (question.IsNullOrEmpty())
            {
                await WriteStreamValidationError();
                return;
            }

            //
            try
            {
                //
                // Configure SSE Response ...
                Response.PrepareSseResponse();

                //
                var userInfo = await GetUserInfo();

                //
                var enumerable = aiService.AskTextAsEnumerable(
                    prompt: question,
                    userInfo: userInfo,
                    cancellationToken: cancellationToken
                );

                //
                // Format: data: {"text":"..."}\n\n
                await foreach (var chunk in enumerable)
                {
                    //
                    // Skip Empty Chunks ...
                    if (string.IsNullOrEmpty(chunk))
                    {
                        continue;
                    }

                    //
                    await Response.WriteSseEventAsync(
                        data: new { text = chunk },
                        cancellationToken: cancellationToken
                    );
                }

                //
                await Response.WriteSseDoneAsync(cancellationToken);
            }
            catch (Exception ex) when (ex.IsClientCancellation(cancellationToken))
            {
                // Client Disconnected ...
            }
            catch (Exception ex)
            {
                //
                Logger.LogError(ex, "AskTextStream Failed");
                if (!Response.HasStarted)
                {
                    //
                    var result = GetExceptionActionResult(ex);
                    await result.ExecuteResultAsync(ControllerContext);
                    return;
                }

                //
                await Response.WriteSseErrorAsync(ex.Message);
            }
        }

        /// <summary>
        /// Ask a Question By Rag Retrive From Knowledge ...
        /// </summary>
        /// <param name="request"></param>
        /// <param name="cancellationToken"></param>
        /// <returns></returns>
        [HttpGet("AskTextFromKnowledge")]
        [Authorize(Policy = XPolicies.EnabledUser)]
        public virtual async Task<ActionResult<string>> AskTextFromKnowledge(
            [FromQuery] XAiResponseRequest request,
            CancellationToken cancellationToken = default
        )
        {
            //
            try
            {
                //
                // Validate ...
                if (!request.IsValid())
                {
                    XException.InvalidArgs.Throw();
                }

                //
                var userInfo = await GetUserInfo();
                var connectionId = GetConnectionId();

                //
                var result = await aiService.AskTextFromKnowledgeAsync(
                    topK: request.TopK,
                    userInfo: userInfo,
                    type: request.Type,
                    prompt: request.Prompt,
                    minScore: request.MinScore,
                    cancellationToken: cancellationToken
                );

                //
                return Ok(result);
            }
            catch (Exception ex)
            {
                //
                var result = GetExceptionActionResult(ex);
                return result;
            }
        }

        /// <summary>
        /// Ask a Question By Rag Retrive From Knowledge and Stream Response ...
        /// </summary>
        /// <param name="request"></param>
        /// <param name="cancellationToken"></param>
        /// <returns></returns>
        [HttpGet("AskTextFromKnowledgeStream")]
        [Authorize(Policy = XPolicies.EnabledUser)]
        public virtual async Task AskTextFromKnowledgeStream(
            [FromQuery] XAiResponseRequest request,
            CancellationToken cancellationToken = default
        )
        {
            //
            // Validate (before Stream Starts -> Proper Http Error) ...
            if (!request.IsValid())
            {
                await WriteStreamValidationError();
                return;
            }

            //
            try
            {
                //
                var userInfo = await GetUserInfo();
                var connectionId = GetConnectionId();

                //
                // Configure SSE Response ...
                Response.PrepareSseResponse();

                //
                var enumerable = aiService.AskTextFromKnowledgeAsEnumerable(
                    topK: request.TopK,
                    userInfo: userInfo,
                    type: request.Type,
                    prompt: request.Prompt,
                    minScore: request.MinScore,
                    cancellationToken: cancellationToken
                );

                //
                // Format: data: {json}\n\n
                await foreach (var resp in enumerable)
                {
                    //
                    // Skip Empty Responses ...
                    if (resp.IsNullOrDefault())
                    {
                        continue;
                    }

                    //
                    await Response.WriteSseEventAsync(
                        data: resp,
                        cancellationToken: cancellationToken
                    );
                }

                //
                await Response.WriteSseDoneAsync(cancellationToken);
            }
            catch (Exception ex) when (ex.IsClientCancellation(cancellationToken))
            {
                // Client Disconnected ...
            }
            catch (Exception ex)
            {
                //
                Logger.LogError(ex, "AskStream Failed ...");
                if (!Response.HasStarted)
                {
                    //
                    var result = GetExceptionActionResult(ex);
                    await result.ExecuteResultAsync(ControllerContext);
                    return;
                }

                //
                await Response.WriteSseErrorAsync(ex.Message);
            }
        }

        /// <summary>
        /// Ask Question and Get Response ...
        /// </summary>
        /// <param name="request"></param>
        /// <param name="cancellationToken"></param>
        /// <returns></returns>
        [HttpPost("Ask")]
        [Authorize(Policy = XPolicies.EnabledUser)]
        public virtual async Task<ActionResult<string>> Ask(
            [FromBody] XAiResponseRequest request,
            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,
                    type: request.Type,
                    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;
            }
        }

        /// <summary>
        /// Ask Question and Get Response Stream ...
        /// </summary>
        /// <param name="request"></param>
        /// <param name="cancellationToken"></param>
        /// <returns></returns>
        [HttpPost("AskStream")]
        [Authorize(Policy = XPolicies.EnabledUser)]
        public virtual 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,
                    type: request.Type,
                    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);
            }
        }

        /// <summary>
        /// Ask Question with Files and Get Response ...
        /// </summary>
        /// <param name="request"></param>
        /// <param name="cancellationToken"></param>
        /// <returns></returns>
        [HttpPost("AskWithFiles")]
        [Consumes("multipart/form-data")]
        [Authorize(Policy = XPolicies.EnabledUser)]
        public virtual async Task<ActionResult<string>> 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,
                    topK: request.TopK,
                    userInfo: userInfo,
                    type: request.Type,
                    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;
            }
        }

        /// <summary>
        /// Ask Question with Files and Get Response Stream ...
        /// </summary>
        /// <param name="request"></param>
        /// <param name="cancellationToken"></param>
        /// <returns></returns>
        [HttpPost("AskWithFilesStream")]
        [Consumes("multipart/form-data")]
        [Authorize(Policy = XPolicies.EnabledUser)]
        public virtual 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,
                    type: request.Type,
                    prompt: request.Prompt,
                    minScore: request.MinScore,
                    connectionId: connectionId,
                    extractFileContents: false,
                    addFilesToKnowledge: false,
                    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

        //
        #region Loaders ...
        /// <summary>
        /// Retrieve AI Projects ...
        /// </summary>
        /// <param name="includeDefaults"></param>
        /// <param name="cancellationToken"></param>
        /// <returns></returns>
        [HttpGet("Projects")]
        [Authorize(Policy = XPolicies.EnabledUser)]
        public async Task<ActionResult<IEnumerable<XAiProjectDto>>> LoadProjects(
            [FromQuery] bool includeDefaults = false,
            CancellationToken cancellationToken = default
        )
        {
            //
            try
            {
                //
                var userInfo = await GetUserInfo();
                var connectionId = GetConnectionId();

                //
                var result = await aiService.LoadProjects(
                    ownerId: userInfo.UserId,
                    connectionId: connectionId,
                    includeDefaults: includeDefaults,
                    cancellationToken: cancellationToken
                );

                //
                return Ok(result);
            }
            catch (Exception ex)
            {
                //
                var result = GetExceptionActionResult(ex);
                return result;
            }
        }

        /// <summary>
        /// Retrieve Specified AI Project's Conversations ...
        /// </summary>
        /// <param name="projectId"></param>
        /// <param name="cancellationToken"></param>
        /// <returns></returns>
        [Authorize(Policy = XPolicies.EnabledUser)]
        [HttpGet("Projects/{projectId}/Conversations")]
        public async Task<ActionResult<IEnumerable<XAiConversationDto>>> LoadConversations(
            [FromRoute] Guid? projectId,
            CancellationToken cancellationToken = default
        )
        {
            //
            try
            {
                //
                var userInfo = await GetUserInfo();
                var connectionId = GetConnectionId();

                //
                var result = await aiService.LoadConversations(
                    projectId: projectId,
                    ownerId: userInfo.UserId,
                    connectionId: connectionId,
                    cancellationToken: cancellationToken
                );

                //
                return Ok(result);
            }
            catch (Exception ex)
            {
                //
                var result = GetExceptionActionResult(ex);
                return result;
            }
        }

        /// <summary>
        /// Retrieve Specified AI Project's Conversations ...
        /// </summary>
        /// <param name="projectId"></param>
        /// <param name="cancellationToken"></param>
        /// <returns></returns>
        [Authorize(Policy = XPolicies.EnabledUser)]
        [HttpGet("Projects/Conversations")]
        public async Task<ActionResult<IEnumerable<XAiConversationDto>>> LoadProjectConversations(
            [FromQuery] Guid? projectId,
            CancellationToken cancellationToken = default
        )
        {
            //
            try
            {
                //
                var userInfo = await GetUserInfo();
                var connectionId = GetConnectionId();

                //
                var result = await aiService.LoadConversations(
                    projectId: projectId,
                    ownerId: userInfo.UserId,
                    connectionId: connectionId,
                    cancellationToken: cancellationToken
                );

                //
                return Ok(result);
            }
            catch (Exception ex)
            {
                //
                var result = GetExceptionActionResult(ex);
                return result;
            }
        }

        /// <summary>
        /// Retrieve Specified AI Conversation's Messages ...
        /// </summary>
        /// <param name="conversationId"></param>
        /// <param name="cancellationToken"></param>
        /// <returns></returns>
        [Authorize(Policy = XPolicies.EnabledUser)]
        [HttpGet("Conversations/{conversationId}/Messages")]
        public async Task<ActionResult<IEnumerable<XAiMessageDto>>> LoadMessages(
            [FromRoute] Guid? conversationId,
            CancellationToken cancellationToken = default
        )
        {
            //
            try
            {
                //
                var userInfo = await GetUserInfo();
                var connectionId = GetConnectionId();
                
                //
                var result = await aiService.LoadMessages(
                    ownerId: userInfo.UserId,
                    connectionId: connectionId,
                    conversationId: conversationId,
                    cancellationToken: cancellationToken
                );

                //
                return Ok(result);
            }
            catch (Exception ex)
            {
                //
                var result = GetExceptionActionResult(ex);
                return result;
            }
        }

        /// <summary>
        /// Retrieve Specified AI Conversation's Messages ...
        /// </summary>
        /// <param name="conversationId"></param>
        /// <param name="cancellationToken"></param>
        /// <returns></returns>
        [Authorize(Policy = XPolicies.EnabledUser)]
        [HttpGet("Conversations/Messages")]
        public async Task<ActionResult<IEnumerable<XAiMessageDto>>> LoadConversationMessages(
            [FromQuery] Guid? conversationId,
            CancellationToken cancellationToken = default
        )
        {
            //
            try
            {
                //
                var userInfo = await GetUserInfo();
                var connectionId = GetConnectionId();
                
                //
                var result = await aiService.LoadMessages(
                    ownerId: userInfo.UserId,
                    connectionId: connectionId,
                    conversationId: conversationId,
                    cancellationToken: cancellationToken
                );

                //
                return Ok(result);
            }
            catch (Exception ex)
            {
                //
                var result = GetExceptionActionResult(ex);
                return result;
            }
        }
        #endregion

        //
        #region Queries ...
        /// <summary>
        /// Query Projects ...
        /// </summary>
        /// <remarks>
        /// </remarks>
        /// <param name="query"></param>
        /// <param name="cancellationToken"></param>
        /// <returns></returns>
        [HttpGet("Projects/Query")]
        [Authorize(Policy = XPolicies.EnabledUser)]
        public async Task<ActionResult<XQueryResult<XAiProjectDto>>> QueryProjects(
            [FromQuery] XQuery query,
            CancellationToken cancellationToken = default
        )
        {
            //
            try
            {
                //
                var userInfo = await GetUserInfo();
                var connectionId = GetConnectionId();

                //
                var result = await aiService.QueryProjects(
                    query: query,
                    ownerId: userInfo.UserId,
                    cancellationToken: cancellationToken
                );

                //
                return Ok(result);
            }
            catch (Exception ex)
            {
                //
                var result = GetExceptionActionResult(ex);
                return result;
            }
        }

        /// <summary>
        /// Query Conversations ...
        /// </summary>
        /// <param name="projectId"></param>
        /// <param name="query"></param>
        /// <param name="cancellationToken"></param>
        /// <returns></returns>
        [Authorize(Policy = XPolicies.EnabledUser)]
        [HttpGet("Projects/{projectId}/Conversations/Query")]
        public async Task<ActionResult<XQueryResult<XAiConversationDto>>> QueryConversations(
            [FromRoute] Guid projectId,
            [FromQuery] XQuery query,
            CancellationToken cancellationToken = default
        )
        {
            //
            try
            {
                //
                var userInfo = await GetUserInfo();
                var connectionId = GetConnectionId();

                //
                var result = await aiService.QueryConversations(
                    query: query,
                    projectId: projectId,
                    ownerId: userInfo.UserId,
                    cancellationToken: cancellationToken
                );

                //
                return Ok(result);
            }
            catch (Exception ex)
            {
                //
                var result = GetExceptionActionResult(ex);
                return result;
            }
        }

        /// <summary>
        /// Query Messages ...
        /// </summary>
        /// <param name="conversationId"></param>
        /// <param name="query"></param>
        /// <param name="cancellationToken"></param>
        /// <returns></returns>
        [Authorize(Policy = XPolicies.EnabledUser)]
        [HttpGet("Conversations/{conversationId}/Messages/Query")]
        public async Task<ActionResult<XQueryResult<XAiMessageDto>>> QueryMessages(
            [FromRoute] Guid conversationId,
            [FromQuery] XQuery query,
            CancellationToken cancellationToken = default
        )
        {
            //
            try
            {
                //
                var userInfo = await GetUserInfo();
                var connectionId = GetConnectionId();

                //
                var result = await aiService.QueryMessages(
                    query: query,
                    ownerId: userInfo.UserId,
                    conversationId: conversationId,
                    cancellationToken: cancellationToken
                );

                //
                return Ok(result);
            }
            catch (Exception ex)
            {
                //
                var result = GetExceptionActionResult(ex);
                return result;
            }
        }
        #endregion

        //
        #region Creators ...
        /// <summary>
        /// Create an AI Project ...
        /// </summary>
        /// <param name="item"></param>
        /// <param name="cancellationToken"></param>
        /// <returns></returns>
        [HttpPost("Projects")]
        [Authorize(Policy = XPolicies.EnabledUser)]
        public async Task<ActionResult<XAiProjectDto>> CreateProject(
            [FromBody] XAiProjectDto item,
            CancellationToken cancellationToken = default
        )
        {
            //
            try
            {
                //
                // Validate ...
                if (item.IsNullOrDefault())
                {
                    XException.InvalidArgs.Throw();
                }

                //
                var userInfo = await GetUserInfo();
                var connectionId = GetConnectionId();

                //
                // Update Required Params ...
                item.OwnerId = userInfo.UserId;
                if (!item.IsValidForAddOrUpdate())
                {
                    XException.InvalidData.Throw();
                }

                //
                var result = await aiService.CreateProject(
                    item: item,
                    ownerId: userInfo.UserId,
                    connectionId: connectionId,
                    cancellationToken: cancellationToken
                );

                //
                return Ok(result);
            }
            catch (Exception ex)
            {
                //
                var result = GetExceptionActionResult(ex);
                return result;
            }
        }

        /// <summary>
        /// Create an AI Conversation ...
        /// </summary>
        /// <param name="projectId"></param>
        /// <param name="item"></param>
        /// <param name="cancellationToken"></param>
        /// <returns></returns>
        [Authorize(Policy = XPolicies.EnabledUser)]
        [HttpPost("Projects/{projectId}/Conversations")]
        public async Task<ActionResult<XAiConversationDto>> CreateConversation(
            [FromRoute] Guid projectId,
            [FromBody] XAiConversationDto item,
            CancellationToken cancellationToken = default
        )
        {
            //
            try
            {
                //
                // Validate ...
                if (projectId.IsDefaultGuid() ||
                    item.IsNullOrDefault())
                {
                    XException.InvalidArgs.Throw();
                }

                //
                var userInfo = await GetUserInfo();
                var connectionId = GetConnectionId();

                //
                // Update Required Params ...
                item.OwnerId = userInfo.UserId;
                if (!item.IsValidForAddOrUpdate())
                {
                    XException.InvalidData.Throw();
                }

                //
                var result = await aiService.CreateConversation(
                    item: item,
                    projectId: projectId,
                    ownerId: userInfo.UserId,
                    connectionId: connectionId,
                    cancellationToken: cancellationToken
                );

                //
                return Ok(result);
            }
            catch (Exception ex)
            {
                //
                var result = GetExceptionActionResult(ex);
                return result;
            }
        }

        /// <summary>
        /// Create an AI Conversation ...
        /// </summary>
        /// <param name="projectId"></param>
        /// <param name="item"></param>
        /// <param name="cancellationToken"></param>
        /// <returns></returns>
        [Authorize(Policy = XPolicies.EnabledUser)]
        [HttpPost("Projects/Conversations")]
        public async Task<ActionResult<XAiConversationDto>> CreateProjectConversation(
            [FromQuery] Guid? projectId,
            [FromBody] XAiConversationDto item,
            CancellationToken cancellationToken = default
        )
        {
            //
            try
            {
                //
                // Validate ...
                if (item.IsNullOrDefault())
                {
                    XException.InvalidArgs.Throw();
                }

                //
                var userInfo = await GetUserInfo();
                var connectionId = GetConnectionId();

                //
                // Update Required Params ...
                item.OwnerId = userInfo.UserId;
                if (!item.IsValidForAddOrUpdate())
                {
                    XException.InvalidData.Throw();
                }

                //
                var result = await aiService.CreateConversation(
                    item: item,
                    projectId: projectId,
                    ownerId: userInfo.UserId,
                    connectionId: connectionId,
                    cancellationToken: cancellationToken
                );

                //
                return Ok(result);
            }
            catch (Exception ex)
            {
                //
                var result = GetExceptionActionResult(ex);
                return result;
            }
        }
        #endregion

        //
        #region Content Extraction ...
        /// <summary>
        /// Extract Files Content ...
        /// </summary>
        /// <param name="files"></param>
        /// <param name="extractors"></param>
        /// <param name="cancellationToken"></param>
        /// <returns></returns>
        [HttpPost("ExtractContent")]
        [Consumes("multipart/form-data")]
        [Authorize(Policy = XPolicies.EnabledUser)]
        public async Task<ActionResult<string>> ExtractContent(
            [FromForm] IFormFileCollection files,
            [FromForm] string extractors = null,
            CancellationToken cancellationToken = default
        )
        {
            //
            try
            {
                //
                // Validate ...
                if (!files.HasChild())
                {
                    XException.InvalidArgs.Throw();
                }

                //
                var userInfo = await GetUserInfo();
                var connectionId = GetConnectionId();

                //
                string[] extractorArr = null;
                if (!extractors.IsNullOrEmpty())
                {
                    extractorArr = [.. extractors.ParseListString<string>()];
                }

                //
                var result = await aiService.ExtractContent(
                    files: files,
                    extractors: extractorArr,
                    cancellationToken: cancellationToken
                );

                //
                return Ok(result);
            }
            catch (Exception ex)
            {
                var result = GetExceptionActionResult(ex);
                return result;
            }
        }
        #endregion

        //
        #region Non Actions ...
        /// <summary>
        /// Write Validation Error for Streaming Endpoints (before Stream Starts) ...
        /// </summary>
        /// <returns></returns>
        [NonAction]
        protected async Task WriteStreamValidationError()
        {
            //
            Response.StatusCode = StatusCodes.Status400BadRequest;
            Response.ContentType = "application/json; charset=utf-8";
            await Response.WriteAsync(XException.InvalidArgs.ToXError().ToJSON());
        }
        #endregion
    }
}

### FILE: C:\Users\saherelm\Documents\Projects\xSaherelmWorkspace\xAiApi\Database\XAiApiDatabaseDescriptor.cs

using xAiApi.Constants;
using xDataService.Interfaces;
using xDataService.Models;

namespace xAiApi.Database
{
    /// <summary>
    /// Ai Api Database Descriptor ... 
    /// </summary>
    public class XAiApiDatabaseDescriptor : XDatabaseDescriptor<XAiApiDbContext>, IXDatabaseDescriptor<XAiApiDbContext>
    {
        public XAiApiDatabaseDescriptor() : base(
            name: XAiApiConstants.XAiApiDbIdentifier,
            repositories: []
        )
        {
            OptionsBuilder = b => b.MigrationsAssembly(XAiApiConstants.XAiApiMigrationsAssemblyIdentifier);
        }
    }
}

### FILE: C:\Users\saherelm\Documents\Projects\xSaherelmWorkspace\xAiApi\Database\XAiApiDbContext.cs

using xDataService.Db;
using xAiApi.Constants;
using xAiModels.Providers;
using xTagService.Providers;
using xDataService.Providers;
using xFileService.Providers;
using xStringService.Providers;
using xDataService.Configuration;
using Microsoft.EntityFrameworkCore;

namespace xAiApi.Database
{
    /// <summary>
    /// Db Context of AiApi ...
    /// </summary>
    public class XAiApiDbContext : XDbContext
    {
        //
        #region DbSets ...
        #endregion

        //
        #region Navigation Property Entities ...
        #endregion

        //
        #region Constructor ...
        public XAiApiDbContext(
            DbContextOptions options,
            XDataServiceConfiguration config,
            XEntityRegisterarHandlerService dynamicEntityHandlers
        ) : base(
            config: config,
            options: options,
            database: XAiApiConstants.XAiApiDbIdentifier,
            dynamicEntityHandlers: dynamicEntityHandlers,
            dynamicEntityRegisterarsNames: [
                nameof(XTagEntityRegisterar),
                nameof(XFileEntityRegisterar),
                nameof(XStringEntityRegisterar),
                nameof(XAiVectorEntityRegisterar),
                nameof(XAiMessageEntityRegisterar),
                nameof(XAiProjectEntityRegisterar),
                nameof(XAiMcpServerEntityRegisterar),
                nameof(XAiConversationEntityRegisterar),
            ]
        )
        { }
        #endregion

        //
        #region Overrides ...
        //
        public override void OnXModelCreating(ModelBuilder modelBuilder)
        { }

        //
        public override void OnXConfiguring(DbContextOptionsBuilder optionsBuilder)
        { }
        #endregion
    }
}

### FILE: C:\Users\saherelm\Documents\Projects\xSaherelmWorkspace\xAiApi\DI\XDIHelperExtension.cs

using System;
using xAiApi.Constants;
using xAiApi.Providers;
using xAiApi.Extensions;
using xAiApi.Interfaces;
using xAiApi.Middlewares;
using xCommons.Extensions;
using xAiApi.Configurations;
using xExceptions.Constants;
using xAiApi.Providers.Extractors;
using xAiApi.Interfaces.Extractors;
using Microsoft.AspNetCore.Builder;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;

namespace xAiApi.DI
{
    public static partial class XDIHelperExtension
    {
        /// <summary>
        /// Extract AI Configuration ...
        /// </summary>
        /// <param name="source"></param>
        /// <returns></returns>
        public static XAiApiConfiguration GetXAiApiConfiguration(this IConfiguration source)
        {
            //
            XAiApiConfiguration result = null;

            //
            var section = source.GetSection(ConfigurationNodeNames.AI_API_NODE);
            if (!section.IsNull())
            {
                result = section.Get<XAiApiConfiguration>();
            }

            //
            return result;
        }

        /// <summary>
        /// Register AiApi Configuration ...
        /// </summary>
        /// <param name="source"></param>
        /// <param name="configuration"></param>
        public static void AddXAiApiConfiguration(
            this IServiceCollection source,
            IConfiguration configuration
        )
        {
            //
            var apiConfig = configuration.GetXAiApiConfiguration();
            source.AddXAiApiConfiguration(apiConfig);
        }

        /// <summary>
        /// Register AiApi Configuration ...
        /// </summary>
        /// <param name="source"></param>
        /// <param name="configuration"></param>
        public static void AddXAiApiConfiguration(
            this IServiceCollection source,
            XAiApiConfiguration configuration
        )
        {
            //
            if (!configuration.IsValid())
            {
                XException.InvalidConfiguration.Throw();
            }

            //
            source.AddSingleton(configuration);
        }

        /// <summary>
        /// Register Rag Service ...
        /// </summary>
        /// <param name="source"></param>
        public static void AddXRagService(
            this IServiceCollection source
        )
        {
            //
            // Persistent RAG (Knowledge over XAiVector Table) ...
            source.AddScoped<IXAiEmbeddingService, XAiEmbeddingService>();         
            source.AddScoped<IXAiRAGService, XAiRAGService>();   
        }

        /// <summary>
        /// Register Ai Services ...
        /// </summary>
        /// <param name="source"></param>
        public static void AddXAiServices(
            this IServiceCollection source
        )
        {
            //
            source.AddScoped<IXAiService, XAiService>();
            source.AddScoped<IXDefaultThinkingAiService, XDefaultThinkingAiService>();
        }

        /// <summary>
        /// Register AiApi File Content Extractor Services ...
        /// </summary>
        /// <param name="source"></param>
        public static void AddXAiFileContentExtractors(
            this IServiceCollection source
        )
        {
            //
            // Register File Content Extractors ...
            source.AddSingleton<IXFileContentExtractorBase, XPdfFileContentExtractor>();
            source.AddSingleton<IXFileContentExtractorBase, XRtfFileContentExtractor>();
            source.AddSingleton<IXFileContentExtractorBase, XEpubFileContentExtractor>();
            source.AddSingleton<IXFileContentExtractorBase, XDocxFileContentExtractor>();
            source.AddSingleton<IXFileContentExtractorBase, XHtmlFileContentExtractor>();
            source.AddSingleton<IXFileContentExtractorBase, XCodeFileContentExtractor>();
            source.AddSingleton<IXFileContentExtractorBase, XImageFileContentExtractor>();
            source.AddSingleton<IXFileContentExtractorBase, XAudioFileContentExtractor>();
            source.AddSingleton<IXFileContentExtractorBase, XExcelFileContentExtractor>();
            source.AddSingleton<IXFileContentExtractorBase, XVisionFileContentExtractor>();
            source.AddSingleton<IXFileContentExtractorBase, XPlainTextFileContentExtractor>();
            source.AddSingleton<IXFileContentExtractorBase, XPowerPointFileContentExtractor>();
            source.AddSingleton<IXFileContentExtractorBase, XOpenDocumentFileContentExtractor>();

            //
            source.AddSingleton<IXFileContentExtractor, XFileContentExtractor>();
        }

        /// <summary>
        /// Register AiApi Text Chunker Service ...
        /// </summary>
        /// <param name="source"></param>
        public static void AddXAiTextChunker(
            this IServiceCollection source
        )
        {
            //
            // Stateless -> Singleton ...
            source.AddSingleton<IXTextChunker, XTextChunker>();
        }

        /// <summary>
        /// Register In-Memory Vector Store Service ...
        /// </summary>
        public static void AddXAiInMemoryVectorStore(this IServiceCollection source)
        {
            source.AddSingleton<IXInMemoryVectorStore, XInMemoryVectorStore>();
            source.AddHostedService<XInMemoryVectorStoreCleanupService>();
        }

        /// <summary>
        /// Register all Services Required for Chat With Documents (In-Memory RAG):
        /// Text Chunker + In-Memory Vector Store (+ Cleanup) ...
        /// </summary>
        /// <param name="source"></param>
        public static void AddXAiChatWithDocuments(this IServiceCollection source)
        {
            source.AddXAiInMemoryVectorStore();
        }

        /// <summary>
        /// Use Model Proxy Provider ...
        /// </summary>
        /// <param name="source"></param>
        /// <returns></returns>
        public static IApplicationBuilder UseXAiModelProxy(
            this IApplicationBuilder source
        )
        {
            return source.UseMiddleware<XAiModelProxyMiddleware>();
        }

        //
        #region Private ...
        /// <summary>
        /// a LogTag for Service ...
        /// </summary>
        private static string XLogTag = XAiApiConstants.XDILogTag;

        /// <summary>
        /// print a log in Console ...
        /// </summary>
        /// <param name="message"></param>
        private static void Log(string message)
        {
            Console.WriteLine($"{XLogTag} => {message}");
        }
        #endregion
    }
}

### FILE: C:\Users\saherelm\Documents\Projects\xSaherelmWorkspace\xAiApi\Extensions\XModelsExtensions.cs

using System;
using OpenAI;
using System.Linq;
using OllamaSharp;
using xAiApi.Models;
using System.Net.Http;
using xAiApi.Constants;
using xAiModels.Models;
using System.Threading;
using System.ClientModel;
using xCommons.Extensions;
using xAiModels.Constants;
using xAiModels.Extensions;
using xAiApi.Configurations;
using xExceptions.Constants;
using Microsoft.Extensions.AI;
using System.Collections.Generic;
using System.ClientModel.Primitives;

namespace xAiApi.Extensions
{
    public static class XModelsExtensions
    {
        /// <summary>
        /// Validate Configurations ...
        /// </summary>
        /// <param name="source"></param>
        /// <returns></returns>
        public static bool IsValid(this XAiApiConfiguration source)
        {
            //
            var result =
                !source.IsNullOrDefault() &&
                source.Models.HasChild() &&
                source.Models.All(m => m.IsValid()) &&
                source.Prompts.All(m => m.IsValid()) &&
                source.Prompts.Any(p => p.Name
                    .Equals(
                        XAiApiConstants.XAiApiIntroductionPromptName,
                        StringComparison.InvariantCultureIgnoreCase));

            //
            return result;
        }

        /// <summary>
        /// Check TextChunker Descriptor is Valid or not ...
        /// </summary>
        /// <param name="source"></param>
        /// <returns></returns>
        public static bool IsValid(this XTextChunkerDescriptor source)
        {
            //
            var result =
                source.ChunkSize > 0 &&
                source.ChunkOverlap >= 0 &&
                source.ChunkOverlap < source.ChunkSize &&
                source.MinChunkSize >= 0 &&
                source.MinChunkSize <= source.ChunkSize;

            //
            return result;
        }

        /// <summary>
        /// Check Document Ask Request is Valid or not ...
        /// </summary>
        /// <param name="source"></param>
        /// <returns></returns>
        public static bool IsValid(this XAiDocumentAskRequest source)
        {
            //
            var result =
                !source.IsNullOrDefault() &&
                !source.Prompt.IsNullOrEmpty() &&
                !source.SessionId.IsDefaultGuid();

            //
            return result;
        }

        /// <summary>
        /// Extract Default Model Descriptor ...
        /// </summary>
        /// <param name="source"></param>
        /// <returns></returns>
        public static XAiModelDescriptor GetDefaultModel(this XAiApiConfiguration source)
        {
            //
            XAiModelDescriptor result = null;

            //
            if (source.IsValid())
            {
                result = source.Models[0];
            }

            //
            return result;
        }

        /// <summary>
        /// Retrieve Specified Model from Config ...
        /// </summary>
        /// <param name="source"></param>
        /// <param name="name"></param>
        /// <returns></returns>
        public static XAiModelDescriptor GetModel(
            this XAiApiConfiguration source,
            string name
        )
        {
            //
            XAiModelDescriptor result = null;

            //
            if (source.IsValid())
            {
                //
                if (name.IsNullOrEmpty())
                {
                    result = source.GetDefaultModel();
                }
                else
                {
                    result = source.Models
                        .FirstOrDefault(m => m.Name
                            .Equals(name, System.StringComparison.InvariantCultureIgnoreCase));
                }
            }

            //
            return result;
        }

        /// <summary>
        /// Retrieve Introduction Prompt ...
        /// </summary>
        /// <param name="source"></param>
        /// <returns></returns>
        public static XAiPromptDescriptor GetIntroductionPrompt(this XAiApiConfiguration source)
        {
            //
            XAiPromptDescriptor result = null;

            //
            if (source.IsValid())
            {
                //
                result = source.Prompts
                    .FirstOrDefault(p => p.Name
                        .Equals(
                            XAiApiConstants.XAiApiIntroductionPromptName,
                            System.StringComparison.InvariantCultureIgnoreCase));
            }

            //
            return result;
        }

        /// <summary>
        /// Select Specified Prompts and Parse it's Template
        /// and Generate Message ...
        /// </summary>
        /// <param name="source"></param>
        /// <param name="name"></param>
        /// <param name="params"></param>
        /// <returns></returns>
        public static string GetPrompt(
            this XAiApiConfiguration source,
            string name = null,
            IDictionary<string, string> @params = null
        )
        {
            //
            var result = string.Empty;

            //
            // Normalize ...
            if (name.IsNullOrEmpty())
            {
                name = XAiApiConstants.XAiApiIntroductionPromptName;
            }

            //
            if (source.IsValid())
            {
                //
                var prompt = source.Prompts
                    .FirstOrDefault(p => p.Name
                        .Equals(
                            name,
                            System.StringComparison.InvariantCultureIgnoreCase
                        )
                    );
                if (!prompt.IsNullOrDefault())
                {
                    //
                    result = prompt.Template;

                    //
                    // Handle Params ...
                    if (!@params.IsNullOrDefault() && @params.HasChild())
                    {
                        //
                        // Select Params ...
                        var existsParams = prompt.Params
                            .Where(p => @params.Any(pr => pr.Key == p.Name))
                            .Distinct()
                            .ToList();

                        //
                        // Replace Selected Params ...
                        existsParams
                            .ForEach(pk =>
                            {
                                result = result.Replace(pk.Param, @params[pk.Name]);
                            });
                    }
                }
            }

            //
            return result;
        }

        /// <summary>
        /// Provide HttpClient for Common Usages ...
        /// </summary>
        /// <param name="source"></param>
        /// <returns></returns>
        public static HttpClient GetHttpClient(this string source)
        {
            //
            var result = new HttpClient
            {
                //
                // Disable timeout completely (not recommended for production)
                Timeout = Timeout.InfiniteTimeSpan,

                //
                BaseAddress = source.IsNullOrEmpty()
                    ? null
                    : new Uri(source),

                //
                // OR set a very long timeout (e.g., 30 minutes for large file uploads)
                // Timeout = TimeSpan.FromMinutes(30)
            };

            //
            return result;
        }

        /// <summary>
        /// Instance and Retrieve Chat Client ...
        /// </summary>
        /// <param name="source"></param>
        /// <returns></returns>
        public static IChatClient GetClient(this XAiModelDescriptor source)
        {
            //
            // Try to Initialize LLm ...
            var model = source.LLM;
            var apiKey = source.ApiKey;
            var url = new Uri(source.Url);
            var httpClient = source.Url.GetHttpClient();

            //
            IChatClient result = null;
            switch (source.Provider)
            {
                //
                case XAiModelProviderType.Ollama:
                    //
                    // Instance Ollama Client using Custom HttpCLient ...
                    var ollamaClient = new OllamaApiClient(httpClient, model);
                    result =
                        new ChatClientBuilder(ollamaClient)
                        .UseFunctionInvocation()
                        .Build();
                    break;

                //
                case XAiModelProviderType.OpenAI:
                    //
                    // Instance Ollama Client using Custom HttpCLient ...
                    var openAiClient = new OpenAIClient(
                        new ApiKeyCredential(apiKey.IsNullOrEmpty() ? XAiModelsConstants.XOpenAINoKey : apiKey),
                        new OpenAIClientOptions
                        {
                            Endpoint = url,
                            Transport = new HttpClientPipelineTransport(httpClient)
                        }
                    );
                    result =
                        new ChatClientBuilder(
                            openAiClient
                            .GetChatClient(model)
                        .AsIChatClient())
                        .UseFunctionInvocation()
                        .Build();
                    break;

                //
                case XAiModelProviderType.DeepSeek:
                    break;

                //
                case XAiModelProviderType.HuggingFace:
                    break;

                //
                default:
                    break;
            }

            //
            if (result.IsNullOrDefault())
            {
                XException.InvalidData.Throw();
            }

            //
            return result;
        }

        // public static IList<AITool> ToAITools(this IList<XAiMcpToolDefinition> source)
        // {
        //     //
        //     var result = new List<AITool>();

        //     //
        //     foreach (var tool in source)
        //     {
        //         //
        //         var declaration = AIFunctionFactory.CreateDeclaration(
        //             name: tool.Name,
        //             jsonSchema: tool.InputSchema,
        //             description: tool.Description
        //         );

        //         //
        //         result.Add(declaration);
        //     }

        //     //
        //     return result;            
        // }
    }
}

### FILE: C:\Users\saherelm\Documents\Projects\xSaherelmWorkspace\xAiApi\Extensions\XProgramExtensions.cs

using System.Linq;
using xIdentityHelper;
using xAiApi.Providers;
using xAiApi.Interfaces;
using xCommons.Extensions;
using xCommons.Authorization;
using System.Collections.Generic;
using xIdentityService.Interfaces;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.HttpOverrides;
using Microsoft.Extensions.DependencyInjection;

namespace xAiApi.Extensions
{
    public static class XProgramExtensions
    {
        /// <summary>
        /// Register MCP Server Provider ...
        /// </summary>
        /// <param name="source"></param>
        public static void AddXAiMcpServerProvider(
            this IServiceCollection source
        )
        {
            source.AddScoped<IXAiMcpServerProvider, XAiMcpServerProvider>();
        }

        /// <summary>
        /// Register Authorization Policies
        /// </summary>
        /// <param name="services"></param>
        /// <param name="policies"></param>
        public static void AddXAuthorization(
            this IServiceCollection services,
            IDictionary<string, AuthorizationPolicy> policies = null
        )
        {
            //
            var policyHandler = services.GetRegisteredService<IXPolicyHandler>();
            services.AddAuthorization(options =>
            {
                //
                if (!policies.IsNull())
                {
                    //
                    // Fill Policies ...
                    using (var policiesEnumerator = policies.GetEnumerator())
                    {
                        while (policiesEnumerator.MoveNext())
                        {
                            var policyDescriptor = policiesEnumerator.Current;
                            options.AddPolicy(policyDescriptor.Key, policyDescriptor.Value);

                            //
                            // Add Policy to Policy Handler ...
                            if (!policyHandler.IsNull())
                            {
                                //
                                // Check Policy is RequiredRole Policy ...
                                var roleRequirements = policyDescriptor.Value.Requirements
                                    .OfType<RequiredRolesRequirement>()
                                    .FirstOrDefault();
                                if (!roleRequirements.IsNull() && 
                                    roleRequirements.Roles.HasChild())
                                {
                                    //
                                    policyHandler.AddPolicy(
                                        policy: policyDescriptor.Key.ToNormalString(),
                                        requiredRoles: roleRequirements.Roles.Select(r => r.ToNormalString())
                                    );
                                }
                            }
                        }
                    }
                }

                //
                var xPolicies = XAuthorizationHelper.GetXAuthorizationPolicies();
                if (!xPolicies.IsNull())
                {
                    //
                    // Fill Policies ...
                    using (var policiesEnumerator = xPolicies.GetEnumerator())
                    {
                        while (policiesEnumerator.MoveNext())
                        {
                            //
                            var policyDescriptor = policiesEnumerator.Current;

                            //
                            // Add Policy to Authorization ...
                            options.AddPolicy(policyDescriptor.Key, policyDescriptor.Value);

                            //
                            // Add Policy to Policy Handler ...
                            if (!policyHandler.IsNull())
                            {
                                //
                                // Check Policy is RequiredRole Policy ...
                                var roleRequirements = policyDescriptor.Value.Requirements
                                    .OfType<RequiredRolesRequirement>()
                                    .FirstOrDefault();
                                if (!roleRequirements.IsNull() && 
                                    roleRequirements.Roles.HasChild())
                                {
                                    //
                                    policyHandler.AddPolicy(
                                        policy: policyDescriptor.Key.ToNormalString(),
                                        requiredRoles: roleRequirements.Roles.Select(r => r.ToNormalString())
                                    );
                                }
                            }
                        }
                    }
                }
            });

            //
            services.AddSingleton<IAuthorizationHandler, RequiredRolesHandler>();
        }

        /// <summary>
        /// Use Forward Headers Options for resolving behind a proxy issues ...
        /// </summary>
        /// <param name="source"></param>
        /// <returns></returns>
        public static void UseXForwardOptions(this IApplicationBuilder source)
        {
            //
            var forwardOptions = new ForwardedHeadersOptions
            {
                ForwardedHeaders = ForwardedHeaders.XForwardedFor | ForwardedHeaders.XForwardedProto,
                RequireHeaderSymmetry = false
            };

            //
            forwardOptions.KnownNetworks.Clear();
            forwardOptions.KnownProxies.Clear();

            //
            // ref: https://github.com/aspnet/Docs/issues/2384
            source.UseForwardedHeaders(forwardOptions);
        }
    }
}

### 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.Threading;
using System.Threading.Tasks;
using Microsoft.Extensions.AI;
using System.Collections.Generic;

namespace xAiApi.Interfaces
{
    /// <summary>
    /// Base Embedding Provider Service ...
    /// </summary>
    public interface IXAiEmbeddingServiceBase // : IXAiServiceBase
    {
        /// <summary>
        /// Embedding Specified String ...
        /// </summary>
        /// <param name="content"></param>
        /// <param name="cancellationToken"></param>
        /// <returns></returns>
        Task<float[]> Embedding(
            string content,
            CancellationToken cancellationToken = default
        );

        /// <summary>
        /// Embedding Specified Batch ...
        /// </summary>
        /// <param name="batch"></param>
        /// <param name="cancellationToken"></param>
        /// <returns></returns>
        Task<IReadOnlyList<float[]>> Embeddings(
            string[] batch,
            CancellationToken cancellationToken = default
        );

        /// <summary>
        /// Embedding Generator ...
        /// </summary>
        /// <returns></returns>
        IEmbeddingGenerator<string, Embedding<float>> GetEmbeddingGenerator();
    }
}

### FILE: C:\Users\saherelm\Documents\Projects\xSaherelmWorkspace\xAiApi\Interfaces\IXAiMcpServerProvider.cs

using System;
using xModels.Dtos;
using System.Threading;
using xAiModels.Models.Dtos;
using xIdentityModels.Models;
using System.Threading.Tasks;
using System.Linq.Expressions;
using xAiModels.Models.Entities;
using System.Collections.Generic;
using ModelContextProtocol.Client;
using Microsoft.Extensions.AI;

namespace xAiApi.Interfaces
{
    /// <summary>
    /// MCP Manager / Provider ...
    /// </summary>
    public interface IXAiMcpServerProvider
    {
        //
        #region Manager ...
        /// <summary>
        /// Get a List Of Available Tools which Provided using registered Mcp Servers ...
        /// </summary>
        /// <param name="forceOwner"></param>
        /// <param name="userInfo"></param>
        /// <param name="cancellationToken"></param>
        /// <returns></returns>
        Task<IList<AITool>> GetAvailableToolsAsync(
            bool forceOwner = false,
            XUserClaimsInfoDto userInfo = null,
            CancellationToken cancellationToken = default
        );

        /// <summary>
        /// Test Specified Mcp Server ...
        /// </summary>
        /// <param name="server"></param>
        /// <param name="connectionId"></param>
        /// <param name="userInfo"></param>
        /// <param name="cancellationToken"></param>
        /// <returns></returns>
        Task<string> TestServerAsync(
            XAiMcpServerDto server,
            string connectionId = null,
            XUserClaimsInfoDto userInfo = null,
            CancellationToken cancellationToken = default
        );

        /// <summary>
        /// Force Refresh Mcp Servers ...
        /// </summary>
        /// <param name="userInfo"></param>
        /// <param name="cancellationToken"></param>
        /// <returns></returns>
        Task RefreshAsync(
            XUserClaimsInfoDto userInfo = null,
            CancellationToken cancellationToken = default
        );        
        #endregion

        //
        #region Actions ...
        /// <summary>
        /// Add an Mcp Server ...
        /// </summary>
        /// <param name="item"></param>
        /// <param name="connectionId"></param>
        /// <param name="userInfo"></param>
        /// <param name="cancellationToken"></param>
        /// <returns></returns>
        Task<XAiMcpServerDto> AddMcpServer(
            XAiMcpServerDto item,
            string connectionId = null,
            XUserClaimsInfoDto userInfo = null,
            CancellationToken cancellationToken = default
        );

        /// <summary>
        /// Get an Mcp Server ...
        /// </summary>
        /// <param name="id"></param>
        /// <param name="userInfo"></param>
        /// <param name="cancellationToken"></param>
        /// <returns></returns>
        Task<XAiMcpServerDto> GetMcpServer(
            Guid id,
            XUserClaimsInfoDto userInfo = null,
            CancellationToken cancellationToken = default
        );

        /// <summary>
        /// Update Specified Mcp Server ...
        /// </summary>
        /// <param name="id"></param>
        /// <param name="item"></param>
        /// <param name="connectionId"></param>
        /// <param name="userInfo"></param>
        /// <param name="cancellationToken"></param>
        /// <returns></returns>
        Task<XAiMcpServerDto> UpdateMcpServer(
            Guid id,
            XAiMcpServerDto item,
            string connectionId = null,
            XUserClaimsInfoDto userInfo = null,
            CancellationToken cancellationToken = default
        );

        /// <summary>
        /// Remove Specified Mcp Server ...
        /// </summary>
        /// <param name="id"></param>
        /// <param name="connectionId"></param>
        /// <param name="userInfo"></param>
        /// <param name="cancellationToken"></param>
        /// <returns></returns>
        Task<XAiMcpServerDto> RemoveMcpServer(
            Guid id,
            string connectionId = null,
            XUserClaimsInfoDto userInfo = null,
            CancellationToken cancellationToken = default
        );

        /// <summary>
        /// Disable Specified Mcp Server ...
        /// </summary>
        /// <param name="id"></param>
        /// <param name="connectionId"></param>
        /// <param name="userInfo"></param>
        /// <param name="cancellationToken"></param>
        /// <returns></returns>
        Task<bool> DisableMcpServer(
            Guid id,
            string connectionId = null,
            XUserClaimsInfoDto userInfo = null,
            CancellationToken cancellationToken = default
        );

        /// <summary>
        /// Enable Specified Mcp Server ...
        /// </summary>
        /// <param name="id"></param>
        /// <param name="connectionId"></param>
        /// <param name="userInfo"></param>
        /// <param name="cancellationToken"></param>
        /// <returns></returns>
        Task<bool> EnableMcpServer(
            Guid id,
            string connectionId = null,
            XUserClaimsInfoDto userInfo = null,
            CancellationToken cancellationToken = default
        );

        /// <summary>
        /// Toggle Specified Mcp Server ...
        /// </summary>
        /// <param name="id"></param>
        /// <param name="connectionId"></param>
        /// <param name="userInfo"></param>
        /// <param name="cancellationToken"></param>
        /// <returns></returns>
        Task<bool> ToggleMcpServer(
            Guid id,
            string connectionId = null,
            XUserClaimsInfoDto userInfo = null,
            CancellationToken cancellationToken = default
        );

        /// <summary>
        /// Retrieve all Mcp Server ...
        /// </summary>
        /// <param name="forceOwner"></param>
        /// <param name="userInfo"></param>
        /// <param name="cancellationToken"></param>
        /// <returns></returns>
        Task<IEnumerable<XAiMcpServerDto>> GetAll(
            bool forceOwner = false,
            XUserClaimsInfoDto userInfo = null,
            CancellationToken cancellationToken = default
        );

        /// <summary>
        /// Find Specified Mcp Server ...
        /// </summary>
        /// <param name="predicate"></param>
        /// <param name="forceOwner"></param>
        /// <param name="userInfo"></param>
        /// <param name="cancellationToken"></param>
        /// <returns></returns>
        Task<XAiMcpServerDto> FindOne(
            Expression<Func<XAiMcpServer, bool>> predicate,
            bool forceOwner = false,
            XUserClaimsInfoDto userInfo = null,
            CancellationToken cancellationToken = default
        );

        /// <summary>
        /// Find a Collection of Specified Mcp Servers ...
        /// </summary>
        /// <param name="predicate"></param>
        /// <param name="forceOwner"></param>
        /// <param name="userInfo"></param>
        /// <param name="cancellationToken"></param>
        /// <returns></returns>
        Task<IEnumerable<XAiMcpServerDto>> FindMany(
            Expression<Func<XAiMcpServer, bool>> predicate,
            bool forceOwner = false,
            XUserClaimsInfoDto userInfo = null,
            CancellationToken cancellationToken = default
        );

        /// <summary>
        /// Query Registered Mcp Servers ...
        /// </summary>
        /// <param name="query"></param>
        /// <param name="forceOwner"></param>
        /// <param name="userInfo"></param>
        /// <param name="cancellationToken"></param>
        /// <returns></returns>
        Task<XQueryResult<XAiMcpServerDto>> Query(
            XQuery query,
            bool forceOwner = false,
            XUserClaimsInfoDto userInfo = null,
            CancellationToken cancellationToken = default
        );
        #endregion
    }
}

### FILE: C:\Users\saherelm\Documents\Projects\xSaherelmWorkspace\xAiApi\Interfaces\IXAiRAGService.cs

using xAiApi.Models;
using System.Threading;
using xAiModels.Models.Dtos;
using System.Threading.Tasks;
using xIdentityModels.Models;
using Microsoft.AspNetCore.Http;
using System.Collections.Generic;

namespace xAiApi.Interfaces
{
    /// <summary>
    /// Persistent RAG Service over XAiVector Table:
    /// Ingest (Extract -> Chunk -> Embed -> Store) and Ask (Embed -> Search -> Generate) ...
    /// Isolation is Scope Based (Conversation / Project / User / Global) ...
    /// </summary>
    public interface IXAiRAGService
    {
        /// <summary>
        /// Ingest Files into Specified Knowledge Scope:
        /// Extract -> Chunk -> Embed -> Store (XAiVector) ...
        /// </summary>
        /// <param name="files"></param>
        /// <param name="scope">Target Scope (Null = User Scope)</param>
        /// <param name="userInfo"></param>
        /// <param name="connectionId"></param>
        /// <param name="replaceExisting"></param>
        /// <param name="cancellationToken"></param>
        /// <returns></returns>
        Task<XAiKnowledgeIngestResult> IngestAsync(
            IFormFileCollection files,
            XAiKnowledgeScopeDescriptor scope = null,
            XUserClaimsInfoDto userInfo = null,
            string connectionId = null,
            bool replaceExisting = true,
            CancellationToken cancellationToken = default
        );

        /// <summary>
        /// Embed Prompt and Retrieve Relevant Chunks (Tiered: Conversation -> Project -> User -> Global) ...
        /// </summary>
        /// <param name="request"></param>
        /// <param name="userInfo"></param>
        /// <param name="cancellationToken"></param>
        /// <returns></returns>
        Task<IList<XAiVectorSearchResult>> RetrieveAsync(
            XAiKnowledgeAskRequest request,
            XUserClaimsInfoDto userInfo = null,
            CancellationToken cancellationToken = default
        );

        /// <summary>
        /// List Ingested Documents of Specified Scope ...
        /// </summary>
        /// <param name="scope">Target Scope (Null = User Scope)</param>
        /// <param name="userInfo"></param>
        /// <param name="cancellationToken"></param>
        /// <returns></returns>
        Task<IList<XAiKnowledgeDocumentInfo>> LoadDocumentsAsync(
            XAiKnowledgeScopeDescriptor scope = null,
            XUserClaimsInfoDto userInfo = null,
            CancellationToken cancellationToken = default
        );

        /// <summary>
        /// Remove All Vectors of a Document in Specified Scope ...
        /// </summary>
        /// <param name="fileName"></param>
        /// <param name="scope">Target Scope (Null = User Scope)</param>
        /// <param name="userInfo"></param>
        /// <param name="connectionId"></param>
        /// <param name="cancellationToken"></param>
        /// <returns>Count of Removed Vectors</returns>
        Task<int> RemoveDocumentAsync(
            string fileName,
            XAiKnowledgeScopeDescriptor scope = null,
            XUserClaimsInfoDto userInfo = null,
            string connectionId = null,
            CancellationToken cancellationToken = default
        );

        /// <summary>
        /// Migrate Legacy Vectors of Owner ("{ownerId}/{fileName}#i") into User Scope ("user/{ownerId}/{fileName}#i") ...
        /// Idempotent: Returns 0 when Nothing Left to Migrate ...
        /// </summary>
        /// <param name="userInfo"></param>
        /// <param name="cancellationToken"></param>
        /// <returns>Count of Migrated Vectors</returns>
        Task<int> MigrateLegacyVectorsAsync(
            XUserClaimsInfoDto userInfo = null,
            CancellationToken cancellationToken = default
        );

        /// <summary>
        /// Map Search Results to Public Sources ...
        /// </summary>
        /// <param name="context"></param>
        /// <returns></returns>
        IList<XAiDocumentSource> ToSources(
            IEnumerable<XAiVectorSearchResult> context
        );
    }
}

### FILE: C:\Users\saherelm\Documents\Projects\xSaherelmWorkspace\xAiApi\Interfaces\IXAiService.cs

namespace xAiApi.Interfaces
{
    public interface IXAiService : IXAiServiceBase
    { }
}

### FILE: C:\Users\saherelm\Documents\Projects\xSaherelmWorkspace\xAiApi\Interfaces\IXAiServiceBase.cs

using System;
using xModels.Dtos;
using System.Threading;
using xAiModels.Models;
using xAiModels.Models.Dtos;
using System.Threading.Tasks;
using xIdentityModels.Models;
using Microsoft.Extensions.AI;
using Microsoft.AspNetCore.Http;
using System.Collections.Generic;

namespace xAiApi.Interfaces
{
    /// <summary>
    /// Describe a Base Service Actions of any Ai Based Services ...
    /// </summary>
    public interface IXAiServiceBase : IDisposable
    {
        /// <summary>
        /// Chat Options ...
        /// </summary>
        ChatOptions Options { get; }

        /// <summary>
        /// Descriptor of Models which used in Service ...
        /// </summary>
        XAiModelDescriptor Descriptor { get; }

        //
        #region Actions ...
        /// <summary>
        /// Base Method for Communicate with LLM ...
        /// </summary>
        /// <param name="prompt"></param>
        /// <param name="userInfo"></param>
        /// <param name="cancellationToken"></param>
        /// <returns></returns>
        Task<string> AskTextAsync(
            string prompt,
            XUserClaimsInfoDto userInfo = null,
            CancellationToken cancellationToken = default
        );

        /// <summary>
        /// Base Method for Communicate with LLM ...
        /// </summary>
        /// <param name="prompt"></param>
        /// <param name="userInfo"></param>
        /// <param name="cancellationToken"></param>
        /// <returns></returns>
        IAsyncEnumerable<string> AskTextAsEnumerable(
            string prompt,
            XUserClaimsInfoDto userInfo = null,
            CancellationToken cancellationToken = default
        );

        /// <summary>
        /// Ask a Question By Providing Vector Search Result ...
        /// </summary>
        /// <param name="prompt"></param>
        /// <param name="context"></param>
        /// <param name="userInfo"></param>
        /// <param name="cancellationToken"></param>
        /// <returns></returns>
        Task<string> AskTextByContextAsync(
            string prompt,
            IList<XAiVectorSearchResult> context = null,
            XUserClaimsInfoDto userInfo = null,
            CancellationToken cancellationToken = default
        );

        /// <summary>
        /// Ask a Question By By Providing Vector Search Result and Stream Response ...
        /// </summary>
        /// <param name="prompt"></param>
        /// <param name="context"></param>
        /// <param name="userInfo"></param>
        /// <param name="cancellationToken"></param>
        /// <returns></returns>
        IAsyncEnumerable<string> AskTextByContextAsEnumerable(
            string prompt,
            IList<XAiVectorSearchResult> context = null,
            XUserClaimsInfoDto userInfo = null,
            CancellationToken cancellationToken = default
        );

        /// <summary>
        /// Ask a Question By Rag Retrive From Knowledge ...
        /// </summary>
        /// <param name="prompt"></param>
        /// <param name="type"></param>
        /// <param name="topK"></param>
        /// <param name="minScore"></param>
        /// <param name="userInfo"></param>
        /// <param name="cancellationToken"></param>
        /// <returns></returns>
        Task<string> AskTextFromKnowledgeAsync(
            string prompt,
            string type = null,
            int? topK = null,
            float? minScore = null,
            XUserClaimsInfoDto userInfo = null,
            CancellationToken cancellationToken = default
        );

        /// <summary>
        /// Ask a Question By Rag Retrive From Knowledge and Stream Response ...
        /// </summary>
        /// <param name="prompt"></param>
        /// <param name="type"></param>
        /// <param name="topK"></param>
        /// <param name="minScore"></param>
        /// <param name="userInfo"></param>
        /// <param name="cancellationToken"></param>
        /// <returns></returns>
        IAsyncEnumerable<string> AskTextFromKnowledgeAsEnumerable(
            string prompt,
            string type = null,
            int? topK = null,
            float? minScore = null,
            XUserClaimsInfoDto userInfo = null,
            CancellationToken cancellationToken = default
        );

        /// <summary>
        /// Ask a Question as Prompt and Retrieve Response ...
        /// </summary>
        /// <param name="prompt"></param>
        /// <param name="type"></param>
        /// <param name="topK"></param>
        /// <param name="minScore"></param>
        /// <param name="projectId"></param>
        /// <param name="conversationId"></param>
        /// <param name="connectionId"></param>
        /// <param name="extractFileContents"></param>
        /// <param name="addFilesToKnowledge"></param>
        /// <param name="files"></param>
        /// <param name="userInfo"></param>
        /// <param name="cancellationToken"></param>
        /// <returns></returns>
        Task<XAiMessageDto> AskAsync(
            string prompt,
            string type = null,
            int? topK = null,
            float? minScore = null,
            Guid? projectId = null,
            Guid? conversationId = null,
            string connectionId = null,
            bool extractFileContents = false,
            bool addFilesToKnowledge = true,
            IFormFileCollection files = null,
            XUserClaimsInfoDto userInfo = null,
            CancellationToken cancellationToken = default
        );

        /// <summary>
        /// Ask a Question as Prompt and Retrieve Response as Async Enumerable ...
        /// </summary>
        /// <param name="prompt"></param>
        /// <param name="type"></param>
        /// <param name="topK"></param>
        /// <param name="minScore"></param>
        /// <param name="projectId"></param>
        /// <param name="conversationId"></param>
        /// <param name="connectionId"></param>
        /// <param name="extractFileContents"></param>
        /// <param name="addFilesToKnowledge"></param>
        /// <param name="files"></param>
        /// <param name="userInfo"></param>
        /// <param name="cancellationToken"></param>
        /// <returns></returns>
        IAsyncEnumerable<XAiResonseMessage> AskAsEnumerable(
            string prompt,
            string type = null,
            int? topK = null,
            float? minScore = null,
            Guid? projectId = null,
            Guid? conversationId = null,
            string connectionId = null,
            bool extractFileContents = false,
            bool addFilesToKnowledge = true,
            IFormFileCollection files = null,
            XUserClaimsInfoDto userInfo = null,
            CancellationToken cancellationToken = default
        );
        #endregion

        //
        #region Loaders ...
        /// <summary>
        /// Load AI Projects ...
        /// </summary>
        /// <param name="ownerId"></param>
        /// <param name="connectionId"></param>
        /// <param name="includeDefaults"></param>
        /// <param name="cancellationToken"></param>
        /// <returns></returns>
        Task<IEnumerable<XAiProjectDto>> LoadProjects(
            string ownerId,
            string connectionId = null,
            bool includeDefaults = false,
            CancellationToken cancellationToken = default
        );

        /// <summary>
        /// Load Conversations of Specified AI Project ...
        /// </summary>
        /// <param name="projectId"></param>
        /// <param name="ownerId"></param>
        /// <param name="connectionId"></param>
        /// <param name="cancellationToken"></param>
        /// <returns></returns>
        Task<IEnumerable<XAiConversationDto>> LoadConversations(
            Guid? projectId,
            string ownerId = null,
            string connectionId = null,
            CancellationToken cancellationToken = default
        );

        /// <summary>
        /// Load Messages of Specified Conversation ...
        /// </summary>
        /// <param name="conversationId"></param>
        /// <param name="ownerId"></param>
        /// <param name="connectionId"></param>
        /// <param name="cancellationToken"></param>
        /// <returns></returns>
        Task<IEnumerable<XAiMessageDto>> LoadMessages(
            Guid? conversationId,
            string ownerId = null,
            string connectionId = null,
            CancellationToken cancellationToken = default
        );
        #endregion

        //
        #region Queries ...
        /// <summary>
        /// Query Projects ...
        /// </summary>
        /// <param name="ownerId"></param>
        /// <param name="query"></param>
        /// <param name="cancellationToken"></param>
        /// <returns></returns>
        Task<XQueryResult<XAiProjectDto>> QueryProjects(
            string ownerId,
            XQuery query,
            CancellationToken cancellationToken = default
        );

        /// <summary>
        /// Query Conversations ...
        /// </summary>
        /// <param name="ownerId"></param>
        /// <param name="projectId"></param>
        /// <param name="query"></param>
        /// <param name="cancellationToken"></param>
        /// <returns></returns>
        Task<XQueryResult<XAiConversationDto>> QueryConversations(
            string ownerId,
            Guid projectId,
            XQuery query,
            CancellationToken cancellationToken = default
        );

        /// <summary>
        /// Query Messages ...
        /// </summary>
        /// <param name="ownerId"></param>
        /// <param name="conversationId"></param>
        /// <param name="query"></param>
        /// <param name="cancellationToken"></param>
        /// <returns></returns>
        Task<XQueryResult<XAiMessageDto>> QueryMessages(
            string ownerId,
            Guid conversationId,
            XQuery query,
            CancellationToken cancellationToken = default
        );
        #endregion

        //
        #region Creators ...
        /// <summary>
        /// Create an AI Project ...
        /// </summary>
        /// <param name="ownerId"></param>
        /// <param name="item"></param>
        /// <param name="connectionId"></param>
        /// <param name="cancellationToken"></param>
        /// <returns></returns>
        Task<XAiProjectDto> CreateProject(
            string ownerId,
            XAiProjectDto item,
            string connectionId = null,
            CancellationToken cancellationToken = default
        );

        /// <summary>
        /// Create an AI Conversation ...
        /// </summary>
        /// <param name="ownerId"></param>
        /// <param name="projectId"></param>
        /// <param name="item"></param>
        /// <param name="connectionId"></param>
        /// <param name="cancellationToken"></param>
        /// <returns></returns>
        Task<XAiConversationDto> CreateConversation(
            string ownerId,
            Guid? projectId,
            XAiConversationDto item,
            string connectionId = null,
            CancellationToken cancellationToken = default
        );
        #endregion

        //
        #region Content Extraction ...
        /// <summary>
        /// Try to Extract Files Content ...
        /// </summary>
        /// <param name="files"></param>
        /// <param name="extractors"></param>
        /// <param name="cancellationToken"></param>
        /// <returns></returns>
        Task<string> ExtractContent(
            IFormFileCollection files,
            string[] extractors = null,
            CancellationToken cancellationToken = default
        );
        #endregion
    }
}

### FILE: C:\Users\saherelm\Documents\Projects\xSaherelmWorkspace\xAiApi\Interfaces\IXDefaultThinkingAiService.cs

namespace xAiApi.Interfaces
{
    public interface IXDefaultThinkingAiService: IXAiServiceBase
    { }
}

### FILE: C:\Users\saherelm\Documents\Projects\xSaherelmWorkspace\xAiApi\Interfaces\IXInMemoryVectorStore.cs

using System;
using xAiApi.Models;
using xAiModels.Models.Dtos;
using System.Collections.Generic;

namespace xAiApi.Interfaces
{
    public interface IXInMemoryVectorStore
    {
        int Count { get; }
        int RemoveExpired();
        Guid CreateSession(
            string ownerId = null, 
            TimeSpan? ttl = null
        );
        Guid CreateSession(
            IEnumerable<XAiVectorDto> vectors, 
            string ownerId = null, 
            TimeSpan? ttl = null
        );
        bool Replace(
            Guid sessionId, 
            IEnumerable<XAiVectorDto> vectors, 
            string ownerId = null
        );
        bool Add(
            Guid sessionId, 
            IEnumerable<XAiVectorDto> vectors, 
            string ownerId = null
        );
        IList<XAiVectorSearchResult> Search(
            Guid sessionId, 
            ReadOnlyMemory<float> queryEmbedding, 
            int topK = 5, 
            float minScore = 0f, 
            string ownerId = null
        );
        bool TryGet(
            Guid sessionId, 
            out XAiDocumentSession session, 
            string ownerId = null
        );
        bool Remove(
            Guid sessionId, 
            string ownerId = null
        );
    }
}

### FILE: C:\Users\saherelm\Documents\Projects\xSaherelmWorkspace\xAiApi\Interfaces\IXTextChunker.cs

using xAiApi.Models;
using System.Collections.Generic;

namespace xAiApi.Interfaces
{
    /// <summary>
    /// a Service for Splitting Long Texts into Overlapping Chunks
    /// which Suitable for Embedding ...
    /// </summary>
    public interface IXTextChunker
    {
        /// <summary>
        /// Split Text into Chunks ...
        /// </summary>
        /// <param name="text">Source Text</param>
        /// <param name="source">Source Name (e.g. File Name) used for Identifier</param>
        /// <returns></returns>
        IList<XTextChunk> Chunk(
            string text,
            string source = null
        );

        /// <summary>
        /// Split Text into Chunks and Return only Texts ...
        /// </summary>
        /// <param name="text"></param>
        /// <returns></returns>
        IList<string> ChunkTexts(
            string text
        );
    }
}

### FILE: C:\Users\saherelm\Documents\Projects\xSaherelmWorkspace\xAiApi\Interfaces\Extractors\IXAudioFileContentExtractor.cs

namespace xAiApi.Interfaces.Extractors
{
    public interface IXAudioFileContentExtractor : IXFileContentExtractorBase
    { }
}

### FILE: C:\Users\saherelm\Documents\Projects\xSaherelmWorkspace\xAiApi\Interfaces\Extractors\IXCodeFileContentExtractor.cs

namespace xAiApi.Interfaces.Extractors
{
    /// <summary> 
    /// Extractor for source code files ...
    /// (C#, Python, JavaScript, TypeScript, Java, Go, Rust, ...) 
    /// </summary> 
    public interface IXCodeFileContentExtractor : IXFileContentExtractorBase
    { }
}

### FILE: C:\Users\saherelm\Documents\Projects\xSaherelmWorkspace\xAiApi\Interfaces\Extractors\IXDocxFileContentExtractor.cs

namespace xAiApi.Interfaces.Extractors
{
    public interface IXDocxFileContentExtractor : IXFileContentExtractorBase
    { }
}

### FILE: C:\Users\saherelm\Documents\Projects\xSaherelmWorkspace\xAiApi\Interfaces\Extractors\IXEpubFileContentExtractor.cs

namespace xAiApi.Interfaces.Extractors
{
    /// <summary>
    /// Extractor for EPUB electronic publication format
    /// (application/epub+zip)
    /// </summary>
    public interface IXEpubFileContentExtractor : IXFileContentExtractorBase
    { }
}

### FILE: C:\Users\saherelm\Documents\Projects\xSaherelmWorkspace\xAiApi\Interfaces\Extractors\IXExcelFileContentExtractor.cs

namespace xAiApi.Interfaces.Extractors
{
    public interface IXExcelFileContentExtractor : IXFileContentExtractorBase
    { }
}

### FILE: C:\Users\saherelm\Documents\Projects\xSaherelmWorkspace\xAiApi\Interfaces\Extractors\IXFileContentExtractor.cs

using System.Collections;
using System.Collections.Generic;
using System.IO;
using System.Threading;
using System.Threading.Tasks;
using xAiModels.Models;

namespace xAiApi.Interfaces.Extractors
{
    /// <summary>
    /// a Base Service for Extracting File Content ...
    /// </summary>
    public interface IXFileContentExtractorBase
    {
        /// <summary>
        /// Check if this extractor supports the specified MIME type ...
        /// </summary>
        bool CanExtract(string mimeType);

        /// <summary>
        /// Extract text content from file stream ...
        /// </summary>
        Task<string> ExtractAsync(
            Stream fileStream,
            string mimeType,
            CancellationToken cancellationToken = default
        );

        /// <summary>
        /// Extract content from stream as Rich Result ...
        /// </summary>
        /// <param name="fileStream"></param>
        /// <param name="fileName"></param>
        /// <param name="mimeType"></param>
        /// <param name="cancellationToken"></param>
        /// <returns></returns>
        Task<XFileExtractionResult> ExtractRichAsync(
            Stream fileStream,
            string fileName,
            string mimeType,
            CancellationToken cancellationToken = default
        );
    }

    /// <summary>
    /// a Service for Extracting File Content ...
    /// </summary>
    public interface IXFileContentExtractor
    {
        /// <summary>
        /// Check if this extractor supports the specified MIME type ...
        /// </summary>
        /// <param name="mimeType"></param>
        /// <param name="extractors"></param>
        /// <returns></returns>
        bool CanExtract(
            string mimeType,
            string[] extractors = null
        );

        /// <summary>
        /// Extract text content from file stream ...
        /// </summary>
        /// <param name="fileStream"></param>
        /// <param name="mimeType"></param>
        /// <param name="extractors"></param>
        /// <param name="cancellationToken"></param>
        /// <returns></returns>
        Task<string> ExtractAsync(
            Stream fileStream,
            string mimeType,
            string[] extractors = null,
            CancellationToken cancellationToken = default
        );

        /// <summary>
        /// Extract content from stream as Rich Result ...
        /// </summary>
        /// <param name="fileStream"></param>
        /// <param name="fileName"></param>
        /// <param name="mimeType"></param>
        /// <param name="extractors"></param>
        /// <param name="cancellationToken"></param>
        /// <returns></returns>
        Task<XFileExtractionResult> ExtractRichAsync(
            Stream fileStream,
            string fileName,
            string mimeType,
            string[] extractors = null,
            CancellationToken cancellationToken = default
        );

    }
}

### FILE: C:\Users\saherelm\Documents\Projects\xSaherelmWorkspace\xAiApi\Interfaces\Extractors\IXHtmlFileContentExtractor.cs

namespace xAiApi.Interfaces.Extractors
{
    /// <summary>
    /// Extractor for HTML documents (text/html, application/xhtml+xml)
    /// </summary>
    public interface IXHtmlFileContentExtractor : IXFileContentExtractorBase
    { }
}

### FILE: C:\Users\saherelm\Documents\Projects\xSaherelmWorkspace\xAiApi\Interfaces\Extractors\IXImageFileContentExtractor.cs

namespace xAiApi.Interfaces.Extractors
{
    public interface IXImageFileContentExtractor : IXFileContentExtractorBase
    { }
}

### FILE: C:\Users\saherelm\Documents\Projects\xSaherelmWorkspace\xAiApi\Interfaces\Extractors\IXOpenDocumentFileContentExtractor.cs

namespace xAiApi.Interfaces.Extractors
{
    /// <summary>
    /// Extractor for OpenDocument Format (ODF) documents
    /// (ODT: OpenDocument Text, ODS: OpenDocument Spreadsheet, ODP: OpenDocument Presentation)
    /// </summary>
    public interface IXOpenDocumentFileContentExtractor : IXFileContentExtractorBase
    { }
}

### FILE: C:\Users\saherelm\Documents\Projects\xSaherelmWorkspace\xAiApi\Interfaces\Extractors\IXPdfFileContentExtractor.cs

namespace xAiApi.Interfaces.Extractors
{
    public interface IXPdfFileContentExtractor : IXFileContentExtractorBase
    { }
}

### FILE: C:\Users\saherelm\Documents\Projects\xSaherelmWorkspace\xAiApi\Interfaces\Extractors\IXPlainTextFileContentExtractor.cs

namespace xAiApi.Interfaces.Extractors
{
    public interface IXPlainTextFileContentExtractor : IXFileContentExtractorBase
    { }
}

### FILE: C:\Users\saherelm\Documents\Projects\xSaherelmWorkspace\xAiApi\Interfaces\Extractors\IXPowerPointFileContentExtractor.cs

namespace xAiApi.Interfaces.Extractors
{
    /// <summary>
    /// Extractor for all PowerPoint Presentation formats
    /// (OpenXML: pptx, ppsx, potx, pptm, ppsm, potm | Legacy Binary: ppt, pps, pot)
    /// </summary>
    public interface IXPowerPointFileContentExtractor : IXFileContentExtractorBase
    { }
}

### FILE: C:\Users\saherelm\Documents\Projects\xSaherelmWorkspace\xAiApi\Interfaces\Extractors\IXRtfFileContentExtractor.cs

namespace xAiApi.Interfaces.Extractors
{
    /// <summary>
    /// Extractor for Rich Text Format (RTF) documents
    /// (application/rtf, text/rtf)
    /// </summary>
    public interface IXRtfFileContentExtractor : IXFileContentExtractorBase
    { }
}

### FILE: C:\Users\saherelm\Documents\Projects\xSaherelmWorkspace\xAiApi\Interfaces\Extractors\IXVisionFileContentExtractor.cs

namespace xAiApi.Interfaces.Extractors
{
    public interface IXVisionFileContentExtractor : IXFileContentExtractorBase
    { }
}

### FILE: C:\Users\saherelm\Documents\Projects\xSaherelmWorkspace\xAiApi\Middlewares\XAiModelProxyMiddleware.cs

using System;
using System.IO;
using System.Net;
using System.Linq;
using System.Text;
using System.Net.Http;
using System.Threading;
using xAiApi.Extensions;
using xCommons.Constants;
using xCommons.Extensions;
using xAiModels.Extensions;
using xAiApi.Configurations;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Http;
using Microsoft.Net.Http.Headers;
using xIdentityService.Constants;
using xIdentityService.Interfaces;
using xIdentityService.Extensions;
using Microsoft.Extensions.Logging;
using xExceptions.Constants;
using xIdentityModels.Models;
using xIdentityModels.Constants;

namespace xAiApi.Middlewares
{
    public class XAiModelProxyMiddleware
    {
        private readonly RequestDelegate next;
        private readonly XAiApiConfiguration configuration;
        private readonly IHttpClientFactory httpClientFactory;
        private readonly ILogger<XAiModelProxyMiddleware> logger;

        public XAiModelProxyMiddleware(
            RequestDelegate next,
            XAiApiConfiguration configuration,
            IHttpClientFactory httpClientFactory,
            ILogger<XAiModelProxyMiddleware> logger
        )
        {
            //
            this.next = next;
            this.logger = logger;
            this.configuration = configuration;
            this.httpClientFactory = httpClientFactory;
        }

        /// <summary>
        /// Handle Routing ...
        /// </summary>
        /// <param name="context"></param>
        /// <returns></returns>
        public async Task InvokeAsync(
            HttpContext context,
            IXIdentityProvider identityProvider
        )
        {
            //
            // Validate ...
            var isValid =
                !configuration.IsNull() &&
                !configuration.ProxyConfiguration.IsNull() &&
                configuration.ProxyConfiguration.Enabled &&
                !configuration.ProxyConfiguration.RoutePrefix.IsNullOrEmpty() &&
                context.Request.Path.StartsWithSegments(configuration.ProxyConfiguration.RoutePrefix, out var remaining);
            if (!isValid)
            {
                //
                await next(context);
                return;
            }

            //
            // Validating Segment ...
            var rawSegments = remaining.Value?
                .Trim('/')
                .Split('/', StringSplitOptions.RemoveEmptyEntries);
            if (!rawSegments.HasChild())
            {
                //
                await next(context);
                return;
            }

            //
            // Extract Model Name and Retrieve Model Descriptor and do Validation ...
            var modelName = Uri.UnescapeDataString(rawSegments[0]);
            var descriptor = configuration.GetModel(modelName);
            if (!descriptor.IsValid())
            {
                //
                // Handle Error ...
                await context.Response.WriteJsonAsync(
                    status: HttpStatusCode.NotFound,
                    data: new
                    {
                        error = $"Model '{modelName}' is not configured."
                    }
                );
                return;
            }

            //
            var errorMessages = new string[] { };
            var apiKey = context.ExtractApiKey();
            var clientIP = context.Request.ExtractClientIP();
            var tokenModel = await context.RetrieveTokensAsXTokenResponse();
            var isAuthenticated =
                //
                (!apiKey.IsNullOrEmpty()) ||
                //
                (!tokenModel.IsNull() && !tokenModel.AccessToken.IsNullOrEmpty())
                ;
            if (isAuthenticated)
            {
                //
                // Handle Authentication ...
                if (!apiKey.IsNullOrEmpty())
                {
                    //
                    // Try to Validate Api Key ...
                    var validationResult = await identityProvider.ValidateApiKey(
                        request: new XApiKeyValidationRequest
                        {
                            ApiKey = apiKey,
                            ClientIP = clientIP,
                            RequiredScope = XApiKeyScope.Read.GetStringValue()
                        }
                    );
                    isAuthenticated = !validationResult.Errors.HasChild();
                    if (!isAuthenticated)
                    {
                        errorMessages = [.. errorMessages, .. validationResult.Errors];
                    }
                }
                else if (!tokenModel.IsNullOrDefault())
                {
                    //
                    // Try To Validate Token ...
                    var validationResult = await identityProvider.Validate(tokenModel);
                    isAuthenticated = !validationResult.IsError;
                    if (!isAuthenticated)
                    {
                        errorMessages = [..errorMessages, validationResult.Error];
                    }
                }
                else
                {
                    isAuthenticated = false;
                }
            }
            if (!isAuthenticated)
            {
                //
                var error = XException.NotAuthorized.ToXError();
                error.Message = $"{error.Message}: {errorMessages.ToListString(',')}";
                await context.Response.WriteJsonAsync(
                    status: HttpStatusCode.Unauthorized,
                    data: error
                );
                return;
            }

            //
            var suffixPath = Uri.UnescapeDataString(string.Join('/', rawSegments.Skip(1)));
            var targetUri = BuildTargetUri(
                descriptor.Url,
                suffixPath,
                context.Request.QueryString
            );

            //
            // Collect Headers which need to Except ...
            var exceptionHeaders = new string[]
            {
                XAuthorization.Header,
                XAuthorization.ExpiresAt,
                XAuthorization.XPoweredBy,
                XAuthorization.AccessToken,
                XAuthorization.RefreshToken,
                XHeader.ApiKey.GetStringValue(),
                XAuthorization.AccessTokenExpired,
                XHeader.ConnectionId.GetStringValue(),
                XHeader.ChecksumDigest.GetStringValue(),
            };

            //
            using var upstreamRequest = new HttpRequestMessage(
                new HttpMethod(context.Request.Method),
                targetUri
            );

            //
            context.CopyRequestHeaders(
                dest: upstreamRequest,
                exceptions: exceptionHeaders
            );

            //
            if (
                context.Request.ContentLength > 0 ||
                context.Request.Headers.ContainsKey(HeaderNames.TransferEncoding)
            )
            {
                //
                context.Request.EnableBuffering();
                using var reader = new StreamReader(
                    context.Request.Body,
                    Encoding.UTF8,
                    detectEncodingFromByteOrderMarks: true,
                    bufferSize: 1024,
                    leaveOpen: true
                );
                var bodyText = await reader.ReadToEndAsync();
                var actualLength = Encoding.UTF8.GetByteCount(bodyText);
                var declaredLength = context.Request.ContentLength;
                var contentType = context.Request.ContentType ?? "application/octet-stream";
                var mediaType = contentType.Split(';')[0].Trim();
                upstreamRequest.Content = new StringContent(
                    bodyText,
                    Encoding.UTF8,
                    mediaType
                );
                context.Request.Body.Position = 0;
                context.CopyRequestHeaders(
                    dest: upstreamRequest.Content,
                    exceptions: exceptionHeaders
                );
            }

            //
            // Handle Api Key of LLM ...
            descriptor.AddModelDescriptorApiKey(
                request: upstreamRequest
            );

            //
            try
            {
                //
                var client = httpClientFactory.CreateClient("XAiModelProxy");
                client.Timeout = Timeout.InfiniteTimeSpan;

                //
                using var upstreamResponse = await client.SendAsync(
                    upstreamRequest,
                    HttpCompletionOption.ResponseHeadersRead,
                    context.RequestAborted
                );

                //
                context.Response.StatusCode = (int)upstreamResponse.StatusCode;

                //
                upstreamResponse.CopyHeaders(
                    response: context.Response,
                    exceptions: exceptionHeaders
                );

                //
                await using var responseStream = await upstreamResponse.Content
                    .ReadAsStreamAsync();
                await responseStream.CopyToAsync(
                    context.Response.Body,
                    context.RequestAborted
                );
            }
            catch (OperationCanceledException) when (context.RequestAborted.IsCancellationRequested)
            { }
            catch (Exception ex)
            {
                //
                logger.LogError(ex, "Proxy failed for model {ModelName}", modelName);
                if (!context.Response.HasStarted)
                {
                    //
                    // Handle Error ...
                    var error = XException.ActionFailed.ToXError();
                    error.Message = $"{error.Message}: {ex.Message}";
                    await context.Response.WriteJsonAsync(
                        status: HttpStatusCode.BadGateway,
                        data: error
                    );
                }
            }
        }

        //
        #region Private ...
        private static Uri BuildTargetUri(
            string baseUrl,
            string suffixPath,
            QueryString query
        )
        {
            //
            var baseUri = new Uri(baseUrl, UriKind.Absolute);
            var builder = new UriBuilder(baseUri);
            var basePath = builder.Path.TrimEnd('/');

            //
            builder.Path = suffixPath.IsNullOrEmpty()
                ? basePath
                : $"{basePath}/{suffixPath.TrimStart('/')}";

            //
            builder.Query = query.HasValue
                ? query.Value.TrimStart('?')
                : string.Empty;

            //
            return builder.Uri;
        }
        #endregion
    }
}

### FILE: C:\Users\saherelm\Documents\Projects\xSaherelmWorkspace\xAiApi\Migrations\20261105072614_InitialMigrationAiApi.cs

using System;
using Microsoft.EntityFrameworkCore.Migrations;

namespace xAiApi.Migrations
{
    public partial class InitialMigrationAiApi : Migration
    {
        protected override void Up(MigrationBuilder migrationBuilder)
        {
            migrationBuilder.CreateTable(
                name: "AiConversations",
                columns: table => new
                {
                    Id = table.Column<Guid>(nullable: false),
                    Deleted = table.Column<bool>(nullable: false),
                    OwnerId = table.Column<string>(maxLength: 255, nullable: false),
                    Title = table.Column<string>(maxLength: 255, nullable: false),
                    CreatedOn = table.Column<DateTime>(nullable: false),
                    UpdatedAt = table.Column<DateTime>(nullable: false),
                    ProjectId = table.Column<Guid>(nullable: false)
                },
                constraints: table =>
                {
                    table.PrimaryKey("PK_AiConversations", x => x.Id);
                });

            migrationBuilder.CreateTable(
                name: "AiMcpServers",
                columns: table => new
                {
                    Id = table.Column<Guid>(nullable: false),
                    Deleted = table.Column<bool>(nullable: false),
                    OwnerId = table.Column<string>(maxLength: 255, nullable: false),
                    Scope = table.Column<int>(nullable: false),
                    Name = table.Column<string>(maxLength: 255, nullable: false),
                    Description = table.Column<string>(maxLength: 1000, nullable: true),
                    Enabled = table.Column<bool>(nullable: false),
                    EnvironmentVariables = table.Column<string>(nullable: true),
                    Endpoint = table.Column<string>(maxLength: 1000, nullable: true),
                    Headers = table.Column<string>(nullable: true),
                    TimeoutSeconds = table.Column<int>(nullable: false),
                    CreatedOn = table.Column<DateTime>(nullable: false),
                    UpdatedAt = table.Column<DateTime>(nullable: false)
                },
                constraints: table =>
                {
                    table.PrimaryKey("PK_AiMcpServers", x => x.Id);
                });

            migrationBuilder.CreateTable(
                name: "AiMessages",
                columns: table => new
                {
                    Id = table.Column<Guid>(nullable: false),
                    Deleted = table.Column<bool>(nullable: false),
                    OwnerId = table.Column<string>(maxLength: 255, nullable: false),
                    Content = table.Column<string>(nullable: false),
                    Role = table.Column<int>(nullable: false),
                    CreatedOn = table.Column<DateTime>(nullable: false),
                    UpdatedAt = table.Column<DateTime>(nullable: false),
                    ConversationId = table.Column<Guid>(maxLength: 255, nullable: false),
                    MetaDatas = table.Column<string>(nullable: true)
                },
                constraints: table =>
                {
                    table.PrimaryKey("PK_AiMessages", x => x.Id);
                });

            migrationBuilder.CreateTable(
                name: "AiProjects",
                columns: table => new
                {
                    Id = table.Column<Guid>(nullable: false),
                    Deleted = table.Column<bool>(nullable: false),
                    OwnerId = table.Column<string>(maxLength: 255, nullable: false),
                    Title = table.Column<string>(maxLength: 255, nullable: false),
                    Description = table.Column<string>(maxLength: 1000, nullable: true),
                    Prompt = table.Column<string>(nullable: true),
                    CreatedOn = table.Column<DateTime>(nullable: false),
                    UpdatedAt = table.Column<DateTime>(nullable: false)
                },
                constraints: table =>
                {
                    table.PrimaryKey("PK_AiProjects", x => x.Id);
                });

            migrationBuilder.CreateTable(
                name: "AiVectors",
                columns: table => new
                {
                    Id = table.Column<Guid>(nullable: false),
                    Deleted = table.Column<bool>(nullable: false),
                    Text = table.Column<string>(nullable: true),
                    Identifier = table.Column<string>(nullable: true),
                    Type = table.Column<string>(maxLength: 100, nullable: true),
                    Embedding = table.Column<string>(nullable: true),
                    Metadata = table.Column<string>(nullable: true)
                },
                constraints: table =>
                {
                    table.PrimaryKey("PK_AiVectors", x => x.Id);
                });

            migrationBuilder.CreateTable(
                name: "Files",
                columns: table => new
                {
                    Id = table.Column<Guid>(nullable: false),
                    Deleted = table.Column<bool>(nullable: false),
                    Type = table.Column<int>(nullable: false),
                    OwnerId = table.Column<string>(maxLength: 255, nullable: false),
                    Name = table.Column<string>(maxLength: 255, nullable: false),
                    Path = table.Column<string>(nullable: false),
                    Thumb = table.Column<string>(nullable: true),
                    ThumbPath = table.Column<string>(nullable: true),
                    UploadedOn = table.Column<DateTime>(nullable: false),
                    FileName = table.Column<string>(nullable: true),
                    References = table.Column<string>(nullable: true)
                },
                constraints: table =>
                {
                    table.PrimaryKey("PK_Files", x => x.Id);
                });

            migrationBuilder.CreateTable(
                name: "Strings",
                columns: table => new
                {
                    Id = table.Column<int>(nullable: false)
                        .Annotation("Sqlite:Autoincrement", true),
                    Deleted = table.Column<bool>(nullable: false),
                    Language = table.Column<string>(maxLength: 10, nullable: false),
                    ResourceTitle = table.Column<string>(maxLength: 255, nullable: false),
                    TranslatedValue = table.Column<string>(nullable: false)
                },
                constraints: table =>
                {
                    table.PrimaryKey("PK_Strings", x => x.Id);
                });

            migrationBuilder.CreateTable(
                name: "Tags",
                columns: table => new
                {
                    Id = table.Column<int>(nullable: false)
                        .Annotation("Sqlite:Autoincrement", true),
                    Deleted = table.Column<bool>(nullable: false),
                    Tag = table.Column<string>(maxLength: 255, nullable: false),
                    References = table.Column<string>(nullable: true)
                },
                constraints: table =>
                {
                    table.PrimaryKey("PK_Tags", x => x.Id);
                });

            migrationBuilder.CreateIndex(
                name: "IX_AiVectors_Identifier",
                table: "AiVectors",
                column: "Identifier");

            migrationBuilder.CreateIndex(
                name: "IX_AiVectors_Type",
                table: "AiVectors",
                column: "Type");
        }

        protected override void Down(MigrationBuilder migrationBuilder)
        {
            migrationBuilder.DropTable(
                name: "AiConversations");

            migrationBuilder.DropTable(
                name: "AiMcpServers");

            migrationBuilder.DropTable(
                name: "AiMessages");

            migrationBuilder.DropTable(
                name: "AiProjects");

            migrationBuilder.DropTable(
                name: "AiVectors");

            migrationBuilder.DropTable(
                name: "Files");

            migrationBuilder.DropTable(
                name: "Strings");

            migrationBuilder.DropTable(
                name: "Tags");
        }
    }
}

### FILE: C:\Users\saherelm\Documents\Projects\xSaherelmWorkspace\xAiApi\Migrations\20261105072614_InitialMigrationAiApi.Designer.cs

// <auto-generated />
using System;
using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.Infrastructure;
using Microsoft.EntityFrameworkCore.Migrations;
using Microsoft.EntityFrameworkCore.Storage.ValueConversion;
using xAiApi.Database;

namespace xAiApi.Migrations
{
    [DbContext(typeof(XAiApiDbContext))]
    [Migration("20261105072614_InitialMigrationAiApi")]
    partial class InitialMigrationAiApi
    {
        protected override void BuildTargetModel(ModelBuilder modelBuilder)
        {
#pragma warning disable 612, 618
            modelBuilder
                .HasAnnotation("ProductVersion", "3.1.14");

            modelBuilder.Entity("xAiModels.Models.Entities.XAiConversation", b =>
                {
                    b.Property<Guid>("Id")
                        .ValueGeneratedOnAdd()
                        .HasColumnType("TEXT");

                    b.Property<DateTime>("CreatedOn")
                        .HasColumnType("TEXT");

                    b.Property<bool>("Deleted")
                        .HasColumnType("INTEGER");

                    b.Property<string>("OwnerId")
                        .IsRequired()
                        .HasColumnType("TEXT")
                        .HasMaxLength(255);

                    b.Property<Guid>("ProjectId")
                        .HasColumnType("TEXT");

                    b.Property<string>("Title")
                        .IsRequired()
                        .HasColumnType("TEXT")
                        .HasMaxLength(255);

                    b.Property<DateTime>("UpdatedAt")
                        .HasColumnType("TEXT");

                    b.HasKey("Id");

                    b.ToTable("AiConversations");
                });

            modelBuilder.Entity("xAiModels.Models.Entities.XAiMcpServer", b =>
                {
                    b.Property<Guid>("Id")
                        .ValueGeneratedOnAdd()
                        .HasColumnType("TEXT");

                    b.Property<DateTime>("CreatedOn")
                        .HasColumnType("TEXT");

                    b.Property<bool>("Deleted")
                        .HasColumnType("INTEGER");

                    b.Property<string>("Description")
                        .HasColumnType("TEXT")
                        .HasMaxLength(1000);

                    b.Property<bool>("Enabled")
                        .HasColumnType("INTEGER");

                    b.Property<string>("Endpoint")
                        .HasColumnType("TEXT")
                        .HasMaxLength(1000);

                    b.Property<string>("EnvironmentVariables")
                        .HasColumnType("TEXT");

                    b.Property<string>("Headers")
                        .HasColumnType("TEXT");

                    b.Property<string>("Name")
                        .IsRequired()
                        .HasColumnType("TEXT")
                        .HasMaxLength(255);

                    b.Property<string>("OwnerId")
                        .IsRequired()
                        .HasColumnType("TEXT")
                        .HasMaxLength(255);

                    b.Property<int>("Scope")
                        .HasColumnType("INTEGER");

                    b.Property<int>("TimeoutSeconds")
                        .HasColumnType("INTEGER");

                    b.Property<DateTime>("UpdatedAt")
                        .HasColumnType("TEXT");

                    b.HasKey("Id");

                    b.ToTable("AiMcpServers");
                });

            modelBuilder.Entity("xAiModels.Models.Entities.XAiMessage", b =>
                {
                    b.Property<Guid>("Id")
                        .ValueGeneratedOnAdd()
                        .HasColumnType("TEXT");

                    b.Property<string>("Content")
                        .IsRequired()
                        .HasColumnType("TEXT");

                    b.Property<Guid>("ConversationId")
                        .HasColumnType("TEXT")
                        .HasMaxLength(255);

                    b.Property<DateTime>("CreatedOn")
                        .HasColumnType("TEXT");

                    b.Property<bool>("Deleted")
                        .HasColumnType("INTEGER");

                    b.Property<string>("MetaDatas")
                        .HasColumnType("TEXT");

                    b.Property<string>("OwnerId")
                        .IsRequired()
                        .HasColumnType("TEXT")
                        .HasMaxLength(255);

                    b.Property<int>("Role")
                        .HasColumnType("INTEGER");

                    b.Property<DateTime>("UpdatedAt")
                        .HasColumnType("TEXT");

                    b.HasKey("Id");

                    b.ToTable("AiMessages");
                });

            modelBuilder.Entity("xAiModels.Models.Entities.XAiProject", b =>
                {
                    b.Property<Guid>("Id")
                        .ValueGeneratedOnAdd()
                        .HasColumnType("TEXT");

                    b.Property<DateTime>("CreatedOn")
                        .HasColumnType("TEXT");

                    b.Property<bool>("Deleted")
                        .HasColumnType("INTEGER");

                    b.Property<string>("Description")
                        .HasColumnType("TEXT")
                        .HasMaxLength(1000);

                    b.Property<string>("OwnerId")
                        .IsRequired()
                        .HasColumnType("TEXT")
                        .HasMaxLength(255);

                    b.Property<string>("Prompt")
                        .HasColumnType("TEXT");

                    b.Property<string>("Title")
                        .IsRequired()
                        .HasColumnType("TEXT")
                        .HasMaxLength(255);

                    b.Property<DateTime>("UpdatedAt")
                        .HasColumnType("TEXT");

                    b.HasKey("Id");

                    b.ToTable("AiProjects");
                });

            modelBuilder.Entity("xAiModels.Models.Entities.XAiVector", b =>
                {
                    b.Property<Guid>("Id")
                        .ValueGeneratedOnAdd()
                        .HasColumnType("TEXT");

                    b.Property<bool>("Deleted")
                        .HasColumnType("INTEGER");

                    b.Property<string>("Embedding")
                        .HasColumnType("TEXT");

                    b.Property<string>("Identifier")
                        .HasColumnType("TEXT");

                    b.Property<string>("Metadata")
                        .HasColumnType("TEXT");

                    b.Property<string>("Text")
                        .HasColumnType("TEXT");

                    b.Property<string>("Type")
                        .HasColumnType("TEXT")
                        .HasMaxLength(100);

                    b.HasKey("Id");

                    b.HasIndex("Identifier");

                    b.HasIndex("Type");

                    b.ToTable("AiVectors");
                });

            modelBuilder.Entity("xFileService.Models.Entities.XFile", b =>
                {
                    b.Property<Guid>("Id")
                        .ValueGeneratedOnAdd()
                        .HasColumnType("TEXT");

                    b.Property<bool>("Deleted")
                        .HasColumnType("INTEGER");

                    b.Property<string>("FileName")
                        .HasColumnType("TEXT");

                    b.Property<string>("Name")
                        .IsRequired()
                        .HasColumnType("TEXT")
                        .HasMaxLength(255);

                    b.Property<string>("OwnerId")
                        .IsRequired()
                        .HasColumnType("TEXT")
                        .HasMaxLength(255);

                    b.Property<string>("Path")
                        .IsRequired()
                        .HasColumnType("TEXT");

                    b.Property<string>("References")
                        .HasColumnType("TEXT");

                    b.Property<string>("Thumb")
                        .HasColumnType("TEXT");

                    b.Property<string>("ThumbPath")
                        .HasColumnType("TEXT");

                    b.Property<int>("Type")
                        .HasColumnType("INTEGER");

                    b.Property<DateTime>("UploadedOn")
                        .HasColumnType("TEXT");

                    b.HasKey("Id");

                    b.ToTable("Files");
                });

            modelBuilder.Entity("xStringService.Models.Entities.XString", b =>
                {
                    b.Property<int>("Id")
                        .ValueGeneratedOnAdd()
                        .HasColumnType("INTEGER");

                    b.Property<bool>("Deleted")
                        .HasColumnType("INTEGER");

                    b.Property<string>("Language")
                        .IsRequired()
                        .HasColumnType("TEXT")
                        .HasMaxLength(10);

                    b.Property<string>("ResourceTitle")
                        .IsRequired()
                        .HasColumnType("TEXT")
                        .HasMaxLength(255);

                    b.Property<string>("TranslatedValue")
                        .IsRequired()
                        .HasColumnType("TEXT");

                    b.HasKey("Id");

                    b.ToTable("Strings");
                });

            modelBuilder.Entity("xTagService.Models.Entities.XTag", b =>
                {
                    b.Property<int>("Id")
                        .ValueGeneratedOnAdd()
                        .HasColumnType("INTEGER");

                    b.Property<bool>("Deleted")
                        .HasColumnType("INTEGER");

                    b.Property<string>("References")
                        .HasColumnType("TEXT");

                    b.Property<string>("Tag")
                        .IsRequired()
                        .HasColumnType("TEXT")
                        .HasMaxLength(255);

                    b.HasKey("Id");

                    b.ToTable("Tags");
                });
#pragma warning restore 612, 618
        }
    }
}

### FILE: C:\Users\saherelm\Documents\Projects\xSaherelmWorkspace\xAiApi\Migrations\XAiApiDbContextModelSnapshot.cs

// <auto-generated />
using System;
using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.Infrastructure;
using Microsoft.EntityFrameworkCore.Storage.ValueConversion;
using xAiApi.Database;

namespace xAiApi.Migrations
{
    [DbContext(typeof(XAiApiDbContext))]
    partial class XAiApiDbContextModelSnapshot : ModelSnapshot
    {
        protected override void BuildModel(ModelBuilder modelBuilder)
        {
#pragma warning disable 612, 618
            modelBuilder
                .HasAnnotation("ProductVersion", "3.1.14");

            modelBuilder.Entity("xAiModels.Models.Entities.XAiConversation", b =>
                {
                    b.Property<Guid>("Id")
                        .ValueGeneratedOnAdd()
                        .HasColumnType("TEXT");

                    b.Property<DateTime>("CreatedOn")
                        .HasColumnType("TEXT");

                    b.Property<bool>("Deleted")
                        .HasColumnType("INTEGER");

                    b.Property<string>("OwnerId")
                        .IsRequired()
                        .HasColumnType("TEXT")
                        .HasMaxLength(255);

                    b.Property<Guid>("ProjectId")
                        .HasColumnType("TEXT");

                    b.Property<string>("Title")
                        .IsRequired()
                        .HasColumnType("TEXT")
                        .HasMaxLength(255);

                    b.Property<DateTime>("UpdatedAt")
                        .HasColumnType("TEXT");

                    b.HasKey("Id");

                    b.ToTable("AiConversations");
                });

            modelBuilder.Entity("xAiModels.Models.Entities.XAiMcpServer", b =>
                {
                    b.Property<Guid>("Id")
                        .ValueGeneratedOnAdd()
                        .HasColumnType("TEXT");

                    b.Property<DateTime>("CreatedOn")
                        .HasColumnType("TEXT");

                    b.Property<bool>("Deleted")
                        .HasColumnType("INTEGER");

                    b.Property<string>("Description")
                        .HasColumnType("TEXT")
                        .HasMaxLength(1000);

                    b.Property<bool>("Enabled")
                        .HasColumnType("INTEGER");

                    b.Property<string>("Endpoint")
                        .HasColumnType("TEXT")
                        .HasMaxLength(1000);

                    b.Property<string>("EnvironmentVariables")
                        .HasColumnType("TEXT");

                    b.Property<string>("Headers")
                        .HasColumnType("TEXT");

                    b.Property<string>("Name")
                        .IsRequired()
                        .HasColumnType("TEXT")
                        .HasMaxLength(255);

                    b.Property<string>("OwnerId")
                        .IsRequired()
                        .HasColumnType("TEXT")
                        .HasMaxLength(255);

                    b.Property<int>("Scope")
                        .HasColumnType("INTEGER");

                    b.Property<int>("TimeoutSeconds")
                        .HasColumnType("INTEGER");

                    b.Property<DateTime>("UpdatedAt")
                        .HasColumnType("TEXT");

                    b.HasKey("Id");

                    b.ToTable("AiMcpServers");
                });

            modelBuilder.Entity("xAiModels.Models.Entities.XAiMessage", b =>
                {
                    b.Property<Guid>("Id")
                        .ValueGeneratedOnAdd()
                        .HasColumnType("TEXT");

                    b.Property<string>("Content")
                        .IsRequired()
                        .HasColumnType("TEXT");

                    b.Property<Guid>("ConversationId")
                        .HasColumnType("TEXT")
                        .HasMaxLength(255);

                    b.Property<DateTime>("CreatedOn")
                        .HasColumnType("TEXT");

                    b.Property<bool>("Deleted")
                        .HasColumnType("INTEGER");

                    b.Property<string>("MetaDatas")
                        .HasColumnType("TEXT");

                    b.Property<string>("OwnerId")
                        .IsRequired()
                        .HasColumnType("TEXT")
                        .HasMaxLength(255);

                    b.Property<int>("Role")
                        .HasColumnType("INTEGER");

                    b.Property<DateTime>("UpdatedAt")
                        .HasColumnType("TEXT");

                    b.HasKey("Id");

                    b.ToTable("AiMessages");
                });

            modelBuilder.Entity("xAiModels.Models.Entities.XAiProject", b =>
                {
                    b.Property<Guid>("Id")
                        .ValueGeneratedOnAdd()
                        .HasColumnType("TEXT");

                    b.Property<DateTime>("CreatedOn")
                        .HasColumnType("TEXT");

                    b.Property<bool>("Deleted")
                        .HasColumnType("INTEGER");

                    b.Property<string>("Description")
                        .HasColumnType("TEXT")
                        .HasMaxLength(1000);

                    b.Property<string>("OwnerId")
                        .IsRequired()
                        .HasColumnType("TEXT")
                        .HasMaxLength(255);

                    b.Property<string>("Prompt")
                        .HasColumnType("TEXT");

                    b.Property<string>("Title")
                        .IsRequired()
                        .HasColumnType("TEXT")
                        .HasMaxLength(255);

                    b.Property<DateTime>("UpdatedAt")
                        .HasColumnType("TEXT");

                    b.HasKey("Id");

                    b.ToTable("AiProjects");
                });

            modelBuilder.Entity("xAiModels.Models.Entities.XAiVector", b =>
                {
                    b.Property<Guid>("Id")
                        .ValueGeneratedOnAdd()
                        .HasColumnType("TEXT");

                    b.Property<bool>("Deleted")
                        .HasColumnType("INTEGER");

                    b.Property<string>("Embedding")
                        .HasColumnType("TEXT");

                    b.Property<string>("Identifier")
                        .HasColumnType("TEXT");

                    b.Property<string>("Metadata")
                        .HasColumnType("TEXT");

                    b.Property<string>("Text")
                        .HasColumnType("TEXT");

                    b.Property<string>("Type")
                        .HasColumnType("TEXT")
                        .HasMaxLength(100);

                    b.HasKey("Id");

                    b.HasIndex("Identifier");

                    b.HasIndex("Type");

                    b.ToTable("AiVectors");
                });

            modelBuilder.Entity("xFileService.Models.Entities.XFile", b =>
                {
                    b.Property<Guid>("Id")
                        .ValueGeneratedOnAdd()
                        .HasColumnType("TEXT");

                    b.Property<bool>("Deleted")
                        .HasColumnType("INTEGER");

                    b.Property<string>("FileName")
                        .HasColumnType("TEXT");

                    b.Property<string>("Name")
                        .IsRequired()
                        .HasColumnType("TEXT")
                        .HasMaxLength(255);

                    b.Property<string>("OwnerId")
                        .IsRequired()
                        .HasColumnType("TEXT")
                        .HasMaxLength(255);

                    b.Property<string>("Path")
                        .IsRequired()
                        .HasColumnType("TEXT");

                    b.Property<string>("References")
                        .HasColumnType("TEXT");

                    b.Property<string>("Thumb")
                        .HasColumnType("TEXT");

                    b.Property<string>("ThumbPath")
                        .HasColumnType("TEXT");

                    b.Property<int>("Type")
                        .HasColumnType("INTEGER");

                    b.Property<DateTime>("UploadedOn")
                        .HasColumnType("TEXT");

                    b.HasKey("Id");

                    b.ToTable("Files");
                });

            modelBuilder.Entity("xStringService.Models.Entities.XString", b =>
                {
                    b.Property<int>("Id")
                        .ValueGeneratedOnAdd()
                        .HasColumnType("INTEGER");

                    b.Property<bool>("Deleted")
                        .HasColumnType("INTEGER");

                    b.Property<string>("Language")
                        .IsRequired()
                        .HasColumnType("TEXT")
                        .HasMaxLength(10);

                    b.Property<string>("ResourceTitle")
                        .IsRequired()
                        .HasColumnType("TEXT")
                        .HasMaxLength(255);

                    b.Property<string>("TranslatedValue")
                        .IsRequired()
                        .HasColumnType("TEXT");

                    b.HasKey("Id");

                    b.ToTable("Strings");
                });

            modelBuilder.Entity("xTagService.Models.Entities.XTag", b =>
                {
                    b.Property<int>("Id")
                        .ValueGeneratedOnAdd()
                        .HasColumnType("INTEGER");

                    b.Property<bool>("Deleted")
                        .HasColumnType("INTEGER");

                    b.Property<string>("References")
                        .HasColumnType("TEXT");

                    b.Property<string>("Tag")
                        .IsRequired()
                        .HasColumnType("TEXT")
                        .HasMaxLength(255);

                    b.HasKey("Id");

                    b.ToTable("Tags");
                });
#pragma warning restore 612, 618
        }
    }
}

### FILE: C:\Users\saherelm\Documents\Projects\xSaherelmWorkspace\xAiApi\Models\XAiDocumentModels.cs

using System;
using System.Collections.Generic;

namespace xAiApi.Models
{
    /// <summary>
    /// Result of Ingesting Documents into an In-Memory Session ...
    /// </summary>
    public class XAiDocumentIngestResult
    {
        /// <summary>
        /// Session Identifier which must be used in Ask Requests ...
        /// </summary>
        public Guid SessionId { get; set; }

        /// <summary>
        /// Count of Successfully Processed Files ...
        /// </summary>
        public int FilesCount { get; set; }

        /// <summary>
        /// Count of Chunks (Vectors) Added to Session ...
        /// </summary>
        public int ChunksCount { get; set; }

        /// <summary>
        /// Total Vectors Count in Session after Ingest ...
        /// </summary>
        public int TotalVectorsCount { get; set; }

        /// <summary>
        /// Files which Skipped (Unsupported / Empty / Failed) ...
        /// </summary>
        public IList<string> SkippedFiles { get; set; } = new List<string>();

        /// <summary>
        /// Session Expiration Time (UTC) based on Last Access ...
        /// </summary>
        public DateTime ExpiresAtUtc { get; set; }
    }

    /// <summary>
    /// Request for Asking a Question over Ingested Documents ...
    /// </summary>
    public class XAiDocumentAskRequest
    {
        /// <summary>
        /// Session Identifier ...
        /// </summary>
        public Guid SessionId { get; set; }

        /// <summary>
        /// User Question ...
        /// </summary>
        public string Prompt { get; set; }

        /// <summary>
        /// Count of Top Chunks used as Context (Optional) ...
        /// </summary>
        public int? TopK { get; set; }

        /// <summary>
        /// Minimum Similarity Score of Chunks (Optional) ...
        /// </summary>
        public float? MinScore { get; set; }
    }

    /// <summary>
    /// a Source Chunk which used for Generating Answer ...
    /// </summary>
    public class XAiDocumentSource
    {
        /// <summary>
        /// Doc and Chunk Identifier (e.g. "file.pdf#3") ...
        /// </summary>
        public string Identifier { get; set; }

        /// <summary>
        /// Source File Name ...
        /// </summary>
        public string FileName { get; set; }

        /// <summary>
        /// Chunk Index in Source File ...
        /// </summary>
        public int? ChunkIndex { get; set; }

        /// <summary>
        /// Similarity Score ...
        /// </summary>
        public float Score { get; set; }

        /// <summary>
        /// Short Snippet of Chunk Text ...
        /// </summary>
        public string Snippet { get; set; }

        /// <summary>
        /// Knowledge Scope the Chunk Retrieved from (Null for Session Based Documents) ...
        /// </summary>
        public string Scope { get; set; }

        /// <summary>
        /// Knowledge Type of the Chunk ...
        /// </summary>
        public string Type { get; set; }
    }

    /// <summary>
    /// Answer of a Chat With Documents Request ...
    /// </summary>
    public class XAiDocumentAnswer
    {
        /// <summary>
        /// Session Identifier ...
        /// </summary>
        public Guid SessionId { get; set; }

        /// <summary>
        /// Generated Answer ...
        /// </summary>
        public string Answer { get; set; }

        /// <summary>
        /// True when no Relevant Chunk Found in Session ...
        /// </summary>
        public bool NoContextFound { get; set; }

        /// <summary>
        /// Sources used for Generating Answer ...
        /// </summary>
        public IList<XAiDocumentSource> Sources { get; set; } = new List<XAiDocumentSource>();
    }

    /// <summary>
    /// Streaming Chunk of a Chat With Documents Answer ...
    /// </summary>
    public class XAiDocumentAnswerChunk
    {
        /// <summary>
        /// Text Delta ...
        /// </summary>
        public string Text { get; set; }

        /// <summary>
        /// True for Last Chunk ...
        /// </summary>
        public bool IsFinal { get; set; }

        /// <summary>
        /// True when no Relevant Chunk Found in Session ...
        /// </summary>
        public bool NoContextFound { get; set; }

        /// <summary>
        /// Sources (Only Filled in First Chunk) ...
        /// </summary>
        public IList<XAiDocumentSource> Sources { get; set; }
    }

    /// <summary>
    /// Public Info of a Document Session (without Embeddings) ...
    /// </summary>
    public class XAiDocumentSessionInfo
    {
        public Guid Id { get; set; }
        public TimeSpan Ttl { get; set; }
        public int VectorsCount { get; set; }
        public DateTime CreatedAtUtc { get; set; }
        public DateTime LastAccessAtUtc { get; set; }
        public DateTime ExpiresAtUtc { get; set; }
        public IList<string> Files { get; set; } = new List<string>();
    }

    /// <summary>
    /// Document RAG Configuration ...
    /// </summary>
    public class XAiDocumentRAGDescriptor
    {
        public int MaxTopK { get; set; } = 20;
        public int DefaultTopK { get; set; } = 5;
        public int DefaultTtlMinutes { get; set; } = 30;
        public int EmbeddingBatchSize { get; set; } = 32;
        public int SourceSnippetLength { get; set; } = 200;
        public float DefaultMinScore { get; set; } = 0.35f;
        public string MetadataFileName { get; set; } = "fileName";
        public string MetadataMimeType { get; set; } = "mimeType";
        public string PromptName { get; set; } = "ChatWithDocuments";
        public string MetadataChunkIndex { get; set; } = "chunkIndex";

        //
        // Knowledge (Persistent RAG) Limits ...
        /// <summary>
        /// Max Files Accepted in a Single Ingest Request (0 = Unlimited) ...
        /// </summary>
        public int MaxFilesPerIngest { get; set; } = 20;

        /// <summary>
        /// Max Size of a Single File in Bytes (0 = Unlimited) ...
        /// </summary>
        public long MaxFileSizeBytes { get; set; } = 25 * 1024 * 1024;

        /// <summary>
        /// Max Distinct Documents Allowed in a Non-Global Scope (0 = Unlimited) ...
        /// </summary>
        public int MaxDocumentsPerScope { get; set; } = 50;
    }
}

### FILE: C:\Users\saherelm\Documents\Projects\xSaherelmWorkspace\xAiApi\Models\XAiDocumentSession.cs

using System;
using xAiModels.Models.Dtos;
using System.Collections.Generic;

namespace xAiApi.Models
{
    public class XAiDocumentSession
    {
        public Guid Id { get; set; }
        public TimeSpan Ttl { get; set; }
        public string OwnerId { get; set; }
        public DateTime CreatedAtUtc { get; set; }
        public DateTime LastAccessAtUtc { get; set; }
        internal object SyncRoot { get; } = new object();
        public IList<XAiVectorDto> Vectors { get; set; } = new List<XAiVectorDto>();
        public bool IsExpired(DateTime utcNow) { return utcNow - LastAccessAtUtc >= Ttl; }
    }
}

### FILE: C:\Users\saherelm\Documents\Projects\xSaherelmWorkspace\xAiApi\Models\XAiKnowledgeModels.cs

using System;
using xAiModels.Constants;
using System.Collections.Generic;

namespace xAiApi.Models
{
    /// <summary>
    /// Describes Target Knowledge Base Scope of an Operation ...
    /// </summary>
    public class XAiKnowledgeScopeDescriptor
    {
        /// <summary>
        /// Scope Kind ...
        /// </summary>
        public XAiKnowledgeScope Scope { get; set; } = XAiKnowledgeScope.User;

        /// <summary>
        /// Scope Identifier (ProjectId / ConversationId) - Null for Global and User ...
        /// </summary>
        public Guid? ScopeId { get; set; }

        /// <summary>
        /// Optional Knowledge Type / Domain Filter ...
        /// </summary>
        public string Type { get; set; }

        /// <summary>
        /// Create User Scope Knowledge Descriptor ...
        /// </summary>
        /// <param name="type"></param>
        /// <returns></returns>
        public static XAiKnowledgeScopeDescriptor User(
            string type = null
        ) => new()
        {
            //
            Type = type ?? XAiModelsConstants.XAiDefaultKnowledgeType,
            ScopeId = null,
            Scope = XAiKnowledgeScope.User,
        };
        
        /// <summary>
        /// Create Global Scope Knowledge Descriptor ...
        /// </summary>
        /// <param name="type"></param>
        /// <returns></returns>
        public static XAiKnowledgeScopeDescriptor Global(
            string type = null
        ) => new()
        {
            Type = type ?? XAiModelsConstants.XAiDefaultKnowledgeType,
            ScopeId = null,
            Scope = XAiKnowledgeScope.Global,
        };
        
        /// <summary>
        /// Create Project Scope Knowledge Descriptor ...
        /// </summary>
        /// <param name="projectId"></param>
        /// <param name="type"></param>
        /// <returns></returns>
        public static XAiKnowledgeScopeDescriptor Project(
            Guid projectId, 
            string type = null
        ) => new()
        {
            Type = type ?? XAiModelsConstants.XAiDefaultKnowledgeType,
            ScopeId = projectId,
            Scope = XAiKnowledgeScope.Project,
        };
        
        /// <summary>
        /// Create Conversational Scope Knowledge Descriptor ...
        /// </summary>
        /// <param name="conversationId"></param>
        /// <param name="type"></param>
        /// <returns></returns>
        public static XAiKnowledgeScopeDescriptor Conversation(
            Guid conversationId, 
            string type = null
        ) => new()
        {
            Type = type ?? XAiModelsConstants.XAiDefaultKnowledgeType,
            ScopeId = conversationId,
            Scope = XAiKnowledgeScope.Conversation,
        };
    }

    /// <summary>
    /// Result of Ingesting Files into Persistent Knowledge Base (XAiVector Table) ...
    /// </summary>
    public class XAiKnowledgeIngestResult
    {
        /// <summary>
        /// Target Scope ...
        /// </summary>
        public XAiKnowledgeScope Scope { get; set; }

        /// <summary>
        /// Target Scope Identifier (Null for Global) ...
        /// </summary>
        public Guid? ScopeId { get; set; }

        /// <summary>
        /// Knowledge Type of Ingested Vectors ...
        /// </summary>
        public string Type { get; set; }

        /// <summary>
        /// Count of Successfully Ingested Files ...
        /// </summary>
        public int FilesCount { get; set; }

        /// <summary>
        /// Count of Stored Chunks (Vectors) in this Request ...
        /// </summary>
        public int ChunksCount { get; set; }

        /// <summary>
        /// Count of Removed Stale Vectors (Re-Ingest) ...
        /// </summary>
        public int ReplacedCount { get; set; }

        /// <summary>
        /// Skipped Files (Empty, Unsupported or Extraction Failed) ...
        /// </summary>
        public IList<string> SkippedFiles { get; set; } = new List<string>();

        /// <summary>
        /// Ingested Documents Info ...
        /// </summary>
        public IList<XAiKnowledgeDocumentInfo> Documents { get; set; } = new List<XAiKnowledgeDocumentInfo>();
    }

    /// <summary>
    /// Ask Request over Persistent Knowledge Base ...
    /// Retrieval is Tiered: Conversation -> Project -> User -> Global (Each Tier Fills Remaining TopK) ...
    /// </summary>
    public class XAiKnowledgeAskRequest
    {
        /// <summary>
        /// Question ...
        /// </summary>
        public string Prompt { get; set; }

        /// <summary>
        /// Optional: Conversation Scope (Caller must be Conversation Owner) ...
        /// When Provided, Conversation's Project is used for Second Tier Automatically ...
        /// </summary>
        public Guid? ConversationId { get; set; }

        /// <summary>
        /// Optional: Project Scope (Caller must be Project Owner) ...
        /// </summary>
        public Guid? ProjectId { get; set; }

        /// <summary>
        /// Include Personal (User) Knowledge Tier (default true) ...
        /// </summary>
        public bool IncludeUser { get; set; } = true;

        /// <summary>
        /// Include Global Knowledge Tier (default true) ...
        /// </summary>
        public bool IncludeGlobal { get; set; } = true;

        /// <summary>
        /// Optional: Restrict Retrieval to a Knowledge Type / Domain ...
        /// </summary>
        public string Type { get; set; }

        /// <summary>
        /// Optional: Restrict Retrieval to a Specific File Name ...
        /// </summary>
        public string FileName { get; set; }

        /// <summary>
        /// Optional: Max Retrieved Chunks ...
        /// </summary>
        public int? TopK { get; set; }

        /// <summary>
        /// Optional: Minimum Cosine Similarity Score ...
        /// </summary>
        public float? MinScore { get; set; }
    }

    /// <summary>
    /// Ingested Document Info ...
    /// </summary>
    public class XAiKnowledgeDocumentInfo
    {
        /// <summary>
        /// Scope ...
        /// </summary>
        public XAiKnowledgeScope Scope { get; set; }

        /// <summary>
        /// Scope Identifier (Null for Global) ...
        /// </summary>
        public Guid? ScopeId { get; set; }

        /// <summary>
        /// Knowledge Type ...
        /// </summary>
        public string Type { get; set; }

        /// <summary>
        /// File Name ...
        /// </summary>
        public string FileName { get; set; }

        /// <summary>
        /// Mime Type ...
        /// </summary>
        public string MimeType { get; set; }

        /// <summary>
        /// Ingesting User Identifier ...
        /// </summary>
        public string OwnerId { get; set; }

        /// <summary>
        /// Count of Stored Chunks ...
        /// </summary>
        public int ChunksCount { get; set; }

        /// <summary>
        /// Ingestion Time (UTC) ...
        /// </summary>
        public DateTime? IngestedAtUtc { get; set; }
    }

    /// <summary>
    /// Public Vector Info (Export) ...
    /// </summary>
    public class XAiKnowledgeVectorInfo
    {
        public Guid Id { get; set; }
        public string Text { get; set; }
        public string Type { get; set; }
        public Guid? ScopeId { get; set; }
        public string FileName { get; set; }
        public int? ChunkIndex { get; set; }
        public string Identifier { get; set; }
        public XAiKnowledgeScope Scope { get; set; }
        public Dictionary<string, string> Metadata { get; set; }

        /// <summary>
        /// Embedding (Only Filled when Requested) ...
        /// </summary>
        public float[] Embedding { get; set; }
    }
}


### FILE: C:\Users\saherelm\Documents\Projects\xSaherelmWorkspace\xAiApi\Models\XAiMcpServerDescriptor.cs

namespace xAiApi.Models
{
    /// <summary>
    /// Describe an Mcp Server for Seeding ...
    /// </summary>
    public class XAiMcpServerDescriptor
    {
        public string Name { get; set; }
        public string OwnerId { get; set; }
        public string Headers { get; set; }
        public string Endpoint { get; set; }
        public string Description { get; set; }
        public bool Enabled { get; set; } = true;
        public int TimeoutSeconds { get; set; } = 30;
        public string EnvironmentVariables { get; set; }
    }
}

### FILE: C:\Users\saherelm\Documents\Projects\xSaherelmWorkspace\xAiApi\Models\XAiModelProxyConfiguration.cs

namespace xAiApi.Models
{
    public class XAiModelProxyConfiguration
    {
        /// <summary>
        /// Enable Proxy or not ...
        /// </summary>
        /// <value></value>
        public bool Enabled { get; set; } = false;

        /// <summary>
        /// Proxy Prefix ...
        /// </summary>
        /// <value></value>
        public string RoutePrefix { get; set; } = "ai-model";
    }
}

### FILE: C:\Users\saherelm\Documents\Projects\xSaherelmWorkspace\xAiApi\Models\XAiOCRDescriptor.cs

using Tesseract;

namespace xAiApi.Models
{
    public class XAiOCRDescriptor
    {
        /// <summary>
        /// Provides Trained Data Path ...
        /// </summary>
        public string DataPath { get; set; }

        /// <summary>
        /// The Engine for Doing OCR ...
        /// </summary>
        public EngineMode EngineMode { get; set; }

        /// <summary>
        /// Enable OCR Fallback using Model ...
        /// </summary>
        public bool EnableOcrFallback { get; set; }

        /// <summary>
        /// Default OCR Language ...
        /// </summary>
        public string DefaultLanguage { get; set; }
    }
}

### FILE: C:\Users\saherelm\Documents\Projects\xSaherelmWorkspace\xAiApi\Models\XAiTransciptDescriptor.cs

namespace xAiApi.Models
{
    public class XAiTransciptDescriptor
    {
        public string Language { get; set; }
        public string ModelsPath { get; set; }
    }
}

### FILE: C:\Users\saherelm\Documents\Projects\xSaherelmWorkspace\xAiApi\Models\XDateTimeDescriptor.cs

namespace xAiApi.Models
{
    public class XDateTimeDescriptor
    {
        /// <summary>
        /// Adding Current DateTime to Prompt ...
        /// </summary>
        public bool InjectIntoSystemPrompt { get; set; } = true;

        /// <summary>
        /// Time Zone ...
        /// </summary>
        public string DefaultTimezone { get; set; } = "Asia/Tehran";

        /// <summary>
        /// Georgian Date Format ...
        /// </summary>
        public string GregorianFormat { get; set; } = "yyyy-MM-dd HH:mm:ss";

        /// <summary>
        /// Include Persian Calendar ...
        /// </summary>
        public bool IncludePersianCalendar { get; set; } = true;

        /// <summary>
        /// Include Day of Week ...
        /// </summary>
        public bool IncludeDayOfWeek { get; set; } = true;

        /// <summary>
        /// Include Unix Timestamp ...
        /// </summary>
        public bool IncludeUnixTimestamp { get; set; } = false;
    }
}

### FILE: C:\Users\saherelm\Documents\Projects\xSaherelmWorkspace\xAiApi\Models\XPDFToImageDescriptor.cs

namespace xAiApi.Models
{
    public class XPDFToImageDescriptor
    {
        public int Dpi { get; set; } = 300;
        public int Width { get; set; } = 0;
        public int Height { get; set; } = 0;
        public bool UseTiling { get; set; } = false;
        public bool WithFormFill { get; set; } = false;
        public bool WithAspectRatio { get; set; } = false;
        public bool WithAnnotations { get; set; } = false;
        public bool DpiRelativeToBounds { get; set; } = false;

        public int MaxImageWidth { get; set; } = 2000;
        public int MinTextLengthThreshold { get; set; } = 50;
        public int MaxPagesForImageFallback { get; set; } = 0;
    }
}

### FILE: C:\Users\saherelm\Documents\Projects\xSaherelmWorkspace\xAiApi\Models\XPreparedChatContext.cs

using xAiModels.Models.Dtos;
using Microsoft.Extensions.AI;
using System.Collections.Generic;

namespace xAiApi.Models
{
    /// <summary>
    /// a Shared Context Between Actions for Generation ... 
    /// </summary>
    public class XPreparedChatContext
    {
        /// <summary>
        /// Specified Related Project, if Exists ...
        /// </summary>
        public XAiProjectDto Project { get; set; } = null;

        /// <summary>
        /// Specified Related Conversation, if Exists ...
        /// </summary>
        public XAiConversationDto Conversation { get; set; } = null;

        /// <summary>
        /// Specified Message History, if Exists ...
        /// </summary>
        public IList<ChatMessage> History { get; set; } = [];

        /// <summary>
        /// Specified Vector Search Conext, if Exists ...
        /// </summary>
        public IList<XAiVectorSearchResult> Context { get; set; } = [];

        /// <summary>
        /// Specified Persisted Prompt, if Exists ...
        /// </summary>
        public XAiMessageDto PersistedPromptMessage { get; set; } = null;
    }
}

### FILE: C:\Users\saherelm\Documents\Projects\xSaherelmWorkspace\xAiApi\Models\XTextChunk.cs

namespace xAiApi.Models
{
    /// <summary>
    /// Represents a Chunk of a Text which Produced by Text Chunker ...
    /// </summary>
    public class XTextChunk
    {
        /// <summary>
        /// Zero Based Index of Chunk in Source Text ...
        /// </summary>
        public int Index { get; set; }

        /// <summary>
        /// Chunk Text Content ...
        /// </summary>
        public string Text { get; set; } = string.Empty;

        /// <summary>
        /// Source Name (e.g. File Name) which Chunk Extracted From ...
        /// </summary>
        public string Source { get; set; }

        /// <summary>
        /// Doc and Chunk Identifier (e.g. "file.pdf#3") ...
        /// </summary>
        public string Identifier { get; set; }

        /// <summary>
        /// Start Offset of Chunk in Normalized Source Text ...
        /// </summary>
        public int StartOffset { get; set; }

        /// <summary>
        /// Length of Chunk Text ...
        /// </summary>
        public int Length => Text?.Length ?? 0;
    }
}

### FILE: C:\Users\saherelm\Documents\Projects\xSaherelmWorkspace\xAiApi\Models\XTextChunkerDescriptor.cs

namespace xAiApi.Models
{
    /// <summary>
    /// Text Chunker Descriptor ...
    /// </summary>
    public class XTextChunkerDescriptor
    {
        /// <summary>
        /// Maximum Characters Count of each Chunk ...
        /// </summary>
        public int ChunkSize { get; set; } = 800;

        /// <summary>
        /// Characters Count which Shared between two Consecutive Chunks ...
        /// </summary>
        public int ChunkOverlap { get; set; } = 150;

        /// <summary>
        /// Chunks Smaller than this Size will be Merged into Previous Chunk ...
        /// </summary>
        public int MinChunkSize { get; set; } = 50;

        /// <summary>
        /// Chunck Identifier Separator ...
        /// </summary>
        public string ChunkIdentifierSeparator { get; set; } = "#";

        /// <summary>
        /// Normalize Line Endings and Repeated Whitespaces before Chunking ...
        /// </summary>
        public bool NormalizeWhitespace { get; set; } = true;
    }
}

### 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<XAiEmbeddingService> 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;
using OpenAI;
using System.Linq;
using OllamaSharp;
using System.Threading;
using xAiApi.Constants;
using xAiModels.Models;
using xAiApi.Extensions;
using xAiApi.Interfaces;
using xAiModels.Helpers;
using System.ClientModel;
using xCommons.Providers;
using xCommons.Extensions;
using xAiModels.Constants;
using xAiModels.Extensions;
using xAiModels.Interfaces;
using xAiApi.Configurations;
using xExceptions.Constants;
using System.Threading.Tasks;
using Microsoft.Extensions.AI;
using System.Collections.Generic;
using Microsoft.Extensions.Logging;
using xAiApi.Interfaces.Extractors;
using System.ClientModel.Primitives;

namespace xAiApi.Providers
{
    /// <summary>
    /// Base Embedding Provider Service ...
    /// </summary>
    public abstract class XAiEmbeddingServiceBase : IXAiEmbeddingServiceBase
    {
        private readonly string embeddingModelName;
        private readonly XAiModelDescriptor descriptor;
        private readonly IXAiDataProvider dataProvider;
        private readonly XAiApiConfiguration configuration;
        private readonly XValidationProvider validationProvider;
        private readonly ILogger<XAiEmbeddingServiceBase> logger;
        private readonly IXFileContentExtractor fileContentExtractor;

        protected XAiEmbeddingServiceBase(
            IXAiDataProvider dataProvider,
            XAiApiConfiguration configuration,
            XValidationProvider validationProvider,
            ILogger<XAiEmbeddingServiceBase> logger,
            IXFileContentExtractor fileContentExtractor,
            string embeddingModelName = XAiApiConstants.XAiEmbeddingModelName
        )
        {
            //
            // Prepare Embedding Model Descriptor ...
            descriptor = configuration.GetModel(embeddingModelName);
            if (!descriptor.IsValid())
            {
                XException.InvalidConfiguration.Throw();
            }

            this.dataProvider = dataProvider;
            this.configuration = configuration;
            this.validationProvider = validationProvider;

            //
            this.logger = logger;
            this.fileContentExtractor = fileContentExtractor;
            this.embeddingModelName = embeddingModelName;
        }

        /// <summary>
        /// Embedding Specified String ...
        /// </summary>
        /// <param name="content"></param>
        /// <param name="cancellationToken"></param>
        /// <returns></returns>
        public virtual async Task<float[]> Embedding(
            string content,
            CancellationToken cancellationToken = default
        )
        {
            //
            // Validate ...
            if (content.IsNullOrEmpty())
            {
                XException.InvalidArgs.Throw();
            }

            //
            var generator = GetEmbeddingGenerator();

            //
            GeneratedEmbeddings<Embedding<float>> response = null;
            response = await generator.GenerateAsync(
                values: [content],
                cancellationToken: cancellationToken
            );

            //
            if (response.IsNullOrDefault())
            {
                XException.ActionFailed.Throw();
            }

            //
            // Generae Result ...
            var result = response
                .First()?
                .Vector
                .ToArray()
               ?? [];
            if (result.Length == 0)
            {
                XException.ActionFailed.Throw();
            }

            //
            // Normalize ...
            VectorHelper.Normalize(result);

            //
            return result;
        }

        /// <summary>
        /// Embedding Specified Batch ...
        /// </summary>
        /// <param name="batch"></param>
        /// <param name="cancellationToken"></param>
        /// <returns></returns>
        public virtual async Task<IReadOnlyList<float[]>> Embeddings(
            string[] batch,
            CancellationToken cancellationToken = default
        )
        {
            //
            // Validate ...
            if (!batch.HasChild() ||
                !batch.All(x => !x.IsNullOrEmpty())
            )
            {
                XException.InvalidArgs.Throw();
            }

            //
            using var generator = GetEmbeddingGenerator();

            //
            GeneratedEmbeddings<Embedding<float>> response = null;
            response = await generator.GenerateAsync(
                values: [.. batch],
                cancellationToken: cancellationToken
            );

            //
            if (response.IsNullOrDefault())
            {
                XException.ActionFailed.Throw();
            }

            //
            var result = response
                .Select(e => e.Vector.ToArray())
                .ToList();

            //
            // Normalize ...
            foreach (var vector in result)
            {
                VectorHelper.Normalize(vector);
            }

            //
            return result;
        }

        /// <summary>
        /// Embedding Generator ...
        /// </summary>
        /// <returns></returns>
        public IEmbeddingGenerator<string, Embedding<float>> GetEmbeddingGenerator()
        {
            //
            IEmbeddingGenerator<string, Embedding<float>> result = null;

            //
            if (!descriptor.IsValid())
            {
                XException.InvalidData.Throw("Invalid Embedding Model ...");
            }

            //
            switch (descriptor.Provider)
            {
                //
                case XAiModelProviderType.OpenAI:
                    //
                    var openAiClient = new OpenAIClient(
                        new ApiKeyCredential(descriptor.ApiKey.IsNullOrEmpty() ? XAiModelsConstants.XOpenAINoKey : descriptor.ApiKey),
                        new OpenAIClientOptions
                        {
                            Endpoint = new Uri(descriptor.Url),
                            Transport = new HttpClientPipelineTransport(descriptor.Url.GetHttpClient())
                        }
                    );
                    result = openAiClient
                        .GetEmbeddingClient(descriptor.LLM)
                        .AsIEmbeddingGenerator();
                    break;

                //
                case XAiModelProviderType.Ollama:
                    //
                    var ollamaClient = new OllamaApiClient(new Uri(descriptor.Url));
                    result = ollamaClient;
                    break;
            }

            //
            if (result.IsNull())
            {
                XException.InvalidData.Throw("Invalid Embedding Model ...");
            }

            //
            return result;
        }
    }
}

### FILE: C:\Users\saherelm\Documents\Projects\xSaherelmWorkspace\xAiApi\Providers\XAiMcpServerProvider.cs

using System;
using System.Linq;
using xModels.Dtos;
using System.Threading;
using System.Text.Json;
using xAiApi.Interfaces;
using xCommons.Providers;
using xCommons.Extensions;
using xAiModels.Constants;
using xAiService.Services;
using xAiModels.Extensions;
using xAiService.Extensions;
using xExceptions.Constants;
using xAiModels.Models.Dtos;
using xIdentityModels.Models;
using System.Threading.Tasks;
using System.Linq.Expressions;
using xCommons.Configurations;
using Microsoft.Extensions.AI;
using xAiModels.Providers.Hubs;
using xAiModels.Models.Entities;
using xAiModels.Interfaces.Dtos;
using xIdentityHelper.Extensions;
using System.Collections.Generic;
using xIdentityService.Interfaces;
using Microsoft.Extensions.Logging;
using Microsoft.AspNetCore.SignalR;
using xAiModels.Interfaces.Entities;
using System.Collections.Concurrent;
using xAiModels.Interfaces.Enrichers;

namespace xAiApi.Providers
{
    /// <summary>
    /// MCP Manager / Provider ...
    /// </summary>
    public class XAiMcpServerProvider : IXAiMcpServerProvider, IAsyncDisposable
    {
        //
        private readonly XAiMcpSessionStore sessionStore;
        private readonly XAiMcpHttpTransport mcpTransport;

        //
        private readonly XAppConfiguration configuration;
        private readonly IHubContext<XAiDataProviderHub> hub;
        private readonly IXIdentityProvider identityProvider;
        private readonly ILogger<XAiMcpServerProvider> logger;
        private readonly XValidationProvider validationProvider;
        private readonly IXAiMcpServerEnricher mcpServerEnricher;
        private readonly IXAiMcpServerServiceProvider mcpServerServiceProvider;
        private readonly IXAiMcpServerRepositoryProvider mcpServerRepositoryProvider;

        //
        private readonly ConcurrentDictionary<Guid, XAiMcpServerDto> mcpServers = [];
        private readonly ConcurrentDictionary<(Guid, string), DateTime> clientExpirations = new();
        private readonly ConcurrentDictionary<(Guid ServerId, string UserId), XAiMcpClient> clients = new();
        private readonly ConcurrentDictionary<(Guid ServerId, string UserId), IList<AITool>> tools = new();

        //
        private bool isInitialized = false;
        private readonly SemaphoreSlim initLock = new(1, 1);

        public XAiMcpServerProvider(
            XAiMcpSessionStore sessionStore,
            XAppConfiguration configuration,
            XAiMcpHttpTransport mcpTransport,
            IHubContext<XAiDataProviderHub> hub,
            IXIdentityProvider identityProvider,
            ILogger<XAiMcpServerProvider> logger,
            XValidationProvider validationProvider,
            IXAiMcpServerEnricher mcpServerEnricher,
            IXAiMcpServerServiceProvider mcpServerServiceProvider,
            IXAiMcpServerRepositoryProvider mcpServerRepositoryProvider
        )
        {
            this.configuration = configuration;
            //
            this.hub = hub;
            this.logger = logger;
            this.sessionStore = sessionStore;
            this.mcpTransport = mcpTransport;
            this.identityProvider = identityProvider;
            this.mcpServerEnricher = mcpServerEnricher;
            this.validationProvider = validationProvider;
            this.mcpServerServiceProvider = mcpServerServiceProvider;
            this.mcpServerRepositoryProvider = mcpServerRepositoryProvider;
        }

        public async ValueTask DisposeAsync()
        {
            //
            foreach (var client in clients.Values)
            {
                try
                {
                    await client.DisposeAsync();
                }
                catch { }
            }
            initLock.Dispose();
        }

        //
        #region Manager ...
        /// <summary>
        /// Get a List Of Available Tools which Provided using registered Mcp Servers ...
        /// </summary>
        /// <param name="forceOwner"></param>
        /// <param name="userInfo"></param>
        /// <param name="cancellationToken"></param>
        /// <returns></returns>
        public async Task<IList<AITool>> GetAvailableToolsAsync(
            bool forceOwner = false,
            XUserClaimsInfoDto userInfo = null,
            CancellationToken cancellationToken = default
        )
        {
            //
            if (userInfo.IsNullOrDefault())
            {
                //
                logger.LogInformation("there isn't any McpServer for non authenticated user ...");
                return [];
            }

            //
            if (!userInfo.IsAdmin())
            {
                forceOwner = true;
            }

            //
            // Load Servers Metadata ...
            await EnsureServersLoadedAsync(cancellationToken);

            //
            // Extract Accessible Mcp Servers ...
            var accessibleServers = mcpServers.Values
                   .Where(s => s.OwnerId == userInfo.UserId ||
                               s.Scope == XAiMcpServerUsageScope.All)
                   .ToList();

            //
            // Create User Speciic Client Connection ...
            foreach (var server in accessibleServers)
            {
                //
                // Create User Specific Client Key ...
                var key = (server.Id, userInfo.UserId);

                //
                // Check Expiration ...
                if (clients.ContainsKey(key) &&
                    clientExpirations.TryGetValue(key, out var exp) &&
                    exp < DateTime.UtcNow)
                {
                    //
                    // Remove Expired Client and Tools ...
                    if (clients.TryRemove(key, out var old))
                    {
                        //
                        try
                        {
                            await old.DisposeAsync();
                        }
                        catch { }
                    }

                    //
                    tools.TryRemove(key, out _);
                    clientExpirations.TryRemove(key, out _);
                }

                //
                if (clients.ContainsKey(key))
                {
                    continue;
                }

                //
                await initLock.WaitAsync(cancellationToken);
                try
                {
                    //
                    if (!clients.ContainsKey(key))
                    {
                        //
                        await ConnectAndValidateAsync(
                            descriptor: server,
                            userInfo: userInfo,
                            cancellationToken: cancellationToken
                        );
                    }
                }
                finally
                {
                    initLock.Release();
                }
            }

            //
            // Extract User Specified Mcp Client Tools ...
            var result = tools
                .Where(kv => kv.Key.UserId == userInfo.UserId)
                .SelectMany(kv => kv.Value)
                .ToList();

            //
            return result;
        }

        /// <summary>
        /// Test Specified Mcp Server ...
        /// </summary>
        /// <param name="server"></param>
        /// <param name="connectionId"></param>
        /// <param name="userInfo"></param>
        /// <param name="cancellationToken"></param>
        /// <returns></returns>
        public async Task<string> TestServerAsync(
            XAiMcpServerDto server,
            string connectionId = null,
            XUserClaimsInfoDto userInfo = null,
            CancellationToken cancellationToken = default
        )
        {
            //
            try
            {
                //
                using var cts = CancellationTokenSource.CreateLinkedTokenSource(cancellationToken);
                cts.CancelAfter(TimeSpan.FromSeconds(server.TimeoutSeconds));

                //
                var client = CreateClientAsync(server, connectionId, userInfo);
                // await client.PingAsync(cancellationToken: cts.Token);
                var serverTools = await client.ListToolsAsync(cancellationToken: cts.Token);

                //
                var names = string.Join(", ", serverTools.Select(t => t.Name));
                return $"✓ Server: '{server.Name}' is Ready to Use, {serverTools.Count} Tools: {names}";
            }
            catch (Exception ex)
            {
                //
                return $"✗ Error: {ex.Message} ...";
            }
        }

        /// <summary>
        /// Force Refresh Mcp Servers ...
        /// </summary>
        /// <param name="userInfo"></param>
        /// <param name="cancellationToken"></param>
        /// <returns></returns>
        public async Task RefreshAsync(
            XUserClaimsInfoDto userInfo = null,
            CancellationToken cancellationToken = default
        )
        {
            //
            if (!userInfo.IsAdmin())
            {
                XException.NotAllowed.Throw();
            }

            //
            logger.LogInformation("MCP: Reinitialize Mcp Servers ...");
            foreach (var client in clients.Values)
            {
                try
                {
                    await client.DisposeAsync();
                }
                catch { }
            }
            tools.Clear();
            clients.Clear();
            mcpServers.Clear();

            //
            isInitialized = false;
            await GetAvailableToolsAsync(
                userInfo: userInfo,
                cancellationToken: cancellationToken
            );
        }
        #endregion

        //
        #region Actions ...
        /// <summary>
        /// Add an Mcp Server ...
        /// </summary>
        /// <param name="item"></param>
        /// <param name="connectionId"></param>
        /// <param name="userInfo"></param>
        /// <param name="cancellationToken"></param>
        /// <returns></returns>
        public async Task<XAiMcpServerDto> AddMcpServer(
            XAiMcpServerDto item,
            string connectionId = null,
            XUserClaimsInfoDto userInfo = null,
            CancellationToken cancellationToken = default
        )
        {
            //
            // Validation ...
            validationProvider
                .GroupValidationBuilder()
                .AddNotNull(item)
                .AddNotNull(userInfo)
                .AddUrl(item.Endpoint)
                .AddNotEmpty(item.Endpoint)
                .AddNotEmpty(userInfo.UserId)
                .ValidateGroup();

            //
            // Normalize Scope ...
            if (!userInfo.IsAdmin())
            {
                item.Scope = XAiMcpServerUsageScope.Owner;
            }
            item.OwnerId = userInfo.UserId;
            item.CreatedOn = DateTime.UtcNow;

            //
            // Normalizing Timeout ...
            if (item.TimeoutSeconds < XAiModelsConstants.XAiMcpServerMinTimeoutSeconds)
            {
                item.TimeoutSeconds = XAiModelsConstants.XAiMcpServerMinTimeoutSeconds;
            }

            //
            // Validate for Add ...
            if (!item.IsValidForAddOrUpdate())
            {
                XException.InvalidArgs.Throw();
            }

            //
            var result = await mcpServerServiceProvider
                .AddAsync(
                    item: item,
                    saveChanges: true,
                    connectionId: connectionId,
                    cancellationToken: cancellationToken
                );

            //
            if (!result.IsNullOrDefault())
            {
                //
                // Handle Enrichment ...
                result = await mcpServerEnricher.Enrich(
                    source: result,
                    cancellationToken: cancellationToken
                );

                //
                // Sending Push ...
                await SendPush(
                    connectionId: connectionId,
                    cancellationToken: cancellationToken,
                    payLoad: result.ToJSON(camelCase: true),
                    action: XAiDataProviderHubActions.McpServerCreated.GetStringValue()
                );

                //
                await initLock.WaitAsync(cancellationToken);
                try
                {
                    //
                    mcpServers[result.Id] = result;
                    await ConnectAndValidateAsync(result, connectionId, userInfo);
                }
                finally
                {
                    initLock.Release();
                }
            }

            //
            return result;
        }

        /// <summary>
        /// Get an Mcp Server ...
        /// </summary>
        /// <param name="id"></param>
        /// <param name="userInfo"></param>
        /// <param name="cancellationToken"></param>
        /// <returns></returns>
        public async Task<XAiMcpServerDto> GetMcpServer(
            Guid id,
            XUserClaimsInfoDto userInfo = null,
            CancellationToken cancellationToken = default
        )
        {
            //
            // Validation ...
            validationProvider
                .GroupValidationBuilder()
                .AddIsGuid(id)
                .AddNotNull(userInfo)
                .AddNotEmpty(userInfo.UserId)
                .ValidateGroup();

            //
            var result = await mcpServerServiceProvider
                .GetAsync(
                    id: id,
                    includeBuilder: null,
                    ignoreSoftDeleteds: true,
                    cancellationToken: cancellationToken
                );

            //
            // Validate Ownership ...
            if (!userInfo.IsAdmin() && result.OwnerId != userInfo.UserId)
            {
                XException.NotAllowed.Throw();
            }

            //
            if (!result.IsNullOrDefault())
            {
                //
                // Handle Enrichment ...
                result = await mcpServerEnricher.Enrich(
                    source: result,
                    cancellationToken: cancellationToken
                );
            }

            //
            return result;
        }

        /// <summary>
        /// Update Specified Mcp Server ...
        /// </summary>
        /// <param name="id"></param>
        /// <param name="item"></param>
        /// <param name="connectionId"></param>
        /// <param name="userInfo"></param>
        /// <param name="cancellationToken"></param>
        /// <returns></returns>
        public async Task<XAiMcpServerDto> UpdateMcpServer(
            Guid id,
            XAiMcpServerDto item,
            string connectionId = null,
            XUserClaimsInfoDto userInfo = null,
            CancellationToken cancellationToken = default
        )
        {
            //
            // Validation ...
            validationProvider
                .GroupValidationBuilder()
                .AddIsGuid(id)
                .AddNotNull(item)
                .AddIsGuid(item.Id)
                .AddNotNull(userInfo)
                .AddUrl(item.Endpoint)
                .AddNotNull(item.CreatedOn)
                .AddNotEmpty(item.Endpoint)
                .AddNotEmpty(userInfo.UserId)
                .ValidateGroup();

            //
            // Normalize Scope ...
            if (!userInfo.IsAdmin())
            {
                item.Scope = XAiMcpServerUsageScope.Owner;
            }
            item.UpdatedAt = DateTime.UtcNow;

            //
            // Validate Ownership ...
            if (!userInfo.IsAdmin() &&
                userInfo.UserId != item.OwnerId)
            {
                XException.NotAllowed.Throw();
            }

            //
            // Normalizing Timeout ...
            if (item.TimeoutSeconds < XAiModelsConstants.XAiMcpServerMinTimeoutSeconds)
            {
                item.TimeoutSeconds = XAiModelsConstants.XAiMcpServerMinTimeoutSeconds;
            }

            //
            // Validate for Add ...
            if (!item.IsValidForAddOrUpdate())
            {
                XException.InvalidArgs.Throw();
            }

            //
            var result = await mcpServerServiceProvider
                .UpdateAsync(
                    id: id,
                    item: item,
                    saveChanges: true,
                    connectionId: connectionId,
                    cancellationToken: cancellationToken
                );

            //
            if (!result.IsNullOrDefault())
            {
                //
                // Handle Enrichment ...
                result = await mcpServerEnricher.Enrich(
                    source: result,
                    cancellationToken: cancellationToken
                );

                //
                // Sending Push ...
                await SendPush(
                    connectionId: connectionId,
                    cancellationToken: cancellationToken,
                    payLoad: result.ToJSON(camelCase: true),
                    action: XAiDataProviderHubActions.McpServerUpdated.GetStringValue()
                );

                //
                await initLock.WaitAsync(cancellationToken);
                try
                {
                    //
                    mcpServers[result.Id] = result;

                    //
                    // Remove Exists ...
                    var keysToRemove = clients.Keys
                        .Where(k => k.ServerId == result.Id)
                        .ToList();
                    foreach (var key in keysToRemove)
                    {
                        //
                        if (clients.TryRemove(key, out var old))
                        {
                            try
                            {
                                await old.DisposeAsync();
                            }
                            catch { }
                        }
                        tools.TryRemove(key, out _);
                    }

                    //
                    // Reconnect ...
                    await ConnectAndValidateAsync(result, connectionId, userInfo, cancellationToken);
                }
                finally
                {
                    initLock.Release();
                }
            }

            //
            return result;
        }

        /// <summary>
        /// Remove Specified Mcp Server ...
        /// </summary>
        /// <param name="id"></param>
        /// <param name="connectionId"></param>
        /// <param name="userInfo"></param>
        /// <param name="cancellationToken"></param>
        /// <returns></returns>
        public async Task<XAiMcpServerDto> RemoveMcpServer(
            Guid id,
            string connectionId = null,
            XUserClaimsInfoDto userInfo = null,
            CancellationToken cancellationToken = default
        )
        {
            //
            // Validate ...
            validationProvider
                .GroupValidationBuilder()
                .AddIsGuid(id)
                .AddNotNull(userInfo)
                .AddNotEmpty(userInfo.UserId)
                .ValidateGroup();

            //
            // Check McpServer Exists ...
            var exists = await mcpServerServiceProvider.GetAsync(
                id: id,
                includeBuilder: null,
                ignoreSoftDeleteds: true,
                cancellationToken: cancellationToken
            );
            if (exists.IsNullOrDefault())
            {
                XException.NotFound.Throw();
            }

            //
            // Validate Ownership ...
            if (!userInfo.IsAdmin() &&
                userInfo.UserId != exists.OwnerId)
            {
                XException.NotAllowed.Throw();
            }

            //
            var result = await mcpServerServiceProvider.RemoveAsync(
                id: id,
                softDelete: true,
                saveChanges: true,
                connectionId: connectionId,
                cancellationToken: cancellationToken
            );

            //
            if (!result.IsNullOrDefault())
            {
                //
                // Handle Enrichment ...
                result = await mcpServerEnricher.Enrich(
                    source: result,
                    cancellationToken: cancellationToken
                );

                //
                // Sending Push ...
                await SendPush(
                    connectionId: connectionId,
                    cancellationToken: cancellationToken,
                    payLoad: result.ToJSON(camelCase: true),
                    action: XAiDataProviderHubActions.McpServerRemoved.GetStringValue()
                );

                //
                await initLock.WaitAsync(cancellationToken);
                try
                {
                    //
                    // Remove Server Descriptor ...
                    mcpServers.TryRemove(result.Id, out _);

                    //
                    // Disconnect all Connections ...
                    var keysToRemove = clients.Keys
                        .Where(k => k.ServerId == result.Id)
                        .ToList();
                    foreach (var key in keysToRemove)
                    {
                        //
                        if (clients.TryRemove(key, out var c))
                        {
                            //
                            try
                            {
                                await c.DisposeAsync();
                            }
                            catch { }
                        }

                        //
                        tools.TryRemove(key, out _);
                    }
                }
                finally
                {
                    initLock.Release();
                }
            }

            //
            return result;
        }

        /// <summary>
        /// Disable Specified Mcp Server ...
        /// </summary>
        /// <param name="id"></param>
        /// <param name="connectionId"></param>
        /// <param name="userInfo"></param>
        /// <param name="cancellationToken"></param>
        /// <returns></returns>
        public async Task<bool> DisableMcpServer(
            Guid id,
            string connectionId = null,
            XUserClaimsInfoDto userInfo = null,
            CancellationToken cancellationToken = default
        )
        {
            //
            // Validate ...
            validationProvider
                .GroupValidationBuilder()
                .AddIsGuid(id)
                .AddNotNull(userInfo)
                .AddNotEmpty(userInfo.UserId)
                .ValidateGroup();

            //
            // Check McpServer Exists ...
            var exists = await mcpServerServiceProvider.GetAsync(
                id: id,
                includeBuilder: null,
                ignoreSoftDeleteds: true,
                cancellationToken: cancellationToken
            );
            if (exists.IsNullOrDefault())
            {
                XException.NotFound.Throw();
            }

            //
            // Validate Ownership ...
            if (!userInfo.IsAdmin() &&
                userInfo.UserId != exists.OwnerId)
            {
                XException.NotAllowed.Throw();
            }

            //
            if (!exists.Enabled)
            {
                return false;
            }
            exists.Enabled = false;

            //
            exists = await mcpServerServiceProvider.UpdateAsync(
                id: id,
                item: exists,
                saveChanges: true,
                connectionId: connectionId,
                cancellationToken: cancellationToken
            );
            var result = !exists.IsNullOrDefault() && !exists.Enabled;

            //
            if (result)
            {
                //
                // Sending Push ...
                await SendPush(
                    connectionId: connectionId,
                    cancellationToken: cancellationToken,
                    payLoad: exists.ToJSON(camelCase: true),
                    action: XAiDataProviderHubActions.McpServerUpdated.GetStringValue()
                );

                //
                await initLock.WaitAsync(cancellationToken);
                try
                {
                    //
                    // Remove Server Descriptor ...
                    mcpServers.TryRemove(exists.Id, out _);

                    //
                    // Disconnect all Connections ...
                    var keysToRemove = clients.Keys
                        .Where(k => k.ServerId == exists.Id)
                        .ToList();
                    foreach (var key in keysToRemove)
                    {
                        //
                        if (clients.TryRemove(key, out var c))
                        {
                            //
                            try
                            {
                                await c.DisposeAsync();
                            }
                            catch { }
                        }

                        //
                        tools.TryRemove(key, out _);
                    }
                }
                finally
                {
                    initLock.Release();
                }
            }

            //
            return result;
        }

        /// <summary>
        /// Enable Specified Mcp Server ...
        /// </summary>
        /// <param name="id"></param>
        /// <param name="connectionId"></param>
        /// <param name="userInfo"></param>
        /// <param name="cancellationToken"></param>
        /// <returns></returns>
        public async Task<bool> EnableMcpServer(
            Guid id,
            string connectionId = null,
            XUserClaimsInfoDto userInfo = null,
            CancellationToken cancellationToken = default
        )
        {
            //
            // Validate ...
            validationProvider
                .GroupValidationBuilder()
                .AddIsGuid(id)
                .AddNotNull(userInfo)
                .AddNotEmpty(userInfo.UserId)
                .ValidateGroup();

            //
            // Check McpServer Exists ...
            var exists = await mcpServerServiceProvider.GetAsync(
                id: id,
                includeBuilder: null,
                ignoreSoftDeleteds: true,
                cancellationToken: cancellationToken
            );
            if (exists.IsNullOrDefault())
            {
                XException.NotFound.Throw();
            }

            //
            // Validate Ownership ...
            if (!userInfo.IsAdmin() &&
                userInfo.UserId != exists.OwnerId)
            {
                XException.NotAllowed.Throw();
            }

            //
            if (exists.Enabled)
            {
                return false;
            }
            exists.Enabled = true;

            //
            exists = await mcpServerServiceProvider.UpdateAsync(
                id: id,
                item: exists,
                saveChanges: true,
                connectionId: connectionId,
                cancellationToken: cancellationToken
            );
            var result = !exists.IsNullOrDefault() && exists.Enabled;

            //
            if (result)
            {
                //
                // Sending Push ...
                await SendPush(
                    connectionId: connectionId,
                    cancellationToken: cancellationToken,
                    payLoad: exists.ToJSON(camelCase: true),
                    action: XAiDataProviderHubActions.McpServerUpdated.GetStringValue()
                );

                //
                await initLock.WaitAsync(cancellationToken);
                try
                {
                    //
                    mcpServers[exists.Id] = exists;
                    await ConnectAndValidateAsync(exists, connectionId, userInfo, cancellationToken);
                }
                finally
                {
                    initLock.Release();
                }
            }

            //
            return result;
        }

        /// <summary>
        /// Toggle Specified Mcp Server ...
        /// </summary>
        /// <param name="id"></param>
        /// <param name="connectionId"></param>
        /// <param name="userInfo"></param>
        /// <param name="cancellationToken"></param>
        /// <returns></returns>
        public async Task<bool> ToggleMcpServer(
            Guid id,
            string connectionId = null,
            XUserClaimsInfoDto userInfo = null,
            CancellationToken cancellationToken = default
        )
        {
            //
            // Validate ...
            validationProvider
                .GroupValidationBuilder()
                .AddIsGuid(id)
                .AddNotNull(userInfo)
                .AddNotEmpty(userInfo.UserId)
                .ValidateGroup();

            //
            // Check McpServer Exists ...
            var exists = await mcpServerServiceProvider.GetAsync(
                id: id,
                includeBuilder: null,
                ignoreSoftDeleteds: true,
                cancellationToken: cancellationToken
            );
            if (exists.IsNullOrDefault())
            {
                XException.NotFound.Throw();
            }

            //
            // Validate Ownership ...
            if (!userInfo.IsAdmin() &&
                userInfo.UserId != exists.OwnerId)
            {
                XException.NotAllowed.Throw();
            }

            //
            exists.Enabled = !exists.Enabled;

            //
            exists = await mcpServerServiceProvider.UpdateAsync(
                id: id,
                item: exists,
                saveChanges: true,
                connectionId: connectionId,
                cancellationToken: cancellationToken
            );
            var result = !exists.IsNullOrDefault();

            //
            if (result)
            {
                //
                // Sending Push ...
                await SendPush(
                    connectionId: connectionId,
                    cancellationToken: cancellationToken,
                    payLoad: exists.ToJSON(camelCase: true),
                    action: XAiDataProviderHubActions.McpServerUpdated.GetStringValue()
                );

                //
                await initLock.WaitAsync(cancellationToken);
                try
                {
                    //
                    if (exists.Enabled)
                    {
                        //
                        mcpServers[exists.Id] = exists;
                        await ConnectAndValidateAsync(exists, connectionId, userInfo, cancellationToken);
                    }
                    else
                    {
                        //
                        // Remove Server Descriptor ...
                        mcpServers.TryRemove(exists.Id, out _);

                        //
                        // Disconnect all Connections ...
                        var keysToRemove = clients.Keys
                            .Where(k => k.ServerId == exists.Id)
                            .ToList();
                        foreach (var key in keysToRemove)
                        {
                            //
                            if (clients.TryRemove(key, out var c))
                            {
                                //
                                try
                                {
                                    await c.DisposeAsync();
                                }
                                catch { }
                            }

                            //
                            tools.TryRemove(key, out _);
                        }
                    }
                }
                finally
                {
                    initLock.Release();
                }
            }

            //
            return result;
        }

        /// <summary>
        /// Retrieve all Mcp Server ...
        /// </summary>
        /// <param name="forceOwner"></param>
        /// <param name="userInfo"></param>
        /// <param name="cancellationToken"></param>
        /// <returns></returns>
        public async Task<IEnumerable<XAiMcpServerDto>> GetAll(
            bool forceOwner = false,
            XUserClaimsInfoDto userInfo = null,
            CancellationToken cancellationToken = default
        )
        {
            //
            // Validate ...
            validationProvider
                .GroupValidationBuilder()
                .AddNotNull(userInfo)
                .AddNotEmpty(userInfo.UserId)
                .ValidateGroup();

            //
            if (!userInfo.IsAdmin())
            {
                forceOwner = true;
            }

            //
            var result = Enumerable.Empty<XAiMcpServerDto>();
            Func<IQueryable<XAiMcpServer>, IOrderedQueryable<XAiMcpServer>> orderBuilder = x => x.OrderByDescending(y => y.CreatedOn);
            if (forceOwner)
            {
                //
                result = await mcpServerServiceProvider
                    .FindManyAsync(
                        predicate: x =>
                            x.OwnerId
                                .Equals(
                                    userInfo.UserId,
                                    StringComparison.InvariantCultureIgnoreCase
                                ),
                        includeBuilder: null,
                        ignoreSoftDeleteds: true,
                        orderBuilder: orderBuilder,
                        cancellationToken: cancellationToken
                    );
            }
            else
            {
                //
                result = await mcpServerServiceProvider
                    .GetAllAsync(
                        includeBuilder: null,
                        ignoreSoftDeleteds: true,
                        orderBuilder: orderBuilder,
                        cancellationToken: cancellationToken
                    );
            }

            //
            if (result.HasChild())
            {
                //
                // Handle Enrichment ...
                result = await mcpServerEnricher.EnrichRange(
                    sources: result,
                    cancellationToken: cancellationToken
                );
            }

            //
            return result;
        }

        /// <summary>
        /// Find Specified Mcp Server ...
        /// </summary>
        /// <param name="predicate"></param>
        /// <param name="forceOwner"></param>
        /// <param name="userInfo"></param>
        /// <param name="cancellationToken"></param>
        /// <returns></returns>
        public async Task<XAiMcpServerDto> FindOne(
            Expression<Func<XAiMcpServer, bool>> predicate,
            bool forceOwner = false,
            XUserClaimsInfoDto userInfo = null,
            CancellationToken cancellationToken = default
        )
        {
            //
            // Validate ...
            validationProvider
                .GroupValidationBuilder()
                .AddNotNull(userInfo)
                .AddNotEmpty(userInfo.UserId)
                .ValidateGroup();

            //
            if (!userInfo.IsAdmin())
            {
                forceOwner = true;
            }

            //
            Expression<Func<XAiMcpServer, bool>> predicator = null;
            if (forceOwner)
            {
                //
                predicator = x =>
                    predicate.Compile()(x) &&
                    x.OwnerId
                        .Equals(
                            userInfo.UserId,
                            StringComparison.InvariantCultureIgnoreCase
                        );
            }
            else
            {
                //
                predicator = x => predicate.Compile()(x);
            }

            //
            var result = await mcpServerServiceProvider.FindOneAsync(
                includeBuilder: null,
                predicate: predicator,
                ignoreSoftDeleteds: true,
                cancellationToken: cancellationToken
            );

            //
            if (!result.IsNullOrDefault())
            {
                //
                // Handle Enrichment ...
                result = await mcpServerEnricher.Enrich(
                    source: result,
                    cancellationToken: cancellationToken
                );
            }

            //
            return result;
        }

        /// <summary>
        /// Find a Collection of Specified Mcp Servers ...
        /// </summary>
        /// <param name="predicate"></param>
        /// <param name="forceOwner"></param>
        /// <param name="userInfo"></param>
        /// <param name="cancellationToken"></param>
        /// <returns></returns>
        public async Task<IEnumerable<XAiMcpServerDto>> FindMany(
            Expression<Func<XAiMcpServer, bool>> predicate,
            bool forceOwner = false,
            XUserClaimsInfoDto userInfo = null,
            CancellationToken cancellationToken = default
        )
        {
            //
            // Validate ...
            validationProvider
                .GroupValidationBuilder()
                .AddNotNull(userInfo)
                .AddNotEmpty(userInfo.UserId)
                .ValidateGroup();

            //
            if (!userInfo.IsAdmin())
            {
                forceOwner = true;
            }

            //
            Expression<Func<XAiMcpServer, bool>> predicator = null;
            if (forceOwner)
            {
                //
                predicator = x =>
                    predicate.Compile()(x) &&
                    x.OwnerId
                        .Equals(
                            userInfo.UserId,
                            StringComparison.InvariantCultureIgnoreCase
                        );
            }
            else
            {
                //
                predicator = x => predicate.Compile()(x);
            }

            //
            var result = await mcpServerServiceProvider.FindManyAsync(
                includeBuilder: null,
                predicate: predicator,
                ignoreSoftDeleteds: true,
                cancellationToken: cancellationToken,
                orderBuilder: x => x.OrderByDescending(y => y.CreatedOn)
            );

            //
            if (result.HasChild())
            {
                //
                // Handle Enrichment ...
                result = await mcpServerEnricher.EnrichRange(
                    sources: result,
                    cancellationToken: cancellationToken
                );
            }

            //
            return result;
        }

        /// <summary>
        /// Query Registered Mcp Servers ...
        /// </summary>
        /// <param name="query"></param>
        /// <param name="forceOwner"></param>
        /// <param name="userInfo"></param>
        /// <param name="cancellationToken"></param>
        /// <returns></returns>
        public async Task<XQueryResult<XAiMcpServerDto>> Query(
            XQuery query,
            bool forceOwner = false,
            XUserClaimsInfoDto userInfo = null,
            CancellationToken cancellationToken = default
        )
        {
            //
            // Validate ...
            validationProvider
                .GroupValidationBuilder()
                .AddNotNull(userInfo)
                .AddNotEmpty(userInfo.UserId)
                .ValidateGroup();

            //
            if (!userInfo.IsAdmin())
            {
                forceOwner = true;
            }

            //
            Expression<Func<XAiMcpServer, bool>> predicator = null;
            if (forceOwner)
            {
                //
                predicator = x =>
                    x.OwnerId
                        .Equals(
                            userInfo.UserId,
                            StringComparison.InvariantCultureIgnoreCase
                        );
            }

            //
            var result = await mcpServerServiceProvider.QueryAsync(
                query: query,
                includeBuilder: null,
                predicate: predicator,
                ignoreSoftDeleteds: true,
                cancellationToken: cancellationToken,
                orderBuilder: x => x.OrderByDescending(y => y.CreatedOn)
            );

            //
            if (!result.IsNullOrDefault() && result.Items.HasChild())
            {
                //
                // Handle Enrichment ...
                result.Items = await mcpServerEnricher.EnrichRange(
                    sources: result.Items,
                    cancellationToken: cancellationToken
                );
            }

            //
            return result;
        }
        #endregion

        //
        #region Private ...
        private static Dictionary<string, string> ParseJsonDict(string json)
            => json.IsNullOrEmpty() ? null
                : JsonSerializer.Deserialize<Dictionary<string, string>>(json);

        private static List<string> ParseJsonList(string json)
            => json.IsNullOrEmpty() ? null
                : JsonSerializer.Deserialize<List<string>>(json);

        private XAiMcpClient CreateClientAsync(
            XAiMcpServerDto descriptor,
            string connectionId = null,
            XUserClaimsInfoDto userInfo = null
        )
        {
            //
            var result = new XAiMcpClient(
                logger: logger,
                userInfo: userInfo,
                transport: mcpTransport,
                serverId: descriptor.Id,
                sessionStore: sessionStore,
                connectionId: connectionId,
                appConfiguration: configuration,
                endpoint: new Uri(descriptor.Endpoint)
            );

            //
            return result;
        }

        private async Task ConnectAndValidateAsync(
            XAiMcpServerDto descriptor,
            string connectionId = null,
            XUserClaimsInfoDto userInfo = null,
            CancellationToken cancellationToken = default
        )
        {
            //
            try
            {
                //
                // Create Specified Cancellation Token ...
                using var cts = CancellationTokenSource
                    .CreateLinkedTokenSource(cancellationToken);
                cts.CancelAfter(TimeSpan.FromSeconds(descriptor.TimeoutSeconds));

                //
                var client = CreateClientAsync(
                    userInfo: userInfo, 
                    descriptor: descriptor, 
                    connectionId: connectionId
                );

                //
                await client.InitializeAsync(cts.Token);

                //
                var clientTools = await client.ListToolsAsync(cts.Token);
                var aiTools = clientTools.ToAITools(client);

                //
                // Key for Cache ...
                var key = (descriptor.Id, userInfo.UserId);

                //
                tools[key] = aiTools;
                clients[key] = client;
                mcpServers[descriptor.Id] = descriptor;
                clientExpirations[key] = DateTime.UtcNow.AddMinutes(15);

                //
                logger.LogInformation(
                    "MCP '{Name}': {Count} Tools Detected for {UserId} ...",
                    descriptor.Name,
                    aiTools.Count,
                    userInfo.UserId
                );
            } catch(Exception ex)
            {
                //
                logger.LogWarning(ex,
                    "MCP '{Name}': Connection Established Failed, Ignored ...",
                    descriptor.Name
                );                
            }
        }

        private async Task EnsureServersLoadedAsync(CancellationToken cancellationToken)
        {
            //
            if (isInitialized)
            {
                return;
            }

            //
            await initLock.WaitAsync(cancellationToken);
            try
            {
                //
                if (isInitialized)
                {
                    return;
                }

                //
                var servers = await mcpServerServiceProvider.FindManyAsync(
                    orderBuilder: null,
                    includeBuilder: null,
                    ignoreSoftDeleteds: true,
                    predicate: x => x.Enabled,
                    cancellationToken: cancellationToken
                );

                //
                if (servers.HasChild())
                {
                    //
                    foreach (var s in servers)
                    {
                        //
                        mcpServers[s.Id] = s;
                    }
                }

                //
                isInitialized = true;
            }
            finally
            {
                initLock.Release();
            }
        }
        #endregion

        //
        #region Hub Actions ...
        /// <summary>
        /// Send Custom Push Message ...
        /// </summary>
        /// <param name="action"></param>
        /// <param name="payLoad"></param>
        /// <param name="connectionId"></param>
        /// <param name="cancellationToken"></param>
        /// <returns></returns>
        public async Task SendPush(
            string action,
            string payLoad,
            string connectionId = null,
            CancellationToken cancellationToken = default
        )
        {
            //
            try
            {
                //
                // Collect Allowed Actions ...
                var actions = new List<string>
                {
                    XAiDataProviderHubActions.McpServerCreated.GetStringValue(),
                    XAiDataProviderHubActions.McpServerUpdated.GetStringValue(),
                    XAiDataProviderHubActions.McpServerRemoved.GetStringValue(),
                };

                //
                // Validate Args ...
                var isValid =
                    !action.IsNullOrEmpty() &&
                    actions.Contains(action);
                if (!isValid)
                {
                    return;
                }

                //
                // Retrieve Connection Id ...
                var clients = hub.Clients.All;
                if (!connectionId.IsNullOrEmpty())
                {
                    clients = hub.Clients.AllExcept(connectionId);
                }

                //
                await clients.SendAsync(
                    action,
                    payLoad,
                    connectionId,
                    cancellationToken
                );
            }
            catch { }
        }
        #endregion            
    }
}

### FILE: C:\Users\saherelm\Documents\Projects\xSaherelmWorkspace\xAiApi\Providers\XAiRAGService.cs

using System;
using System.IO;
using System.Linq;
using xAiApi.Models;
using xIdentityHelper;
using System.Threading;
using xAiApi.Interfaces;
using xAiModels.Constants;
using xCommons.Extensions;
using xAiModels.Interfaces;
using xAiApi.Configurations;
using xExceptions.Constants;
using xAiModels.Models.Dtos;
using System.Threading.Tasks;
using xIdentityModels.Models;
using xFileService.Interfaces;
using Microsoft.AspNetCore.Http;
using System.Collections.Generic;
using Microsoft.Extensions.Logging;
using xAiApi.Interfaces.Extractors;
using xFileService.Models.Dtos;

namespace xAiApi.Providers
{
    /// <summary>
    /// Persistent RAG Service over XAiVector Table ...
    /// Isolation (Identifier Layout):
    ///   Conversation: "conversation/{conversationId}/{fileName}#{i}"
    ///   Project     : "project/{projectId}/{fileName}#{i}"
    ///   User        : "user/{ownerId}/{fileName}#{i}"
    ///   Global      : "global/{fileName}#{i}"
    /// Retrieval is Tiered: Conversation -> Project -> User -> Global ...
    /// </summary>
    public class XAiRAGService : IXAiRAGService
    {
        private readonly IXTextChunker textChunker;
        private readonly IXFileProvider fileProvider;
        private readonly IXAiDataProvider dataProvider;
        private readonly ILogger<XAiRAGService> logger;
        private readonly XAiApiConfiguration configuration;
        private readonly IXAiEmbeddingService embeddingService;
        private readonly IXFileContentExtractor fileContentExtractor;

        /// <summary>
        /// Characters which are not Allowed in File Name Part of Identifier ...
        /// </summary>
        private static readonly char[] UnsafeFileNameChars = ['/', '\\', '#'];

        public XAiRAGService(
            IXTextChunker textChunker,
            IXFileProvider fileProvider,
            IXAiDataProvider dataProvider,
            ILogger<XAiRAGService> logger,
            XAiApiConfiguration configuration,
            IXAiEmbeddingService embeddingService,
            IXFileContentExtractor fileContentExtractor
        )
        {
            //
            this.logger = logger;
            this.textChunker = textChunker;
            this.fileProvider = fileProvider;
            this.dataProvider = dataProvider;
            this.configuration = configuration;
            this.embeddingService = embeddingService;
            this.fileContentExtractor = fileContentExtractor;
        }

        //
        #region Ingest ...
        /// <summary>
        /// Ingest Files into Specified Knowledge Scope:
        /// Extract -> Chunk -> Embed -> Store (XAiVector) ...
        /// </summary>
        /// <param name="files"></param>
        /// <param name="scope"></param>
        /// <param name="userInfo"></param>
        /// <param name="connectionId"></param>
        /// <param name="replaceExisting"></param>
        /// <param name="cancellationToken"></param>
        /// <returns></returns>
        public async Task<XAiKnowledgeIngestResult> IngestAsync(
            IFormFileCollection files,
            XAiKnowledgeScopeDescriptor scope = null,
            XUserClaimsInfoDto userInfo = null,
            string connectionId = null,
            bool replaceExisting = true,
            CancellationToken cancellationToken = default
        )
        {
            //
            // Validate ...
            if (!files.HasChild() || !IsValidUser(userInfo))
            {
                XException.InvalidArgs.Throw();
            }

            //
            var rag = configuration.RAGDescriptor;
            if (rag.MaxFilesPerIngest > 0 && files.Count > rag.MaxFilesPerIngest)
            {
                XException.InvalidArgs.Throw();
            }

            //
            // Resolve & Authorize Scope (Write) ...
            scope = NormalizeScope(scope);
            await EnsureAccess(scope, userInfo, isWrite: true, cancellationToken);

            //
            var knowledgeType = scope.Type.IsNullOrEmpty()
                ? XAiModelsConstants.XAiDefaultKnowledgeType
                : scope.Type;
            var scopePrefix = GetScopePrefix(scope, userInfo);

            //
            var result = new XAiKnowledgeIngestResult
            {
                Type = knowledgeType,
                Scope = scope.Scope,
                ScopeId = scope.ScopeId,
            };
            var ingestedAt = DateTime.UtcNow;
            var ingestedAtUtc = ingestedAt.ToString("O");

            //
            // Existing Documents (for MaxDocumentsPerScope Limit) ...
            var existingDocuments = await LoadDocumentNames(scopePrefix, cancellationToken);

            //
            // Loop through Files ...
            foreach (var file in files)
            {
                //
                XFileDto uploadedFile = null;

                //
                try
                {
                    //
                    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,
                        connectionId: connectionId,
                        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
                    );
                }
                catch (Exception ex)
                {
                    //
                    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
                        );
                    }
                }
            }

            //
            return result;
        }
        #endregion

        //
        #region Ask ...
        /// <summary>
        /// Embed Prompt and Retrieve Relevant Chunks (Tiered: Conversation -> Project -> User -> Global) ...
        /// Each Tier Fills Remaining TopK; Duplicates are Removed ...
        /// </summary>
        /// <param name="request"></param>
        /// <param name="userInfo"></param>
        /// <param name="cancellationToken"></param>
        /// <returns></returns>
        public async Task<IList<XAiVectorSearchResult>> RetrieveAsync(
            XAiKnowledgeAskRequest request,
            XUserClaimsInfoDto userInfo = null,
            CancellationToken cancellationToken = default
        )
        {
            //
            // Validate ...
            if (
                request.IsNullOrDefault() ||
                request.Prompt.IsNullOrEmpty() ||
                !IsValidUser(userInfo)
            )
            {
                XException.InvalidArgs.Throw();
            }

            //
            var rag = configuration.RAGDescriptor;
            var effectiveTopK = Math.Clamp(request.TopK ?? rag.DefaultTopK, 1, rag.MaxTopK);
            var effectiveMinScore = request.MinScore ?? rag.DefaultMinScore;

            //
            // Resolve Tiers (with Ownership Checks) before Embedding ...
            var tiers = await ResolveTiers(request, userInfo, cancellationToken);
            if (!tiers.HasChild())
            {
                return [];
            }

            //
            // Embed Question (Once) ...
            var queryEmbedding = await embeddingService.Embedding(
                content: request.Prompt,
                cancellationToken: cancellationToken
            );
            if (queryEmbedding.IsNullOrDefault() || queryEmbedding.Length == 0)
            {
                XException.ActionFailed.Throw();
            }

            //
            var fileName = NormalizeFileName(request.FileName);
            var result = new List<XAiVectorSearchResult>();
            var seen = new HashSet<string>(StringComparer.Ordinal);
            foreach (var tier in tiers)
            {
                //
                var remaining = effectiveTopK - result.Count;
                if (remaining <= 0)
                {
                    break;
                }

                //
                var scopePrefix = GetScopePrefix(tier, userInfo);
                var prefix = fileName.IsNullOrEmpty()
                    ? scopePrefix
                    : GetDocumentChunkPrefix(scopePrefix, fileName);

                //
                var searchResult = await dataProvider.SearchVectorsAsync(
                    topK: remaining,
                    type: request.Type,
                    identifierPrefix: prefix,
                    minScore: effectiveMinScore,
                    queryEmbedding: queryEmbedding,
                    cancellationToken: cancellationToken
                );

                //
                foreach (var item in searchResult ?? [])
                {
                    if (seen.Add(item.Identifier ?? item.Id.ToString()))
                    {
                        result.Add(item);
                    }
                }
            }

            //
            return result;
        }
        #endregion

        //
        #region Documents ...
        /// <summary>
        /// List Ingested Documents of Specified Scope ...
        /// </summary>
        /// <param name="scope"></param>
        /// <param name="userInfo"></param>
        /// <param name="cancellationToken"></param>
        /// <returns></returns>
        public async Task<IList<XAiKnowledgeDocumentInfo>> LoadDocumentsAsync(
            XAiKnowledgeScopeDescriptor scope = null,
            XUserClaimsInfoDto userInfo = null,
            CancellationToken cancellationToken = default
        )
        {
            //
            // Validate ...
            if (!IsValidUser(userInfo))
            {
                XException.InvalidArgs.Throw();
            }

            //
            // Resolve & Authorize Scope (Read) ...
            scope = NormalizeScope(scope);
            await EnsureAccess(scope, userInfo, isWrite: false, cancellationToken);

            //
            var vectors = await dataProvider.LoadVectorsAsync(
                type: scope.Type,
                includeEmbedding: false,
                cancellationToken: cancellationToken,
                identifierPrefix: GetScopePrefix(scope, userInfo)
            );

            //
            var rag = configuration.RAGDescriptor;
            var result = (vectors ?? [])
                .GroupBy(v => v.Metadata.GetMetadata(rag.MetadataFileName).IsNullOrEmpty()
                    ? v.Identifier
                    : v.Metadata.GetMetadata(rag.MetadataFileName))
                .Select(g =>
                {
                    //
                    var first = g.First();
                    var ingestedText = first.Metadata.GetMetadata(XAiModelsConstants.XAiKnowledgeMetadataIngestedAtUtc);

                    //
                    return new XAiKnowledgeDocumentInfo
                    {
                        FileName = g.Key,
                        Type = first.Type,
                        Scope = scope.Scope,
                        ChunksCount = g.Count(),
                        ScopeId = scope.ScopeId,
                        MimeType = first.Metadata.GetMetadata(rag.MetadataMimeType),
                        OwnerId = first.Metadata.GetMetadata(XAiModelsConstants.XAiKnowledgeMetadataOwnerId),
                        IngestedAtUtc = DateTime.TryParse(
                            ingestedText, null, System.Globalization.DateTimeStyles.RoundtripKind, out var dt
                        ) ? dt : null
                    };
                })
                .OrderBy(d => d.FileName)
                .ToList();

            //
            return result;
        }

        /// <summary>
        /// Remove All Vectors of a Document in Specified Scope ...
        /// </summary>
        /// <param name="fileName"></param>
        /// <param name="scope"></param>
        /// <param name="userInfo"></param>
        /// <param name="connectionId"></param>
        /// <param name="cancellationToken"></param>
        /// <returns>Count of Removed Vectors</returns>
        public async Task<int> RemoveDocumentAsync(
            string fileName,
            XAiKnowledgeScopeDescriptor scope = null,
            XUserClaimsInfoDto userInfo = null,
            string connectionId = null,
            CancellationToken cancellationToken = default
        )
        {
            //
            // Validate ...
            var normalizedFileName = NormalizeFileName(fileName);
            if (normalizedFileName.IsNullOrEmpty() || !IsValidUser(userInfo))
            {
                XException.InvalidArgs.Throw();
            }

            //
            // Resolve & Authorize Scope (Write) ...
            scope = NormalizeScope(scope);
            await EnsureAccess(scope, userInfo, isWrite: true, cancellationToken);

            //
            var result = await dataProvider.RemoveVectorsAsync(
                cancellationToken: cancellationToken,
                identifierPrefix: GetDocumentChunkPrefix(GetScopePrefix(scope, userInfo), normalizedFileName)
            );
            if (result > 0)
            {
                //
                // Remove Files using ...
                var file = await fileProvider.FindOne(
                    x => x.FileName
                        .Equals(
                            fileName,
                            StringComparison.InvariantCultureIgnoreCase) &&
                        x.OwnerId
                            .Equals(
                                userInfo.UserId,
                                StringComparison.InvariantCultureIgnoreCase),
                    cancellationToken: cancellationToken
                );

                //
                if (!file.IsNullOrDefault())
                {
                    //
                    await fileProvider.Remove(
                        id: file.Id,
                        userInfo: userInfo,
                        connectionId: connectionId,
                        cancellationToken: cancellationToken
                    );
                }
            }

            //
            return result;
        }

        /// <summary>
        /// Migrate Legacy Vectors of Owner ("{ownerId}/{fileName}#i") into User Scope ("user/{ownerId}/{fileName}#i") ...
        /// Store First then Remove Legacy (no Data Loss on Failure); Idempotent ...
        /// </summary>
        /// <param name="userInfo"></param>
        /// <param name="cancellationToken"></param>
        /// <returns>Count of Migrated Vectors</returns>
        public async Task<int> MigrateLegacyVectorsAsync(
            XUserClaimsInfoDto userInfo = null,
            CancellationToken cancellationToken = default
        )
        {
            //
            // Validate ...
            if (!IsValidUser(userInfo))
            {
                XException.InvalidArgs.Throw();
            }

            //
            var legacyPrefix = $"{userInfo.UserId}{XAiModelsConstants.XAiKnowledgeOwnerSeparator}";
            var legacyVectors = await dataProvider.LoadVectorsAsync(
                includeEmbedding: true,
                identifierPrefix: legacyPrefix,
                cancellationToken: cancellationToken
            );
            if (!legacyVectors.HasChild())
            {
                return 0;
            }

            //
            var scope = XAiKnowledgeScopeDescriptor.User();
            var scopePrefix = GetScopePrefix(scope, userInfo);
            var migrated = legacyVectors
                .Select(v =>
                {
                    //
                    var type = v.Type.IsNullOrEmpty() ? XAiModelsConstants.XAiDefaultKnowledgeType : v.Type;
                    var metadata = v.Metadata ?? new Dictionary<string, string>();
                    metadata[XAiModelsConstants.XAiKnowledgeMetadataType] = type;
                    metadata[XAiModelsConstants.XAiKnowledgeMetadataScopeId] = string.Empty;
                    metadata[XAiModelsConstants.XAiKnowledgeMetadataScope] = scope.Scope.ToString();
                    metadata[XAiModelsConstants.XAiKnowledgeMetadataOwnerId] = userInfo.UserId;

                    //
                    return new XAiVectorDto
                    {
                        Type = type,
                        Text = v.Text,
                        Metadata = metadata,
                        Embedding = v.Embedding,
                        Identifier = $"{scopePrefix}{v.Identifier.Substring(legacyPrefix.Length)}",
                    };
                })
                .ToList();

            //
            var result = await dataProvider.UpsertVectorsAsync(
                items: migrated,
                cancellationToken: cancellationToken
            );
            await dataProvider.RemoveVectorsAsync(
                identifierPrefix: legacyPrefix,
                cancellationToken: cancellationToken
            );

            //
            logger.LogInformation(
                "Knowledge: Migrated {Count} Legacy Vectors of {OwnerId} into User Scope",
                result, userInfo.UserId
            );

            //
            return result;
        }

        /// <summary>
        /// Map Search Results to Public Sources ...
        /// </summary>
        /// <param name="context"></param>
        /// <returns></returns>
        public IList<XAiDocumentSource> ToSources(
            IEnumerable<XAiVectorSearchResult> context
        )
        {
            //
            var rag = configuration.RAGDescriptor;
            var result = (context ?? [])
                .Select(c =>
                {
                    //
                    var text = c.Text ?? string.Empty;
                    var snippetLength = Math.Min(text.Length, rag.SourceSnippetLength);
                    var chunkIndexText = c.Metadata.GetMetadata(rag.MetadataChunkIndex);

                    //
                    return new XAiDocumentSource
                    {
                        Type = c.Type,
                        Score = c.Score,
                        Identifier = c.Identifier,
                        Snippet = text.Substring(0, snippetLength),
                        FileName = c.Metadata.GetMetadata(rag.MetadataFileName),
                        Scope = c.Metadata.GetMetadata(XAiModelsConstants.XAiKnowledgeMetadataScope),
                        ChunkIndex = int.TryParse(chunkIndexText, out var idx) ? idx : null
                    };
                })
                .ToList();

            //
            return result;
        }
        #endregion

        //
        #region Private ...
        /// <summary>
        /// Extract Plain Text of a File (Text or Audio Transcript) ...
        /// </summary>
        private async Task<string> 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;
            }
        }

        /// <summary>
        /// Embed Chunks in Batches and Build Vectors (with Scope Metadata) ...
        /// </summary>
        private async Task<IList<XAiVectorDto>> EmbedChunks(
            XAiKnowledgeScopeDescriptor scope,
            IList<XTextChunk> 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<XAiVectorDto>(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<string, string>
                        {
                            [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 ...
        /// <summary>
        /// Normalize Scope (Null => User, Clear ScopeId for User/Global, Require ScopeId for Project/Conversation) ...
        /// </summary>
        private XAiKnowledgeScopeDescriptor NormalizeScope(XAiKnowledgeScopeDescriptor scope)
        {
            //
            var result = scope ?? XAiKnowledgeScopeDescriptor.User();
            switch (result.Scope)
            {
                case XAiKnowledgeScope.User:
                case XAiKnowledgeScope.Global:
                    result.ScopeId = null;
                    break;

                case XAiKnowledgeScope.Project:
                case XAiKnowledgeScope.Conversation:
                    if (!result.ScopeId.HasValue || result.ScopeId.Value == Guid.Empty)
                    {
                        XException.InvalidArgs.Throw();
                    }
                    break;

                default:
                    XException.InvalidArgs.Throw();
                    break;
            }

            //
            return result;
        }

        /// <summary>
        /// Ensure Caller has Access to Scope:
        ///   User: Own Data | Global: Read = Everyone, Write = Admin
        ///   Project / Conversation: Caller must be Owner ...
        /// </summary>
        private async Task EnsureAccess(
            XAiKnowledgeScopeDescriptor scope,
            XUserClaimsInfoDto userInfo,
            bool isWrite,
            CancellationToken cancellationToken
        )
        {
            //
            switch (scope.Scope)
            {
                case XAiKnowledgeScope.Global:
                    if (isWrite && !IsAdmin(userInfo))
                    {
                        XException.NotAuthorized.Throw();
                    }
                    break;

                case XAiKnowledgeScope.Project:
                    await EnsureProjectOwner(scope.ScopeId.Value, userInfo, cancellationToken);
                    break;

                case XAiKnowledgeScope.Conversation:
                    await EnsureConversationOwner(scope.ScopeId.Value, userInfo, cancellationToken);
                    break;
            }
        }

        /// <summary>
        /// Ensure Caller Owns Project ...
        /// </summary>
        private async Task<XAiProjectDto> EnsureProjectOwner(
            Guid projectId,
            XUserClaimsInfoDto userInfo,
            CancellationToken cancellationToken
        )
        {
            //
            var result = await dataProvider.GetProject(
                id: projectId,
                cancellationToken: cancellationToken
            );
            if (result.IsNullOrDefault())
            {
                XException.NotFound.Throw();
            }
            if (!string.Equals(result.OwnerId, userInfo.UserId, StringComparison.Ordinal))
            {
                XException.NotAuthorized.Throw();
            }

            //
            return result;
        }

        /// <summary>
        /// Ensure Caller Owns Conversation ...
        /// </summary>
        private async Task<XAiConversationDto> EnsureConversationOwner(
            Guid conversationId,
            XUserClaimsInfoDto userInfo,
            CancellationToken cancellationToken
        )
        {
            //
            var result = await dataProvider.GetConversation(
                id: conversationId,
                cancellationToken: cancellationToken
            );
            if (result.IsNullOrDefault())
            {
                XException.NotFound.Throw();
            }
            if (!string.Equals(result.OwnerId, userInfo.UserId, StringComparison.Ordinal))
            {
                XException.NotAuthorized.Throw();
            }

            //
            return result;
        }

        /// <summary>
        /// Resolve Retrieval Tiers (Ordered): Conversation -> Project -> User -> Global ...
        /// </summary>
        private async Task<IList<XAiKnowledgeScopeDescriptor>> ResolveTiers(
            XAiKnowledgeAskRequest request,
            XUserClaimsInfoDto userInfo,
            CancellationToken cancellationToken
        )
        {
            //
            var result = new List<XAiKnowledgeScopeDescriptor>();
            Guid? projectId = request.ProjectId.HasValue && request.ProjectId.Value != Guid.Empty
                ? request.ProjectId
                : null;

            //
            // Conversation Tier (+ Implicit Project) ...
            if (request.ConversationId.HasValue && request.ConversationId.Value != Guid.Empty)
            {
                //
                var conversation = await EnsureConversationOwner(
                    request.ConversationId.Value, userInfo, cancellationToken
                );
                result.Add(XAiKnowledgeScopeDescriptor.Conversation(request.ConversationId.Value));

                //
                // Conversation must Belong to Requested Project ...
                if (
                    projectId.HasValue &&
                    conversation.ProjectId != Guid.Empty &&
                    projectId.Value != conversation.ProjectId
                )
                {
                    XException.InvalidArgs.Throw();
                }
                if (conversation.ProjectId != Guid.Empty)
                {
                    projectId = conversation.ProjectId;
                }
            }

            //
            // Project Tier ...
            if (projectId.HasValue)
            {
                await EnsureProjectOwner(projectId.Value, userInfo, cancellationToken);
                result.Add(XAiKnowledgeScopeDescriptor.Project(projectId.Value));
            }

            //
            // User / Global Tiers ...
            if (request.IncludeUser)
            {
                result.Add(XAiKnowledgeScopeDescriptor.User());
            }
            if (request.IncludeGlobal)
            {
                result.Add(XAiKnowledgeScopeDescriptor.Global());
            }

            //
            return result;
        }

        /// <summary>
        /// Scope Prefix (Always Ends with Separator so "a" never Matches "ab"):
        /// "conversation/{id}/" | "project/{id}/" | "user/{ownerId}/" | "global/" ...
        /// </summary>
        private static string GetScopePrefix(
            XAiKnowledgeScopeDescriptor scope,
            XUserClaimsInfoDto userInfo
        )
        {
            //
            var separator = XAiModelsConstants.XAiKnowledgeSeparator;
            var result = scope.Scope switch
            {
                XAiKnowledgeScope.Global => $"{XAiModelsConstants.XAiKnowledgeGlobalPrefix}{separator}",
                XAiKnowledgeScope.User => $"{XAiModelsConstants.XAiKnowledgeUserPrefix}{separator}{userInfo.UserId}{separator}",
                XAiKnowledgeScope.Project => $"{XAiModelsConstants.XAiKnowledgeProjectPrefix}{separator}{scope.ScopeId:D}{separator}",
                XAiKnowledgeScope.Conversation => $"{XAiModelsConstants.XAiKnowledgeConversationPrefix}{separator}{scope.ScopeId:D}{separator}",
                _ => null
            };
            if (result.IsNullOrEmpty())
            {
                XException.InvalidArgs.Throw();
            }

            //
            return result;
        }

        /// <summary>
        /// Document Chunk Prefix: "{scopePrefix}{fileName}#" ...
        /// Separator Suffix Prevents "a.pdf" from Matching "a.pdf.bak" ...
        /// </summary>
        private string GetDocumentChunkPrefix(
            string scopePrefix,
            string fileName
        )
        {
            return $"{scopePrefix}{fileName}{configuration.TextChunker.ChunkIdentifierSeparator}";
        }

        /// <summary>
        /// Normalize File Name for Identifier (Strip Client Path, Replace Separators) ...
        /// </summary>
        private string NormalizeFileName(string fileName)
        {
            //
            if (string.IsNullOrWhiteSpace(fileName))
            {
                return null;
            }

            //
            // Strip Client Side Path (Both Separators) ...
            var name = Path.GetFileName(fileName.Replace('\\', '/'))?.Trim();
            if (name.IsNullOrEmpty())
            {
                return null;
            }

            //
            foreach (var c in UnsafeFileNameChars)
            {
                name = name.Replace(c, '_');
            }
            var chunkSeparator = configuration.TextChunker.ChunkIdentifierSeparator;
            if (!chunkSeparator.IsNullOrEmpty())
            {
                name = name.Replace(chunkSeparator, "_");
            }

            //
            return name;
        }

        /// <summary>
        /// Load Distinct Document Names of a Scope ...
        /// </summary>
        private async Task<HashSet<string>> LoadDocumentNames(
            string scopePrefix,
            CancellationToken cancellationToken
        )
        {
            //
            var vectors = await dataProvider.LoadVectorsAsync(
                includeEmbedding: false,
                identifierPrefix: scopePrefix,
                cancellationToken: cancellationToken
            );

            //
            var rag = configuration.RAGDescriptor;
            var result = new HashSet<string>(
                (vectors ?? [])
                    .Select(v => v.Metadata.GetMetadata(rag.MetadataFileName))
                    .Where(n => !n.IsNullOrEmpty()),
                StringComparer.Ordinal
            );

            //
            return result;
        }

        /// <summary>
        /// Is Valid User ...
        /// </summary>
        private static bool IsValidUser(XUserClaimsInfoDto userInfo)
        {
            return !userInfo.IsNullOrDefault() && !userInfo.UserId.IsNullOrEmpty();
        }

        /// <summary>
        /// Is Caller Admin ...
        /// </summary>
        private static bool IsAdmin(XUserClaimsInfoDto userInfo)
        {
            //
            var result =
                !userInfo.IsNullOrDefault() &&
                !userInfo.Roles.IsNullOrDefault() &&
                userInfo.Roles.Any(r => string.Equals(r, XUserRoles.ADMIN, StringComparison.OrdinalIgnoreCase));

            //
            return result;
        }
        #endregion        
        #endregion
    }
}

### FILE: C:\Users\saherelm\Documents\Projects\xSaherelmWorkspace\xAiApi\Providers\XAiService.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 XAiService : XAIServiceBase, IXAiService
    {
        public XAiService(
            IXAiRAGService ragProvider,
            IXAiDataProvider dataProvider,
            ILogger<XAiService> logger,
            XAiApiConfiguration configuration,
            XValidationProvider validationProvider,
            IXAiMcpServerProvider mcpServerProvider,
            IXFileContentExtractor fileContentExtractor
        ) : base(
            ragProvider,
            dataProvider,
            logger,
            configuration,
            validationProvider,
            mcpServerProvider,
            fileContentExtractor,
            XAiApiConstants.XAiDefaultModelName
        )
        { }
    }
}

### FILE: C:\Users\saherelm\Documents\Projects\xSaherelmWorkspace\xAiApi\Providers\XAIServiceBase.cs

using System;
using System.Linq;
using System.Text;
using xModels.Dtos;
using xAiApi.Models;
using System.Threading;
using xAiApi.Constants;
using xAiModels.Models;
using TimeZoneConverter;
using xAiApi.Interfaces;
using xAiApi.Extensions;
using xCommons.Providers;
using xCommons.Extensions;
using xAiModels.Constants;
using xAiModels.Interfaces;
using xAiModels.Extensions;
using System.Globalization;
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 MongoDB.Driver.Core.Connections;

namespace xAiApi.Providers
{
    /// <summary>
    /// Base Ai Service ...
    /// </summary>
    public abstract class XAIServiceBase : IXAiServiceBase
    {
        /// <summary>
        /// Chat Options ...
        /// </summary>
        public ChatOptions Options { get; }

        /// <summary>
        /// Descriptor of Models which used in Service ...
        /// </summary>        
        public XAiModelDescriptor Descriptor { get; }

        private readonly IXAiRAGService ragProvider;
        private readonly IXAiDataProvider dataProvider;
        private readonly ILogger<XAIServiceBase> logger;
        private readonly XAiApiConfiguration configuration;
        private readonly XValidationProvider validationProvider;
        private readonly IXAiMcpServerProvider mcpServerProvider;
        private readonly IXFileContentExtractor fileContentExtractor;

        //
        private readonly bool useProvidedMcpServers;

        protected XAIServiceBase(
            IXAiRAGService ragProvider,
            IXAiDataProvider dataProvider,
            ILogger<XAIServiceBase> logger,
            XAiApiConfiguration configuration,
            XValidationProvider validationProvider,
            IXAiMcpServerProvider mcpServerProvider,
            IXFileContentExtractor fileContentExtractor,
            string model = null,
            bool useProvidedMcpServers = true
        )
        {
            //
            this.logger = logger;
            this.ragProvider = ragProvider;
            this.dataProvider = dataProvider;
            this.configuration = configuration;
            this.mcpServerProvider = mcpServerProvider;
            this.validationProvider = validationProvider;
            this.fileContentExtractor = fileContentExtractor;
            this.useProvidedMcpServers = useProvidedMcpServers;

            //
            // 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 ...
        /// <summary>
        /// Base Method for Communicate with LLM ...
        /// </summary>
        /// <param name="prompt"></param>
        /// <param name="userInfo"></param>
        /// <param name="cancellationToken"></param>
        /// <returns></returns>
        public virtual async Task<string> AskTextAsync(
            string prompt,
            XUserClaimsInfoDto userInfo = null,
            CancellationToken cancellationToken = default
        )
        {
            //
            // Check Prompt Exists ...
            if (prompt.IsNullOrEmpty())
            {
                XException.InvalidArgs.Throw();
            }

            //
            using var client = Descriptor.GetClient();
            var history = GetHistory(prompt);

            //
            // Handle Provided MCP Servers ...
            if (useProvidedMcpServers)
            {
                //
                var availableTools = await mcpServerProvider
                    .GetAvailableToolsAsync(
                        userInfo: userInfo,
                        cancellationToken: cancellationToken
                );

                //
                Options.Tools = [.. availableTools];
            }

            //
            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;
        }

        /// <summary>
        /// Base Method for Communicate with LLM ...
        /// </summary>
        /// <param name="prompt"></param>
        /// <param name="userInfo"></param>
        /// <param name="cancellationToken"></param>
        /// <returns></returns>
        public virtual async IAsyncEnumerable<string> AskTextAsEnumerable(
            string prompt,
            XUserClaimsInfoDto userInfo = null,
            [EnumeratorCancellation]
            CancellationToken cancellationToken = default
        )
        {
            //
            // Check Prompt Exists ...
            if (prompt.IsNullOrEmpty())
            {
                XException.InvalidArgs.Throw();
            }

            //
            using var client = Descriptor.GetClient();
            var history = GetHistory(prompt);

            //
            // Handle Provided MCP Servers ...
            if (useProvidedMcpServers)
            {
                //
                var availableTools = await mcpServerProvider
                    .GetAvailableToolsAsync(
                        userInfo: userInfo,
                        cancellationToken: cancellationToken
                );

                //
                Options.Tools = [.. availableTools.Cast<AITool>()];
            }

            //
            var enumerable = client.GetStreamingResponseAsync(
                options: Options,
                messages: history
            );

            //
            await foreach (var res in enumerable)
            {
                //
                // Cancellation Token ...
                if (cancellationToken.IsCancellationRequested)
                {
                    yield break;
                }

                //
                yield return res.Text;
            }
        }

        /// <summary>
        /// Ask a Question By Providing Vector Search Result ...
        /// </summary>
        /// <param name="prompt"></param>
        /// <param name="context"></param>
        /// <param name="userInfo"></param>
        /// <param name="cancellationToken"></param>
        /// <returns></returns>
        public virtual async Task<string> AskTextByContextAsync(
            string prompt,
            IList<XAiVectorSearchResult> context = null,
            XUserClaimsInfoDto userInfo = null,
            CancellationToken cancellationToken = default
        )
        {
            //
            // Validate Args ...
            validationProvider
                .GroupValidationBuilder()
                .AddNotEmpty(prompt)
                .AddNotNull(userInfo)
                .AddNotEmpty(userInfo.UserId)
                .ValidateGroup();

            //
            using var client = Descriptor.GetClient();
            var history = GetHistory(prompt, context);

            //
            // Handle Provided MCP Servers ...
            if (useProvidedMcpServers)
            {
                //
                var availableTools = await mcpServerProvider
                    .GetAvailableToolsAsync(
                        userInfo: userInfo,
                        cancellationToken: cancellationToken
                );

                //
                Options.Tools = [.. availableTools.Cast<AITool>()];
            }

            //            
            var response = await client.GetResponseAsync(
                options: Options,
                messages: history,
                cancellationToken: cancellationToken
            );

            //
            // Validate Response ...
            if (!response.IsValid())
            {
                client.Dispose();
                XException.ActionFailed.Throw();
            }

            //
            var result = response.Text;

            //
            return result;
        }

        /// <summary>
        /// Ask a Question By By Providing Vector Search Result and Stream Response ...
        /// </summary>
        /// <param name="prompt"></param>
        /// <param name="context"></param>
        /// <param name="userInfo"></param>
        /// <param name="cancellationToken"></param>
        /// <returns></returns>
        public virtual async IAsyncEnumerable<string> AskTextByContextAsEnumerable(
            string prompt,
            IList<XAiVectorSearchResult> context = null,
            XUserClaimsInfoDto userInfo = null,
            [EnumeratorCancellation]
            CancellationToken cancellationToken = default
        )
        {
            //
            // Validate Args ...
            validationProvider
                .GroupValidationBuilder()
                .AddNotEmpty(prompt)
                .AddNotNull(userInfo)
                .AddNotEmpty(userInfo.UserId)
                .ValidateGroup();

            //
            using var client = Descriptor.GetClient();
            var history = GetHistory(prompt, context);

            //
            // Handle Provided MCP Servers ...
            if (useProvidedMcpServers)
            {
                //
                var availableTools = await mcpServerProvider
                    .GetAvailableToolsAsync(
                        userInfo: userInfo,
                        cancellationToken: cancellationToken
                );

                //
                Options.Tools = [.. availableTools.Cast<AITool>()];
            }

            //
            var enumerable = client.GetStreamingResponseAsync(
                options: Options,
                messages: history,
                cancellationToken: cancellationToken
            );

            //
            await foreach (var res in enumerable)
            {
                //
                if (cancellationToken.IsCancellationRequested)
                {
                    yield break;
                }

                //
                yield return res.Text;
            }
        }

        /// <summary>
        /// Ask a Question By Rag Retrive From Knowledge ...
        /// </summary>
        /// <param name="prompt"></param>
        /// <param name="type"></param>
        /// <param name="topK"></param>
        /// <param name="minScore"></param>
        /// <param name="userInfo"></param>
        /// <param name="cancellationToken"></param>
        /// <returns></returns>
        public virtual async Task<string> AskTextFromKnowledgeAsync(
            string prompt,
            string type = null,
            int? topK = null,
            float? minScore = null,
            XUserClaimsInfoDto userInfo = null,
            CancellationToken cancellationToken = default
        )
        {
            //
            // Validation ...
            validationProvider
                .GroupValidationBuilder()
                    .AddNotEmpty(prompt)
                    .AddNotNull(userInfo)
                    .AddNotEmpty(userInfo.UserId)
                    .ValidateGroup();

            //
            // Prepare Requirements ...
            var prep = await PrepareChatRequirementsAsync(
                topK: topK,
                type: type,
                files: null,
                prompt: prompt,
                projectId: null,
                minScore: minScore,
                userInfo: userInfo,
                connectionId: null,
                conversationId: null,
                persistPrompt: false,
                additionalContents: null,
                addFilesToKnowledge: false,
                resolveConversation: false,
                extractFileContents: false,
                cancellationToken: cancellationToken
            );

            //
            using var client = Descriptor.GetClient();

            //
            // Handle Provided MCP Servers ...
            if (useProvidedMcpServers)
            {
                //
                var availableTools = await mcpServerProvider
                    .GetAvailableToolsAsync(
                        userInfo: userInfo,
                        cancellationToken: cancellationToken
                );

                //
                Options.Tools = [.. availableTools.Cast<AITool>()];
            }

            //
            var response = await client
                .GetResponseAsync(
                    options: Options,
                    messages: prep.History,
                    cancellationToken: cancellationToken
                );
            if (!response.IsValid())
            {
                client.Dispose();
                XException.ActionFailed.Throw();
            }

            //
            return response.Text;
        }

        /// <summary>
        /// Ask a Question By Rag Retrive From Knowledge and Stream Response ...
        /// </summary>
        /// <param name="prompt"></param>
        /// <param name="type"></param>
        /// <param name="topK"></param>
        /// <param name="minScore"></param>
        /// <param name="userInfo"></param>
        /// <param name="cancellationToken"></param>
        /// <returns></returns>
        public virtual async IAsyncEnumerable<string> AskTextFromKnowledgeAsEnumerable(
            string prompt,
            string type = null,
            int? topK = null,
            float? minScore = null,
            XUserClaimsInfoDto userInfo = null,
            [EnumeratorCancellation]
            CancellationToken cancellationToken = default
        )
        {
            //
            // Validation ...
            validationProvider
                .GroupValidationBuilder()
                    .AddNotEmpty(prompt)
                    .AddNotNull(userInfo)
                    .AddNotEmpty(userInfo.UserId)
                    .ValidateGroup();

            //
            // Prepare Requirements ...
            var prep = await PrepareChatRequirementsAsync(
                topK: topK,
                type: type,
                files: null,
                prompt: prompt,
                projectId: null,
                minScore: minScore,
                userInfo: userInfo,
                connectionId: null,
                conversationId: null,
                persistPrompt: false,
                additionalContents: null,
                resolveConversation: false,
                addFilesToKnowledge: false,
                extractFileContents: false,
                cancellationToken: cancellationToken
            );

            //
            using var client = Descriptor.GetClient();

            //
            // Handle Provided MCP Servers ...
            if (useProvidedMcpServers)
            {
                //
                var availableTools = await mcpServerProvider
                    .GetAvailableToolsAsync(
                        userInfo: userInfo,
                        cancellationToken: cancellationToken
                );

                //
                Options.Tools = [.. availableTools.Cast<AITool>()];
            }

            //
            var stream = client
                .GetStreamingResponseAsync(
                    options: Options,
                    messages: prep.History,
                    cancellationToken: cancellationToken
                );
            await foreach (var res in stream)
            {
                //
                if (cancellationToken.IsCancellationRequested)
                {
                    yield break;
                }

                //
                yield return res.Text;
            }
        }

        /// <summary>
        /// Ask a Question as Prompt and Retrieve Response ...
        /// </summary>
        /// <param name="prompt"></param>
        /// <param name="type"></param>
        /// <param name="topK"></param>
        /// <param name="minScore"></param>
        /// <param name="projectId"></param>
        /// <param name="conversationId"></param>
        /// <param name="connectionId"></param>
        /// <param name="extractFileContents"></param>
        /// <param name="addFilesToKnowledge"></param>
        /// <param name="files"></param>
        /// <param name="userInfo"></param>
        /// <param name="cancellationToken"></param>
        /// <returns></returns>
        public virtual async Task<XAiMessageDto> AskAsync(
            string prompt,
            string type = null,
            int? topK = null,
            float? minScore = null,
            Guid? projectId = null,
            Guid? conversationId = null,
            string connectionId = null,
            bool extractFileContents = false,
            bool addFilesToKnowledge = true,
            IFormFileCollection files = null,
            XUserClaimsInfoDto userInfo = null,
            CancellationToken cancellationToken = default
        )
        {
            //
            // Validate Args ...
            validationProvider
                .GroupValidationBuilder()
                .AddNotEmpty(prompt)
                .AddNotNull(userInfo)
                .AddNotEmpty(userInfo.UserId)
                .ValidateGroup();

            //
            var prep = await PrepareChatRequirementsAsync(
                type: type,
                topK: topK,
                files: files,
                prompt: prompt,
                minScore: minScore,
                userInfo: userInfo,
                persistPrompt: true,
                projectId: projectId,
                additionalContents: null,
                resolveConversation: true,
                connectionId: connectionId,
                conversationId: conversationId,
                cancellationToken: cancellationToken,
                extractFileContents: extractFileContents,
                addFilesToKnowledge: addFilesToKnowledge
            );

            //
            using var client = Descriptor.GetClient();

            //
            // Handle Provided MCP Servers ...
            if (useProvidedMcpServers)
            {
                //
                var availableTools = await mcpServerProvider
                    .GetAvailableToolsAsync(
                        userInfo: userInfo,
                        cancellationToken: cancellationToken
                );

                //
                Options.Tools = [.. availableTools.Cast<AITool>()];
            }

            //
            var response = await client.GetResponseAsync(
                options: Options,
                messages: prep.History,
                cancellationToken: cancellationToken
            );
            if (!response.IsValid())
            {
                //
                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: prep.Conversation.Id,
                cancellationToken: cancellationToken
            );

            //
            return result;
        }

        /// <summary>
        /// Ask a Question as Prompt and Retrieve Response as Async Enumerable ...
        /// </summary>
        /// <param name="prompt"></param>
        /// <param name="type"></param>
        /// <param name="topK"></param>
        /// <param name="minScore"></param>
        /// <param name="projectId"></param>
        /// <param name="conversationId"></param>
        /// <param name="connectionId"></param>
        /// <param name="extractFileContents"></param>
        /// <param name="addFilesToKnowledge"></param>
        /// <param name="files"></param>
        /// <param name="userInfo"></param>
        /// <param name="cancellationToken"></param>
        /// <returns></returns>
        public virtual async IAsyncEnumerable<XAiResonseMessage> AskAsEnumerable(
            string prompt,
            string type = null,
            int? topK = null,
            float? minScore = null,
            Guid? projectId = null,
            Guid? conversationId = null,
            string connectionId = null,
            bool extractFileContents = false,
            bool addFilesToKnowledge = true,
            IFormFileCollection files = null,
            XUserClaimsInfoDto userInfo = null,
            [EnumeratorCancellation]
            CancellationToken cancellationToken = default
        )
        {
            //
            // Validate Args ...
            validationProvider
                .GroupValidationBuilder()
                .AddNotEmpty(prompt)
                .AddNotNull(userInfo)
                .AddNotEmpty(userInfo.UserId)
                .ValidateGroup();

            //
            var prep = await PrepareChatRequirementsAsync(
                type: type,
                topK: topK,
                files: files,
                prompt: prompt,
                minScore: minScore,
                userInfo: userInfo,
                persistPrompt: true,
                projectId: projectId,
                additionalContents: null,
                resolveConversation: true,
                connectionId: connectionId,
                conversationId: conversationId,
                cancellationToken: cancellationToken,
                extractFileContents: extractFileContents,
                addFilesToKnowledge: addFilesToKnowledge
            );

            //
            using var client = Descriptor.GetClient();

            //
            // Handle Provided MCP Servers ...
            if (useProvidedMcpServers)
            {
                //
                var availableTools = await mcpServerProvider
                    .GetAvailableToolsAsync(
                        userInfo: userInfo,
                        cancellationToken: cancellationToken
                );

                //
                Options.Tools = [.. availableTools.Cast<AITool>()];
            }

            //
            var stream = client
                .GetStreamingResponseAsync(
                    options: Options,
                    messages: prep.History,
                    cancellationToken: cancellationToken
                );

            //
            var answer = new System.Text.StringBuilder();
            long sequence = 1;
            await foreach (var res in stream)
            {
                //
                if (cancellationToken.IsCancellationRequested)
                {
                    yield break;
                }

                //
                answer.Append(res.Text);
                yield return new XAiResonseMessage
                {
                    Content = res.Text,
                    Sequence = sequence++,
                    OwnerId = userInfo.UserId,
                    Role = XAiChatRole.Assistant,
                    RespondedOn = DateTime.UtcNow,
                    RespondTo = prep.PersistedPromptMessage.Id,
                };
            }

            //
            // 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: prep.Conversation.Id,
                cancellationToken: cancellationToken
            );
        }
        #endregion

        //
        #region Loaders ...
        /// <summary>
        /// Load AI Projects ...
        /// </summary>
        /// <param name="ownerId"></param>
        /// <param name="connectionId"></param>
        /// <param name="includeDefaults"></param>
        /// <param name="cancellationToken"></param>
        /// <returns></returns>
        public virtual async Task<IEnumerable<XAiProjectDto>> 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.GetDafaultProject(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;
        }

        /// <summary>
        /// Load Conversations of Specified AI Project ...
        /// </summary>
        /// <param name="projectId"></param>
        /// <param name="ownerId"></param>
        /// <param name="connectionId"></param>
        /// <param name="cancellationToken"></param>
        /// <returns></returns>
        public virtual async Task<IEnumerable<XAiConversationDto>> LoadConversations(
            Guid? projectId,
            string ownerId = null,
            string connectionId = null,
            CancellationToken cancellationToken = default
        )
        {
            //
            var result = await dataProvider.LoadConversations(
                ownerId: ownerId,
                fillMessages: false,
                projectId: projectId,
                connectionId: connectionId,
                cancellationToken: cancellationToken
            );

            //
            return result;
        }

        /// <summary>
        /// Load Messages of Specified Conversation ...
        /// </summary>
        /// <param name="conversationId"></param>
        /// <param name="ownerId"></param>
        /// <param name="connectionId"></param>
        /// <param name="cancellationToken"></param>
        /// <returns></returns>
        public virtual async Task<IEnumerable<XAiMessageDto>> LoadMessages(
            Guid? conversationId,
            string ownerId = null,
            string connectionId = null,
            CancellationToken cancellationToken = default
        )
        {
            //
            var result = await dataProvider.LoadMessages(
                ownerId: ownerId,
                connectionId: connectionId,
                conversationId: conversationId,
                cancellationToken: cancellationToken
            );

            //
            return result;
        }
        #endregion

        //
        #region Queries ...
        /// <summary>
        /// Query Projects ...
        /// </summary>
        /// <param name="ownerId"></param>
        /// <param name="query"></param>
        /// <param name="cancellationToken"></param>
        /// <returns></returns>
        public virtual async Task<XQueryResult<XAiProjectDto>> 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;
        }

        /// <summary>
        /// Query Conversations ...
        /// </summary>
        /// <param name="ownerId"></param>
        /// <param name="projectId"></param>
        /// <param name="query"></param>
        /// <param name="cancellationToken"></param>
        /// <returns></returns>
        public virtual async Task<XQueryResult<XAiConversationDto>> 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;
        }

        /// <summary>
        /// Query Messages ...
        /// </summary>
        /// <param name="ownerId"></param>
        /// <param name="conversationId"></param>
        /// <param name="query"></param>
        /// <param name="cancellationToken"></param>
        /// <returns></returns>
        public virtual async Task<XQueryResult<XAiMessageDto>> 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 ...
        /// <summary>
        /// Create an AI Project ...
        /// </summary>
        /// <param name="ownerId"></param>
        /// <param name="item"></param>
        /// <param name="connectionId"></param>
        /// <param name="cancellationToken"></param>
        /// <returns></returns>
        public virtual async Task<XAiProjectDto> 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;
        }

        /// <summary>
        /// Create an AI Conversation ...
        /// </summary>
        /// <param name="ownerId"></param>
        /// <param name="projectId"></param>
        /// <param name="item"></param>
        /// <param name="connectionId"></param>
        /// <param name="cancellationToken"></param>
        /// <returns></returns>
        public virtual async Task<XAiConversationDto> 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 ...
        /// <summary>
        /// Try to Extract Files Content ...
        /// </summary>
        /// <param name="files"></param>
        /// <param name="extractors"></param>
        /// <param name="cancellationToken"></param>
        /// <returns></returns>
        public async Task<string> ExtractContent(
            IFormFileCollection files,
            string[] extractors = null,
            CancellationToken cancellationToken = default
        )
        {
            //
            if (!files.HasChild())
            {
                XException.InvalidArgs.Throw();
            }

            //
            var extractionResults = new List<XFileExtractionResult>();
            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;
                }
            }

            //
            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

        /// <summary>
        /// Base Dispose Action ...
        /// </summary>
        /// <exception cref="NotImplementedException"></exception>
        public virtual void Dispose()
        { }

        //
        #region Private ...
        /// <summary>
        /// Prepare a Message History List for LLM Communication based on Prompt ...
        /// </summary>
        /// <param name="prompt"></param>
        /// <param name="forcePrompt"></param>
        /// <returns></returns>
        private IList<ChatMessage> 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<ChatMessage> result =
            [
                introductionPrompt,
            ];

            //
            // Prepare Datetime ...
            var datetimeContext = BuildDateTimeContext();
            if (!datetimeContext.IsNullOrEmpty())
            {
                //
                result.Add(new ChatMessage(
                    ChatRole.Assistant,
                    datetimeContext
                ));
            }

            //
            if (forcePrompt &&
                prompt is not null &&
                !prompt.IsNullOrEmpty())
            {
                result.Add(promptMessage);
            }

            //
            return result;
        }

        /// <summary>
        /// Build Chat History for RAG:
        /// [System: Introduction + ChatWithDocuments Prompt + Context Block] + [User: Prompt] ...
        /// </summary>
        /// <param name="prompt"></param>
        /// <param name="context"></param>
        /// <returns></returns>
        private IList<ChatMessage> GetHistory(
            string prompt,
            IEnumerable<XAiVectorSearchResult> context
        )
        {
            //
            var introductionPrompt = configuration.GetPrompt();
            var ragPrompt = configuration.GetPrompt(XAiApiConstants.XAiApiRagPromptName);
            if (ragPrompt.IsNullOrEmpty())
            {
                XException.InvalidConfiguration.Throw();
            }

            //
            var datetimeContext = BuildDateTimeContext();
            var contextBlock = BuildContextBlock(context);
            var systemText = introductionPrompt;
            if (context.HasChild() &&
                !contextBlock.IsNullOrEmpty()
            )
            {
                //
                systemText =
                    $"{introductionPrompt}{Environment.NewLine}{Environment.NewLine}";

                //
                if (!datetimeContext.IsNullOrEmpty())
                {
                    //
                    systemText += $"{datetimeContext}{Environment.NewLine}{Environment.NewLine}";
                }

                //
                systemText +=
                    $"{ragPrompt}{Environment.NewLine}{Environment.NewLine}" +
                    $"Context:{Environment.NewLine}{contextBlock}";
            }

            //
            List<ChatMessage> result =
            [
                new ChatMessage(ChatRole.System, systemText),
                new ChatMessage(ChatRole.User, prompt),
            ];

            //
            return result;
        }

        /// <summary>
        /// Implementing Memory Strategy here ...
        /// </summary>
        /// <param name="project"></param>
        /// <param name="messages"></param>
        /// <param name="context"></param>
        /// <param name="cancellationToken"></param>
        /// <returns></returns>
        private async Task<IList<ChatMessage>> PrepareMemory(
            XAiProjectDto project,
            IEnumerable<XAiMessageDto> messages,
            IEnumerable<XAiVectorSearchResult> context = null,
            CancellationToken cancellationToken = default
        )
        {
            //
            var result = new List<ChatMessage>();

            //
            await Task.FromResult(true);

            //
            // 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}";
            }

            //
            // Prepare Datetime ...
            var datetimeContext = BuildDateTimeContext();
            if (!datetimeContext.IsNullOrEmpty())
            {
                //
                systemText +=
                    $"{datetimeContext}{Environment.NewLine}{Environment.NewLine}";
            }

            //
            // Apply Project Prompt as System Text ...
            if (!project.IsNullOrDefault() &&
                !project.Prompt.IsNullOrEmpty())
            {
                systemText += $"{project.Prompt}{Environment.NewLine}{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;
        }

        /// <summary>
        /// Convert Context Chunks to a Numbered Text Block ...
        /// </summary>
        /// <param name="context"></param>
        /// <returns></returns>
        private string BuildContextBlock(
            IEnumerable<XAiVectorSearchResult> 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;
        }

        /// <summary>
        /// Normalizing Rag Params ...
        /// </summary>
        /// <param name="topK"></param>
        /// <param name="minScore"></param>
        /// <param name="type"></param>
        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;
            }
        }

        /// <summary>
        /// Retrieve Prepared Chat Context ...
        /// </summary>
        /// <param name="topK"></param>
        /// <param name="type"></param>
        /// <param name="prompt"></param>
        /// <param name="minScore"></param>
        /// <param name="projectId"></param>
        /// <param name="persistPrompt"></param>
        /// <param name="connectionId"></param>
        /// <param name="conversationId"></param>
        /// <param name="resolveConversation"></param>
        /// <param name="files"></param>
        /// <param name="userInfo"></param>
        /// <param name="extractFileContents"></param>
        /// <param name="addFilesToKnowledge"></param>
        /// <param name="additionalContents"></param>
        /// <param name="cancellationToken"></param>
        /// <returns></returns>
        private async Task<XPreparedChatContext> PrepareChatRequirementsAsync(
            int? topK,
            string type,
            string prompt,
            float? minScore,
            Guid? projectId,
            bool persistPrompt,
            string connectionId,
            Guid? conversationId,
            bool resolveConversation,
            IFormFileCollection files,
            XUserClaimsInfoDto userInfo,
            bool extractFileContents = true,
            bool addFilesToKnowledge = false,
            IList<AIContent> additionalContents = null,
            CancellationToken cancellationToken = default
        )
        {
            //
            // Validate Args ...
            validationProvider
                .GroupValidationBuilder()
                .AddNotEmpty(prompt)
                .AddNotNull(userInfo)
                .AddNotEmpty(userInfo.UserId)
                .ValidateGroup();

            //
            // 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 &&
                addFilesToKnowledge
            )
            {
                //
                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
                    );
                }
            }

            //
            // If there isn't Files need to add Files to Knowledge ...
            if (files.HasChild() &&
                !addFilesToKnowledge
            )
            {
                //
                // Extract File Content and add them to Additional Contents ...
                foreach (var file in files)
                {
                    //
                    var mimeType = file.ContentType?.ToLowerInvariant() ?? string.Empty;
                    if (mimeType.IsNullOrEmpty() ||
                    !fileContentExtractor.CanExtract(mimeType))
                    {
                        continue;
                    }

                    //
                    using var stream = file.OpenReadStream();

                    //
                    // Extract File Content if necessary ...
                    if (extractFileContents)
                    {
                        //
                        var content = await fileContentExtractor.ExtractAsync(
                            fileStream: stream,
                            mimeType: mimeType,
                            cancellationToken: cancellationToken
                        );
                        if (!content.IsNullOrEmpty())
                        {
                            //
                            var fileContent = new TextContent($"File:{Environment.NewLine}{file.FileName}{Environment.NewLine}{content}");
                            additionalContents = [.. additionalContents, fileContent];
                        }
                    }
                    else
                    {
                        //
                        var fileContent = await DataContent.LoadFromAsync(stream, mimeType, cancellationToken);
                        if (additionalContents.IsNull())
                        {
                            additionalContents = [];
                        }

                        //
                        additionalContents = [.. additionalContents, fileContent];
                    }
                }
            }

            // 
            // 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
            );

            //
            // Prepare History and Persisted Prompt Message ...
            IList<ChatMessage> history;
            XAiMessageDto persistedPromptMessage = null;
            if (persistPrompt)
            {
                //
                // 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);
            }

            //
            // Prepare Result ...
            var result = new XPreparedChatContext
            {
                Project = project,
                Context = context,
                History = history,
                Conversation = conversation,
                PersistedPromptMessage = persistedPromptMessage,
            };

            //
            return result;
        }

        private string BuildDateTimeContext()
        {
            //
            var cfg = configuration.DateTime;
            if (cfg == null || !cfg.InjectIntoSystemPrompt)
            {
                return string.Empty;
            }

            //
            try
            {
                //
                var tz = ResolveTimezone(cfg.DefaultTimezone);
                var nowUtc = DateTime.UtcNow;
                var nowLocal = TimeZoneInfo.ConvertTimeFromUtc(nowUtc, tz);

                //
                var sb = new StringBuilder();
                sb.AppendLine("[CURRENT DATETIME — for your reference]");
                sb.AppendLine($"Now (local, {tz.Id}): {nowLocal.ToString(cfg.GregorianFormat)}");

                //
                if (cfg.IncludeDayOfWeek)
                {
                    sb.AppendLine($"Day of week: {nowLocal:dddd}");
                }

                //
                if (cfg.IncludePersianCalendar)
                {
                    //
                    var pc = new PersianCalendar();
                    sb.AppendLine($"Now (Persian): {pc.GetYear(nowLocal):D4}/{pc.GetMonth(nowLocal):D2}/{pc.GetDayOfMonth(nowLocal):D2} {nowLocal:HH:mm:ss}");
                }

                //
                if (cfg.IncludeUnixTimestamp)
                {
                    sb.AppendLine($"Unix timestamp: {new DateTimeOffset(nowUtc).ToUnixTimeSeconds()}");
                }

                //
                sb.AppendLine("Use this information when the user asks about 'today', 'now', 'this week', relative dates, or any time-sensitive calculations.");
                return sb.ToString().TrimEnd();
            }
            catch
            {
                return string.Empty;
            }
        }

        private static TimeZoneInfo ResolveTimezone(string id)
        {
            //
            if (id.IsNullOrEmpty())
            {
                return TimeZoneInfo.Utc;
            }

            //
            try
            {
                return TZConvert.GetTimeZoneInfo(id);
            }
            catch
            {
                return TimeZoneInfo.Utc;
            }
        }
        #endregion
    }
}

### FILE: C:\Users\saherelm\Documents\Projects\xSaherelmWorkspace\xAiApi\Providers\XDefaultThinkingAiService.cs

using xAiApi.Constants;
using xAiApi.Interfaces;
using xCommons.Providers;
using xAiModels.Interfaces;
using xAiApi.Configurations;
using Microsoft.Extensions.AI;
using Microsoft.Extensions.Logging;
using xAiApi.Interfaces.Extractors;

namespace xAiApi.Providers
{
    public class XDefaultThinkingAiService : XAIServiceBase, IXDefaultThinkingAiService
    {
        public XDefaultThinkingAiService(
            IXAiRAGService ragProvider,
            IXAiDataProvider dataProvider,
            ILogger<XAIServiceBase> logger,
            XAiApiConfiguration configuration,
            XValidationProvider validationProvider,
            IXAiMcpServerProvider mcpServerProvider,
            IXFileContentExtractor fileContentExtractor,
            ReasoningEffort effort = ReasoningEffort.Medium,
            ReasoningOutput output = ReasoningOutput.Full
        ) : base(
            ragProvider,
            dataProvider,
            logger,
            configuration,
            validationProvider,
            mcpServerProvider,
            fileContentExtractor,
            XAiApiConstants.XAiDefaultThinkingModelName
        )
        {
            //
            // Preparing Reasoning ...
            Options.Reasoning = new ReasoningOptions
            {
                Output = output,
                Effort = effort,
            };
        }
    }
}

### FILE: C:\Users\saherelm\Documents\Projects\xSaherelmWorkspace\xAiApi\Providers\XInMemoryVectorStore.cs

using System;
using System.Linq;
using xAiApi.Models;
using xAiApi.Interfaces;
using xAiModels.Helpers;
using xAiModels.Models.Dtos;
using System.Collections.Generic;
using System.Collections.Concurrent;

namespace xAiApi.Providers
{
    public class XInMemoryVectorStore : IXInMemoryVectorStore
    {
        private const int DefaultTtlMinutes = 30;
        private readonly ConcurrentDictionary<Guid, XAiDocumentSession> sessions = new ConcurrentDictionary<Guid, XAiDocumentSession>();
        public int Count { get { RemoveExpired(); return sessions.Count; } }

        public Guid CreateSession(
            string ownerId = null,
            TimeSpan? ttl = null
        )
        {
            //
            var result = CreateSession(null, ownerId, ttl);
            return result;
        }

        public Guid CreateSession(
            IEnumerable<XAiVectorDto> vectors,
            string ownerId = null,
            TimeSpan? ttl = null
        )
        {
            //
            var now = DateTime.UtcNow;
            var session = new XAiDocumentSession
            {
                Id = Guid.NewGuid(),
                OwnerId = ownerId,
                CreatedAtUtc = now,
                LastAccessAtUtc = now,
                Ttl = NormalizeTtl(ttl),
                Vectors = Copy(vectors)
            };
            sessions[session.Id] = session;
            var result = session.Id;
            return result;
        }

        public bool Replace(
            Guid sessionId,
            IEnumerable<XAiVectorDto> vectors,
            string ownerId = null
        )
        {
            //
            XAiDocumentSession session;
            if (!TryGet(sessionId, out session, ownerId))
            {
                return false;
            }

            //
            lock (session.SyncRoot)
            {
                session.Vectors = Copy(vectors);
                session.LastAccessAtUtc = DateTime.UtcNow;
            }

            //
            return true;
        }

        public bool Add(
            Guid sessionId,
            IEnumerable<XAiVectorDto> vectors,
            string ownerId = null
        )
        {
            //
            XAiDocumentSession session;
            if (!TryGet(sessionId, out session, ownerId))
            {
                return false;
            }
            var additions = Copy(vectors);
            lock (session.SyncRoot)
            {
                //
                foreach (var vector in additions)
                {
                    session.Vectors.Add(vector);
                }

                // 
                session.LastAccessAtUtc = DateTime.UtcNow;
            }
            return true;
        }

        public IList<XAiVectorSearchResult> Search(
            Guid sessionId,
            ReadOnlyMemory<float> queryEmbedding,
            int topK = 5,
            float minScore = 0f,
            string ownerId = null
        )
        {
            //
            var result = new List<XAiVectorSearchResult>();
            if (topK <= 0 || queryEmbedding.Length == 0)
            {
                return result;
            }

            //
            XAiDocumentSession session;
            if (!TryGet(sessionId, out session, ownerId))
            {
                return result;
            }

            //
            var query = queryEmbedding.ToArray();
            lock (session.SyncRoot)
            {
                //
                session.LastAccessAtUtc = DateTime.UtcNow;
                foreach (var vector in session.Vectors)
                {
                    //
                    if (vector == null || vector.Embedding.Length == 0)
                    {
                        continue;
                    }

                    //
                    var score = VectorHelper.CosineSimilarity(
                        query,
                        vector.Embedding.ToArray()
                    );

                    //
                    if (score >= minScore)
                    {
                        //
                        result.Add(new XAiVectorSearchResult
                        {
                            Score = score,
                            Id = vector.Id,
                            Text = vector.Text,
                            Metadata = vector.Metadata,
                            Identifier = vector.Identifier,
                        });
                    }
                }
            }

            //
            result = [.. result
                .OrderByDescending(x => x.Score)
                .Take(topK)];

            //
            return result;
        }

        public bool TryGet(
            Guid sessionId,
            out XAiDocumentSession session,
            string ownerId = null
        )
        {
            //
            session = null;
            XAiDocumentSession found;
            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(
            Guid sessionId,
            string ownerId = null
        )
        {
            //
            XAiDocumentSession session;
            if (!TryGet(sessionId, out session, ownerId)) return false;
            return sessions.TryRemove(sessionId, out session);
        }

        public int RemoveExpired()
        {
            //
            var now = DateTime.UtcNow; var removed = 0;
            foreach (var pair in sessions) { if (pair.Value.IsExpired(now) && sessions.TryRemove(pair.Key, out _)) removed++; }
            return removed;
        }

        //
        #region Private ...
        private static bool OwnerMatches(
            XAiDocumentSession session,
            string ownerId
        )
        {
            return string.IsNullOrEmpty(session.OwnerId) || string.Equals(session.OwnerId, ownerId, StringComparison.Ordinal);
        }

        private static TimeSpan NormalizeTtl(
            TimeSpan? ttl
        )
        {
            return !ttl.HasValue || ttl.Value <= TimeSpan.Zero ? TimeSpan.FromMinutes(DefaultTtlMinutes) : ttl.Value;
        }

        private static IList<XAiVectorDto> Copy(
            IEnumerable<XAiVectorDto> vectors
        )
        {
            return vectors == null ? new List<XAiVectorDto>() : vectors.Where(x => x != null).ToList();
        }
        #endregion
    }
}

### FILE: C:\Users\saherelm\Documents\Projects\xSaherelmWorkspace\xAiApi\Providers\XInMemoryVectorStoreCleanupService.cs

using System;
using System.Threading;
using xAiApi.Interfaces;
using System.Threading.Tasks;
using Microsoft.Extensions.Hosting;
using Microsoft.Extensions.Logging;

namespace xAiApi.Providers
{
    /// <summary>
    /// Periodically Removes Expired Document Sessions from In-Memory Vector Store ...
    /// </summary>
    public class XInMemoryVectorStoreCleanupService : BackgroundService
    {
        /// <summary>
        /// Default Cleanup Interval ...
        /// </summary>
        public static readonly TimeSpan DefaultInterval = TimeSpan.FromMinutes(5);

        private readonly TimeSpan interval;
        private readonly IXInMemoryVectorStore vectorStore;
        private readonly ILogger<XInMemoryVectorStoreCleanupService> logger;

        public XInMemoryVectorStoreCleanupService(
            IXInMemoryVectorStore vectorStore,
            ILogger<XInMemoryVectorStoreCleanupService> logger
        )
        {
            this.logger = logger;
            this.vectorStore = vectorStore;
            this.interval = DefaultInterval;
        }

        /// <summary>
        /// Cleanup Loop ...
        /// </summary>
        /// <param name="stoppingToken"></param>
        /// <returns></returns>
        protected override async Task ExecuteAsync(CancellationToken stoppingToken)
        {
            //
            try
            {
                //
                while (!stoppingToken.IsCancellationRequested)
                {
                    //
                    await Task.Delay(interval, stoppingToken);

                    //
                    try
                    {
                        //
                        var removed = vectorStore.RemoveExpired();
                        if (removed > 0)
                        {
                            //
                            logger.LogInformation(
                                "InMemoryVectorStore Cleanup: {Removed} Expired Session(s) Removed, {Count} Remaining",
                                removed,
                                vectorStore.Count
                            );
                        }
                    }
                    catch (Exception ex)
                    {
                        logger.LogError(ex, "InMemoryVectorStore Cleanup Failed");
                    }
                }
            }
            catch (OperationCanceledException)
            {
                // Shutdown ...
            }
        }
    }
}

### FILE: C:\Users\saherelm\Documents\Projects\xSaherelmWorkspace\xAiApi\Providers\XTextChunker.cs

using System.Linq;
using System.Text;
using xAiApi.Models;
using xAiApi.Interfaces;
using xAiApi.Extensions;
using xCommons.Extensions;
using xAiApi.Configurations;
using xExceptions.Constants;
using System.Collections.Generic;
using System.Text.RegularExpressions;

namespace xAiApi.Providers
{
    /// <summary>
    /// Splits Long Texts into Overlapping Chunks using a Hierarchical Strategy:
    /// Paragraphs -> Sentences -> Words -> Hard Cut ...
    /// </summary>
    public class XTextChunker : IXTextChunker
    {
        /// <summary>
        /// Default Options which used when no Options Provided ...
        /// </summary>
        private readonly XAiApiConfiguration configuration;

        /// <summary>
        /// Matches Paragraph Boundaries (two or more Line Breaks) ...
        /// </summary>
        private static readonly Regex ParagraphSplitter = new(
            @"\n\s*\n+",
            RegexOptions.Compiled
        );

        /// <summary>
        /// Matches Sentence Boundaries, Supports Latin, Persian and CJK Terminators ...
        /// </summary>
        private static readonly Regex SentenceSplitter = new(
            @"(?<=[\.\!\?؟。！？])\s+|(?<=\n)",
            RegexOptions.Compiled
        );

        /// <summary>
        /// Matches Repeated Horizontal Whitespaces ...
        /// </summary>
        private static readonly Regex HorizontalWhitespace = new(
            @"[ \t\f\v\u00A0]{2,}",
            RegexOptions.Compiled
        );

        /// <summary>
        /// Matches Three or more Line Breaks ...
        /// </summary>
        private static readonly Regex ExcessiveLineBreaks = new(
            @"\n{3,}",
            RegexOptions.Compiled
        );

        public XTextChunker(
            XAiApiConfiguration configuration
        )
        {
            //
            // Validate Configuration ...
            if (
                !configuration.IsValid() ||
                !configuration.TextChunker.IsValid()
            )
            {
                XException.InvalidConfiguration.Throw();
            }

            //
            this.configuration = configuration;
        }

        /// <summary>
        /// Split Text into Chunks ...
        /// </summary>
        /// <param name="text"></param>
        /// <param name="source"></param>
        /// <returns></returns>
        public IList<XTextChunk> Chunk(
            string text,
            string source = null
        )
        {
            //
            var result = new List<XTextChunk>();
            if (text.IsNullOrEmpty() || string.IsNullOrWhiteSpace(text))
            {
                return result;
            }

            //
            // Normalize ...
            var normalized = configuration.TextChunker.NormalizeWhitespace
                ? Normalize(text)
                : text;

            //
            // Short Circuit for Small Texts ...
            if (normalized.Length <= configuration.TextChunker.ChunkSize)
            {
                //
                result.Add(CreateChunk(normalized, 0, 0, source));
                return result;
            }

            //
            // Build Atomic Units (never larger than ChunkSize) ...
            var units = BuildUnits(normalized);

            //
            // Accumulate Units into Chunks with Overlap ...
            var chunks = Accumulate(units);

            //
            // Merge too Small Tail Chunks ...
            chunks = MergeSmallChunks(chunks);

            //
            for (var i = 0; i < chunks.Count; i++)
            {
                result.Add(CreateChunk(chunks[i].Text, chunks[i].Offset, i, source));
            }

            //
            return result;
        }

        /// <summary>
        /// Split Text into Chunks and Return only Texts ...
        /// </summary>
        /// <param name="text"></param>
        /// <returns></returns>
        public IList<string> ChunkTexts(string text)
        {
            //
            var result = Chunk(text, null)
                .Select(c => c.Text)
                .ToList();

            //
            return result;
        }

        //
        #region Private ...
        /// <summary>
        /// Internal Text Unit with its Offset in Normalized Source ...
        /// </summary>
        private readonly struct Unit
        {
            public Unit(string text, int offset)
            {
                Text = text;
                Offset = offset;
            }

            public string Text { get; }
            public int Offset { get; }
        }

        /// <summary>
        /// Normalize Line Endings and Whitespaces ...
        /// </summary>
        /// <param name="text"></param>
        /// <returns></returns>
        private string Normalize(string text)
        {
            //
            var result = text
                .Replace("\r\n", "\n")
                .Replace('\r', '\n');

            //
            result = HorizontalWhitespace.Replace(result, " ");
            result = ExcessiveLineBreaks.Replace(result, "\n\n");

            //
            result = result.Trim();

            //
            return result;
        }

        /// <summary>
        /// Create Chunk Model ...
        /// </summary>
        /// <param name="text"></param>
        /// <param name="offset"></param>
        /// <param name="index"></param>
        /// <param name="source"></param>
        /// <returns></returns>
        private XTextChunk CreateChunk(
            string text,
            int offset,
            int index,
            string source
        )
        {
            //
            var identifier = source.IsNullOrEmpty()
                ? index.ToString()
                : $"{source}{configuration.TextChunker.ChunkIdentifierSeparator}{index}";

            //
            var result = new XTextChunk
            {
                Text = text,
                Index = index,
                Source = source,
                StartOffset = offset,
                Identifier = identifier
            };

            //
            return result;
        }

        /// <summary>
        /// Split Text into Atomic Units; each Unit Guaranteed to fit in ChunkSize ...
        /// </summary>
        /// <param name="text"></param>
        /// <returns></returns>
        private List<Unit> BuildUnits(string text)
        {
            //
            var result = new List<Unit>();

            //
            foreach (var paragraph in SplitWithOffsets(text, ParagraphSplitter, 0))
            {
                //
                if (paragraph.Text.Length <= configuration.TextChunker.ChunkSize)
                {
                    //
                    result.Add(paragraph);
                    continue;
                }

                //
                // Paragraph too Long -> Sentences ...
                foreach (var sentence in SplitWithOffsets(paragraph.Text, SentenceSplitter, paragraph.Offset))
                {
                    //
                    if (sentence.Text.Length <= configuration.TextChunker.ChunkSize)
                    {
                        //
                        result.Add(sentence);
                        continue;
                    }

                    //
                    // Sentence too Long -> Word Boundary Hard Cut ...
                    result.AddRange(HardSplit(sentence, configuration.TextChunker.ChunkSize));
                }
            }

            //
            return result;
        }

        /// <summary>
        /// Split Text by Regex while Tracking Offsets, Skipping Empty Parts ...
        /// </summary>
        /// <param name="text"></param>
        /// <param name="splitter"></param>
        /// <param name="baseOffset"></param>
        /// <returns></returns>
        private IEnumerable<Unit> SplitWithOffsets(
            string text,
            Regex splitter,
            int baseOffset
        )
        {
            //
            var position = 0;
            foreach (Match match in splitter.Matches(text))
            {
                //
                var part = text.Substring(position, match.Index - position);
                var unit = TrimUnit(part, baseOffset + position);
                if (!unit.Text.IsNullOrEmpty())
                {
                    yield return unit;
                }

                //
                position = match.Index + match.Length;
            }

            //
            if (position < text.Length)
            {
                //
                var tail = TrimUnit(text.Substring(position), baseOffset + position);
                if (!tail.Text.IsNullOrEmpty())
                {
                    yield return tail;
                }
            }
        }

        /// <summary>
        /// Trim Unit Text while Adjusting its Offset ...
        /// </summary>
        /// <param name="text"></param>
        /// <param name="offset"></param>
        /// <returns></returns>
        private Unit TrimUnit(
            string text,
            int offset
        )
        {
            //
            var start = 0;
            while (start < text.Length && char.IsWhiteSpace(text[start]))
            {
                start++;
            }

            //
            var end = text.Length;
            while (end > start && char.IsWhiteSpace(text[end - 1]))
            {
                end--;
            }

            //
            var result = new Unit(text.Substring(start, end - start), offset + start);

            //
            return result;
        }

        /// <summary>
        /// Cut a Unit into Pieces no Longer than Max Size, Preferring Whitespace Boundaries ...
        /// </summary>
        /// <param name="unit"></param>
        /// <param name="maxSize"></param>
        /// <returns></returns>
        private IEnumerable<Unit> HardSplit(
            Unit unit,
            int maxSize
        )
        {
            //
            var text = unit.Text;
            var position = 0;

            //
            while (position < text.Length)
            {
                //
                var remaining = text.Length - position;
                if (remaining <= maxSize)
                {
                    //
                    yield return TrimUnit(text.Substring(position), unit.Offset + position);
                    yield break;
                }

                //
                // Find Last Whitespace within Window ...
                var cut = text.LastIndexOfAny(WordBoundaries, position + maxSize - 1, maxSize);
                if (cut <= position)
                {
                    //
                    // No Whitespace -> Hard Cut ...
                    cut = position + maxSize;
                }

                //
                var piece = TrimUnit(text.Substring(position, cut - position), unit.Offset + position);
                if (!piece.Text.IsNullOrEmpty())
                {
                    yield return piece;
                }

                //
                position = cut;
                while (position < text.Length && char.IsWhiteSpace(text[position]))
                {
                    position++;
                }
            }
        }

        /// <summary>
        /// Accumulate Units into Chunks up to ChunkSize, Carrying Overlap to Next Chunk ...
        /// </summary>
        /// <param name="units"></param>
        /// <returns></returns>
        private List<Unit> Accumulate(List<Unit> units)
        {
            //
            var result = new List<Unit>();
            if (!units.HasChild())
            {
                return result;
            }

            //
            var buffer = new StringBuilder();
            var buffered = new List<Unit>();
            var bufferOffset = -1;

            //
            foreach (var unit in units)
            {
                //
                var separator = buffer.Length > 0 ? " " : string.Empty;
                var projected = buffer.Length + separator.Length + unit.Text.Length;

                //
                if (projected > configuration.TextChunker.ChunkSize && buffer.Length > 0)
                {
                    //
                    // Close Current Chunk ...
                    var closed = buffer.ToString();
                    result.Add(new Unit(closed, bufferOffset));

                    //
                    // Seed Next Chunk with Overlap Tail (only if Unit still Fits) ...
                    var overlap = TakeOverlap(closed, configuration.TextChunker.ChunkOverlap);
                    var fits = overlap.Length + 1 + unit.Text.Length <= configuration.TextChunker.ChunkSize;

                    //
                    buffer.Clear();
                    if (!overlap.IsNullOrEmpty() && fits)
                    {
                        //
                        bufferOffset = ComputeOverlapOffset(buffered, overlap.Length);
                        buffer.Append(overlap);
                        separator = " ";
                    }
                    else
                    {
                        //
                        bufferOffset = -1;
                        separator = string.Empty;
                    }

                    //
                    buffered.Clear();
                }

                //
                if (bufferOffset < 0)
                {
                    bufferOffset = unit.Offset;
                }

                //
                buffer.Append(separator).Append(unit.Text);
                buffered.Add(unit);
            }

            //
            if (buffer.Length > 0)
            {
                result.Add(new Unit(buffer.ToString(), bufferOffset));
            }

            //
            return result;
        }

        /// <summary>
        /// Map Trailing Overlap Length of Buffered Units back to Source Offset ...
        /// Units Joined by Single Space Separator in Buffer ...
        /// </summary>
        /// <param name="buffered"></param>
        /// <param name="overlapLength"></param>
        /// <returns></returns>
        private int ComputeOverlapOffset(
            List<Unit> buffered,
            int overlapLength
        )
        {
            //
            var result = 0;
            var remaining = overlapLength;
            for (var i = buffered.Count - 1; i >= 0; i--)
            {
                //
                var unit = buffered[i];
                if (remaining <= unit.Text.Length)
                {
                    //
                    result = unit.Offset + unit.Text.Length - remaining;
                    return result;
                }

                //
                // Consume Unit and its Leading Separator ...
                remaining -= unit.Text.Length + 1;
                if (remaining <= 0)
                {
                    //
                    result = unit.Offset;
                    return result;
                }
            }

            //
            result = buffered.Count > 0 ? buffered[0].Offset : 0;

            //
            return result;
        }

        /// <summary>
        /// Take Trailing Overlap from Text, Aligned to Word Boundary ...
        /// </summary>
        /// <param name="text"></param>
        /// <param name="overlap"></param>
        /// <returns></returns>
        private string TakeOverlap(
            string text,
            int overlap
        )
        {
            //
            if (overlap <= 0 || text.Length <= overlap)
            {
                return string.Empty;
            }

            //
            var start = text.Length - overlap;
            var boundary = text.IndexOfAny(WordBoundaries, start);
            if (boundary < 0 || boundary >= text.Length - 1)
            {
                //
                // No Boundary inside Window -> Skip Overlap ...
                return string.Empty;
            }

            //
            return text.Substring(boundary + 1).Trim();
        }

        /// <summary>
        /// Merge Chunks Smaller than MinChunkSize into their Predecessor ...
        /// </summary>
        /// <param name="chunks"></param>
        /// <returns></returns>
        private List<Unit> MergeSmallChunks(List<Unit> chunks)
        {
            //
            if (configuration.TextChunker.MinChunkSize <= 0 || chunks.Count < 2)
            {
                return chunks;
            }

            //
            var result = new List<Unit>();
            foreach (var chunk in chunks)
            {
                //
                if (chunk.Text.Length < configuration.TextChunker.MinChunkSize && result.Count > 0)
                {
                    //
                    var previous = result[result.Count - 1];
                    var merged = $"{previous.Text} {chunk.Text}";
                    if (merged.Length <= configuration.TextChunker.ChunkSize)
                    {
                        result[result.Count - 1] = new Unit(merged, previous.Offset);
                        continue;
                    }
                }

                //
                result.Add(chunk);
            }

            //
            return result;
        }

        /// <summary>
        /// Characters Considered as Word Boundaries ...
        /// </summary>
        private readonly char[] WordBoundaries = [' ', '\n', '\t'];
        #endregion
    }
}

### FILE: C:\Users\saherelm\Documents\Projects\xSaherelmWorkspace\xAiApi\Providers\Extractors\XAudioFileContentExtractor.cs

using System;
using System.IO;
using FFMpegCore;
using System.Linq;
using Whisper.net;
using System.Threading;
using xAiModels.Models;
using xCommons.Extensions;
using xAiApi.Configurations;
using xExceptions.Constants;
using System.Threading.Tasks;
using xAiApi.Interfaces.Extractors;

namespace xAiApi.Providers.Extractors
{
    /// <summary>
    /// Extracts text content from Audio files ...
    /// </summary>    
    public class XAudioFileContentExtractor : IXAudioFileContentExtractor
    {
        /// <summary>
        /// Supported MIME Types ...
        /// </summary>
        private static readonly string[] SupportedMimeTypes =
        [
            "audio/mpeg",
            "audio/mp3",
            "audio/wav",
            "audio/wave",
            "audio/x-wav",
            "audio/ogg",
            "audio/m4a",
            "audio/mp4",
            "audio/aac",
            "audio/x-m4a",
            "audio/webm"
        ];

        private readonly XAiApiConfiguration configuration;

        public XAudioFileContentExtractor(
            XAiApiConfiguration configuration
        )
        {
            //
            if (configuration.Transcript.IsNullOrDefault() ||
                configuration.Transcript.ModelsPath.IsNullOrEmpty())
            {
                XException.InvalidConfiguration.Throw();
            }

            //
            this.configuration = configuration;
        }

        /// <summary>
        /// Check if this extractor supports the specified MIME type ...
        /// </summary>
        public bool CanExtract(string mimeType)
        {
            //
            return SupportedMimeTypes.Contains(
                mimeType?.ToLowerInvariant() ?? string.Empty
            );
        }

        /// <summary>
        /// Extract text content from file stream ...
        /// </summary>
        public async Task<string> ExtractAsync(
            Stream fileStream,
            string mimeType,
            CancellationToken cancellationToken = default
        )
        {
            //
            var result = await ExtractRichAsync(
                fileStream,
                "audio",
                mimeType,
                cancellationToken
            );

            //
            return result.AudioTranscript;
        }

        /// <summary>
        /// Extract content from stream as Rich Result ...
        /// </summary>
        /// <param name="fileStream"></param>
        /// <param name="fileName"></param>
        /// <param name="mimeType"></param>
        /// <param name="cancellationToken"></param>
        /// <returns></returns>
        public async Task<XFileExtractionResult> ExtractRichAsync(
            Stream fileStream,
            string fileName,
            string mimeType,
            CancellationToken cancellationToken = default
        )
        {
            //
            var result = new XFileExtractionResult
            {
                FileName = fileName,
                MimeType = mimeType
            };

            //
            try
            {
                //
                using var memoryStream = new MemoryStream();
                await fileStream.CopyToAsync(memoryStream, cancellationToken);
                memoryStream.Position = 0;

                //
                using var wavStream = await ConvertToWavAsync(
                    mimeType: mimeType,
                    inputStream: memoryStream,
                    cancellationToken: cancellationToken
                );

                //
                using var factory = WhisperFactory.FromPath(configuration.Transcript.ModelsPath);
                using var processor = factory.CreateBuilder()
                    .WithLanguage(configuration.Transcript.Language)
                    .Build();

                //
                var segments = new System.Text.StringBuilder();
                await foreach (var segment in processor.ProcessAsync(wavStream, cancellationToken))
                {
                    segments.Append(segment.Text);
                }

                //
                result.AudioTranscript = segments.ToString().Trim();
                result.Text = result.AudioTranscript;
            }
            catch (Exception ex)
            {
                result.ErrorMessage = $"Audio extraction failed: {ex.Message}";
            }

            //
            return result;
        }

        //
        #region Private ...
        /// <summary>
        /// Audio Format Converting to WAV 16kHz Mono 16-bit PCM ...
        /// </summary>
        private async Task<Stream> ConvertToWavAsync(
            Stream inputStream,
            string mimeType,
            CancellationToken cancellationToken = default
        )
        {
            //
            var tempInput = Path.Combine(
                Path.GetTempPath(),
                $"audio_in_{Guid.NewGuid()}{GetExtensionFromMime(mimeType)}"
            );
            var tempOutput = Path.Combine(
                Path.GetTempPath(),
                $"audio_out_{Guid.NewGuid()}.wav"
            );

            //
            MemoryStream result = null;
            try
            {
                //
                using var fs = File.Create(tempInput);
                await inputStream.CopyToAsync(fs, cancellationToken);
                await FFMpegArguments
                    .FromFileInput(tempInput)
                    .OutputToFile(tempOutput, overwrite: true, options => options
                        .WithAudioCodec("pcm_s16le")
                        .WithCustomArgument("-ar 16000")
                        .WithCustomArgument("-ac 1")
                        .ForceFormat("wav"))
                    .ProcessAsynchronously();

                //
                result = new();
                using var fsTmp = File.OpenRead(tempOutput);
                await fsTmp.CopyToAsync(result, cancellationToken);
                result.Position = 0;
            }
            catch
            {
                result = null;
            }
            finally
            {
                //
                // Remove Temparory Files ...
                if (File.Exists(tempInput)) File.Delete(tempInput);
                if (File.Exists(tempOutput)) File.Delete(tempOutput);
            }

            //
            if (result.IsNull())
            {
                XException.ActionFailed.Throw();
            }

            //
            return result;
        }

        /// <summary>
        /// Retrieve File Extension based on mime type ...
        /// </summary>
        /// <param name="mimeType"></param>
        /// <returns></returns>
        private string GetExtensionFromMime(string mimeType)
        {
            //
            return mimeType?.ToLowerInvariant() switch
            {
                "audio/mpeg" or "audio/mp3" => ".mp3",
                "audio/m4a" or "audio/mp4" or "audio/aac" or "audio/x-m4a" => ".m4a",
                "audio/ogg" => ".ogg",
                "audio/webm" => ".webm",
                "audio/wav" or "audio/wave" or "audio/x-wav" => ".wav",
                _ => ".tmp"
            };
        }
        #endregion
    }
}

### FILE: C:\Users\saherelm\Documents\Projects\xSaherelmWorkspace\xAiApi\Providers\Extractors\XCodeFileContentExtractor.cs

using System;
using System.Linq;
using xCommons.Extensions;
using System.Threading.Tasks;
using System.Collections.Generic;
using xAiApi.Interfaces.Extractors;
using System.IO;
using System.Threading;
using xAiModels.Models;
using System.Text;

namespace xAiApi.Providers.Extractors
{
    /// <summary> 
    /// Extractor for source code files ...
    /// (C#, Python, JavaScript, TypeScript, Java, Go, Rust, ...) 
    /// </summary> 
    public class XCodeFileContentExtractor : IXCodeFileContentExtractor
    {
        /// <summary>
        /// Supported MIME Types ...
        /// </summary>
        private static readonly string[] SupportedMimeTypes =
        [
            "text/x-c",
            "text/x-go",
            "text/yaml",
            "text/x-php",
            "text/x-c++",
            "text/x-sql",
            "text/x-java",
            "text/x-rust",
            "text/x-ruby",
            "text/x-csharp",
            "text/x-python",
            "text/javascript",
            "text/typescript",
            "text/x-java-source",
            "application/x-yaml",
            "application/x-csharp",
            "application/x-python",
            "application/javascript",
            "application/typescript",
        ];

        /// <summary>
        /// Check if this extractor supports the specified MIME type ...
        /// </summary>
        /// <param name="mimeType"></param>
        /// <returns></returns>
        public bool CanExtract(string mimeType)
        {
            //
            return SupportedMimeTypes.Contains(
                mimeType?.ToLowerInvariant() ?? string.Empty
            );
        }

        /// <summary>
        /// Extract text content from file stream ...
        /// </summary>
        /// <param name="fileStream"></param>
        /// <param name="mimeType"></param>
        /// <param name="cancellationToken"></param>
        /// <returns></returns>
        public async Task<string> ExtractAsync(
            Stream fileStream,
            string mimeType,
            CancellationToken cancellationToken = default
        )
        {
            //
            var result = await ExtractRichAsync(
                fileStream,
                string.Empty,
                mimeType,
                cancellationToken
            );

            //
            return result.Text;
        }

        /// <summary>
        /// Extract content from stream as Rich Result ...
        /// </summary>
        /// <param name="fileStream"></param>
        /// <param name="fileName"></param>
        /// <param name="mimeType"></param>
        /// <param name="cancellationToken"></param>
        /// <returns></returns>
        public async Task<XFileExtractionResult> ExtractRichAsync(
            Stream fileStream,
            string fileName,
            string mimeType,
            CancellationToken cancellationToken = default
        )
        {
            //
            var result = new XFileExtractionResult
            {
                FileName = fileName,
                MimeType = mimeType
            };

            //
            // Read entire source code as UTF-8 (with BOM detection) ...
            using var reader = new StreamReader(
                fileStream,
                Encoding.UTF8,
                leaveOpen: false,
                detectEncodingFromByteOrderMarks: true
            );

            //
            var content = await reader.ReadToEndAsync();

            //
            // Normalize line endings for consistent downstream processing ...
            content = content?
                .Replace("\r\n", "\n")
                .Replace("\r", "\n");

            //
            result.Text = content;

            //
            return result;
        }
    }
}

### FILE: C:\Users\saherelm\Documents\Projects\xSaherelmWorkspace\xAiApi\Providers\Extractors\XDocxFileContentExtractor.cs

using System;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading;
using xAiModels.Models;
using System.Threading.Tasks;
using xAiApi.Interfaces.Extractors;
using DocumentFormat.OpenXml.Drawing;
using DocumentFormat.OpenXml.Packaging;

namespace xAiApi.Providers.Extractors
{
    /// <summary>
    /// Extracts text content from DOCX files using DocumentFormat.OpenXml ...
    /// </summary>    
    public class XDocxFileContentExtractor : IXDocxFileContentExtractor
    {
        /// <summary>
        /// Supported MIME Types ...
        /// </summary>
        private static readonly string[] SupportedMimeTypes =
        [
            "application/vnd.openxmlformats-officedocument.wordprocessingml.document"
        ];

        /// <summary>
        /// Check if this extractor supports the specified MIME type ...
        /// </summary>
        public bool CanExtract(string mimeType)
        {
            //
            return SupportedMimeTypes.Contains(
                mimeType?.ToLowerInvariant() ?? string.Empty
            );
        }

        /// <summary>
        /// Extract text content from file stream ...
        /// </summary>
        public async Task<string> ExtractAsync(
            Stream fileStream,
            string mimeType,
            CancellationToken cancellationToken = default
        )
        {
            //
            using var memoryStream = new MemoryStream();
            await fileStream.CopyToAsync(memoryStream, cancellationToken);
            memoryStream.Position = 0;

            //
            var stringBuilder = new StringBuilder();

            //
            using (var wordDocument = WordprocessingDocument.Open(memoryStream, false))
            {
                //
                var body = wordDocument.MainDocumentPart?.Document?.Body;
                if (body != null)
                {
                    //
                    var paragraphs = body.Elements<Paragraph>();
                    foreach (var paragraph in paragraphs)
                    {
                        //
                        var text = paragraph.InnerText?.Trim();
                        if (!string.IsNullOrEmpty(text))
                        {
                            stringBuilder.AppendLine(text);
                        }
                    }
                }
            }

            //
            return stringBuilder.ToString();
        }

        /// <summary>
        /// Extract content from stream as Rich Result ...
        /// </summary>
        /// <param name="fileStream"></param>
        /// <param name="fileName"></param>
        /// <param name="mimeType"></param>
        /// <param name="cancellationToken"></param>
        /// <returns></returns>
        public async Task<XFileExtractionResult> ExtractRichAsync(
            Stream fileStream,
            string fileName,
            string mimeType,
            CancellationToken cancellationToken = default
        )
        {
            //
            var content = await ExtractAsync(
                mimeType: mimeType,
                fileStream: fileStream,
                cancellationToken: cancellationToken
            );

            //
            var result = new XFileExtractionResult
            {
                Text = content,
                FileName = fileName,
                MimeType = mimeType
            };

            //
            return result;
        }
    }
}

### FILE: C:\Users\saherelm\Documents\Projects\xSaherelmWorkspace\xAiApi\Providers\Extractors\XEpubFileContentExtractor.cs

using System;
using System.IO;
using System.Linq;
using System.Text;
using VersOne.Epub;
using HtmlAgilityPack;
using System.Threading;
using xAiModels.Models;
using xCommons.Extensions;
using System.Threading.Tasks;
using xAiApi.Interfaces.Extractors;

namespace xAiApi.Providers.Extractors
{
    /// <summary>
    /// Extractor for EPUB electronic publication format
    /// (application/epub+zip)
    /// </summary>    
    public class XEpubFileContentExtractor : IXEpubFileContentExtractor
    {
        /// <summary>
        /// Supported MIME Types ...
        /// </summary>
        private static readonly string[] SupportedMimeTypes =
        [
            "application/epub+zip"
        ];

        /// <summary>
        /// Check if this extractor supports the specified MIME type ...
        /// </summary>
        /// <param name="mimeType"></param>
        /// <returns></returns>
        public bool CanExtract(string mimeType)
        {
            //
            return SupportedMimeTypes.Contains(
                mimeType?.ToLowerInvariant() ?? string.Empty
            );
        }

        /// <summary>
        /// Extract text content from file stream ...
        /// </summary>
        /// <param name="fileStream"></param>
        /// <param name="mimeType"></param>
        /// <param name="cancellationToken"></param>
        /// <returns></returns>
        public async Task<string> ExtractAsync(
            Stream fileStream,
            string mimeType,
            CancellationToken cancellationToken = default
        )
        {
            //
            var result = await ExtractRichAsync(
                fileStream,
                "book.epub",
                mimeType,
                cancellationToken
            );

            //
            return result.Text;
        }

        /// <summary>
        /// Extract content from stream as Rich Result ...
        /// </summary>
        /// <param name="fileStream"></param>
        /// <param name="fileName"></param>
        /// <param name="mimeType"></param>
        /// <param name="cancellationToken"></param>
        /// <returns></returns>
        public async Task<XFileExtractionResult> ExtractRichAsync(
            Stream fileStream,
            string fileName,
            string mimeType,
            CancellationToken cancellationToken = default
        )
        {
            //
            var result = new XFileExtractionResult
            {
                FileName = fileName,
                MimeType = mimeType
            };

            //
            try
            {
                //
                result.Text = await ExtractEpubAsync(
                    fileStream,
                    cancellationToken
                );
            }
            catch (Exception ex)
            {
                //
                result.ErrorMessage =
                    $"EPUB extraction failed: {ex.Message}";
            }

            //
            return result;
        }

        /// <summary>
        /// Extract Epub Content ...
        /// </summary>
        /// <param name="fileStream"></param>
        /// <param name="cancellationToken"></param>
        /// <returns></returns>
        private async Task<string> ExtractEpubAsync(
            Stream fileStream,
            CancellationToken cancellationToken
        )
        {
            //
            // Copy to MemoryStream (VersOne.Epub requires seekable stream) ...
            await using var ms = new MemoryStream();
            await fileStream.CopyToAsync(ms, cancellationToken);
            ms.Position = 0;

            //
            // Load EPUB book ...
            EpubBook book = await EpubReader.ReadBookAsync(ms);
            var sb = new StringBuilder();

            //
            // Extract metadata ...

            //
            if (!book.Title.IsNullOrEmpty())
            {
                sb.AppendLine($"Title: {book.Title}");
            }

            //
            if (!book.Author.IsNullOrEmpty())
            {
                sb.AppendLine($"Author: {book.Author}");
            }

            //
            sb.AppendLine();

            //
            // Extract chapters in reading order ...
            var chapterIndex = 0;
            foreach (var textContentFile in book.ReadingOrder)
            {
                //
                if (cancellationToken.IsCancellationRequested)
                {
                    break;
                }

                //
                chapterIndex++;
                sb.AppendLine($"[Chapter {chapterIndex}]");
                var plainText = ExtractTextFromHtml(
                    textContentFile.Content
                );
                if (!plainText.IsNullOrEmpty())
                {
                    sb.AppendLine(plainText);
                }

                //
                sb.AppendLine();
            }

            //
            var result = sb.ToString().TrimEnd();

            //
            return result;
        }

        /// <summary>
        /// Extract Text Content from HTML ...
        /// </summary>
        /// <param name="html"></param>
        /// <returns></returns>
        private string ExtractTextFromHtml(string html)
        {
            //
            var result = string.Empty;

            //
            if (html.IsNullOrEmpty())
            {
                return result;
            }

            //
            var htmlDocument = new HtmlDocument();
            htmlDocument.LoadHtml(html);

            //
            var sb = new StringBuilder();
            var textNodes = htmlDocument.DocumentNode
                .SelectNodes("//text()");

            //
            if (textNodes == null)
            {
                return result;
            }

            //
            foreach (var node in textNodes)
            {
                //
                var text = node.InnerText?.Trim();
                if (!text.IsNullOrEmpty())
                {
                    sb.AppendLine(text);
                }
            }

            //
            result = sb.ToString().TrimEnd();

            //
            return result;
        }
    }
}

### FILE: C:\Users\saherelm\Documents\Projects\xSaherelmWorkspace\xAiApi\Providers\Extractors\XExcelFileContentExtractor.cs

using System;
using System.IO;
using System.Data;
using System.Linq;
using System.Text;
using ExcelDataReader;
using System.Threading;
using xAiModels.Models;
using System.Threading.Tasks;
using xAiApi.Interfaces.Extractors;

namespace xAiApi.Providers.Extractors
{
    public class XExcelFileContentExtractor : IXExcelFileContentExtractor
    {
        /// <summary>
        /// Supported MIME Types ...
        /// </summary>
        private static readonly string[] SupportedMimeTypes =
        [
            "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet", // .xlsx
            "application/vnd.ms-excel" // .xls        
        ];

        /// <summary>
        /// Check if this extractor supports the specified MIME type ...
        /// </summary>
        public bool CanExtract(string mimeType)
        {
            //
            return SupportedMimeTypes.Contains(
                mimeType?.ToLowerInvariant() ?? string.Empty
            );
        }

        /// <summary>
        /// Extract text content from file stream ...
        /// </summary>
        public async Task<string> ExtractAsync(
            Stream fileStream,
            string mimeType,
            CancellationToken cancellationToken = default
        )
        {
            //
            Encoding.RegisterProvider(CodePagesEncodingProvider.Instance);

            //
            using var memoryStream = new MemoryStream();
            await fileStream.CopyToAsync(memoryStream, cancellationToken);
            memoryStream.Position = 0;

            //
            var stringBuilder = new StringBuilder();

            //
            using (var reader = ExcelReaderFactory.CreateReader(memoryStream))
            {
                //
                var result = reader.AsDataSet();
                foreach (DataTable table in result.Tables)
                {
                    //
                    stringBuilder.AppendLine($"--- Sheet: {table.TableName} ---");

                    //
                    var headers = new string[table.Columns.Count];
                    for (int i = 0; i < table.Columns.Count; i++)
                    {
                        headers[i] = table.Columns[i].ColumnName;
                    }
                    stringBuilder.AppendLine(string.Join(" | ", headers));
                    stringBuilder.AppendLine(new string('-', 50));

                    //
                    foreach (DataRow row in table.Rows)
                    {
                        //
                        var rowValues = new string[row.ItemArray.Length];
                        for (int i = 0; i < row.ItemArray.Length; i++)
                        {
                            rowValues[i] = row.ItemArray[i]?.ToString()?.Trim() ?? string.Empty;
                        }
                        stringBuilder.AppendLine(string.Join(" | ", rowValues));
                    }
                    stringBuilder.AppendLine();
                }
            }

            //
            return stringBuilder.ToString();
        }

        /// <summary>
        /// Extract content from stream as Rich Result ...
        /// </summary>
        /// <param name="fileStream"></param>
        /// <param name="fileName"></param>
        /// <param name="mimeType"></param>
        /// <param name="cancellationToken"></param>
        /// <returns></returns>
        public async Task<XFileExtractionResult> ExtractRichAsync(
            Stream fileStream,
            string fileName,
            string mimeType,
            CancellationToken cancellationToken = default
        )
        {
            //
            var content = await ExtractAsync(
                mimeType: mimeType, 
                fileStream: fileStream, 
                cancellationToken: cancellationToken
            );

            //
            var result = new XFileExtractionResult
            {
                Text = content,
                FileName = fileName,
                MimeType = mimeType
            };

            //
            return result;
        }
    }
}

### FILE: C:\Users\saherelm\Documents\Projects\xSaherelmWorkspace\xAiApi\Providers\Extractors\XFileContentExtractor.cs

using System.IO;
using System.Linq;
using System.Threading;
using xAiModels.Models;
using xCommons.Extensions;
using xExceptions.Constants;
using System.Threading.Tasks;
using System.Collections.Generic;
using xAiApi.Interfaces.Extractors;

namespace xAiApi.Providers.Extractors
{
    /// <summary>
    /// Composite extractor that delegates to appropriate extractor 
    /// based on MIME type ...
    /// </summary>    
    public class XFileContentExtractor : IXFileContentExtractor
    {
        //
        private readonly IList<IXFileContentExtractorBase> _extractors = [];

        public XFileContentExtractor(
            IEnumerable<IXFileContentExtractorBase> availableExtractors
        )
        {
            //
            _extractors = [.. availableExtractors
                .Where(e => e.GetType() != typeof(XFileContentExtractor))];
        }

        /// <summary>
        /// Check if this extractor supports the specified MIME type ...
        /// </summary>
        /// <param name="mimeType"></param>
        /// <param name="extractors"></param>
        /// <returns></returns>
        public bool CanExtract(
            string mimeType,
            string[] extractors = null
        )
        {
            //
            return GetExtractors(extractors)
                .Any(e => e.CanExtract(mimeType));
        }

        /// <summary>
        /// Extract text content from file stream ...
        /// </summary>
        /// <param name="fileStream"></param>
        /// <param name="mimeType"></param>
        /// <param name="extractors"></param>
        /// <param name="cancellationToken"></param>
        /// <returns></returns>
        public async Task<string> ExtractAsync(
            Stream fileStream,
            string mimeType,
            string[] extractors = null,
            CancellationToken cancellationToken = default
        )
        {
            //
            var extractor = GetExtractors(extractors)
                .FirstOrDefault(e => e.CanExtract(mimeType));
            if (extractor.IsNull())
            {
                //
                XException.NotAllowed.Throw(
                    $"Unsupported file type: {mimeType}"
                );
            }

            //
            var result = await extractor
                .ExtractAsync(
                    mimeType: mimeType,
                    fileStream: fileStream,
                    cancellationToken: cancellationToken
                );

            //
            return result;
        }

        /// <summary>
        /// Extract content from stream as Rich Result ...
        /// </summary>
        /// <param name="fileStream"></param>
        /// <param name="fileName"></param>
        /// <param name="mimeType"></param>
        /// <param name="extractors"></param>
        /// <param name="cancellationToken"></param>
        /// <returns></returns>
        public async Task<XFileExtractionResult> ExtractRichAsync(
            Stream fileStream,
            string fileName,
            string mimeType,
            string[] extractors = null,
            CancellationToken cancellationToken = default
        )
        {
            //
            var extractor = GetExtractors(extractors)
                .FirstOrDefault(e => e.CanExtract(mimeType));
            if (extractor.IsNull())
            {
                //
                XException.NotAllowed.Throw(
                    $"Unsupported file type: {mimeType}"
                );
            }

            //
            var result = await extractor
                .ExtractRichAsync(
                    mimeType: mimeType,
                    fileName: fileName,
                    fileStream: fileStream,
                    cancellationToken: cancellationToken
                );

            //
            return result;
        }

        /// <summary>
        /// Extract Provided Extractors ...
        /// </summary>
        /// <param name="extractors"></param>
        /// <returns></returns>
        private IList<IXFileContentExtractorBase> GetExtractors(string[] extractors = null)
        {
            //
            var result = new List<IXFileContentExtractorBase>();

            //
            if (extractors.IsNull() || !extractors.HasChild())
            {
                //
                result = [.. _extractors];
            }
            else
            {
                //
                result = [.. _extractors
                    .Where(e => extractors
                        .Any(ex => e.GetType().FullName.Contains(ex)))];
            }

            //
            return result;
        }
    }
}

### FILE: C:\Users\saherelm\Documents\Projects\xSaherelmWorkspace\xAiApi\Providers\Extractors\XHtmlFileContentExtractor.cs

using System;
using System.IO;
using System.Linq;
using System.Text;
using HtmlAgilityPack;
using System.Threading;
using xAiModels.Models;
using xCommons.Extensions;
using System.Threading.Tasks;
using xAiApi.Interfaces.Extractors;

namespace xAiApi.Providers.Extractors
{
    /// <summary>
    /// Extractor for HTML documents (text/html, application/xhtml+xml)
    /// </summary>
    public class XHtmlFileContentExtractor : IXHtmlFileContentExtractor
    {
        /// <summary>
        /// Supported MIME Types ...
        /// </summary>
        private static readonly string[] SupportedMimeTypes =
        [
            "text/html",
            "application/xhtml+xml"
        ];

        /// <summary>
        /// Check if this extractor supports the specified MIME type ...
        /// </summary>
        /// <param name="mimeType"></param>
        /// <returns></returns>
        public bool CanExtract(string mimeType)
        {
            //
            return SupportedMimeTypes.Contains(
                mimeType?.ToLowerInvariant() ?? string.Empty
            );
        }

        /// <summary>
        /// Extract text content from file stream ...
        /// </summary>
        /// <param name="fileStream"></param>
        /// <param name="mimeType"></param>
        /// <param name="cancellationToken"></param>
        /// <returns></returns>
        public async Task<string> ExtractAsync(
            Stream fileStream,
            string mimeType,
            CancellationToken cancellationToken = default
        )
        {
            //
            var result = await ExtractRichAsync(
                fileStream,
                "document.html",
                mimeType,
                cancellationToken
            );

            //
            return result.Text;
        }

        /// <summary>
        /// Extract content from stream as Rich Result ...
        /// </summary>
        /// <param name="fileStream"></param>
        /// <param name="fileName"></param>
        /// <param name="mimeType"></param>
        /// <param name="cancellationToken"></param>
        /// <returns></returns>
        public async Task<XFileExtractionResult> ExtractRichAsync(
            Stream fileStream,
            string fileName,
            string mimeType,
            CancellationToken cancellationToken = default
        )
        {
            //
            var result = new XFileExtractionResult
            {
                FileName = fileName,
                MimeType = mimeType
            };

            //
            try
            {
                //
                result.Text = await ExtractHtmlAsync(
                    fileStream,
                    cancellationToken
                );
            }
            catch (Exception ex)
            {
                result.ErrorMessage =
                    $"HTML extraction failed: {ex.Message}";
            }

            //
            return result;
        }

        /// <summary>
        /// Extract Html Content as Text ...
        /// </summary>
        /// <param name="fileStream"></param>
        /// <param name="cancellationToken"></param>
        /// <returns></returns>
        private async Task<string> ExtractHtmlAsync(
            Stream fileStream,
            CancellationToken cancellationToken
        )
        {
            // Load HTML into HtmlDocument
            var html = new HtmlDocument();
            html.Load(fileStream);

            // Remove noise nodes (script, style, etc.)
            RemoveNoiseNodes(html);

            // Extract title
            var title = ExtractTitle(html);

            // Extract body text
            var body = html.DocumentNode
                .SelectSingleNode("//body");
            var bodyText = body?.InnerText ?? string.Empty;

            // Clean and normalize text
            var cleanedText = CleanText(bodyText);

            // Build structured output
            var sb = new StringBuilder();
            if (!string.IsNullOrWhiteSpace(title))
            {
                sb.AppendLine($"Title: {title}");
                sb.AppendLine();
            }
            sb.AppendLine(cleanedText);

            return sb.ToString().TrimEnd();
        }

        /// <summary>
        /// Remove Noisy Nodes ...
        /// </summary>
        /// <param name="html"></param>
        private void RemoveNoiseNodes(HtmlDocument html)
        {
            //
            // Remove script and style tags ...
            var noiseTags = new[] { "script", "style", "noscript", "iframe" };
            foreach (var tag in noiseTags)
            {
                //
                var nodes = html.DocumentNode
                    .Descendants(tag)
                    .ToList();
                foreach (var node in nodes)
                {
                    node.Remove();
                }
            }
        }

        /// <summary>
        /// Extract Title ...
        /// </summary>
        /// <param name="html"></param>
        /// <returns></returns>
        private string ExtractTitle(HtmlDocument html)
        {
            //
            var titleNode = html.DocumentNode
                .SelectSingleNode("//title");

            //
            var result = titleNode?.InnerText?.Trim() ?? string.Empty;

            //
            return result;
        }

        /// <summary>
        /// Clean Text ...
        /// </summary>
        /// <param name="text"></param>
        /// <returns></returns>
        private string CleanText(string text)
        {
            //
            var result = string.Empty;

            //
            if (text.IsNullOrEmpty())
            {
                result = string.Empty;
            }

            //
            // Decode HTML entities ...
            text = System.Net.WebUtility.HtmlDecode(text);

            //
            // Normalize whitespace ...
            text = System.Text.RegularExpressions.Regex
                .Replace(text, @"\s+", " ")
                .Trim();

            //
            result = text;

            //
            return result;
        }
    }
}

### FILE: C:\Users\saherelm\Documents\Projects\xSaherelmWorkspace\xAiApi\Providers\Extractors\XImageFileContentExtractor.cs

using System;
using System.IO;
using System.Linq;
using System.Threading;
using xAiModels.Models;
using System.Threading.Tasks;
using xAiApi.Interfaces.Extractors;
using xAiApi.Configurations;
using xCommons.Extensions;
using xExceptions.Constants;
using Tesseract;

namespace xAiApi.Providers.Extractors
{
    public class XImageFileContentExtractor : IXImageFileContentExtractor
    {
        /// <summary>
        /// Supported MIME Types ...
        /// </summary>
        private static readonly string[] SupportedMimeTypes =
        [
            "image/png",
            "image/jpeg",
            "image/jpg",
            "image/gif",
            "image/webp",
            "image/bmp"
        ];

        /// <summary>
        /// AI Api Configuration ...
        /// </summary>
        private readonly XAiApiConfiguration configuration;

        public XImageFileContentExtractor(
            XAiApiConfiguration configuration
        )
        {
            //
            if (configuration.IsNullOrDefault() ||
                configuration.OCR.IsNullOrDefault() ||
                configuration.OCR.DataPath.IsNullOrEmpty() ||
                configuration.OCR.DefaultLanguage.IsNullOrEmpty())
            {
                XException.InvalidConfiguration.Throw();
            }

            //
            this.configuration = configuration;
        }

        /// <summary>
        /// Check if this extractor supports the specified MIME type ...
        /// </summary>
        public bool CanExtract(string mimeType)
        {
            //
            return SupportedMimeTypes.Contains(
                mimeType?.ToLowerInvariant() ?? string.Empty
            );
        }

        /// <summary>
        /// Extract text content from file stream ...
        /// </summary>
        public async Task<string> ExtractAsync(
            Stream fileStream,
            string mimeType,
            CancellationToken cancellationToken = default
        )
        {
            //
            var result = await ExtractRichAsync(
                fileStream,
                "image",
                mimeType,
                cancellationToken
            );

            //
            return result.Text;
        }

        /// <summary>
        /// Extract content from stream as Rich Result ...
        /// </summary>
        /// <param name="fileStream"></param>
        /// <param name="fileName"></param>
        /// <param name="mimeType"></param>
        /// <param name="cancellationToken"></param>
        /// <returns></returns>
        public async Task<XFileExtractionResult> ExtractRichAsync(
            Stream fileStream,
            string fileName,
            string mimeType,
            CancellationToken cancellationToken = default
        )
        {
            //
            var result = new XFileExtractionResult
            {
                FileName = fileName,
                MimeType = mimeType
            };

            //
            using var memoryStream = new MemoryStream();
            await fileStream.CopyToAsync(memoryStream, cancellationToken);
            var imageBytes = memoryStream.ToArray();

            //
            result.Images.Add(new XExtractedImage
            {
                Bytes = imageBytes,
                MimeType = mimeType,
                Description = $"Attached image: {fileName}"
            });

            //
            // OCR Fallback ...
            if (configuration.OCR.EnableOcrFallback)
            {
                //
                try
                {
                    //
                    var ocrText = await PerformOcrAsync(imageBytes, cancellationToken);
                    if (!string.IsNullOrWhiteSpace(ocrText))
                    {
                        result.Text = ocrText;
                    }
                }
                catch
                {
                    // OCR failed, but image is still available for Vision
                }
            }

            //
            return result;
        }

        /// <summary>
        /// Do OCR on Image for Text Extraction ...
        /// </summary>
        private async Task<string> PerformOcrAsync(
            byte[] imageBytes,
            CancellationToken cancellationToken
        )
        {
            //
            return await Task.Run(() =>
            {
                //
                // Validate Path ...
                if (!Directory.Exists(configuration.OCR.DataPath))
                {
                    //
                    throw new DirectoryNotFoundException(
                        $"TessData directory not found at: {configuration.OCR.DataPath}. " +
                        "Please download traineddata files from https://github.com/tesseract-ocr/tessdata"
                    );
                }
            
                //
                using var engine = new TesseractEngine(
                    datapath: configuration.OCR.DataPath,
                    language: configuration.OCR.DefaultLanguage,
                    engineMode: configuration.OCR.EngineMode
                );

                //
                using var pix = Pix.LoadFromMemory(imageBytes);

                //
                cancellationToken.ThrowIfCancellationRequested();

                //
                using var page = engine.Process(pix);

                //
                var text = page.GetText();

                //
                text = text?.Trim();

                //
                return text ?? string.Empty;
            }, cancellationToken);
        }
    }
}

### FILE: C:\Users\saherelm\Documents\Projects\xSaherelmWorkspace\xAiApi\Providers\Extractors\XOpenDocumentFileContentExtractor.cs

using System;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading;
using xAiModels.Models;
using xCommons.Extensions;
using System.Threading.Tasks;
using OfficeIMO.OpenDocument;
using System.Collections.Generic;
using xAiApi.Interfaces.Extractors;

namespace xAiApi.Providers.Extractors
{
    /// <summary>
    /// Extractor for OpenDocument Format (ODF) documents
    /// (ODT: OpenDocument Text, ODS: OpenDocument Spreadsheet, ODP: OpenDocument Presentation)
    /// </summary>    
    public class XOpenDocumentFileContentExtractor : IXOpenDocumentFileContentExtractor
    {
        /// <summary>
        /// Supported MIME Types ...
        /// </summary>
        private static readonly string[] SupportedMimeTypes =
        [
            "application/vnd.oasis.opendocument.text",          // .odt
            "application/vnd.oasis.opendocument.spreadsheet",   // .ods
            "application/vnd.oasis.opendocument.presentation"   // .odp
        ];

        /// <summary>
        /// Check if this extractor supports the specified MIME type ...
        /// </summary>
        /// <param name="mimeType"></param>
        /// <returns></returns>
        public bool CanExtract(string mimeType)
        {
            //
            return SupportedMimeTypes.Contains(
                mimeType?.ToLowerInvariant() ?? string.Empty
            );
        }

        /// <summary>
        /// Extract text content from file stream ...
        /// </summary>
        public async Task<string> ExtractAsync(
            Stream fileStream,
            string mimeType,
            CancellationToken cancellationToken = default
        )
        {
            //
            var result = await ExtractRichAsync(
                fileStream,
                "document.rtf",
                mimeType,
                cancellationToken
            );

            //
            return result.Text;
        }

        /// <summary>
        /// Extract content from stream as Rich Result ...
        /// </summary>
        /// <param name="fileStream"></param>
        /// <param name="fileName"></param>
        /// <param name="mimeType"></param>
        /// <param name="cancellationToken"></param>
        /// <returns></returns>
        public async Task<XFileExtractionResult> ExtractRichAsync(
            Stream fileStream,
            string fileName,
            string mimeType,
            CancellationToken cancellationToken = default
        )
        {
            //
            var result = new XFileExtractionResult
            {
                FileName = fileName,
                MimeType = mimeType
            };

            // 
            try
            {
                //
                if (IsOdt(mimeType))
                {
                    result.Text = await ExtractOdtAsync(fileStream, cancellationToken);
                }
                else if (IsOds(mimeType))
                {
                    result.Text = await ExtractOdsAsync(fileStream, cancellationToken);
                }
                else if (IsOdp(mimeType))
                {
                    result.Text = await ExtractOdpAsync(fileStream, cancellationToken);
                }
                else
                {
                    result.ErrorMessage =
                        $"Unsupported OpenDocument MIME type: {mimeType}";
                }
            }
            catch (Exception ex)
            {
                //
                result.ErrorMessage =
                    $"RTF extraction failed: {ex.Message}";
            }

            //
            return result;
        }

        /// <summary>
        /// Check Mime Type ...
        /// </summary>
        /// <param name="mimeType"></param>
        /// <returns></returns>
        private bool IsOdt(string mimeType)
        {
            //
            var result = mimeType?
                .ToLowerInvariant() == "application/vnd.oasis.opendocument.text";

            //
            return result;
        }

        /// <summary>
        /// Check Mime Type ...
        /// </summary>
        /// <param name="mimeType"></param>
        /// <returns></returns>
        private bool IsOds(string mimeType)
        {
            //
            var result = mimeType?
                .ToLowerInvariant() == "application/vnd.oasis.opendocument.spreadsheet";

            //
            return result;
        }

        /// <summary>
        /// Check Mime Type ...
        /// </summary>
        /// <param name="mimeType"></param>
        /// <returns></returns>
        private bool IsOdp(string mimeType)
        {
            //
            var result = mimeType?
                .ToLowerInvariant() == "application/vnd.oasis.opendocument.presentation";

            //
            return result;
        }

        /// <summary>
        /// Extract ODT File Content ...
        /// </summary>
        /// <param name="fileStream"></param>
        /// <param name="cancellationToken"></param>
        /// <returns></returns>
        private async Task<string> ExtractOdtAsync(
            Stream fileStream,
            CancellationToken cancellationToken
        )
        {
            //
            await using var ms = new MemoryStream();
            await fileStream.CopyToAsync(ms, cancellationToken);
            ms.Position = 0;

            //
            var document = OdtDocument.Load(ms);

            //
            var sb = new StringBuilder();
            foreach (var paragraph in document.Paragraphs)
            {
                //
                if (cancellationToken.IsCancellationRequested)
                {
                    break;
                }

                //
                if (!paragraph.Text.IsNullOrEmpty())
                {
                    sb.AppendLine(paragraph.Text.Trim());
                }
            }

            //
            // 4. استخراج جداول
            var tableIndex = 0;
            foreach (var table in document.Tables)
            {
                //
                if (cancellationToken.IsCancellationRequested)
                {
                    break;
                }

                //
                tableIndex++;
                sb.AppendLine();
                sb.AppendLine($"[Table {tableIndex}]");

                //
                foreach (var row in table.Rows)
                {
                    //
                    var cellTexts = new List<string>();
                    foreach (var cell in row.Cells)
                    {
                        //
                        var cellText = string.Join(
                            " ",
                            cell.Paragraphs
                                .Select(p => p.Text?.Trim())
                                .Where(t => !string.IsNullOrWhiteSpace(t))
                        );
                        cellTexts.Add(cellText);
                    }

                    //
                    sb.AppendLine($"  | {string.Join(" | ", cellTexts)} |");
                }

                //
                sb.AppendLine();
            }

            //
            var result = sb.ToString().TrimEnd();

            //
            return result;
        }

        /// <summary>
        /// Extract ODS File Content ...
        /// </summary>
        /// <param name="fileStream"></param>
        /// <param name="cancellationToken"></param>
        /// <returns></returns>
        private async Task<string> ExtractOdsAsync(
            Stream fileStream,
            CancellationToken cancellationToken
        )
        {
            //
            await using var ms = new MemoryStream();
            await fileStream.CopyToAsync(ms, cancellationToken);
            ms.Position = 0;

            //
            var document = OdsDocument.Load(ms);
            var sb = new StringBuilder();
            var sheetIndex = 0;
            foreach (var sheet in document.Sheets)
            {
                //
                if (cancellationToken.IsCancellationRequested)
                {
                    break;
                }

                //
                sheetIndex++;
                sb.AppendLine($"--- Sheet: {sheet.Name} ---");

                //
                for (long row = 0; row < sheet.RowCount; row++)
                {
                    //
                    if (cancellationToken.IsCancellationRequested)
                    {
                        break;
                    }

                    //
                    var cellValues = new List<string>();
                    var columnCount = sheet.ColumnRuns.Sum(r => r.RepeatCount);
                    for (long col = 0; col < columnCount; col++)
                    {
                        //
                        var value = sheet.GetValue(row, col);
                        if (!value.IsNull())
                        {
                            var text = value.LexicalValue?.Trim() ?? string.Empty;
                            cellValues.Add(text);
                        }
                    }

                    //
                    if (cellValues.Any(v => !string.IsNullOrWhiteSpace(v)))
                    {
                        sb.AppendLine(string.Join(" | ", cellValues));
                    }
                }

                //
                sb.AppendLine();
            }

            //
            var result = sb.ToString().TrimEnd();

            //
            return result;
        }

        /// <summary>
        /// Extract ODS File Content ...
        /// </summary>
        /// <param name="fileStream"></param>
        /// <param name="cancellationToken"></param>
        /// <returns></returns>
        private async Task<string> ExtractOdpAsync(
            Stream fileStream,
            CancellationToken cancellationToken
        )
        {
            //
            await using var ms = new MemoryStream();
            await fileStream.CopyToAsync(ms, cancellationToken);
            ms.Position = 0;

            //
            var presentation = OdpPresentation.Load(ms);
            var sb = new StringBuilder();
            var slideIndex = 0;
            foreach (var slide in presentation.Slides)
            {
                //
                if (cancellationToken.IsCancellationRequested)
                {
                    break;
                }

                //
                slideIndex++;
                sb.AppendLine($"[Slide {slideIndex}]");
                var textParts = new List<string>();

                //
                foreach (var shape in slide.Shapes)
                {
                    //
                    if (shape is OdpTextBox textBox)
                    {
                        //
                        foreach (var paragraph in textBox.Paragraphs)
                        {
                            //
                            if (!paragraph.Text.IsNullOrEmpty())
                            {
                                textParts.Add(paragraph.Text.Trim());
                            }
                        }
                    }
                    else if (shape is OdpShape odpShape)
                    {
                        //
                        foreach (var paragraph in odpShape.TextParagraphs)
                        {
                            //
                            if (!paragraph.Text.IsNullOrEmpty())
                            {
                                textParts.Add(paragraph.Text.Trim());
                            }
                        }
                    }
                }

                //
                if (textParts.Count > 0)
                {
                    //
                    sb.AppendLine("Content:");
                    foreach (var text in textParts)
                    {
                        sb.AppendLine($"  - {text}");
                    }
                }

                //
                sb.AppendLine();
            }

            //
            var result = sb.ToString().TrimEnd();

            //
            return result;
        }
    }
}

### FILE: C:\Users\saherelm\Documents\Projects\xSaherelmWorkspace\xAiApi\Providers\Extractors\XPdfFileContentExtractor.cs

using System;
using System.IO;
using SkiaSharp;
using PDFtoImage;
using System.Linq;
using System.Text;
using System.Threading;
using xAiModels.Models;
using xAiApi.Configurations;
using System.Threading.Tasks;
using xAiApi.Interfaces.Extractors;

namespace xAiApi.Providers.Extractors
{
    /// <summary>
    /// Extracts content from PDF files using PdfPig ...
    /// </summary>    
    public class XPdfFileContentExtractor : IXPdfFileContentExtractor
    {
        /// <summary>
        /// Supported MIME Types ...
        /// </summary>
        private static readonly string[] SupportedMimeTypes =
        [
            "application/pdf"
        ];

        /// <summary>
        /// Api Configuration ...
        /// </summary>
        private readonly XAiApiConfiguration configuration;

        public XPdfFileContentExtractor(XAiApiConfiguration configuration)
        {
            this.configuration = configuration;
        }

        /// <summary>
        /// Check if this extractor supports the specified MIME type ...
        /// </summary>
        /// <param name="mimeType"></param>
        /// <returns></returns>
        public bool CanExtract(string mimeType)
        {
            //
            return SupportedMimeTypes.Contains(
                mimeType?.ToLowerInvariant() ?? string.Empty
            );
        }

        /// <summary>
        /// Extract text content from file stream ...
        /// </summary>
        /// <param name="fileStream"></param>
        /// <param name="mimeType"></param>
        /// <param name="cancellationToken"></param>
        /// <returns></returns>
        public async Task<string> ExtractAsync(
            Stream fileStream,
            string mimeType,
            CancellationToken cancellationToken = default
        )
        {
            //
            var result = await ExtractRichAsync(
                fileStream,
                "document.pdf",
                mimeType,
                cancellationToken
            );

            //
            return result.Text;
        }

        /// <summary>
        /// Extract content from stream as Rich Result ...
        /// </summary>
        /// <param name="fileStream"></param>
        /// <param name="fileName"></param>
        /// <param name="mimeType"></param>
        /// <param name="cancellationToken"></param>
        /// <returns></returns>
        public async Task<XFileExtractionResult> ExtractRichAsync(
            Stream fileStream,
            string fileName,
            string mimeType,
            CancellationToken cancellationToken = default
        )
        {
            //
            var result = new XFileExtractionResult
            {
                FileName = fileName,
                MimeType = mimeType
            };

            //
            using var memoryStream = new MemoryStream();
            await fileStream.CopyToAsync(memoryStream, cancellationToken);
            memoryStream.Position = 0;

            //
            var extractedText = await ExtractTextAsync(
                memoryStream,
                cancellationToken
            );
            if (IsTextSufficient(extractedText))
            {
                // PDF متنی است
                result.Text = extractedText;
            }
            else
            {
                // PDF اسکن‌شده است - Fallback به تصویر
                memoryStream.Position = 0;
                result = await FallbackToImageExtractionAsync(
                    memoryStream,
                    fileName,
                    mimeType,
                    cancellationToken
                );
                result.UsedImageFallback = true;
            }

            //
            return result;
        }

        /// <summary>
        /// Extract Text From PDF Files using Common way ...
        /// </summary>
        /// <param name="pdfStream"></param>
        /// <param name="cancellationToken"></param>
        /// <returns></returns>
        private async Task<string> ExtractTextAsync(
            Stream pdfStream,
            CancellationToken cancellationToken
        )
        {
            //
            var result = await Task.Run(() =>
            {
                //
                var sb = new StringBuilder();
                using var document = UglyToad.PdfPig.PdfDocument.Open(pdfStream);
                foreach (var page in document.GetPages())
                {
                    //
                    var text = page.Text?.Trim();
                    if (!string.IsNullOrEmpty(text))
                    {
                        //
                        sb.AppendLine(text);
                        sb.AppendLine();
                    }
                }

                //
                return sb.ToString();
            }, cancellationToken);

            //
            return result;
        }

        /// <summary>
        /// Check Extracted Content is Sufficient or not ...
        /// if not try to Falling Back using Images ...
        /// </summary>
        /// <param name="text"></param>
        /// <returns></returns>
        private bool IsTextSufficient(string text)
        {
            //
            if (string.IsNullOrWhiteSpace(text))
            {
                return false;
            }

            //
            // حذف فاصله‌ها و بررسی طول
            var cleanText = new string(text.Where(c => !char.IsWhiteSpace(c)).ToArray());

            //
            var result = cleanText.Length >= configuration.PDFToImageDescriptor.MinTextLengthThreshold;

            //
            return result;
        }

        /// <summary>
        /// Fallback Converts PDF Pages to Images ...
        /// </summary>
        /// <param name="pdfStream"></param>
        /// <param name="fileName"></param>
        /// <param name="mimeType"></param>
        /// <param name="cancellationToken"></param>
        /// <returns></returns>
        private async Task<XFileExtractionResult> FallbackToImageExtractionAsync(
            Stream pdfStream,
            string fileName,
            string mimeType,
            CancellationToken cancellationToken
        )
        {
            //
            var result = new XFileExtractionResult
            {
                FileName = fileName,
                MimeType = mimeType,
                UsedImageFallback = true
            };

            //
            await Task.Run(() =>
            {
                //
                try
                {
                    //
                    // Calculating With ...
                    var width = configuration.PDFToImageDescriptor.Width;
                    if (width >= 0 && configuration.PDFToImageDescriptor.MaxImageWidth > 0)
                    {
                        //
                        width = Math.Min(
                            width,
                            configuration.PDFToImageDescriptor.MaxImageWidth
                        );
                    }

                    //
                    // Preparing Render Options ...
                    var renderOptions = new RenderOptions
                    {
                        Width = width,
                        Dpi = configuration.PDFToImageDescriptor.Dpi,
                        Height = configuration.PDFToImageDescriptor.Height,
                        UseTiling = configuration.PDFToImageDescriptor.UseTiling,
                        WithFormFill = configuration.PDFToImageDescriptor.WithFormFill,
                        WithAspectRatio = configuration.PDFToImageDescriptor.WithAspectRatio,
                        WithAnnotations = configuration.PDFToImageDescriptor.WithAnnotations,
                        DpiRelativeToBounds = configuration.PDFToImageDescriptor.DpiRelativeToBounds,
                    };

                    //
                    // Preparing Images to Fallback ...
                    var pagesCount = Conversion.GetPageCount(pdfStream);
                    pdfStream.Position = 0;

                    //
                    if (configuration.PDFToImageDescriptor.MaxPagesForImageFallback > 0)
                    {
                        //
                        pagesCount = Math.Min(
                            pagesCount,
                            configuration.PDFToImageDescriptor.MaxPagesForImageFallback
                        );
                    }

                    //                    
                    for (int pageIndex = 0; pageIndex < pagesCount; pageIndex++)
                    {
                        //
                        //  Check Cancellation Token ...
                        if (cancellationToken.IsCancellationRequested)
                        {
                            break;
                        }

                        //
                        try
                        {
                            //
                            var skBitmap = Conversion.ToImage(
                                page: pageIndex,
                                pdfStream: pdfStream,
                                options: renderOptions
                            );
                            pdfStream.Position = 0;

                            //
                            using (skBitmap)
                            using (var image = SKImage.FromBitmap(skBitmap))
                            using (var data = image.Encode(SKEncodedImageFormat.Png, 100))
                            using (var ms = new MemoryStream())
                            {
                                //
                                data.SaveTo(ms);
                                result.Images.Add(new XExtractedImage
                                {
                                    Bytes = ms.ToArray(),
                                    MimeType = "image/png",
                                    Description = $"Page {pageIndex + 1}, rendered from {fileName}"
                                });
                            }
                        }
                        catch { }
                    }
                }
                catch (Exception ex)
                {
                    result.ErrorMessage = $"PDF image extraction failed: {ex.Message}";
                }
            }, cancellationToken);

            //
            return result;
        }
    }
}

### FILE: C:\Users\saherelm\Documents\Projects\xSaherelmWorkspace\xAiApi\Providers\Extractors\XPlainTextFileContentExtractor.cs

using System;
using System.IO;
using System.Linq;
using System.Threading;
using xAiModels.Models;
using System.Threading.Tasks;
using xAiApi.Interfaces.Extractors;

namespace xAiApi.Providers.Extractors
{
    /// <summary>
    /// Extracts content from plain text files (txt, md, csv, json, xml) ...
    /// </summary>    
    public class XPlainTextFileContentExtractor : IXPlainTextFileContentExtractor
    {
        /// <summary>
        /// Supported MIME Types ...
        /// </summary>
        private static readonly string[] SupportedMimeTypes =
        [
            "text/plain",
            "text/markdown",
            "text/csv",
            "text/xml",
            "application/json",
            "application/xml"
        ];

        /// <summary>
        /// Check if this extractor supports the specified MIME type ...
        /// </summary>
        /// <param name="mimeType"></param>
        /// <returns></returns>
        public bool CanExtract(string mimeType)
        {
            //
            return SupportedMimeTypes.Contains(
                mimeType?.ToLowerInvariant() ?? string.Empty
            );
        }

        /// <summary>
        /// Extract text content from file stream ...
        /// </summary>
        public async Task<string> ExtractAsync(
            Stream fileStream,
            string mimeType,
            CancellationToken cancellationToken = default
        )
        {
            //
            using var reader = new StreamReader(fileStream);
            return await reader.ReadToEndAsync();
        }

        /// <summary>
        /// Extract content from stream as Rich Result ...
        /// </summary>
        /// <param name="fileStream"></param>
        /// <param name="fileName"></param>
        /// <param name="mimeType"></param>
        /// <param name="cancellationToken"></param>
        /// <returns></returns>
        public async Task<XFileExtractionResult> ExtractRichAsync(
            Stream fileStream,
            string fileName,
            string mimeType,
            CancellationToken cancellationToken = default
        )
        {
            //
            var content = await ExtractAsync(
                mimeType: mimeType,
                fileStream: fileStream,
                cancellationToken: cancellationToken
            );

            //
            var result = new XFileExtractionResult
            {
                Text = content,
                FileName = fileName,
                MimeType = mimeType
            };

            //
            return result;
        }
    }
}

### FILE: C:\Users\saherelm\Documents\Projects\xSaherelmWorkspace\xAiApi\Providers\Extractors\XPowerPointFileContentExtractor.cs

using System;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading;
using xAiModels.Models;
using xCommons.Extensions;
using OfficeIMO.PowerPoint;
using xExceptions.Constants;
using System.Threading.Tasks;
using System.Collections.Generic;
using xAiApi.Interfaces.Extractors;
using DocumentFormat.OpenXml.Packaging;
using DrawingText = DocumentFormat.OpenXml.Drawing.Text;

namespace xAiApi.Providers.Extractors
{
    /// <summary>
    /// Extracts content from all PowerPoint formats
    /// (OpenXML: pptx/ppsx/potx/pptm/ppsm/potm | Legacy Binary: ppt/pps/pot)
    /// </summary>    
    public class XPowerPointFileContentExtractor : IXPowerPointFileContentExtractor
    {
        /// <summary>
        /// Supported MIME Types ...
        /// </summary>
        private static readonly string[] SupportedMimeTypes =
        [
            // OpenXML Formats
            "application/vnd.openxmlformats-officedocument.presentationml.presentation", // .pptx
            "application/vnd.openxmlformats-officedocument.presentationml.slideshow",    // .ppsx
            "application/vnd.openxmlformats-officedocument.presentationml.template",     // .potx
            "application/vnd.ms-powerpoint.presentation.macroEnabled.12",               // .pptm
            "application/vnd.ms-powerpoint.slideshow.macroEnabled.12",                  // .ppsm
            "application/vnd.ms-powerpoint.template.macroEnabled.12",                   // .potm
            // Legacy Binary Formats (.ppt / .pps / .pot share same MIME)
            "application/vnd.ms-powerpoint"
        ];

        /// <summary>
        /// Check if this extractor supports the specified MIME type ...
        /// </summary>
        public bool CanExtract(string mimeType)
        {
            //
            return SupportedMimeTypes.Contains(
                mimeType?.ToLowerInvariant() ?? string.Empty
            );
        }

        /// <summary>
        /// Extract text content from file stream ...
        /// </summary>
        public async Task<string> ExtractAsync(
            Stream fileStream,
            string mimeType,
            CancellationToken cancellationToken = default
        )
        {
            //
            var result = await ExtractRichAsync(
                fileStream: fileStream,
                fileName: "presentation",
                mimeType: mimeType,
                cancellationToken: cancellationToken
            );
            return result.Text;
        }

        /// <summary>
        /// Extract content from stream as Rich Result ...
        /// </summary>
        /// <param name="fileStream"></param>
        /// <param name="fileName"></param>
        /// <param name="mimeType"></param>
        /// <param name="cancellationToken"></param>
        /// <returns></returns>
        public async Task<XFileExtractionResult> ExtractRichAsync(
            Stream fileStream,
            string fileName,
            string mimeType,
            CancellationToken cancellationToken = default
        )
        {
            //
            var result = new XFileExtractionResult
            {
                FileName = fileName,
                MimeType = mimeType
            };

            //
            try
            {
                //
                if (IsOpenXmlFormat(mimeType))
                {
                    //
                    result.Text = await ExtractOpenXmlAsync(
                        fileStream,
                        cancellationToken
                    );
                }
                else if (IsLegacyFormat(mimeType))
                {
                    //
                    result.Text = await ExtractLegacyAsync(
                        fileStream,
                        cancellationToken
                    );
                }
                else
                {
                    //
                    result.ErrorMessage =
                        $"Unsupported PowerPoint MIME type: {mimeType}";
                }
            }
            catch (Exception ex)
            {
                result.ErrorMessage =
                    $"PowerPoint extraction failed: {ex.Message}";
            }

            //
            return result;
        }

        /// <summary>
        /// Check Open XML Format ...
        /// </summary>
        /// <param name="mimeType"></param>
        /// <returns></returns>
        private bool IsOpenXmlFormat(string mimeType)
        {
            //
            var result = mimeType?.ToLowerInvariant() switch
            {
                "application/vnd.openxmlformats-officedocument.presentationml.presentation" => true,
                "application/vnd.openxmlformats-officedocument.presentationml.slideshow" => true,
                "application/vnd.openxmlformats-officedocument.presentationml.template" => true,
                "application/vnd.ms-powerpoint.presentation.macroEnabled.12" => true,
                "application/vnd.ms-powerpoint.slideshow.macroEnabled.12" => true,
                "application/vnd.ms-powerpoint.template.macroEnabled.12" => true,
                _ => false
            };

            //
            return result;
        }

        /// <summary>
        /// Check Legacy Format ...
        /// </summary>
        /// <param name="mimeType"></param>
        /// <returns></returns>
        private bool IsLegacyFormat(string mimeType)
        {
            //
            var result = mimeType?.ToLowerInvariant() == "application/vnd.ms-powerpoint";
            return result;
        }

        /// <summary>
        /// Extract an Slide Title ...
        /// </summary>
        /// <param name="slidePart"></param>
        /// <returns></returns>
        private string GetSlideTitle(SlidePart slidePart)
        {
            //
            var result = string.Empty;

            //
            // Title placeholder has specific type
            var titleShape = slidePart.Slide
                .Descendants<DocumentFormat.OpenXml.Presentation.Shape>()
                .FirstOrDefault(s => s.NonVisualShapeProperties?
                    .NonVisualDrawingProperties?
                    .Name?.Value?
                    .StartsWith("Title", StringComparison.OrdinalIgnoreCase) == true
                );
            if (titleShape != null)
            {
                //
                var titleText = titleShape
                    .Descendants<DrawingText>()
                    .Select(t => t.Text?.Trim())
                    .Where(t => !string.IsNullOrWhiteSpace(t));
                result = string.Join(" ", titleText);
            }

            //
            return result;
        }

        /// <summary>
        /// Extract Speaker Notes ...
        /// </summary>
        /// <param name="slidePart"></param>
        /// <returns></returns>
        private string GetSpeakerNotes(SlidePart slidePart)
        {
            //
            var result = string.Empty;

            //
            var notesSlidePart = slidePart.NotesSlidePart;
            if (notesSlidePart?.NotesSlide == null)
            {
                return result;
            }

            //
            var notesTexts = notesSlidePart.NotesSlide
                .Descendants<DrawingText>()
                .Select(t => t.Text?.Trim())
                .Where(t => !string.IsNullOrWhiteSpace(t))
                .ToList();

            //
            result = notesTexts.Count > 0
                ? string.Join(Environment.NewLine, notesTexts)
                : null;

            //
            return result;
        }

        /// <summary>
        /// Extract OpenXML Tables ...
        /// </summary>
        /// <param name="slidePart"></param>
        /// <returns></returns>
        private static string ExtractOpenXmlTables(SlidePart slidePart)
        {
            //
            var sb = new StringBuilder();

            //
            var tableElements = slidePart.Slide
                .Descendants<DocumentFormat.OpenXml.Drawing.Table>();

            //
            var tableIndex = 0;
            foreach (var table in tableElements)
            {
                //
                tableIndex++;
                sb.AppendLine($"  Table {tableIndex}:");

                //
                foreach (var row in table
                    .Descendants<DocumentFormat.OpenXml.Drawing.TableRow>())
                {
                    //
                    var cells = row
                        .Descendants<DocumentFormat.OpenXml.Drawing.TableCell>()
                        .Select(c => string.Join(" ", c
                            .Descendants<DrawingText>()
                            .Select(t => t.Text?.Trim())
                            .Where(t => !string.IsNullOrWhiteSpace(t))))
                        .ToList();

                    //
                    if (cells.Count > 0)
                    {
                        sb.AppendLine($"    | {string.Join(" | ", cells)} |");
                    }
                }

                //
                sb.AppendLine();
            }

            //
            var result = sb.ToString();

            //
            return result;
        }

        /// <summary>
        /// Extract Open XML Format ...
        /// </summary>
        /// <param name="fileStream"></param>
        /// <param name="cancellationToken"></param>
        /// <returns></returns>
        private async Task<string> ExtractOpenXmlAsync(
            Stream fileStream,
            CancellationToken cancellationToken
        )
        {
            //
            var sb = new StringBuilder();

            //
            // Copy to MemoryStream (OpenXml requires seekable stream)
            await using var ms = new MemoryStream();
            await fileStream.CopyToAsync(ms, cancellationToken);
            ms.Position = 0;

            //
            using var presentationDocument = PresentationDocument.Open(ms, false);
            var presentationPart = presentationDocument.PresentationPart;
            if (presentationPart == null)
            {
                XException.InvalidData.Throw();
            }

            //
            var slideParts = presentationPart.SlideParts.ToList();
            var slideIndex = 0;
            foreach (var slidePart in slideParts)
            {
                //
                if (cancellationToken.IsCancellationRequested) break;
                slideIndex++;

                //
                sb.AppendLine($"[Slide {slideIndex}]");

                //
                // 1. Extract slide title
                var slideTitle = GetSlideTitle(slidePart);
                if (!string.IsNullOrWhiteSpace(slideTitle))
                {
                    sb.AppendLine($"Title: {slideTitle}");
                }

                //
                // 2. Extract body texts
                var bodyTexts = slidePart.Slide
                    .Descendants<DrawingText>()
                    .Select(t => t.Text?.Trim())
                    .Where(t => !string.IsNullOrWhiteSpace(t) && t != slideTitle)
                    .ToList();
                if (bodyTexts.Count > 0)
                {
                    //
                    sb.AppendLine("Content:");
                    foreach (var text in bodyTexts)
                    {
                        sb.AppendLine($"  - {text}");
                    }
                }

                //
                // 3. Extract tables
                var tables = ExtractOpenXmlTables(slidePart);
                if (!string.IsNullOrWhiteSpace(tables))
                {
                    //
                    sb.AppendLine("[Tables]");
                    sb.AppendLine(tables);
                }

                //
                // 4. Extract speaker notes
                var notes = GetSpeakerNotes(slidePart);
                if (!string.IsNullOrWhiteSpace(notes))
                {
                    //
                    sb.AppendLine("[Speaker Notes]");
                    sb.AppendLine(notes);
                }

                //
                // 5. Image count metadata
                var imageCount = slidePart.ImageParts?.Count() ?? 0;
                if (imageCount > 0)
                {
                    sb.AppendLine($"[Images: {imageCount}]");
                }

                //
                sb.AppendLine();
            }

            //
            var result = sb.ToString().TrimEnd();

            //
            return result;
        }

        /// <summary>
        /// Extract Legacy Format ...
        /// </summary>
        /// <param name="fileStream"></param>
        /// <param name="cancellationToken"></param>
        /// <returns></returns>
        private async Task<string> ExtractLegacyAsync(
            Stream fileStream,
            CancellationToken cancellationToken
        )
        {
            //
            var sb = new StringBuilder();

            //
            await using var ms = new MemoryStream();
            await fileStream.CopyToAsync(ms, cancellationToken);
            ms.Position = 0;

            //
            using var presentation = PowerPointPresentation.Load(ms);
            var slideIndex = 0;
            foreach (var slide in presentation.Slides)
            {
                //
                if (cancellationToken.IsCancellationRequested)
                {
                    break;
                }
                slideIndex++;

                //
                sb.AppendLine($"[Slide {slideIndex}]");

                //
                var textParts = new List<string>();
                var imageCount = 0;
                foreach (var shape in slide.Shapes)
                {
                    //
                    if (shape is PowerPointTextBox textBox)
                    {
                        //
                        if (!textBox.Text.IsNullOrEmpty())
                        {
                            textParts.Add(textBox.Text.Trim());
                        }
                    }
                    else if (shape is PowerPointAutoShape autoShape)
                    {
                        //
                        if (!autoShape.AltText.IsNullOrEmpty())
                        {
                            textParts.Add(autoShape.AltText.Trim());
                        }
                    }
                    else if (shape is PowerPointPicture picture)
                    {
                        imageCount++;
                    }
                }

                //
                if (textParts.Count > 0)
                {
                    //
                    sb.AppendLine("Content:");
                    foreach (var text in textParts)
                    {
                        sb.AppendLine($"  - {text}");
                    }
                }

                //
                if (imageCount > 0)
                {
                    sb.AppendLine($"[Images: {imageCount}]");
                }

                //
                sb.AppendLine();
            }

            //
            var result = sb.ToString().TrimEnd();

            //
            return result;
        }
    }
}

### FILE: C:\Users\saherelm\Documents\Projects\xSaherelmWorkspace\xAiApi\Providers\Extractors\XRtfFileContentExtractor.cs

using System;
using RtfPipe;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading;
using xAiModels.Models;
using xCommons.Extensions;
using System.Threading.Tasks;
using xAiApi.Interfaces.Extractors;
using System.Text.RegularExpressions;

namespace xAiApi.Providers.Extractors
{
    /// <summary>
    /// Extractor for Rich Text Format (RTF) documents
    /// (application/rtf, text/rtf)
    /// </summary>
    public class XRtfFileContentExtractor : IXRtfFileContentExtractor
    {
        /// <summary>
        /// Supported MIME Types ...
        /// </summary>
        private static readonly string[] SupportedMimeTypes =
        [
            "text/rtf",
            "application/rtf",
        ];

        /// <summary>
        /// Check if this extractor supports the specified MIME type ...
        /// </summary>
        /// <param name="mimeType"></param>
        /// <returns></returns>
        public bool CanExtract(string mimeType)
        {
            //
            return SupportedMimeTypes.Contains(
                mimeType?.ToLowerInvariant() ?? string.Empty
            );
        }

        /// <summary>
        /// Extract text content from file stream ...
        /// </summary>
        /// <param name="fileStream"></param>
        /// <param name="mimeType"></param>
        /// <param name="cancellationToken"></param>
        /// <returns></returns>
        public async Task<string> ExtractAsync(
            Stream fileStream,
            string mimeType,
            CancellationToken cancellationToken = default
        )
        {
            //
            var result = await ExtractRichAsync(
                fileStream,
                "document.rtf",
                mimeType,
                cancellationToken
            );

            //
            return result.Text;
        }

        /// <summary>
        /// Extract content from stream as Rich Result ...
        /// </summary>
        /// <param name="fileStream"></param>
        /// <param name="fileName"></param>
        /// <param name="mimeType"></param>
        /// <param name="cancellationToken"></param>
        /// <returns></returns>
        public async Task<XFileExtractionResult> ExtractRichAsync(
            Stream fileStream,
            string fileName,
            string mimeType,
            CancellationToken cancellationToken = default
        )
        {
            //
            var result = new XFileExtractionResult
            {
                FileName = fileName,
                MimeType = mimeType
            };

            // 
            try
            {
                //
                result.Text = await ExtractRtfAsync(
                    fileStream,
                    cancellationToken
                );
            }
            catch (Exception ex)
            {
                //
                result.ErrorMessage =
                    $"RTF extraction failed: {ex.Message}";
            }

            //
            return result;
        }

        /// <summary>
        /// Extract RTF Content ...
        /// </summary>
        /// <param name="fileStream"></param>
        /// <param name="cancellationToken"></param>
        /// <returns></returns>
        private async Task<string> ExtractRtfAsync(
            Stream fileStream,
            CancellationToken cancellationToken
        )
        {
            //
            var result = string.Empty;

            //
            // Read RTF content as string ...
            using var reader = new StreamReader(
                fileStream,
                Encoding.UTF8,
                detectEncodingFromByteOrderMarks: true,
                leaveOpen: true
            );
            var rtfContent = await reader.ReadToEndAsync();
            if (rtfContent.IsNullOrEmpty())
            {
                result = string.Empty;
            }

            //
            // Convert RTF to HTML using RtfPipe ...
            var html = Rtf.ToHtml(rtfContent);

            //
            // Convert HTML to plain text ...
            result = HtmlToPlainText(html);

            //
            return result;
        }

        /// <summary>
        /// Converts Html to Text ...
        /// </summary>
        /// <param name="html"></param>
        /// <returns></returns>
        private string HtmlToPlainText(string html)
        {
            //
            var result = string.Empty;

            //
            if (html.IsNullOrEmpty())
            {
                result = string.Empty;
            }

            //
            // Remove HTML tags ...
            result = Regex.Replace(
                html,
                "<.*?>",
                string.Empty,
                RegexOptions.Singleline
            );

            //
            // Decode HTML entities ...
            result = System.Net.WebUtility.HtmlDecode(result);

            //
            // Normalize whitespace ...
            result = Regex.Replace(result, @"\s+", " ").Trim();

            //
            return result;
        }
    }
}

### FILE: C:\Users\saherelm\Documents\Projects\xSaherelmWorkspace\xAiApi\Providers\Extractors\XVisionFileContentExtractor.cs

using System;
using System.IO;
using System.Linq;
using System.Threading;
using xAiApi.Constants;
using xAiModels.Models;
using xAiApi.Extensions;
using xAiApi.Interfaces;
using xCommons.Extensions;
using xAiModels.Extensions;
using xAiApi.Configurations;
using xExceptions.Constants;
using System.Threading.Tasks;
using Microsoft.Extensions.AI;
using System.Collections.Generic;
using xAiApi.Interfaces.Extractors;
using System.Runtime.CompilerServices;

namespace xAiApi.Providers.Extractors
{
    /// <summary>
    /// Extracts content from files using Vision Model ...
    /// </summary>    
    public class XVisionFileContentExtractor : IXVisionFileContentExtractor
    {
        /// <summary>
        /// Supported MIME Types ...
        /// </summary>
        private static readonly string[] SupportedMimeTypes =
        [
            "image/png",
            "image/jpeg",
            "image/jpg",
            "image/webp",
            "image/bmp",
            "application/pdf",
        ];

        //
        private readonly string prompt;
        private readonly XAiModelDescriptor descriptor;

        public XVisionFileContentExtractor(
            XAiApiConfiguration configuration,
            string promptName = XAiApiConstants.XAiApiContentExtractionPromptName,
            string modelName = XAiApiConstants.XAiDefaultVisionModelName
        )
        {
            // 
            // Retrieve Descriptoir ...
            if (modelName.IsNullOrEmpty())
            {
                XException.InvalidArgs.Throw();
            }
            descriptor = configuration.GetModel(modelName);

            //
            // Retrieve Extraction Prompt ...
            if (promptName.IsNullOrEmpty())
            {
                XException.InvalidArgs.Throw();
            }
            prompt = configuration.GetPrompt(
                name: promptName,
                @params: null
            );

            //
            // Validate Requirements ...
            if (prompt.IsNullOrEmpty() || descriptor.IsNullOrDefault())
            {
                XException.InvalidData.Throw();
            }
        }

        /// <summary>
        /// Check if this extractor supports the specified MIME type ...
        /// </summary>
        public bool CanExtract(string mimeType)
        {
            //
            return SupportedMimeTypes.Contains(
                mimeType?.ToLowerInvariant() ?? string.Empty
            );
        }

        /// <summary>
        /// Extract text content from file stream ...
        /// </summary>
        public async Task<string> ExtractAsync(
            Stream fileStream,
            string mimeType,
            CancellationToken cancellationToken = default
        )
        {
            var result = await ExtractRichAsync(fileStream, "file", mimeType, cancellationToken);
            return result.Text;
        }

        /// <summary>
        /// Extract content from stream as Rich Result ...
        /// </summary>
        /// <param name="fileStream"></param>
        /// <param name="fileName"></param>
        /// <param name="mimeType"></param>
        /// <param name="cancellationToken"></param>
        /// <returns></returns>
        public async Task<XFileExtractionResult> ExtractRichAsync(
            Stream fileStream,
            string fileName,
            string mimeType,
            CancellationToken cancellationToken = default
        )
        {
            //
            var result = new XFileExtractionResult
            {
                FileName = fileName,
                MimeType = mimeType
            };

            //
            try
            {
                //
                using var memoryStream = new MemoryStream();
                await fileStream.CopyToAsync(memoryStream, cancellationToken);
                var imageBytes = memoryStream.ToArray();
                var messages = new[]
                {
                    //
                    new ChatMessage(ChatRole.User, new[]
                    {
                        new DataContent(imageBytes, mimeType)
                    })
                };

                //
                var extractedContent = await RequestOCRAsync(
                    messages: messages,
                    cancellationToken: cancellationToken
                );
                if (!extractedContent.IsNullOrEmpty())
                {
                    result.Text = extractedContent.Trim();
                }
                else
                {
                    result.ErrorMessage = "there is not any Extracted Content ...";
                }
            }
            catch (Exception ex)
            {
                result.ErrorMessage = $"Error in Vision Extraction: {ex.Message} ...";
            }

            //
            return result;
        }
    
        //
        #region OCR ...
        /// <summary>
        /// Request for Doing OCR on Given Data Contents ...
        /// </summary>
        /// <param name="messages"></param>
        /// <param name="cancellationToken"></param>
        /// <returns></returns>        
        public virtual async Task<string> RequestOCRAsync(
            IList<ChatMessage> messages,
            CancellationToken cancellationToken = default
        )
        {
            //
            // Validate ...
            if (!messages.HasChild())
            {
                XException.InvalidArgs.Throw();
            }

            //
            using var client = descriptor.GetClient();

            //
            // Preparing Extraction Prompt Message ...
            var pMessage = new ChatMessage(
                ChatRole.System,
                prompt
            );

            //
            messages = [pMessage, .. messages];

            //
            var response = await client.GetResponseAsync(
                messages: messages,
                cancellationToken: cancellationToken
            );

            //
            // Validate Response ...
            if (!response.IsValid())
            {
                //
                // Dispose Client ...
                client.Dispose();
                XException.ActionFailed.Throw();
            }

            //
            // Retrieve Response Text ...
            var result = response.Text;

            //
            return result;
        }

        /// <summary>
        /// Request for Doing OCR on Given Data Contents as Stream ...
        /// </summary>
        /// <param name="messages"></param>
        /// <param name="cancellationToken"></param>
        /// <returns></returns>        
        public virtual async IAsyncEnumerable<string> RequestOCRAsEnumerable(
            IList<ChatMessage> messages,
            [EnumeratorCancellation]
            CancellationToken cancellationToken = default
        )
        {
            //
            // Validate ...
            if (!messages.HasChild())
            {
                XException.InvalidArgs.Throw();
            }

            //
            using var client = descriptor.GetClient();

            //
            // Preparing Extraction Prompt Message ...
            var pMessage = new ChatMessage(
                ChatRole.System,
                prompt
            );

            //
            messages = [pMessage, .. messages];

            //
            var enumerable = client.GetStreamingResponseAsync(
                options: null,
                messages: messages
            );

            //
            await foreach (var res in enumerable)
            {
                //
                // Cancellation Token ...
                if (cancellationToken.IsCancellationRequested)
                {
                    yield break;
                }

                //
                yield return res.Text;
            }
        }
        #endregion    
     }
}
