diff --git a/Documents/Codes/McpServerController.cs b/Documents/Codes/McpServerController.cs new file mode 100644 index 0000000..64840d0 --- /dev/null +++ b/Documents/Codes/McpServerController.cs @@ -0,0 +1,473 @@ +using System; +using xModels.Dtos; +using xModels.Base; +using xIdentityHelper; +using System.Threading; +using xCommons.Providers; +using xAiModels.Models.Dtos; +using System.Threading.Tasks; +using xCommons.Configurations; +using Microsoft.AspNetCore.Mvc; +using xAiModels.Interfaces.Dtos; +using System.Collections.Generic; +using xIdentityService.Interfaces; +using Microsoft.Extensions.Logging; +using xIdentityService.Controllers; +using Microsoft.AspNetCore.Authorization; + +namespace xAiApi.Controllers +{ + [Authorize] + public class McpServerController : XBaseIdentityApiV1Controller + { + public McpServerController( + XAppConfiguration appConfiguration, + ILogger logger, + IXIdentityProvider identityProvider, + XValidationProvider validationProvider, + IXAiMcpServerRepositoryService repositoryService + ) : base( + logger, + appConfiguration, + identityProvider, + validationProvider + ) + { } + + // + #region Provider ... + [HttpPost] + [Authorize(Policy = XPolicies.EnabledUser)] + public static async Task> AddMcpServer( + [FromBody] XAiMcpServerDto item, + 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 Actions ... + // + #region Add ... + /// + /// Add Specified Item ... + /// + /// + /// + /// + /// + /// + [HttpPost] + [Authorize(Policy = XPolicies.EnabledAdmin)] + public override async Task> Add( + [FromBody] XAiMcpServerDto item, + CancellationToken cancellationToken = default + ) + { + // + var result = await base.Add( + item: item, + cancellationToken: cancellationToken + ); + + // + return result; + } + + /// + /// Add or Update Specified Item ... + /// + /// + /// + /// + /// + /// + [HttpPost("AddOrUpdate")] + [Authorize(Policy = XPolicies.EnabledAdmin)] + public override async Task> AddOrUpdate( + [FromBody] XAiMcpServerDto item, + CancellationToken cancellationToken = default + ) + { + // + var result = await base.AddOrUpdate( + item: item, + cancellationToken: cancellationToken + ); + + // + return result; + } + + /// + /// Add a Collection of Items ... + /// + /// + /// + /// + /// + /// + [HttpPost("AddMany")] + [Authorize(Policy = XPolicies.EnabledAdmin)] + public override async Task AddMany( + [FromBody] XBaseRangeRequest request, + CancellationToken cancellationToken = default + ) + { + // + var result = await base.AddMany( + request: request, + cancellationToken: cancellationToken + ); + + // + return result; + } + #endregion + + // + #region Retrieve ... + /// + /// Get Specified Item ... + /// + /// + /// + /// + /// + /// + /// + /// + [HttpGet("{id}")] + [Authorize(Policy = XPolicies.EnabledAdmin)] + public override async Task> Get( + [FromRoute] Guid id, + [FromQuery] bool ignoreSoftDeleteds = true, + [FromQuery] bool useDefaultIncludes = false, + CancellationToken cancellationToken = default + ) + { + // + var result = await base.Get( + id: id, + cancellationToken: cancellationToken, + ignoreSoftDeleteds: ignoreSoftDeleteds, + useDefaultIncludes: useDefaultIncludes + ); + + // + return result; + } + + /// + /// Get All Items ... + /// + /// + /// + /// + /// + /// + /// + /// + [HttpGet] + [Authorize(Policy = XPolicies.EnabledAdmin)] + public override async Task>> GetAll( + [FromQuery] bool ignoreSoftDeleteds = true, + [FromQuery] bool useDefaultOrders = false, + [FromQuery] bool useDefaultIncludes = false, + CancellationToken cancellationToken = default + ) + { + // + var result = await base.GetAll( + useDefaultOrders: useDefaultOrders, + cancellationToken: cancellationToken, + ignoreSoftDeleteds: ignoreSoftDeleteds, + useDefaultIncludes: useDefaultIncludes + ); + + // + return result; + } + + /// + /// Find Specified Item ... + /// + /// + /// + /// + /// + /// + /// + /// + [HttpGet("FindOne/{query}")] + [Authorize(Policy = XPolicies.EnabledAdmin)] + public override async Task> FindOne( + [FromRoute] string query, + [FromQuery] bool ignoreSoftDeleteds = true, + [FromQuery] bool useDefaultIncludes = false, + CancellationToken cancellationToken = default + ) + { + // + var result = await base.FindOne( + query: query, + cancellationToken: cancellationToken, + ignoreSoftDeleteds: ignoreSoftDeleteds, + useDefaultIncludes: useDefaultIncludes + ); + + // + return result; + } + + /// + /// Find Many Items ... + /// + /// + /// + /// + /// + /// + /// + /// + /// + [HttpGet("FindMany/{query}")] + [Authorize(Policy = XPolicies.EnabledAdmin)] + public override async Task>> FindMany( + [FromRoute] string query, + [FromQuery] bool ignoreSoftDeleteds = true, + [FromQuery] bool useDefaultOrders = false, + [FromQuery] bool useDefaultIncludes = false, + CancellationToken cancellationToken = default + ) + { + // + var result = await base.FindMany( + query: query, + useDefaultOrders: useDefaultOrders, + cancellationToken: cancellationToken, + ignoreSoftDeleteds: ignoreSoftDeleteds, + useDefaultIncludes: useDefaultIncludes + ); + + // + return result; + } + + /// + /// Retrieve Items Based on Query Mechanism ... + /// + /// + /// + /// + /// + /// + /// + /// + /// + [HttpGet("Query")] + [Authorize(Policy = XPolicies.EnabledAdmin)] + public override async Task>> Query( + [FromQuery] XQuery query, + [FromQuery] bool ignoreSoftDeleteds = true, + [FromQuery] bool useDefaultOrders = false, + [FromQuery] bool useDefaultIncludes = false, + CancellationToken cancellationToken = default + ) + { + // + var result = await base.Query( + query: query, + useDefaultOrders: useDefaultOrders, + cancellationToken: cancellationToken, + ignoreSoftDeleteds: ignoreSoftDeleteds, + useDefaultIncludes: useDefaultIncludes + ); + + // + return result; + } + #endregion + + // + #region Update ... + /// + /// Update Item ... + /// + /// + /// + /// + /// + /// + /// + [HttpPut("{id}")] + [Authorize(Policy = XPolicies.EnabledAdmin)] + public override async Task> Update( + [FromRoute] Guid id, + [FromBody] XAiMcpServerDto item, + CancellationToken cancellationToken = default + ) + { + // + var result = await base.Update( + id: id, + item: item, + cancellationToken: cancellationToken + ); + + // + return result; + } + + /// + /// Update a Collection of items ... + /// + /// + /// + /// + /// + /// + [HttpPost("UpdateMany")] + [Authorize(Policy = XPolicies.EnabledAdmin)] + public override async Task> UpdateMany( + [FromBody] XBaseRangeRequest request, + CancellationToken cancellationToken = default + ) + { + // + var result = await base.UpdateMany( + request: request, + cancellationToken: cancellationToken + ); + + // + return result; + } + #endregion + + // + #region Exists ... + /// + ///Check an Item Exists or not ... + /// + /// + /// + /// + /// + /// + /// + [HttpGet("{id}/IsExists")] + [Authorize(Policy = XPolicies.EnabledAdmin)] + public override async Task> IsExists( + [FromRoute] Guid id, + [FromQuery] bool ignoreSoftDeleteds = true, + CancellationToken cancellationToken = default + ) + { + // + var result = await base.IsExists( + id: id, + cancellationToken: cancellationToken, + ignoreSoftDeleteds: ignoreSoftDeleteds + ); + + // + return result; + } + #endregion + + // + #region Remove ... + /// + /// Remove an Items ... + /// + /// + /// + /// + /// + /// + /// + [HttpDelete("{id}")] + [Authorize(Policy = XPolicies.EnabledAdmin)] + public override async Task> Remove( + [FromRoute] Guid id, + [FromQuery] bool softDelete = false, + CancellationToken cancellationToken = default + ) + { + // + var result = await base.Remove( + id: id, + softDelete: softDelete, + cancellationToken: cancellationToken + ); + + // + return result; + } + + /// + /// Remove Many Items ... + /// + /// + /// + /// + /// + /// + /// + [HttpPost("RemoveMany")] + [Authorize(Policy = XPolicies.EnabledAdmin)] + public override async Task RemoveMany( + [FromBody] XBaseRangeRequest request, + [FromQuery] bool softDelete = false, + CancellationToken cancellationToken = default + ) + { + // + var result = await base.RemoveMany( + request: request, + softDelete: softDelete, + cancellationToken: cancellationToken + ); + + // + return result; + } + #endregion + #endregion + } +} \ No newline at end of file diff --git a/Documents/Codes/Program xAiMcpServer.cs b/Documents/Codes/Program xAiMcpServer.cs new file mode 100644 index 0000000..efb709d --- /dev/null +++ b/Documents/Codes/Program xAiMcpServer.cs @@ -0,0 +1,26 @@ +using System; +using Grapevine; + +namespace xAiMcpServer +{ + public class Program + { + public static void Main(string[] args) + { + // + var server = RestServerBuilder + .From() + .Build(); + + // + server.Start(); + + // + Console.WriteLine("MCP Server running on https://localhost:7001/mcp"); + Console.ReadLine(); + + // + server.Stop(); + } + } +} diff --git a/Documents/Codes/Startup xAiMcpServer.cs b/Documents/Codes/Startup xAiMcpServer.cs new file mode 100644 index 0000000..1f803b7 --- /dev/null +++ b/Documents/Codes/Startup xAiMcpServer.cs @@ -0,0 +1,156 @@ +using System; +using System.IO; +using Grapevine; +using System.Net.Http; +using xAiMcpServer.DI; +using Newtonsoft.Json; +using System.Reflection; +using xIdentityService.DI; +using xCommons.Extensions; +using xAiService.Extensions; +using xCommons.Configurations; +using Grapevine.Extensions.Mcp; +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 xAiMcpServer +{ + public class Startup + { + public Startup(IConfiguration configuration) + { + Configuration = configuration; + } + + public IConfiguration Configuration { get; } + + public void ConfigureServices(IServiceCollection services) + { + // + // Register MCP Handler ... + services.AddXAiMcpHandler(); + + // + // Register Validation Provider and all XCommons Module Services ... + services.AddXCommons(Configuration); + + // + // Register App Configuration ... + services.AddXAppConfiguration(Configuration); + var appConfiguration = services.GetRegisteredService(); + + // + // 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); + + // + // 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; + + // + // Register XIdentity Service ... + services.AddXIdentityService( + lifeTime: lifeTime, + configuration: Configuration + ); + + // + // Register MCP Server ... + services + .AddMcpServer() + .WithHttpTransport() + .WithToolsFromAssembly(); + } + + public void ConfigureServer(IRestServer server) + { + server.Prefixes.Add("https://localhost:7001/"); + } + + public void Configure(IApplicationBuilder app, IWebHostEnvironment env) + { + // + // Configure the HTTP request pipeline ... + var isDevelopmentEnvironment = env.IsDevelopment(); + if (isDevelopmentEnvironment) + { + app.UseDeveloperExceptionPage(); + } + else + { + app.UseHsts(); + } + + // + // Force Https Redirection ... + app.UseHttpsRedirection(); + + // + // Use Swagger Middleware (Only in Development) ... + if (isDevelopmentEnvironment) + { + app.UseXSwagger(); + } + + // + // Using Cors (before Proxy so Browser Requests get CORS Headers) ... + app.UseXCors(); + + // + // Using Routing ... + app.UseRouting(); + + // + // Use xIdentityService (Authentication) ... + app.UseXIdentityService(); + + // + // Use Authorization ... + app.UseAuthorization(); + + // + app.UseEndpoints(endpoints => + { + endpoints.MapControllers(); + }); + } + } +} diff --git a/Documents/Codes/XAiMcpServerControllerBase.cs b/Documents/Codes/XAiMcpServerControllerBase.cs new file mode 100644 index 0000000..d4cb07c --- /dev/null +++ b/Documents/Codes/XAiMcpServerControllerBase.cs @@ -0,0 +1,35 @@ +using System; +using System.Linq; +using xCommons.Providers; +using xAiModels.Models.Dtos; +using xDataService.Interfaces; +using xCommons.Configurations; +using xDataService.Controllers; +using xAiModels.Models.Entities; +using Microsoft.Extensions.Logging; +using Microsoft.EntityFrameworkCore.Query; +using xPushService.Controllers; +using xAiModels.Providers.Dtos; + +namespace xAiModels.Controllers +{ + public abstract class XAiMcpServerControllerBase : XBaseServiceProviderController + { + protected XAiMcpServerControllerBase( + ILogger logger, + XAppConfiguration appConfiguration, + XValidationProvider validationProvider, + IXBaseRepositoryService repositoryService, + Func, IOrderedQueryable> defaultOrderBuilder = null, + Func, IIncludableQueryable> defaultIncludeBuilder = null + ) : base( + logger, + appConfiguration, + validationProvider, + repositoryService, + defaultOrderBuilder, + defaultIncludeBuilder + ) + { } + } +} \ No newline at end of file diff --git a/Documents/Docs/Developer/Connect xAiMcpServer to xAiApi 1.html b/Documents/Docs/Developer/Connect xAiMcpServer to xAiApi 1.html new file mode 100644 index 0000000..f7b61f8 --- /dev/null +++ b/Documents/Docs/Developer/Connect xAiMcpServer to xAiApi 1.html @@ -0,0 +1,998 @@ + + + + + +تحلیل تغییرات و راهنمای آزمون MCP Server با Prompt | xAiApi + + + + +
+ +
+
+
+ +
+
+
شماره مستند: MCP-1405-002
+
نسخه: ۱.۰
+
تاریخ تهیه: آبان ۱۴۰۵
+
طبقه‌بندی: فنی / محرمانه
+
+
+ +
+ TECHNICAL ANALYSIS & TEST GUIDE +

تحلیل تغییرات و راهنمای آزمون MCP Server با Prompt

+

بررسی یکپارچگی MCP در xAiApi، xAiMcpServer، xAiModels و xAiService

+
+
+ +
+ +
+ خلاصه هدف:
+ این مستند بر اساس فایل‌های ارائه‌شده، تغییرات و قابلیت‌های مرتبط با MCP Server را تحلیل می‌کند و سپس یک مسیر عملی و گام‌به‌گام برای آزمون استفاده از ابزارهای MCP توسط مدل زبانی از طریق Prompt ارائه می‌دهد. تمرکز اصلی روی این پرسش است: «چگونه مطمئن شویم مدل، ابزار MCP را در پاسخ به یک Prompt واقعاً فراخوانی می‌کند؟» +
+ +
+
+
۱
+
+

خلاصه اجرایی

+
Executive Summary
+
+
+
+

در کد ارائه‌شده، MCP در دو نقش مستقل پیاده‌سازی شده است:

+ +
+ + +
+

xAiMcpServer

+
    +
  • وظیفه ارائه MCP Server نمونه
  • +
  • کلیدواژه XAiMcpHandler / XAiMcpToolScanner
  • +
  • مسیر POST /mcp
  • +
  • ابزار نمونه XEchoTools.Echo
  • +
+
+
+ +
+ نتیجه کلیدی: برای آزمون با Prompt، باید ابتدا یک MCP Server در xAiApi ثبت و فعال شود، سپس از یکی از Endpointهای AI مانند POST /api/v1/XAi/Ask استفاده شود. مدل با دیدن ابزارهای MCP در ChatOptions.Tools و با دستور صریح در Prompt، ابزار را فراخوانی می‌کند. ابزار نمونه Echo مقدار hello {message} را برمی‌گرداند؛ بنابراین با یک پیام یکتا می‌توان صحت فراخوانی را تشخیص داد. +
+ +
+ نکته مهم: خود Prompt به‌تنهایی جادو نمی‌کند. سه شرط باید هم‌زمان برقرار باشد: (۱) MCP Server متصل و ابزارها کشف شده باشند، (۲) مدل انتخابی از Function Calling / Tool Calling پشتیبانی کند، (۳) Prompt صریحاً به استفاده از ابزار اشاره کند. +
+
+
+ +
+
+
۲
+
+

تحلیل تغییرات کلیدی

+
Key Changes Analysis
+
+
+
+

بر اساس فایل‌های ارائه‌شده، تغییرات و قابلیت‌های زیر قابل مشاهده است:

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
ماژول / بخشتغییر یا قابلیت کلیدیاثر عملی
xAiApiافزودن McpServersController، XAiMcpServerProvider، DI مربوطه و جدول AiMcpServers در MigrationCRUD، Enable/Disable/Toggle، Query و Refresh برای MCP Serverها؛ اتصال به MCP Server و کشف ابزارها
xAiApi / XAIServiceBaseتزریق IXAiMcpServerProvider و افزودن ابزارهای MCP به ChatOptions.Toolsمدل زبانی در زمان پاسخ‌دهی، ابزارهای MCP را به‌عنوان Tool می‌بیند و می‌تواند آن‌ها را فراخوانی کند
xAiApi / XModelsExtensionsساخت ChatClient با UseFunctionInvocation()زیرساخت اجرای Tool Call در سمت کلاینت فراهم شده است
xAiModelsافزودن Attributeهای XAiMcpToolType، XAiMcpTool، XAiMcpToolParam؛ Entity/DTO مربوط به MCP Server؛ Scope استفادهتعریف ابزارها به‌صورت Declarative و مدیریت دسترسی Owner/All
xAiServiceافزودن XAiMcpHandler، XAiMcpToolScanner، XAiMcpToolBlueprint و XAiMcpControllerBaseپیاده‌سازی JSON-RPC MCP شامل initialize، tools/list، tools/call و ping
xAiMcpServerپروژه Host مستقل MCP Server، کنترلر /mcp و ابزار نمونه XEchoToolsامکان اجرای یک MCP Server واقعی برای تست End-to-End
RAG / Knowledge / ChatWithDocumentsافزودن سرویس‌های RAG، Vector Store، Text Chunker و Extractorsخارج از تمرکز این مستند، اما از همان مسیر XAIServiceBase برای ابزارهای MCP استفاده می‌کنند
+ +

جریان فنی MCP در xAiApi

+ +
+
+
+
+
۱. ثبت MCP Server
+

از طریق POST /api/v1/McpServers یک رکورد با Endpoint، Headers، Timeout و Scope ایجاد می‌شود.

+
+
+
+
+
+
۲. اتصال و کشف ابزار
+

XAiMcpServerProvider.ConnectAndValidateAsync با McpClient به Endpoint وصل شده و ListToolsAsync را اجرا می‌کند.

+
+
+
+
+
+
۳. تزریق ابزارها به مدل
+

در XAIServiceBase متد GetAvailableToolsAsync فراخوانی و نتیجه به Options.Tools اضافه می‌شود.

+
+
+
+
+
+
۴. فراخوانی توسط مدل
+

مدل بر اساس Prompt و Description ابزار، Tool Call تولید می‌کند. UseFunctionInvocation اجرای آن را مدیریت می‌کند.

+
+
+
+
+
+
۵. بازگشت نتیجه ابزار
+

نتیجه اجرای ابزار به مدل برمی‌گردد و پاسخ نهایی در Ask یا AskStream به کاربر نمایش داده می‌شود.

+
+
+
+ +
+ نکته فنی قابل توجه: در GetAvailableToolsAsync، در اولین مقداردهی (isInitialized == false) خروجی نهایی همه ابزارهای متصل را برمی‌گرداند و فیلترینگ Owner/All فقط در فراخوانی‌های بعدی اعمال می‌شود. برای محیط چندکاربره، بهتر است این رفتار بازبینی و اصلاح شود. +
+
+
+ +
+
+
۳
+
+

پیش‌نیازهای آزمون با Prompt

+
Prerequisites
+
+
+
+

قبل از آزمون Prompt، موارد زیر را کنترل کنید:

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
پیش‌نیازتوضیحنشانه عدم برقراری
اجرای xAiMcpServerپروژه MCP Server باید در حال اجرا باشد و مسیر POST /mcp پاسخ دهد.خطای Connection refused یا Timeout در xAiApi
دسترسی شبکه و گواهیxAiApi باید بتواند Endpoint را صدا بزند. برای HTTPS از گواهی معتبر یا Dev Certificate استفاده کنید.خطای SSL / Certificate Validation در لاگ اتصال MCP
ثبت و فعال بودن MCP Serverرکورد MCP Server در xAiApi ایجاد و Enabled = true باشد.GetAvailableToolsAsync خالی برمی‌گردد
دسترسی کاربرکاربر غیرادمین فقط MCP Serverهای Owner خودش را می‌بیند. برای Scope=All نیاز به ادمین است.ابزار در لیست نیست، اما رکورد در DB وجود دارد
مدل با پشتیبانی Tool Callingمدل انتخابی باید Function Calling را پشتیبانی کند. مدل‌های ضعیف ممکن است ابزار را نادیده بگیرند.پاسخ متنی بدون فراخوانی ابزار
Prompt صریحدر Prompt نام ابزار و ورودی آن را مشخص کنید و از مدل بخواهید خروجی ابزار را برگرداند.مدل از حافظه پاسخ می‌دهد یا ابزار را نادیده می‌گیرد
+ +
+ نکته درباره Scope: در enum XAiMcpServerUsageScope مقدار All = 1 و Owner = 2 است. در Add/Update، اگر کاربر ادمین نباشد، Scope به‌صورت خودکار روی Owner تنظیم می‌شود. مقدار پیش‌فرض Entity نیز Owner است. +
+
+
+ +
+
+
۴
+
+

آزمون مستقیم MCP Server با JSON-RPC

+
Direct MCP Server Test
+
+
+
+

قبل از آزمون با Prompt، ابتدا مطمئن شوید خود MCP Server درست کار می‌کند. مسیر پیش‌فرض در XAiMcpControllerBase برابر /mcp است و متد POST را می‌پذیرد. اگر سرور روی https://localhost:7001 اجرا شده باشد:

+ +
curl -k -X POST "https://localhost:7001/mcp" ^ + -H "Content-Type: application/json" ^ + -d "{\"jsonrpc\":\"2.0\",\"id\":1,\"method\":\"initialize\",\"params\":{\"protocolVersion\":\"2024-11-05\",\"capabilities\":{},\"clientInfo\":{\"name\":\"curl-test\",\"version\":\"1.0\"}}}"
+ +

سپس لیست ابزارها را بگیرید:

+ +
curl -k -X POST "https://localhost:7001/mcp" ^ + -H "Content-Type: application/json" ^ + -d "{\"jsonrpc\":\"2.0\",\"id\":2,\"method\":\"tools/list\",\"params\":{}}"
+ +

باید ابزار Echo را در خروجی ببینید. سپس آن را فراخوانی کنید:

+ +
curl -k -X POST "https://localhost:7001/mcp" ^ + -H "Content-Type: application/json" ^ + -d "{\"jsonrpc\":\"2.0\",\"id\":3,\"method\":\"tools/call\",\"params\":{\"name\":\"Echo\",\"arguments\":{\"message\":\"MCP-Direct-Test-1405\"}}}"
+ +
+ خروجی مورد انتظار: در result.content[0].text مقدار hello MCP-Direct-Test-1405 برگردد. اگر این مرحله موفق شد، زیرساخت MCP Server سالم است و مشکل احتمالی بعدی مربوط به اتصال xAiApi یا Prompt است. +
+ +

روش‌های پشتیبانی‌شده در XAiMcpHandler:

+ + + + + + + + + + + +
متد JSON-RPCکارکرد
initializeبازگرداندن protocolVersion، capabilities و serverInfo
tools/listلیست ابزارهای کشف‌شده با name، description و inputSchema
tools/callاجرای ابزار با name و arguments
pingپاسخ ساده برای بررسی سلامت
سایر متدهاخطای -32601 Method not found
+
+
+ +
+
+
۵
+
+

ثبت MCP Server در xAiApi و آزمون با Prompt

+
Register in xAiApi & Prompt Test
+
+
+
+

برای آزمون اصلی، MCP Server را در xAiApi ثبت کنید. مسیرهای زیر بر اساس الگوی XBaseIdentityApiV1Controller است؛ مسیر دقیق را در Swagger تأیید کنید. معمولاً به‌صورت /api/v1/McpServers و /api/v1/XAi/Ask است.

+ +

گام ۱: ثبت MCP Server

+ +
POST /api/v1/McpServers +Authorization: Bearer <ACCESS_TOKEN> +Content-Type: application/json + +{ + "name": "Local Echo MCP", + "description": "Echo tool for MCP prompt test", + "endpoint": "https://localhost:7001/mcp", + "headers": "{}", + "timeoutSeconds": 30, + "enabled": true, + "scope": 2 +}
+ +

scope = 2 یعنی Owner و scope = 1 یعنی All. اگر Swagger مقدار رشته‌ای نشان می‌دهد، از همان مقدار استفاده کنید. برای Headers احراز هویت، یک JSON String بدهید؛ مثلاً:

+ +
"headers": "{\"Authorization\":\"Bearer YOUR_MCP_TOKEN\"}"
+ +

گام ۲: بررسی، فعال‌سازی و Refresh

+ +
GET /api/v1/McpServers?forceOwner=true +Authorization: Bearer <ACCESS_TOKEN> + +POST /api/v1/McpServers/{id}/Enable +Authorization: Bearer <ACCESS_TOKEN> + +POST /api/v1/McpServers/Refresh +Authorization: Bearer <ADMIN_TOKEN>
+ +
+ Refresh چه زمانی لازم است؟ وقتی MCP Server بعد از راه‌اندازی xAiApi بالا آمده باشد، یا ابزارهای سمت سرور تغییر کرده باشند. Refresh کلاینت‌ها و کش ابزارها را پاک و مجدداً مقداردهی می‌کند. این Endpoint نیاز به نقش ادمین دارد. +
+ +

گام ۳: ارسال Prompt صریح

+ +

اکنون از یکی از Endpointهای AI استفاده کنید. بهترین گزینه برای تست سریع، POST /api/v1/XAi/Ask است:

+ +
POST /api/v1/XAi/Ask +Authorization: Bearer <ACCESS_TOKEN> +Content-Type: application/json + +{ + "prompt": "Use the Echo tool from the connected MCP server. Call it with {\"message\":\"MCP-Prompt-Test-1405-01\"} and return exactly the tool output. Do not answer from memory.", + "type": "XAiKnowledge", + "topK": 5 +}
+ +

برای مدل‌هایی که با فارسی بهتر Tool Call می‌کنند، از Prompt فارسی صریح استفاده کنید:

+ +
+ از ابزار Echo استفاده کن و ورودی آن را {"message":"MCP-Prompt-Test-1405-01"} قرار بده. فقط و فقط خروجی دقیق ابزار را برگردان و از حافظه پاسخ نده. +
+ +
+ پاسخ مورد انتظار: پاسخ نهایی باید شامل hello MCP-Prompt-Test-1405-01 باشد. چون این مقدار یکتا است، اگر مدل دقیقاً همین را برگرداند، احتمال بسیار زیاد ابزار Echo واقعاً اجرا شده است. برای اطمینان بیشتر، هم‌زمان لاگ‌های xAiApi و xAiMcpServer را بررسی کنید. +
+ +

گام ۴: آزمون Streaming

+ +

برای آزمون جریان پاسخ، از AskStream استفاده کنید. خروجی SSE است و در نهایت پاسخ مدل را نشان می‌دهد:

+ +
POST /api/v1/XAi/AskStream +Authorization: Bearer <ACCESS_TOKEN> +Content-Type: application/json + +{ + "prompt": "Call the Echo MCP tool with message=\"MCP-Stream-Test-1405\". Return only the exact tool output.", + "type": "XAiKnowledge" +}
+ +
+ مهم: اگر مدل از Tool Calling پشتیبانی نکند یا Prompt صریح نباشد، ممکن است پاسخ متنی تولید کند و ابزار را فراخوانی نکند. در این حالت، پاسخ شامل مقدار یکتا نخواهد بود یا مقدار را از خود می‌سازد. آزمون مستقیم JSON-RPC و استفاده از پیام یکتا، بهترین راه تفکیک این حالت است. +
+
+
+ +
+
+
۶
+
+

سناریوهای تست پیشنهادی

+
Recommended Test Scenarios
+
+
+
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
سناریوPromptانتظار
تست پایه Tool CallUse the Echo tool with message="TEST-001" and return exactly the output.پاسخ شامل hello TEST-001
تست فارسیاز ابزار Echo استفاده کن و message را "TEST-002" بگذار؛ فقط خروجی ابزار را برگردان.پاسخ شامل hello TEST-002
تست عدم استفاده از ابزاربدون استفاده از هیچ ابزاری، حاصل ۲+۲ را بگو.پاسخ 4 بدون فراخوانی ابزار
تست ابزار ناموجوداز ابزار NotExists استفاده کن.مدل باید عدم وجود ابزار را بیان کند یا از ابزار موجود استفاده نکند
تست پس از Refreshبعد از POST /McpServers/Refresh همان Prompt پایه را تکرار کنید.ابزارها مجدداً کشف شوند و پاسخ موفق باشد
+ +
+

بهترین روش برای اثبات واقعی بودن Tool Call، استفاده از یک مقدار یکتا در ورودی ابزار و بررسی بازگشت دقیق همان مقدار توسط ابزار است. صرفاً دیدن نام ابزار در پاسخ مدل، اثبات اجرای واقعی نیست.

+
— راهنمای عملی آزمون MCP
+
+
+
+ +
+
+
۷
+
+

عیب‌یابی خطاهای رایج

+
Troubleshooting
+
+
+
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
علامتعلت احتمالیاقدام
ابزارها خالی هستندMCP Server غیرفعال است، اتصال برقرار نشده، یا Endpoint اشتباه استEndpoint را با curl تست کنید؛ رکورد را Enable کنید؛ POST /McpServers/Refresh بزنید
خطای SSL / Certificateگواهی self-signed است و کلاینت MCP اعتبارسنجی می‌کنداز گواهی معتبر یا Dev Certificate استفاده کنید؛ در کد فعلی برای MCP کلاینت Bypass SSL تنظیم نشده است
ابزار برای کاربر غیرادمین دیده نمی‌شودScope روی Owner است و OwnerId با کاربر جاری یکی نیستبا همان کاربری که رکورد را ساخته تست کنید یا با ادمین Scope=All ثبت کنید
مدل ابزار را صدا نمی‌زندمدل Tool Calling را پشتیبانی نمی‌کند یا Prompt صریح نیستمدل مناسب انتخاب کنید؛ Prompt انگلیسی صریح با نام ابزار و ورودی دقیق بدهید
پاسخ شبیه خروجی ابزار است اما مطمئن نیستیممدل ممکن است مقدار را از حافظه بسازدمقدار یکتا بدهید؛ لاگ MCP Server را بررسی کنید؛ مستقیم tools/call بزنید
بعد از تغییر ابزارها هنوز قدیمی استکش tools در Provider به‌روز نشدهPOST /api/v1/McpServers/Refresh با توکن ادمین
Timeout در اتصالTimeout کمتر از حداقل یا شبکه کند استTimeoutSeconds را حداقل ۳۰ و مناسب تنظیم کنید
+ +
+ نکته امنیتی: در محیط عملیاتی، Endpointهای MCP را بدون احراز هویت و بدون محدودیت شبکه منتشر نکنید. از Headers معتبر، TLS، محدودیت IP و Scope مناسب استفاده کنید. همچنین خروجی ابزارها را قبل از بازگرداندن به مدل، از نظر حساسیت داده بررسی کنید. +
+
+
+ +
+
+
۸
+
+

جمع‌بندی و پیشنهاد نهایی

+
Final Summary & Recommendation
+
+
+
+

یکپارچگی MCP در کد ارائه‌شده کامل و قابل استفاده است: xAiMcpServer یک MCP Server واقعی با ابزار Echo ارائه می‌دهد، xAiService هندلر JSON-RPC و Scanner را پیاده‌سازی کرده، و xAiApi به‌عنوان MCP Client ابزارها را کشف و به مدل تزریق می‌کند.

+ +
+
+
۱
+
ابتدا MCP Server را مستقیم با JSON-RPC تست کنید
+
+
+
۲
+
سپس MCP Server را در xAiApi ثبت و Refresh کنید
+
+
+
۳
+
در نهایت با Prompt صریح و مقدار یکتا Tool Call را بسنجید
+
+
+ +
+

🎯 پیشنهاد نهایی

+

برای آزمون استفاده از MCP Server با Prompt، مسیر زیر را طی کنید:

+

اجرای xAiMcpServer → تست مستقیم tools/list و tools/call → ثبت MCP Server در xAiApi → Enable و Refresh → ارسال Prompt صریح به /api/v1/XAi/Ask با پیام یکتا → بررسی بازگشت hello <unique-message>.

+
+ 💎 معیار موفقیت:
+ بازگشت دقیق مقدار یکتای ورودی ابزار در پاسخ نهایی + مشاهده ابزار در tools/list + عدم خطای اتصال در لاگ‌ها. +
+
+ +
+ گام بعدی پیشنهادی: در صورت نیاز به تست چندابزاری، یک ابزار جدید با [XAiMcpToolType] و [XAiMcpTool] در xAiMcpServer اضافه کنید، سرویس را ری‌استارت و در xAiApi Refresh بزنید. سپس Prompt را طوری بنویسید که مدل بین دو ابزار انتخاب کند تا کیفیت Tool Selection نیز سنجیده شود. +
+
+
+ +
+ این مستند فنی و محرمانه است و صرفاً برای تحلیل و آزمون یکپارچگی MCP در مجموعه xSaherelmWorkspace تهیه شده است. +
+ +
+ +
+ + +
تاریخ تهیه: آبان ۱۴۰۵  |  نسخه: ۱.۰  |  طبقه‌بندی: فنی / محرمانه
+
+ +
+ + + \ No newline at end of file diff --git a/Documents/Docs/Developer/Connect xAiMcpServer to xAiApi.html b/Documents/Docs/Developer/Connect xAiMcpServer to xAiApi.html new file mode 100644 index 0000000..ab22652 --- /dev/null +++ b/Documents/Docs/Developer/Connect xAiMcpServer to xAiApi.html @@ -0,0 +1,265 @@ + اتصال XAiMcpServer به XAiApi | راهنمای گام‌به‌گام + +
شماره مستند: MCP-1405-001
نسخه: ۱.۰
تاریخ تهیه: آبان ۱۴۰۵
طبقه‌بندی: فنی
MCP INTEGRATION GUIDE

اتصال XAiMcpServer به XAiApi

راهنمای گام‌به‌گام اتصال سرور MCP ساده به API هوش مصنوعی

هدف این مستند:
XAiMcpServer یک MCP Server ساده و مستقل است که قبلاً به‌صورت مستقیم تست شده و ابزار نمونه Echo را ارائه می‌دهد. در این مستند، روش‌های اتصال این سرور به XAiApi به‌صورت گام‌به‌گام، همراه با پیش‌نیازها، نکات بحرانی، روش‌های ثبت، راستی‌آزمایی و عیب‌یابی شرح داده می‌شود.
۱

خلاصه اجرایی

Executive Summary

XAiApi یک کلاینت MCP داخلی با نام XAiMcpServerProvider دارد. این کلاینت سرورهای MCP فعال را از جدول AiMcpServers خوانده، با HttpClientTransport به Endpoint آن‌ها متصل می‌شود، ابزارها را با ListToolsAsync دریافت می‌کند و در اختیار لایه هوش مصنوعی قرار می‌دهد.

XAiMcpServer نیز یک MCP Server ساده ASP.NET Core است که endpoint اصلی آن POST /mcp و endpoint SSE آن GET /mcp/sse می‌باشد. ابزار Echo در کلاس XEchoTools قرار دارد و با attributeهای XAiMcpToolType و XAiMcpTool شناسایی می‌شود.

نتیجه کلیدی: اتصال پایه از طریق ثبت مشخصات XAiMcpServer در XAiApi و سپس فعال بودن آن در جدول AiMcpServers انجام می‌شود. اما برای اینکه مدل زبانی واقعاً از ابزارها استفاده کند، باید IXAiMcpServerProvider را در سرویس هوش مصنوعی تزریق کرده و ابزارهای دریافتی را به ChatOptions.Tools اختصاص دهید.
۲

وضعیت فعلی XAiMcpServer

Simple MCP Server — Directly Tested

XAiMcpServer یک سرور MCP ساده است که مستقیماً تست شده و حداقل یک ابزار نمونه دارد:

مؤلفه توضیح
Controller McpController با route mcp
Endpoint اصلی POST /mcp برای JSON-RPC
Endpoint SSE GET /mcp/sse
Handler XAiMcpHandler با پشتیبانی از initialize، tools/list، tools/call و ping
Tool Scanner XAiMcpToolScanner اسمبلی‌های xAi* را اسکن می‌کند
ابزار نمونه XEchoTools.Echo با نام Echo

تست مستقیم سرور با curl:

curl -k -X POST https://localhost:5001/mcp \ -H "Content-Type: application/json" \ -d '{"jsonrpc":"2.0","id":1,"method":"initialize","params":{}}'
curl -k -X POST https://localhost:5001/mcp \ -H "Content-Type: application/json" \ -d '{"jsonrpc":"2.0","id":2,"method":"tools/list","params":{}}'
curl -k -X POST https://localhost:5001/mcp \ -H "Content-Type: application/json" \ -d '{"jsonrpc":"2.0","id":3,"method":"tools/call","params":{"name":"Echo","arguments":{"message":"test"}}}'
نکته: اگر پورت یا scheme متفاوت است، آدرس را با پورت واقعی XAiMcpServer جایگزین کنید. برای محیط توسعه می‌توان از HTTP استفاده کرد تا مشکل گواهی self-signed پیش نیاید.
۳

معماری اتصال

How XAiApi Connects to XAiMcpServer

جریان اتصال در XAiApi به این صورت است:

مرحله مؤلفه عملیات
۱ XAiMcpServerProvider.GetAvailableToolsAsync سرورهای فعال را از AiMcpServers می‌خواند
۲ ConnectAndValidateAsync برای هر سرور کلاینت MCP می‌سازد، Ping و ListTools انجام می‌دهد
۳ CreateClientAsync با HttpClientTransport و TransportMode.AutoDetect به Endpoint وصل می‌شود
۴ XAiService / XAIServiceBase در صورت تزریق Provider، ابزارها را به ChatOptions.Tools می‌دهد
۵ مدل زبانی با UseFunctionInvocation ابزار را فراخوانی می‌کند
نکته بسیار مهم: در کد فعلی XAIServiceBase مقدار Options = new ChatOptions() است و هیچ‌جا IXAiMcpServerProvider.GetAvailableToolsAsync فراخوانی نمی‌شود. بنابراین اتصال در سطح Provider برقرار می‌شود، اما تا زمانی که ابزارها به Options.Tools اضافه نشوند، مدل زبانی از آن‌ها استفاده نمی‌کند.
۴

پیش‌نیازها و نکات بحرانی

Prerequisites & Critical Notes
پیش‌نیاز توضیح
دسترسی شبکه‌ای XAiApi باید بتواند به آدرس XAiMcpServer وصل شود (پورت، فایروال، DNS)
گواهی SSL معتبر در صورت استفاده از HTTPS، گواهی باید معتبر باشد؛ Provider پیش‌فرض handler سفارشی برای نادیده‌گرفتن خطای SSL ندارد
جدول AiMcpServers باید در دیتابیس XAiApi وجود داشته باشد. در migration اولیه ارائه‌شده این جدول دیده نمی‌شود؛ در صورت نیاز migration جدید اضافه کنید
ثبت IXAiMcpServerProvider در DI فعلی XAiApi ثبت نشده است؛ برای استفاده در سرویس AI باید ثبت شود
توکن ادمین برای ثبت از طریق API مدیریتی، توکن با Policy EnabledAdmin لازم است
Scope اگر کاربر ادمین نباشد، Provider به‌صورت خودکار Scope را Owner می‌کند
هشدار migration: در فایل migration اولیه XAiApi جدول AiMcpServers ساخته نشده است. اگر دیتابیس شما بر اساس همان migration است، قبل از ثبت سرور باید migration جدید برای entity XAiMcpServer اضافه و اعمال شود.
۵

روش ۱: ثبت از طریق API مدیریتی XAiApi

Recommended — Register via Admin API

این روش توصیه‌شده است porque از مسیر رسمی McpServerController استفاده می‌کند.

گام ۱: XAiMcpServer را اجرا و مستقیماً تست کنید (بخش ۲). مطمئن شوید tools/list ابزار Echo را برمی‌گرداند.

گام ۲: توکن ادمین XAiApi را دریافت کنید. این توکن باید Policy EnabledAdmin را داشته باشد.

گام ۳: سرور را با درخواست POST ثبت کنید. مسیر دقیق را از Swagger بردارید؛ معمولاً مسیری مانند /api/v1/McpServer است.

curl -k -X POST https://localhost:7001/api/v1/McpServer \ -H "Authorization: Bearer <ADMIN_TOKEN>" \ -H "Content-Type: application/json" \ -d '{ "ownerId": "<ADMIN_USER_ID>", "name": "xAiMcpServer", "description": "Simple Echo MCP Server - directly tested", "endpoint": "https://localhost:5001/mcp", "enabled": true, "scope": 2, "headers": "{}", "timeoutSeconds": 30, "createdOn": "2026-11-05T00:00:00Z" }'
فیلد مقدار پیشنهادی توضیح
name xAiMcpServer نام نمایشی سرور
endpoint https://host:port/mcp برای Streamable HTTP. اگر اتصال برقرار نشد، /mcp/sse را امتحان کنید
enabled true فقط سرورهای فعال توسط Provider خوانده می‌شوند
scope 2 یا 1 Owner=2 برای استفاده مالک، All=1 برای استفاده همه (ادمین)
headers "{}" اگر سرور احراز هویت دارد، JSON شامل هدرها مثل Authorization
timeoutSeconds 30 یا بیشتر حداقل مقدار مجاز در ثابت‌ها ۳۰ ثانیه است

گام ۴: XAiApi را ری‌استارت کنید یا در صورت وجود، متد RefreshAsync را فراخوانی کنید. Provider نتایج را cache می‌کند و سرور جدید تا refresh یا restart شناسایی نمی‌شود.

گام ۵: در لاگ XAiApi عبارت زیر را جستجو کنید:

MCP 'xAiMcpServer': {Count} Tools Detected ...
نتیجه: اگر این لاگ را دیدید، اتصال HTTP برقرار شده و ابزارها دریافت شده‌اند. ابزار Echo باید در لیست باشد.
۶

روش ۲: ثبت مستقیم در دیتابیس یا Seeder

Direct DB Insert / EF Seeder

اگر نمی‌خواهید از API مدیریتی استفاده کنید، می‌توانید یک رکورد در جدول AiMcpServers درج کنید. این روش برای محیط توسعه یا Seed اولیه مناسب است.

ستون مقدار نمونه
Idیک GUID جدید
Deleted0
OwnerIdشناسه کاربر مالک
Scope2 (Owner) یا 1 (All)
NamexAiMcpServer
DescriptionSimple Echo MCP Server
Enabled1
Endpointhttps://localhost:5001/mcp
Headers{}
TimeoutSeconds30
CreatedOnزمان UTC
UpdatedAtزمان UTC

سپس XAiApi را ری‌استارت کنید تا Provider سرور را بارگذاری کند.

پیشنهاد: برای محیط عملیاتی، Seed مستقیم را فقط برای داده اولیه استفاده کنید و مدیریت تغییرات را از طریق API مدیریتی انجام دهید.
۷

روش ۳: ثبت برنامه‌نویسی با IXAiMcpServerProvider

Programmatic Registration

اگر می‌خواهید در Startup یا یک سرویس مدیریتی، سرور را ثبت کنید، از متد AddMcpServer در IXAiMcpServerProvider استفاده کنید.

گام ۱: Provider را در DI ثبت کنید:

services.AddScoped<IXAiMcpServerProvider, XAiMcpServerProvider>();

گام ۲: در یک سرویس دارای دسترسی ادمین، DTO زیر را بسازید و متد AddMcpServer را فراخوانی کنید:

var item = new XAiMcpServerDto { Name = "xAiMcpServer", Description = "Simple Echo MCP Server", Endpoint = "https://localhost:5001/mcp", Enabled = true, Scope = XAiMcpServerUsageScope.Owner, Headers = "{}", TimeoutSeconds = 30 }; var result = await mcpProvider.AddMcpServer( item: item, userInfo: adminUserInfo, cancellationToken: cancellationToken );
مزیت این روش: اعتبارسنجی، ذخیره در دیتابیس، Enrichment و اتصال/دریافت ابزارها به‌صورت یکجا انجام می‌شود.
۸

اتصال ابزارها به مدل زبانی

Inject Tools into ChatOptions

این مرحله برای «استفاده واقعی مدل از ابزار» ضروری است. در کد فعلی XAIServiceBase گزینه‌های Chat خالی است و ابزارها به مدل داده نمی‌شوند.

گام ۱: IXAiMcpServerProvider را به XAiService یا XAIServiceBase تزریق کنید.

گام ۲: در متدهای AskTextAsync، AskAsync، AskAsEnumerable و مشابه آن، قبل از فراخوانی مدل، ابزارها را دریافت و به Options.Tools اختصاص دهید:

var availableTools = await mcpProvider.GetAvailableToolsAsync( userInfo: userInfo, cancellationToken: cancellationToken ); Options.Tools = availableTools .Cast<AITool>() .ToList();

گام ۳: مطمئن شوید کلاینت مدل با UseFunctionInvocation ساخته می‌شود. در XModelsExtensions.GetClient این کار انجام شده است.

نکته: ابزارها بر اساس userInfo فیلتر می‌شوند. اگر userInfo نال باشد، GetAvailableToolsAsync لیست خالی برمی‌گرداند. بنابراین حتماً کاربر احراز هویت‌شده را پاس دهید.
اگر خطای کامپایل گرفتید: نوع McpClientTool ممکن است مستقیماً AITool نباشد. در آن صورت از تبدیل مناسب SDK یا Select استفاده کنید. در نسخه‌های جدید ModelContextProtocol، ابزارها معمولاً به‌صورت AIFunction قابل استفاده هستند.
۹

راستی‌آزمایی و تست نهایی

Verification Checklist
# تست نتیجه مورد انتظار
۱ POST /mcp با متد initialize پاسخ JSON-RPC شامل protocolVersion و serverInfo
۲ POST /mcp با متد tools/list لیست ابزارها شامل Echo
۳ POST /mcp با متد tools/call برای Echo پاسخ متنی مانند hello test
۴ ثبت سرور در XAiApi رکورد در AiMcpServers با Enabled=true
۵ ری‌استارت XAiApi لاگ MCP 'xAiMcpServer': N Tools Detected
۶ پرسش از مدل با درخواست استفاده از Echo مدل ابزار را فراخوانی و پاسخ مناسب تولید می‌کند
۱۰

عیب‌یابی خطاهای رایج

Troubleshooting
علامت علت احتمالی راه‌حل
اتصال برقرار نمی‌شود آدرس اشتباه، پورت بسته یا فایروال از همان ماشین XAiApi با curl تست کنید؛ HTTP را امتحان کنید
خطای SSL گواهی self-signed گواهی معتبر نصب کنید یا در توسعه از HTTP استفاده کنید
404 روی /mcp مسیر یا پورت اشتباه مسیر دقیق را از Swagger یا لاگ XAiMcpServer بردارید
هیچ ابزاری تشخیص داده نمی‌شود اسمبلی ابزارها اسکن نشده یا attributeها وجود ندارند وجود [XAiMcpToolType] و [XAiMcpTool] را بررسی کنید
سرور جدید دیده نمی‌شود Provider cache شده است XAiApi را ری‌استارت کنید یا RefreshAsync را صدا بزنید
خطای جدول وجود ندارد migration AiMcpServers اعمال نشده migration جدید اضافه و database update کنید
مدل از ابزار استفاده نمی‌کند Options.Tools پر نشده بخش ۸ را پیاده‌سازی کنید
401 / 403 توکن ادمین یا Policy نامعتبر توکن با Policy EnabledAdmin دریافت کنید
۱۱

جمع‌بندی و پیشنهاد نهایی

Final Recommendation

XAiMcpServer یک MCP Server ساده و تست‌شده است. برای اتصال آن به XAiApi، مسیر پیشنهادی زیر است:

اولویت اقدام
۱ تست مستقیم XAiMcpServer با initialize، tools/list و tools/call
۲ اطمینان از وجود جدول AiMcpServers و ثبت IXAiMcpServerProvider در DI
۳ ثبت سرور از طریق API مدیریتی XAiApi با Endpoint /mcp
۴ ری‌استارت XAiApi و بررسی لاگ دریافت ابزارها
۵ تزریق ابزارها به ChatOptions.Tools برای استفاده واقعی مدل

🎯 پیشنهاد نهایی

برای شروع، روش ۱ (ثبت از طریق API مدیریتی) را انتخاب کنید و پس از دیدن لاگ اتصال، بخش ۸ (تزریق ابزارها به مدل) را تکمیل کنید.

💎 نتیجه:
اتصال پایه با ثبت Endpoint و فعال‌سازی سرور انجام می‌شود؛ استفاده واقعی از ابزارها نیازمند تزریق IXAiMcpServerProvider و پرکردن ChatOptions.Tools است.
گام بعدی: پس از اتصال موفق، ابزار Echo را از طریق یک درخواست Ask آزمایش کنید و سپس ابزارهای واقعی‌تر را با همان الگوی [XAiMcpToolType] و [XAiMcpTool] به XAiMcpServer اضافه کنید.
این مستند فنی صرفاً برای تیم توسعه XAiApi و XAiMcpServer تهیه شده است.
نسخه ۱.۰  |  آبان ۱۴۰۵  |  طبقه‌بندی: فنی
diff --git a/Documents/Docs/Developer/MCP Server HttpTransport 10.html b/Documents/Docs/Developer/MCP Server HttpTransport 10.html new file mode 100644 index 0000000..d7155b4 --- /dev/null +++ b/Documents/Docs/Developer/MCP Server HttpTransport 10.html @@ -0,0 +1,1687 @@ + + + + + +کشف خودکار تولزها با Reflection در MCP Server | راهنمای گام‌به‌گام + + + + +
+ +
+
+
+ +
+
+
شماره مستند: TECH-1405-004
+
نسخه: ۱.۰
+
تاریخ تهیه: آبان ۱۴۰۵
+
طبقه‌بندی: فنی
+
+
+ +
+ REFLECTION-BASED TOOL DISCOVERY +

کشف خودکار تولزها با Reflection در MCP Server

+

پیاده‌سازی گام‌به‌گام مکانیزم Auto-Register در XAiMcpHandler

+
+
+ +
+ +
+ هدف:
+ در پیاده‌سازی فعلی، هر تولز جدید باید به‌صورت دستی در متد RegisterTools() سرویس XAiMcpHandler ثبت شود. این مستند یک راهکار کامل مبتنی بر Reflection پیشنهاد می‌دهد که در آن کافی است کلاس‌های تولز را در هر جای پروژه با اتریبیوت‌های سبک تزئین کنید و بقیه‌ی کارها (کشف، ساخت Schema، ساخت Delegate، ثبت خودکار) به‌صورت خودکار انجام شود. +
+ + +
+
+
۱
+
+

معماری کلی راهکار

+
High-Level Architecture
+
+
+
+ +

راهکار پیشنهادی شامل سه لایه است که با مکانیزم Reflection به هم متصل می‌شوند:

+ +
+
Attributeها
(تعریف سبک)
+ ← +
Scanner
(کشف خودکار)
+ ← +
Blueprints
(متادیتای کش‌شده)
+ ← +
Register
(خودکار در Handler)
+
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
لایهمسئولیتمحل استقرارLifetime
Attributeهاعلامت‌گذاری کلاس و متد تولزxAiModels/Attributes/Stateless
Scannerاسکن اسمبلی‌ها، استخراج متادیتا، ساخت Schema و ExecutexAiService/Providers/Singleton (با Lazy)
Integrationتبدیل Blueprint به Descriptor و ثبت در DictionaryxAiService/Services/XAiMcpHandler.csScoped
+ +
+ 💡 مزیت کلیدی: پس از پیاده‌سازی، برای افزودن یک تولز جدید، توسعه‌دهنده فقط یک متد عمومی با اتریبیوت [XMcpTool] در یک کلاس با اتریبیوت [XMcpToolType] می‌نویسد و پروژه را Rebuild می‌کند. هیچ تغییری در XAiMcpHandler لازم نیست. +
+ +
+
+ + +
+
+
۲
+
+

گام ۱: تعریف Attributeهای اختصاصی

+
Step 1 — Custom Attributes
+
+
+
+ +

ابتدا سه اتریبیوت سبک تعریف می‌کنیم. این اتریبیوت‌ها از اتریبیوت‌های SDK ([McpServerTool]) مستقل هستند تا با مکانیزم فعلی تداخل نداشته باشند و بتوانیم رفتار خودمان (پشتیبانی از DI، Binding خودکار و ...) را کنترل کنیم.

+ +
+ فایل جدید +
xAiModels/Attributes/XMcpToolAttributes.cs
+ +
using System; + +namespace xAiModels.Attributes +{ + /// <summary> کلاس حاوی متدهای تولز را علامت‌گذاری می‌کند </summary> + [AttributeUsage(AttributeTargets.Class, AllowMultiple = false, Inherited = false)] + public sealed class XMcpToolTypeAttribute : Attribute { } + + /// <summary> یک متد را به‌عنوان تولز MCP معرفی می‌کند </summary> + [AttributeUsage(AttributeTargets.Method, AllowMultiple = false, Inherited = false)] + public sealed class XMcpToolAttribute : Attribute + { + /// <summary> نام یکتای تولز (پیش‌فرض: نام متد) </summary> + public string Name { get; } + + /// <summary> توضیح تولز برای LLM </summary> + public string Description { get; set; } + + public XMcpToolAttribute(string name = null) => Name = name; + } + + /// <summary> متادیتای هر پارامتر تولز را تعریف می‌کند </summary> + [AttributeUsage(AttributeTargets.Parameter, AllowMultiple = false, Inherited = false)] + public sealed class XMcpToolParamAttribute : Attribute + { + /// <summary> نام پارامتر در JSON (پیش‌فرض: نام پارامتر C#) </summary> + public string Name { get; } + + /// <summary> توضیح پارامتر برای LLM </summary> + public string Description { get; set; } + + /// <summary> آیا این پارامتر الزامی است؟ (پیش‌فرض: بله) </summary> + public bool Required { get; set; } = true; + + public XMcpToolParamAttribute(string name = null) => Name = name; + } +}
+ +
+ 💡 چرا نه در xAiService؟ چون کلاس‌های تولز ممکن است در پروژه‌های مختلفی مثل xAiMcpServer تعریف شوند. قرار دادن Attributeها در xAiModels که لایه‌ی مشترک است، دسترسی را برای همه‌ی پروژه‌ها فراهم می‌کند. +
+
+ +
+
+ + +
+
+
۳
+
+

گام ۲: مدل Blueprint برای کش متادیتا

+
Step 2 — XMcpToolBlueprint
+
+
+
+ +

هر تولز کشف‌شده یک Blueprint (نقشه‌ی ساخت) تولید می‌کند که متادیتای آن یک‌بار محاسبه و تا پایان عمر برنامه کش می‌شود. سپس در هر درخواست، از روی Blueprint یک XAiMcpToolDescriptor تازه ساخته می‌شود که Execute آن به IServiceProvider جاری (per-request) Bind می‌شود.

+ +
+ فایل جدید +
xAiService/Models/XMcpToolBlueprint.cs
+ +
using System; +using System.Reflection; +using System.Threading; +using System.Threading.Tasks; +using Newtonsoft.Json.Linq; +using xAiModels.Models; + +namespace xAiService.Models +{ + /// <summary> نقشه‌ی ساخت یک تولز کشف‌شده </summary> + public sealed class XMcpToolBlueprint + { + public string Name { get; init; } + public string Description { get; init; } + public JObject InputSchema { get; init; } + + internal MethodInfo Method { get; init; } + internal Type DeclaringType { get; init; } + + /// <summary> + /// یک Descriptor قابل اجرا برای IServiceProvider جاری می‌سازد. + /// </summary> + public XAiMcpToolDescriptor ToDescriptor(IServiceProvider serviceProvider) + { + return new XAiMcpToolDescriptor + { + Name = Name, + Description = Description, + InputSchema = InputSchema, + Execute = BuildExecute(serviceProvider) + }; + } + + private Func<JObject, CancellationToken, Task<string>> BuildExecute( + IServiceProvider serviceProvider) + { + var method = Method; + var declaringType = DeclaringType; + + return async (args, ct) => + { + try + { + // 1. ساخت/گرفتن Instance + var instance = method.IsStatic + ? null + : (serviceProvider.GetService(declaringType) + ?? Activator.CreateInstance(declaringType)); + + // 2. Binding آرگومان‌ها + var parameters = method.GetParameters(); + var values = new object[parameters.Length]; + for (var i = 0; i < parameters.Length; i++) + { + var p = parameters[i]; + + // CancellationToken از بیرون تزریق می‌شود + if (p.ParameterType == typeof(CancellationToken)) + { + values[i] = ct; + continue; + } + + var attr = p.GetCustomAttribute<xAiModels.Attributes.XMcpToolParamAttribute>(); + var jsonName = attr?.Name ?? p.Name; + values[i] = XMcpArgumentBinder.Bind(args?[jsonName], p.ParameterType); + } + + // 3. فراخوانی و Await + object raw; + try { raw = method.Invoke(instance, values); } + catch (TargetInvocationException tie) when (tie.InnerException != null) + { throw tie.InnerException; } + + // 4. استخراج نتیجه + return await XMcpResultExtractor.ExtractAsync(raw, method.ReturnType); + } + catch (Exception ex) + { + return $"Error: {ex.Message}"; + } + }; + } + } +}
+ +
+ ✓ نکته: چون Execute در زمان ساخت Descriptor، IServiceProvider جاری (Scoped) را در Closure نگه می‌دارد، هر درخواست به‌طور خودکار Scope خودش را خواهد داشت و سرویس‌های Scoped (مثل DbContext) به‌درستی Resolve می‌شوند. +
+
+ +
+
+ + +
+
+
۴
+
+

گام ۳: Argument Binder و Result Extractor

+
Step 3 — Argument Binder & Result Extractor
+
+
+
+ +

دو کلاس کمکی برای تبدیل JToken به نوع .NET و همچنین استخراج نتیجه از متدهایی که ممکن است Task<T>، ValueTask<T> یا نوع ساده برگردانند:

+ +
+ فایل جدید +
xAiService/Helpers/XMcpArgumentBinder.cs
+ +
using System; +using System.Linq; +using Newtonsoft.Json.Linq; + +namespace xAiService.Helpers +{ + internal static class XMcpArgumentBinder + { + public static object Bind(JToken token, Type targetType) + { + var underlying = Nullable.GetUnderlyingType(targetType) ?? targetType; + + // مقدار null + if (token == null || token.Type == JTokenType.Null || token.Type == JTokenType.Undefined) + { + if (!targetType.IsValueType || Nullable.GetUnderlyingType(targetType) != null) + return null; + return Activator.CreateInstance(targetType); + } + + // انواع پایه + if (underlying == typeof(string)) return token.ToString(); + if (underlying == typeof(int)) return token.Value<int>(); + if (underlying == typeof(long)) return token.Value<long>(); + if (underlying == typeof(short)) return token.Value<short>(); + if (underlying == typeof(float)) return token.Value<float>(); + if (underlying == typeof(double)) return token.Value<double>(); + if (underlying == typeof(decimal)) return token.Value<decimal>(); + if (underlying == typeof(bool)) return token.Value<bool>(); + if (underlying == typeof(Guid)) return token.Value<Guid>(); + if (underlying == typeof(DateTime)) return token.Value<DateTime>(); + + // Enum + if (underlying.IsEnum) + return Enum.Parse(underlying, token.ToString(), ignoreCase: true); + + // آرایه‌ها + if (underlying.IsArray && token is JArray jarr) + { + var elementType = underlying.GetElementType(); + var arr = Array.CreateInstance(elementType, jarr.Count); + for (var i = 0; i < jarr.Count; i++) + arr.SetValue(Bind(jarr[i], elementType), i); + return arr; + } + + // Fallback: JSON Deserialize + return token.ToObject(underlying); + } + } +}
+ +
+ فایل جدید +
xAiService/Helpers/XMcpResultExtractor.cs
+ +
using System; +using System.Threading.Tasks; +using Newtonsoft.Json; +using Newtonsoft.Json.Linq; + +namespace xAiService.Helpers +{ + internal static class XMcpResultExtractor + { + public static async Task<string> ExtractAsync(object raw, Type returnType) + { + // Task / Task<T> + if (raw is Task task) + { + await task.ConfigureAwait(false); + if (returnType.IsGenericType && + returnType.GetGenericTypeDefinition() == typeof(Task<>)) + { + var value = returnType.GetProperty("Result").GetValue(task); + return Format(value); + } + return string.Empty; + } + + // ValueTask (non-generic) + if (returnType == typeof(ValueTask)) + { + await ((ValueTask)raw).ConfigureAwait(false); + return string.Empty; + } + + // ValueTask<T> + if (returnType.IsGenericType && + returnType.GetGenericTypeDefinition() == typeof(ValueTask<>)) + { + var asTask = (Task)returnType.GetMethod("AsTask").Invoke(raw, null); + await asTask.ConfigureAwait(false); + var value = asTask.GetType().GetProperty("Result").GetValue(asTask); + return Format(value); + } + + // void / T سنکرون + return Format(raw); + } + + private static string Format(object value) + { + if (value == null) return string.Empty; + if (value is string s) return s; + if (value is JToken jt) return jt.ToString(Formatting.None); + if (value.GetType().IsPrimitive || value is decimal) return value.ToString(); + return JToken.FromObject(value).ToString(Formatting.None); + } + } +}
+ +
+ ⚠ محدودیت: خروجی همه‌ی تولزها به‌صورت رشته بازگردانده می‌شود (چون Execute فقط string برمی‌گرداند). اگر به خروجی غنی (تصویر، فایل و ...) نیاز دارید، باید HandleToolCallAsync را در XAiMcpHandler سفارشی‌سازی کنید. +
+
+ +
+
+ + +
+
+
۵
+
+

گام ۴: پیاده‌سازی Scanner

+
Step 4 — XMcpToolScanner
+
+
+
+ +

این کلاس مسئول اسکن اسمبلی‌ها، کشف کلاس‌ها و متدهای دارای اتریبیوت، ساخت InputSchema و تولید Blueprint است. نتیجه با Lazy<> یک‌بار محاسبه و در طول عمر برنامه نگهداری می‌شود.

+ +
+ فایل جدید +
xAiService/Providers/XMcpToolScanner.cs
+ +
using System; +using System.Collections.Generic; +using System.ComponentModel; +using System.Linq; +using System.Reflection; +using System.Threading; +using Newtonsoft.Json.Linq; +using xAiModels.Attributes; +using xAiService.Models; + +namespace xAiService.Providers +{ + public sealed class XMcpToolScanner + { + private readonly Assembly[] assemblies; + private readonly Lazy<IReadOnlyList<XMcpToolBlueprint>> blueprints; + + public XMcpToolScanner(IEnumerable<Assembly> assemblies) + { + this.assemblies = assemblies? + .Where(a => a != null && !a.IsDynamic) + .Distinct() + .ToArray() ?? []; + + blueprints = new Lazy<IReadOnlyList<XMcpToolBlueprint>>( + Scan, + LazyThreadSafetyMode.ExecutionAndPublication + ); + } + + public IReadOnlyList<XMcpToolBlueprint> Blueprints => blueprints.Value; + + // --------------------------------------------------------- + // Scanning + // --------------------------------------------------------- + private IReadOnlyList<XMcpToolBlueprint> Scan() + { + var result = new List<XMcpToolBlueprint>(); + var seenNames = new HashSet<string>(StringComparer.Ordinal); + + foreach (var asm in assemblies) + { + foreach (var type in SafeGetTypes(asm)) + { + if (type.GetCustomAttribute<XMcpToolTypeAttribute>() == null) + continue; + + foreach (var method in type.GetMethods( + BindingFlags.Public | + BindingFlags.Instance | + BindingFlags.Static)) + { + var attr = method.GetCustomAttribute<XMcpToolAttribute>(); + if (attr == null) continue; + + var name = string.IsNullOrWhiteSpace(attr.Name) + ? method.Name + : attr.Name.Trim(); + + if (!seenNames.Add(name)) + throw new InvalidOperationException( + $"Duplicate MCP tool name '{name}' detected in {type.FullName}.{method.Name}."); + + var description = attr.Description + ?? method.GetCustomAttribute<DescriptionAttribute>()?.Description + ?? string.Empty; + + result.Add(new XMcpToolBlueprint + { + Name = name, + Description = description, + DeclaringType = type, + Method = method, + InputSchema = BuildInputSchema(method) + }); + } + } + } + + return result; + } + + // --------------------------------------------------------- + // Input Schema Builder + // --------------------------------------------------------- + private static JObject BuildInputSchema(MethodInfo method) + { + var properties = new JObject(); + var required = new JArray(); + + foreach (var p in method.GetParameters()) + { + // CancellationToken در Schema نمی‌آید + if (p.ParameterType == typeof(CancellationToken)) + continue; + + var attr = p.GetCustomAttribute<XMcpToolParamAttribute>(); + var jsonName = attr?.Name ?? p.Name; + var description = attr?.Description + ?? p.GetCustomAttribute<DescriptionAttribute>()?.Description + ?? string.Empty; + + var propSchema = new JObject + { + ["type"] = MapJsonType(p.ParameterType) + }; + + if (!string.IsNullOrWhiteSpace(description)) + propSchema["description"] = description; + + // آرایه‌ها: تعریف items + var underlying = Nullable.GetUnderlyingType(p.ParameterType) ?? p.ParameterType; + if (underlying.IsArray) + { + propSchema["items"] = new JObject + { + ["type"] = MapJsonType(underlying.GetElementType()) + }; + } + + properties[jsonName] = propSchema; + + // الزامی بودن + var isRequired = attr?.Required ?? true; + if (isRequired) + required.Add(jsonName); + } + + return new JObject + { + ["type"] = "object", + ["properties"] = properties, + ["required"] = required + }; + } + + private static string MapJsonType(Type type) + { + var t = Nullable.GetUnderlyingType(type) ?? type; + + if (t == typeof(string) || t == typeof(char) || t == typeof(Guid) || t == typeof(DateTime)) + return "string"; + + if (t == typeof(int) || t == typeof(long) || t == typeof(short) || t == typeof(byte)) + return "integer"; + + if (t == typeof(float) || t == typeof(double) || t == typeof(decimal)) + return "number"; + + if (t == typeof(bool)) + return "boolean"; + + if (t.IsArray || typeof(System.Collections.IEnumerable).IsAssignableFrom(t)) + return "array"; + + if (t.IsEnum) + return "string"; + + return "object"; + } + + // --------------------------------------------------------- + // Helpers + // --------------------------------------------------------- + private static IEnumerable<Type> SafeGetTypes(Assembly asm) + { + try { return asm.GetTypes(); } + catch (ReflectionTypeLoadException ex) + { return ex.Types.Where(t => t != null)!; } + } + } +}
+ +
+ 💡 نکات کلیدی: +
    +
  • Lazy<> با ExecutionAndPublication از اجرای هم‌زمان Scan جلوگیری می‌کند.
  • +
  • SafeGetTypes خطاهای ReflectionTypeLoadException را مدیریت می‌کند (گاهی در اسمبلی‌های وابسته به پکیج‌های ناقص رخ می‌دهد).
  • +
  • نام تکراری با InvalidOperationException رد می‌شود تا رفتار پیش‌بینی‌پذیر بماند.
  • +
  • پارامترهای CancellationToken از Schema حذف می‌شوند و در زمان اجرا تزریق می‌گردند.
  • +
+
+
+ +
+
+ + +
+
+
۶
+
+

گام ۵: ادغام در XAiMcpHandler

+
Step 5 — Integrate into Handler
+
+
+
+ +

اکنون XAiMcpHandler را طوری بازنویسی می‌کنیم که علاوه بر تولزهای دستی، Blueprintهای کشف‌شده را هم ثبت کند:

+ +
+ ویرایش فایل +
xAiService/Services/XAiMcpHandler.cs
+ +
using System; +using System.Threading; +using Newtonsoft.Json.Linq; +using xAiService.Interfaces; +using xAiService.Providers; +using System.Threading.Tasks; +using System.Collections.Generic; + +namespace xAiService.Services +{ + public class XAiMcpHandler : IXAiMcpHandler + { + private readonly Dictionary<string, XAiMcpToolDescriptor> tools = new(); + private readonly XMcpToolScanner scanner; + private readonly IServiceProvider serviceProvider; + + public XAiMcpHandler( + XMcpToolScanner scanner, + IServiceProvider serviceProvider) + { + this.scanner = scanner; + this.serviceProvider = serviceProvider; + RegisterTools(); + } + + public async Task<JObject> ProcessAsync(JObject request, CancellationToken cancellationToken = default) + { + var method = request["method"]?.ToString(); + var id = request["id"]; + + return method switch + { + "initialize" => HandleInitialize(id), + "tools/list" => HandleToolsList(id), + "tools/call" => await HandleToolCallAsync(request, id, cancellationToken), + "ping" => HandlePing(id), + _ => CreateError(id, -32601, $"Method not found: {method}") + }; + } + + // --------------------------------------------------------- + // 🔥 نقطه‌ی اصلی: ثبت خودکار تولزها + // --------------------------------------------------------- + private void RegisterTools() + { + // 1) تولزهای دستی (حفظ سازگاری با گذشته) + RegisterManualTools(); + + // 2) تولزهای کشف‌شده با Reflection + foreach (var blueprint in scanner.Blueprints) + { + if (tools.ContainsKey(blueprint.Name)) + { + // تولز دستی اولویت دارد؛ یا برعکس، بسته به سیاست شما + continue; + } + tools[blueprint.Name] = blueprint.ToDescriptor(serviceProvider); + } + } + + private void RegisterManualTools() + { + // نمونه‌ی تولز قبلی - برای سازگاری + tools["search_knowledge"] = new XAiMcpToolDescriptor + { + Name = "search_knowledge", + Description = "Search in knowledge base", + InputSchema = new JObject + { + ["type"] = "object", + ["properties"] = new JObject + { + ["query"] = new JObject { ["type"] = "string" } + }, + ["required"] = new JArray("query") + }, + Execute = async (args, ct) => + { + var query = args?["query"]?.ToString() ?? ""; + return $"Results for: {query}"; + } + }; + } + + // ... بقیه‌ی متدهای HandleInitialize، HandleToolsList، ... + // بدون تغییر باقی می‌مانند + } +}
+ +
+ ✓ نتیجه: از این پس هر کلاسی که با [XMcpToolType] تزئین شده و متدهای [XMcpTool] دارد، به‌طور خودکار در tools/list ظاهر و در tools/call قابل فراخوانی خواهد بود. +
+
+ +
+
+ + +
+
+
۷
+
+

گام ۶: ثبت در DI

+
Step 6 — Dependency Injection
+
+
+
+ +

در فایل xAiService/Extensions/DIExtensions.cs، ثبت‌ها را به‌روزرسانی می‌کنیم:

+ +
+ ویرایش فایل +
xAiService/Extensions/DIExtensions.cs
+ +
using System; +using System.Linq; +using System.Reflection; +using xAiService.Services; +using xAiService.Providers; +using xAiService.Interfaces; +using Microsoft.Extensions.DependencyInjection; + +namespace xAiService.Extensions +{ + public static class DIExtensions + { + public static void AddXAiMcpHandler(this IServiceCollection source) + { + // 1) Scanner به‌صورت Singleton با کش Lazy داخلی + source.AddSingleton<XMcpToolScanner>(sp => + { + // اسکن همه‌ی اسمبلی‌های xAi* + ورودی برنامه + var asms = AppDomain.CurrentDomain + .GetAssemblies() + .Where(a => !a.IsDynamic && + a.GetName().Name != null && + a.GetName().Name!.StartsWith("xAi", StringComparison.OrdinalIgnoreCase)) + .Append(Assembly.GetEntryAssembly()!) + .ToArray(); + + return new XMcpToolScanner(asms); + }); + + // 2) Handler - Scoped (برای هماهنگی با IServiceProvider جاری) + source.AddScoped<IXAiMcpHandler, XAiMcpHandler>(); + } + } +}
+ +
+ ⚠ نکته مهم درباره انتخاب اسمبلی‌ها: اگر تولزها در اسمبلی خاصی هستند که نامش با xAi شروع نمی‌شود، باید آن اسمبلی را هم به لیست اضافه کنید. راه بهتر: امکان تزریق IEnumerable<Assembly> یا استفاده از یک Options Pattern برای پیکربندی. +
+
+ +
+
+ + +
+
+
۸
+
+

گام ۷: نوشتن اولین تولز نمونه

+
Step 7 — Sample Tool Class
+
+
+
+ +

اکنون می‌توانید یک کلاس تولز جدید بسازید. نمونه‌ی کامل با پشتیبانی از DI (اختیاری):

+ +
+ فایل جدید +
xAiMcpServer/Tools/SampleTools.cs
+ +
بدون وابستگی
+
using System; +using System.ComponentModel; +using System.Threading; +using System.Threading.Tasks; +using xAiModels.Attributes; + +namespace xAiMcpServer.Tools +{ + [XMcpToolType] + public class SampleTools + { + [XMcpTool("calculate_bmi", + Description = "Calculates Body Mass Index (BMI) given weight in kg and height in meters.")] + public string CalculateBmi( + [XMcpToolParam("weight", Description = "Weight in kilograms (e.g. 72.5)")] double weight, + [XMcpToolParam("height", Description = "Height in meters (e.g. 1.78)")] double height, + CancellationToken cancellationToken = default) + { + if (weight <= 0 || height <= 0) + return "Error: weight and height must be positive."; + + var bmi = weight / (height * height); + var category = bmi < 18.5 ? "Underweight" + : bmi < 25 ? "Normal" + : bmi < 30 ? "Overweight" + : "Obese"; + + return $"BMI = {bmi:F2} ({category})"; + } + + [XMcpTool(Description = "Returns the current UTC time in ISO 8601 format.")] + public async Task<string> GetUtcNow(CancellationToken cancellationToken = default) + { + await Task.CompletedTask; + return DateTime.UtcNow.ToString("O"); + } + + [XMcpTool("sum_numbers", + Description = "Sums an array of numbers and returns the total.")] + public double SumNumbers( + [XMcpToolParam("values", Description = "Array of numbers to sum")] double[] values) + { + double total = 0; + foreach (var v in values ?? []) + total += v; + return total; + } + } +}
+ +
با وابستگی به سرویس (DI)
+
using System.Threading; +using System.Threading.Tasks; +using xAiModels.Attributes; + +namespace xAiMcpServer.Tools +{ + [XMcpToolType] + public class DatabaseTools + { + private readonly IMyDataService dataService; + + // سازنده‌ی با تزریق وابستگی (باید در DI ثبت شده باشد) + public DatabaseTools(IMyDataService dataService) + { + this.dataService = dataService; + } + + [XMcpTool("get_user_count", + Description = "Returns the total number of registered users.")] + public async Task<string> GetUserCount(CancellationToken cancellationToken = default) + { + var count = await dataService.CountUsersAsync(cancellationToken); + return $"Total users: {count}"; + } + } +}
+ +
+ 💡 درباره DI در تولزها: اگر DatabaseTools را در ConfigureServices با services.AddScoped<DatabaseTools>() ثبت کرده باشید، XMcpToolScanner هنگام اجرا آن را از IServiceProvider جاری Resolve می‌کند. در غیر این‌صورت، به Activator.CreateInstance فالبک می‌کند (که برای کلاس‌های دارای وابستگی، خطا خواهد داد - پس حتماً ثبت کنید). +
+
+ +
+
+ + +
+
+
۹
+
+

گام ۸: تست و اعتبارسنجی

+
Step 8 — Testing & Validation
+
+
+
+ +

پس از Rebuild و اجرای سرور، با استفاده از cURL یا Postman می‌توانید تست کنید:

+ +
1) بررسی لیست تولزها
+
curl -X POST https://localhost:7001/mcp \ + -H "Content-Type: application/json" \ + -d '{ + "jsonrpc": "2.0", + "id": 1, + "method": "tools/list" + }'
+ +

در پاسخ باید سه تولز calculate_bmi، get_utc_now و sum_numbers (به‌علاوه‌ی تولز دستی search_knowledge) را ببینید.

+ +
2) فراخوانی calculate_bmi
+
curl -X POST https://localhost:7001/mcp \ + -H "Content-Type: application/json" \ + -d '{ + "jsonrpc": "2.0", + "id": 2, + "method": "tools/call", + "params": { + "name": "calculate_bmi", + "arguments": { "weight": 75, "height": 1.78 } + } + }'
+ +
3) تست آرایه (sum_numbers)
+
curl -X POST https://localhost:7001/mcp \ + -H "Content-Type: application/json" \ + -d '{ + "jsonrpc": "2.0", + "id": 3, + "method": "tools/call", + "params": { + "name": "sum_numbers", + "arguments": { "values": [1, 2.5, 3, 4.5] } + } + }'
+ +
4) تست خطا (پارامتر ناموجود)
+
curl -X POST https://localhost:7001/mcp \ + -H "Content-Type: application/json" \ + -d '{ + "jsonrpc": "2.0", + "id": 4, + "method": "tools/call", + "params": { + "name": "calculate_bmi", + "arguments": { "weight": 75 } + } + }'
+ +

در این حالت باید پاسخ "Error: ..." یا -32602 دریافت کنید (بسته به این‌که پیاده‌سازی شما ورودی‌های ناقص را چطور مدیریت می‌کند).

+ +

چک‌لیست تست

+
    +
  • ✓ همه‌ی کلاس‌های [XMcpToolType] اسکن شده‌اند.
  • +
  • ✓ tools/list همه‌ی تولزها را با inputSchema صحیح برمی‌گرداند.
  • +
  • ✓ پارامترهای CancellationToken در Schema ظاهر نمی‌شوند.
  • +
  • ✓ تولزهای Async (Task<T>، ValueTask<T>) به‌درستی Await می‌شوند.
  • +
  • ✓ تولزهای دارای آرایه، Enum، Nullable درست Bind می‌شوند.
  • +
  • ✓ تولزهای دارای وابستگی، از DI Resolve می‌شوند.
  • +
  • ✓ نام تکراری باعث پرتاب Exception می‌شود.
  • +
+ +
+
+ + +
+
+
۱۰
+
+

ملاحظات پیشرفته و بهترین شیوه‌ها

+
Advanced Considerations & Best Practices
+
+
+
+ +
+

۱۰-۱. کشف اسمبلی‌ها به‌صورت قابل‌پیکربندی

+

برای پروژه‌های بزرگ بهتر است اسمبلی‌ها از کانفیگ خوانده شوند. نمونه:

+ +
public sealed class XMcpToolScannerOptions +{ + public string[] AssemblyNames { get; set; } = []; +}
+ +
// در DI: +source.AddSingleton<XMcpToolScanner>(sp => +{ + var options = sp.GetRequiredService<XMcpToolScannerOptions>(); + var asms = options.AssemblyNames + .Select(n => Assembly.Load(n)) + .ToArray(); + return new XMcpToolScanner(asms); +});
+ +
// appsettings.json +{ + "McpToolScanner": { + "AssemblyNames": ["xAiMcpServer", "MyOtherToolProject"] + } +}
+
+ +
+

۱۰-۲. پشتیبانی از تولزهای غیرفعال

+

می‌توانید به XMcpToolAttribute یک خاصیت Enabled اضافه کنید:

+ +
public bool Enabled { get; set; } = true;
+ +

و در Scanner:

+
if (!attr.Enabled) continue;
+
+ +
+

۱۰-۳. تعیین Scope مجوز

+

اگر می‌خواهید تولزهای حساس فقط برای ادمین در دسترس باشند، می‌توانید فیلد RequiredScope اضافه کنید و در HandleToolsList بر اساس Context.User فیلتر کنید (نیازمند تغییر کوچک در XAiMcpControllerBase).

+
+ +
+

۱۰-۴. Logging و Diagnose

+

پیشنهاد می‌شود در زمان Scan، لاگ مناسبی ثبت شود:

+ +
private readonly ILogger<XMcpToolScanner> logger; + +// در Scan: +logger.LogInformation( + "MCP Scanner: {Count} tools discovered from {AsmCount} assemblies.", + result.Count, assemblies.Length); + +foreach (var bp in result) + logger.LogDebug(" ✓ {Name} ({Type})", bp.Name, bp.DeclaringType.Name);
+
+ +
+

۱۰-۵. محدودیت‌ها

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
محدودیتراهکار
خروجی فقط textسفارشی‌سازی HandleToolCallAsync برای انواع دیگر
عدم پشتیبانی از Streamingتغییر در پایپ‌لاین Controller
Generic Methodsدر Scan، متدهای IsGenericMethodDefinition را رد کنید
متدهای PrivateScan فقط Public را می‌بیند (تصمیم امنیتی)
Overload با نام یکسانالزام name صریح در اتریبیوت
+
+ +
+

۱۰-۶. پیشنهاد برای تست‌پذیری

+

می‌توانید XMcpToolScanner را طوری بازنویسی کنید که Assembly[] را از XMcpToolScannerOptions بگیرد. این کار نوشتن Unit Test را آسان می‌کند:

+ +
[Fact] +public void Scanner_Should_Discover_Tools_In_Sample_Assembly() +{ + var scanner = new XMcpToolScanner([typeof(SampleTools).Assembly]); + var tools = scanner.Blueprints; + Assert.Contains(tools, t => t.Name == "calculate_bmi"); +}
+
+ +
+
+ + +
+
+
۱۱
+
+

جمع‌بندی و مقایسه‌ی نهایی

+
Summary & Final Comparison
+
+
+
+ +

با پیاده‌سازی این راهکار، سه روش ثبت تولز در پروژه خواهیم داشت:

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
روشنحوه‌ی تعریفمزیتمعایب
دستی در RegisterToolsافزودن مستقیم XAiMcpToolDescriptorکنترل کاملتکرار کد، خطای انسانی
Attribute-Based SDK[McpServerToolType] + [McpServerTool]خودکار از طریق WithToolsFromAssemblyفقط برای Grapevine MCP، جدا از XAiMcpHandler
Reflection-Based (این مستند)[XMcpToolType] + [XMcpTool]خودکار + قابل استفاده در Handler + DI-awareپیچیدگی اولیه‌ی بیشتر
+ +
+

🎯 نتیجه‌گیری

+

با پیاده‌سازی Reflection-Based Auto-Discovery، افزودن یک تولز جدید به سه خط کد کاهش می‌یابد: یک کلاس، یک اتریبیوت کلاس، و یک متد با اتریبیوت [XMcpTool].

+
+ 💎 ارزش پیشنهادی:
+ کاهش خطای انسانی + توسعه‌پذیری + پشتیبانی از DI + عدم نیاز به تغییر Handler برای هر تولز جدید + سازگاری کامل با ساختار موجود +
+
+ +

فایل‌های جدید و تغییرات

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
فایلوضعیتمسئولیت
xAiModels/Attributes/XMcpToolAttributes.csجدیدتعریف اتریبیوت‌ها
xAiService/Models/XMcpToolBlueprint.csجدیدنگهداری متادیتای کش‌شده
xAiService/Helpers/XMcpArgumentBinder.csجدیدتبدیل JToken به .NET
xAiService/Helpers/XMcpResultExtractor.csجدیداستخراج نتیجه از متد
xAiService/Providers/XMcpToolScanner.csجدیداسکن اسمبلی‌ها و ساخت Blueprint
xAiService/Services/XAiMcpHandler.csتغییرادغام Scanner در RegisterTools
xAiService/Extensions/DIExtensions.csتغییرثبت Scanner و به‌روزرسانی Handler
xAiMcpServer/Tools/SampleTools.csجدیدنمونه‌ی تولز
+ +
+
+ +
+ این مستند فنی برای استفاده‌ی تیم توسعه‌ی xSaherelmWorkspace تهیه شده است. تمامی نمونه‌کدها با ساختار فعلی پروژه سازگار بوده و بر اساس .NET 8 و Newtonsoft.Json نوشته شده‌اند. +
+ +
+ +
+ + +
تاریخ تهیه: آبان ۱۴۰۵  |  نسخه: ۱.۰  |  طبقه‌بندی: فنی
+
+ +
+ + + \ No newline at end of file diff --git a/Documents/Docs/Developer/MCP Server HttpTransport 7.html b/Documents/Docs/Developer/MCP Server HttpTransport 7.html new file mode 100644 index 0000000..9a4f395 --- /dev/null +++ b/Documents/Docs/Developer/MCP Server HttpTransport 7.html @@ -0,0 +1,1069 @@ + + + + + +تحلیل و رفع مشکل اجرای پروژه xAiMcpServer + + + + +
+ +
+
+
+ +
+
+
شماره مستند: TECH-1405-002
+
نسخه: ۱.۰
+
تاریخ تهیه: آبان ۱۴۰۵
+
طبقه‌بندی: فنی
+
+
+ +
+ TECHNICAL DIAGNOSIS & SOLUTION +

تحلیل و رفع مشکل اجرای xAiMcpServer

+

ریشه‌یابی خطا + راه‌حل کامل + کنترلرها + راه‌های تضمین اجرا

+
+
+ +
+ +
+ همکار گرامی،
+ پروژه xAiMcpServer به دلیل ترکیب نادرست دو فریم‌ورک متفاوت (Grapevine و ASP.NET Core) در فایل Program.cs و Startup.cs اجرا نمی‌شود. در این مستند، ابتدا ریشه مشکل شناسایی می‌شود، سپس کد صحیح بازنویسی می‌گردد و در نهایت راه‌های جامع برای تضمین اجرای صحیح و تست آن ارائه می‌شود. +
+ + +
+
+
۱
+
+

خلاصه اجرایی

+
Executive Summary
+
+
+
+

پروژه xAiMcpServer در واقع یک ASP.NET Core Web API است (به دلیل استفاده از XBaseIdentityApiV1Controller، DI Container، Swagger و ...). اما فایل Program.cs از Grapevine (یک کتابخانه HTTP سبک و کاملاً متفاوت) برای اجرا استفاده می‌کند. نتیجه این است که:

+ +
+
+
✓
+
Startup ثبت می‌شود ولی Configure اجرا نمی‌شود
+
+
+
✗
+
کنترلرها هیچ‌گاه Map نمی‌شوند
+
+
+
✗
+
MCP SDK Endpoint فعال نمی‌شود
+
+
+ +
+ ⚠️ علت اصلی: متد RestServerBuilder.From<Startup>() در Grapevine، فقط ConfigureServer(IRestServer) را فراخوانی می‌کند و هرگز Configure(IApplicationBuilder, IWebHostEnvironment) را صدا نمی‌زند. چون تمام Routing، Controllers، Authentication و MCP در متد Configure تعریف شده‌اند، هیچ‌کدام از آن‌ها اجرا نمی‌شوند. +
+
+
+ + +
+
+
۲
+
+

ریشه‌یابی دقیق مشکل

+
Root Cause Analysis
+
+
+
+

مشکلات موجود را می‌توان به ۵ دسته تقسیم کرد:

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
#مشکلفایلاثر
۱استفاده از Grapevine در Program.cs به جای ASP.NET Core HostProgram.csکشنده — هیچ کنترلی اجرا نمی‌شود
۲متد Configure هرگز توسط Grapevine فراخوانی نمی‌شودStartup.csMiddleware Pipeline اجرا نمی‌شود
۳ترکیب دو سیستم MCP هم‌زمان: (الف) McpController با Route mcp و (ب) .AddMcpServer().WithHttpTransport() از SDK رسمیStartup.cs + McpController.csتداخل و ابهام در Endpoint
۴استفاده از IHostBuilder (Console Host) به جای WebApplication یا ConfigureWebHostDefaultsProgram.csWeb Host راه‌اندازی نمی‌شود
۵عدم ثبت صریح Endpoint برای MapMcp() در صورت استفاده از SDK رسمیStartup.csMCP Tools در دسترس نیستند
+ +
+ 💡 نکته کلیدی: پروژه شما در واقع یک ASP.NET Core Web API است که می‌خواهد روی https://localhost:7001/mcp هم به عنوان یک MCP Server عمل کند. برای این کار باید یا از SDK رسمی ModelContextProtocol استفاده کنید، یا کنترلر سفارشی XAiMcpControllerBase را نگه دارید. استفاده از هر دو در یک پروژه باعث تداخل می‌شود. +
+
+
+ + +
+
+
۳
+
+

راه‌حل ۱: بازنویسی Program.cs با ASP.NET Core

+
Fix Program.cs - Use WebApplication
+
+
+
+

فایل Program.cs فعلی با Grapevine کار می‌کند که باعث می‌شود Startup.Configure هرگز اجرا نشود. نسخه صحیح با WebApplication به شکل زیر است:

+ +
Program.cs — نسخه صحیح
+
using System.Text;
+using Microsoft.AspNetCore.Builder;
+using Microsoft.Extensions.Hosting;
+using xAiMcpServer;
+
+var builder = WebApplication.CreateBuilder(args);
+
+// Register Encoding Provider
+Encoding.RegisterProvider(CodePagesEncodingProvider.Instance);
+
+// Use Startup pattern for compatibility with current project
+builder.Host
+    .UseDefaultServiceProvider(options =>
+    {
+        options.ValidateScopes = builder.Environment.IsDevelopment();
+        options.ValidateOnBuild = true;
+    });
+
+var startup = new Startup(builder.Configuration);
+startup.ConfigureServices(builder.Services);
+
+var app = builder.Build();
+startup.Configure(app, app.Environment);
+
+app.Run();
+ +
+ ✓ چرا این کد درست است؟ +
    +
  • WebApplication.CreateBuilder یک Web Host کامل می‌سازد.
  • +
  • متد Configure از Startup به‌درستی فراخوانی می‌شود.
  • +
  • Swagger، Controllers، Authentication و MCP همگی فعال می‌شوند.
  • +
  • پورت از launchSettings.json یا appsettings.json خوانده می‌شود (پیش‌فرض 7001 در نظر گرفته شده).
  • +
+
+
+
+ + +
+
+
۴
+
+

راه‌حل ۲: اصلاح Startup.cs برای اجرای Endpointها

+
Fix Startup.cs - Map Controllers & MCP
+
+
+
+

مشکل دیگر این است که در Startup.cs فعلی، MCP SDK ثبت شده ولی Endpoint آن Map نشده است. همچنین باید تصمیم بگیرید از کدام سیستم MCP استفاده می‌کنید: کنترلر سفارشی یا SDK رسمی.

+ +
+
+

🔵 گزینه A: SDK رسمی (ModelContextProtocol)

+
    +
  • پکیج اصلی ModelContextProtocol.AspNetCore
  • +
  • کلاس‌ها XEchoTools
  • +
  • Endpoint MapMcp()
  • +
  • Discovery خودکار
  • +
+
+ + +
+ +
+ ⚠️ نکته مهم: انتخاب یک مسیر کافی است. اگر هر دو را هم‌زمان فعال کنید، هر دو روی /mcp سوار می‌شوند و تداخل می‌کنند. +
+ +

گزینه B (کنترلر سفارشی) را انتخاب می‌کنیم چون ساختار موجود پروژه (XAiMcpControllerBase) به همین شکل نوشته شده است:

+ +
Startup.cs — نسخه اصلاح‌شده
+
using System;
+using System.IO;
+using System.Reflection;
+using xAiMcpServer.DI;
+using Newtonsoft.Json;
+using xIdentityService.DI;
+using xCommons.Extensions;
+using xAiService.Extensions;
+using xCommons.Configurations;
+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 xAiMcpServer
+{
+    public class Startup
+    {
+        public Startup(IConfiguration configuration)
+        {
+            Configuration = configuration;
+        }
+
+        public IConfiguration Configuration { get; }
+
+        public void ConfigureServices(IServiceCollection services)
+        {
+            // 1) MCP Handler (کنترلر سفارشی)
+            services.AddXAiMcpHandler();
+
+            // 2) XCommons (Validation, AppConfig, ...)
+            services.AddXCommons(Configuration);
+            services.AddXAppConfiguration(Configuration);
+            var appConfiguration = services.GetRegisteredService<XAppConfiguration>();
+
+            // 3) CORS
+            services.AddXCors(appConfiguration.AllowedOrigins);
+
+            // 4) Swagger
+            var xmlFile = $"{Assembly.GetExecutingAssembly().GetName().Name}.xml";
+            var xmlPath = Path.Combine(AppContext.BaseDirectory, xmlFile);
+            services.AddXSwagger(Configuration, xmlFilePath: xmlPath);
+
+            // 5) API Versioning
+            services.AddXApiV1Versioning();
+
+            // 6) OAuth Introspection HttpClient (SSL bypass for dev)
+            services.AddHttpClient(OAuth2IntrospectionDefaults.BackChannelHttpClientName)
+                .ConfigurePrimaryHttpMessageHandler(() => new HttpClientHandler
+                {
+                    ServerCertificateCustomValidationCallback =
+                        (sender, certificate, chain, sslPolicyErrors) => true
+                });
+
+            // 7) Authorization
+            services.AddXAuthorization();
+
+            // 8) MVC / Controllers
+            services.AddControllers()
+                .AddNewtonsoftJson(x =>
+                {
+                    x.SerializerSettings.ReferenceLoopHandling = ReferenceLoopHandling.Ignore;
+                    x.SerializerSettings.ContractResolver = new CamelCasePropertyNamesContractResolver();
+                });
+
+            // 9) Identity
+            services.AddXIdentityService(
+                lifeTime: ServiceLifetime.Scoped,
+                configuration: Configuration);
+        }
+
+        public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
+        {
+            var isDev = env.IsDevelopment();
+            if (isDev) app.UseDeveloperExceptionPage();
+            else app.UseHsts();
+
+            app.UseHttpsRedirection();
+
+            if (isDev) app.UseXSwagger();
+            app.UseXCors();
+            app.UseRouting();
+            app.UseXIdentityService();
+            app.UseAuthorization();
+
+            app.UseEndpoints(endpoints =>
+            {
+                // ✅ این خط کنترلرها (از جمله McpController و StartupController) را Map می‌کند
+                endpoints.MapControllers();
+            });
+        }
+    }
+}
+ +
+ ✓ تفاوت‌های کلیدی با نسخه قبلی: +
    +
  • حذف .AddMcpServer().WithHttpTransport().WithToolsFromAssembly() برای جلوگیری از تداخل با کنترلر سفارشی.
  • +
  • حذف متد ConfigureServer(IRestServer) که مخصوص Grapevine بود.
  • +
  • حفظ کامل Configure برای ASP.NET Core.
  • +
  • استفاده فقط از MapControllers().
  • +
+
+
+
+ + +
+
+
۵
+
+

بررسی صحت ثبت کنترلرها

+
Verify Controllers Registration
+
+
+
+

با تنظیمات بالا، سه کنترلر در پروژه وجود دارند:

+ + + + + + + + + + + + + + + + + + + + + + + + +
کنترلرBase ClassRouteهدف
McpControllerXAiMcpControllerBase/mcpدریافت درخواست‌های JSON-RPC از MCP Client
StartupControllerXBaseController/Welcome Message + Health
+ +
+ 📌 نکته: کنترلر StartupController در حال حاضر در Namespace xAiApi.Controllers تعریف شده است (به اشتباه)، در حالی که فایل آن در پروژه xAiMcpServer است. بهتر است Namespace آن به xAiMcpServer.Controllers تغییر کند تا Map خودکار کنترلرها به مشکل نخورد. +
+ +
رفع Namespace در StartupController.cs
+
// فایل: xAiMcpServer\Controllers\StartupController.cs
+namespace xAiMcpServer.Controllers   // ← اصلاح شود
+{
+    // ...
+}
+
+
+ + +
+
+
۶
+
+

تضمین اجرای صحیح — چک‌لیست جامع

+
Verification & Testing Strategy
+
+
+
+

پس از اعمال تغییرات بالا، برای اطمینان از اجرای صحیح، مراحل زیر را طی کنید:

+ +

مرحله ۱: بررسی Build و اجرا

+
PowerShell / Terminal
+
dotnet build xAiMcpServer.csproj
+dotnet run --project xAiMcpServer.csproj --urls "https://localhost:7001"
+
+# اگر خطا داشت، این دستور را اجرا کنید:
+dotnet run --project xAiMcpServer.csproj --urls "https://localhost:7001" --launch-profile "https"
+ +

مرحله ۲: تست Endpointهای اصلی

+
PowerShell / Terminal
+
# 1) تست Startup (Welcome Message) — باید 200 برگرداند
+curl -k https://localhost:7001/
+
+# 2) تست Swagger — باید HTML صفحه Swagger UI برگرداند
+curl -k https://localhost:7001/swagger/index.html
+
+# 3) تست Endpoint سلامت
+curl -k https://localhost:7001/health
+
+# 4) تست MCP initialize (JSON-RPC 2.0)
+curl -k -X POST https://localhost:7001/mcp `
+  -H "Content-Type: application/json" `
+  -d '{\"jsonrpc\":\"2.0\",\"id\":1,\"method\":\"initialize\",\"params\":{}}'
+
+# 5) تست MCP tools/list
+curl -k -X POST https://localhost:7001/mcp `
+  -H "Content-Type: application/json" `
+  -d '{\"jsonrpc\":\"2.0\",\"id\":2,\"method\":\"tools/list\"}'
+
+# 6) تست MCP tools/call
+curl -k -X POST https://localhost:7001/mcp `
+  -H "Content-Type: application/json" `
+  -d '{\"jsonrpc\":\"2.0\",\"id\":3,\"method\":\"tools/call\",\"params\":{\"name\":\"search_knowledge\",\"arguments\":{\"query\":\"test\"}}}'
+ +

مرحله ۳: استفاده از MCP Inspector (توصیه می‌شود)

+

ابزار رسمی MCP Inspector برای تست تعاملی سرور:

+
Terminal
+
npx @modelcontextprotocol/inspector
+
+# سپس در مرورگر باز کنید:
+# http://localhost:6274
+
+# در بخش Transport: HTTP (یا SSE)
+# URL: https://localhost:7001/mcp
+# روی Connect کلیک کنید → باید tools را ببینید
+ +

مرحله ۴: اضافه کردن Health Check Endpoint

+

یک Endpoint ساده برای بررسی سلامت و اجرای صحیح:

+ +
HealthController.cs (جدید)
+
using Microsoft.AspNetCore.Authorization;
+using Microsoft.AspNetCore.Mvc;
+
+namespace xAiMcpServer.Controllers
+{
+    [ApiController]
+    [Route("health")]
+    [AllowAnonymous]
+    public class HealthController : ControllerBase
+    {
+        [HttpGet]
+        public IActionResult Get()
+        {
+            return Ok(new
+            {
+                status = "Healthy",
+                service = "xAiMcpServer",
+                timestamp = DateTime.UtcNow,
+                environment = Environment.GetEnvironmentVariable("ASPNETCORE_ENVIRONMENT")
+                              ?? "Production",
+                version = typeof(Program).Assembly.GetName().Version?.ToString()
+            });
+        }
+    }
+}
+ +

مرحله ۵: لاگ‌گیری ساختاریافته

+

در Program.cs بعد از builder.Build() اضافه کنید:

+ +
Program.cs — افزودن لاگ راه‌اندازی
+
var logger = app.Services.GetRequiredService<ILogger<Program>>();
+logger.LogInformation("🚀 xAiMcpServer started on {Urls}",
+    app.Urls.Count > 0 ? string.Join(", ", app.Urls) : "configured endpoints");
+logger.LogInformation("📡 MCP endpoint: /mcp");
+logger.LogInformation("📖 Swagger UI: /swagger");
+logger.LogInformation("❤️  Health: /health");
+
+
+ + +
+
+
۷
+
+

چک‌لیست نهایی تضمین اجرا

+
Final Verification Checklist
+
+
+
+
    +
  • + ☐ ۱. Program.cs جایگزین شد + از WebApplication.CreateBuilder استفاده می‌شود، نه Grapevine. +
  • +
  • + ☐ ۲. Startup.cs اصلاح شد + متد ConfigureServer حذف و MapControllers() موجود است. +
  • +
  • + ☐ ۳. Namespace StartupController اصلاح شد + از xAiApi.Controllers به xAiMcpServer.Controllers تغییر یافت. +
  • +
  • + ☐ ۴. تنها یک سیستم MCP فعال است + یا SDK رسمی (MapMcp) یا کنترلر سفارشی — نه هر دو. +
  • +
  • + ☐ ۵. Endpoint سلامت اضافه شد + GET /health پاسخ 200 می‌دهد. +
  • +
  • + ☐ ۶. Swagger باز می‌شود + https://localhost:7001/swagger لیست کنترلرها را نشان می‌دهد. +
  • +
  • + ☐ ۷. تست initialize موفق است + POST /mcp با method:"initialize" پاسخ JSON-RPC معتبر می‌دهد. +
  • +
  • + ☐ ۸. تست tools/list موفق است + حداقل یک Tool (search_knowledge) برگردانده می‌شود. +
  • +
  • + ☐ ۹. MCP Inspector متصل می‌شود + Inspector tools را می‌بیند و می‌تواند فراخوانی کند. +
  • +
  • + ☐ ۱۰. لاگ‌ها پیام راه‌اندازی را نشان می‌دهند + در Console عبارت "xAiMcpServer started" دیده می‌شود. +
  • +
+ +
+ 🔧 اگر با خطای SSL مواجه شدید: از dotnet dev-certs https --trust استفاده کنید، یا با curl -k تست کنید. +
+ +
+ ⚠️ اگر پورت 7001 اشغال بود: در appsettings.json یا launchSettings.json پورت را تغییر دهید یا پروسه اشغال‌کننده را با netstat -ano | findstr :7001 پیدا و متوقف کنید. +
+
+
+ + +
+
+
۸
+
+

نمونه کامل Program.cs نهایی

+
Final Complete Program.cs
+
+
+
+

برای سهولت، کل فایل Program.cs نهایی را در یک نگاه:

+ +
Program.cs — نسخه نهایی (کپی-پیست)
+
using System.Text;
+using Microsoft.AspNetCore.Builder;
+using Microsoft.Extensions.DependencyInjection;
+using Microsoft.Extensions.Hosting;
+using Microsoft.Extensions.Logging;
+
+namespace xAiMcpServer
+{
+    public class Program
+    {
+        public static void Main(string[] args)
+        {
+            Encoding.RegisterProvider(CodePagesEncodingProvider.Instance);
+
+            var builder = WebApplication.CreateBuilder(args);
+
+            // Configure services via Startup
+            var startup = new Startup(builder.Configuration);
+            startup.ConfigureServices(builder.Services);
+
+            var app = builder.Build();
+
+            // Configure pipeline via Startup
+            startup.Configure(app, app.Environment);
+
+            // Startup log
+            var logger = app.Services.GetRequiredService<ILogger<Program>>();
+            logger.LogInformation("🚀 xAiMcpServer started");
+            logger.LogInformation("📡 MCP:     /mcp");
+            logger.LogInformation("📖 Swagger: /swagger");
+            logger.LogInformation("❤️  Health:  /health");
+
+            app.Run();
+        }
+    }
+}
+ +
+ ✓ نتیجه: با این تنظیمات، پروژه به‌درستی به عنوان ASP.NET Core Web API اجرا می‌شود، McpController روی /mcp پاسخ می‌دهد، Swagger در دسترس است و می‌توانید با MCP Inspector اتصال را تست کنید. +
+
+
+ + +
+
+
۹
+
+

جمع‌بندی و پیشنهاد نهایی

+
Final Summary
+
+
+
+
+

🎯 مشکل اصلی در یک جمله

+

ترکیب Grapevine و ASP.NET Core در یک پروژه، باعث می‌شود متد Configure هرگز اجرا نشود و در نتیجه هیچ کنترلر، Swagger یا MCP Endpoint فعال نگردد.

+
+ 💎 راه‌حل پیشنهادی:
+ ۱. Program.cs را با WebApplication.CreateBuilder بازنویسی کنید.
+ ۲. فقط یک سیستم MCP (کنترلر سفارشی یا SDK رسمی) را فعال نگه دارید.
+ ۳. Endpoint /health اضافه کنید و با MCP Inspector تست نمایید. +
+
+ +
+ 📞 گام بعدی: پس از اعمال تغییرات، ابتدا dotnet build بگیرید، سپس با curl سه Endpoint اصلی (/، /health، /mcp) را تست کنید. اگر هر سه پاس شدند، اتصال از طریق MCP Inspector را امتحان کنید. +
+
+
+ +
+ این مستند فنی صرفاً جهت رفع مشکل و بهبود پروژه xAiMcpServer تهیه شده است. +
+ +
+ +
+ + +
تاریخ تهیه: آبان ۱۴۰۵  |  نسخه: ۱.۰  |  طبقه‌بندی: فنی
+
+ +
+ + + \ No newline at end of file diff --git a/Documents/Docs/Developer/MCP Server HttpTransport 8.html b/Documents/Docs/Developer/MCP Server HttpTransport 8.html new file mode 100644 index 0000000..78c776f --- /dev/null +++ b/Documents/Docs/Developer/MCP Server HttpTransport 8.html @@ -0,0 +1,1124 @@ + + + + + +راهنمای ساخت تولز در MCP Server و اتصال به xAiApi | تحلیل فنی + + + + +
+ +
+
+
+ +
+
+
شماره مستند: TECH-1405-002
+
نسخه: ۱.۰
+
تاریخ تهیه: آبان ۱۴۰۵
+
طبقه‌بندی: فنی
+
+
+ +
+ TECHNICAL GUIDE +

راهنمای ساخت تولز در MCP Server و اتصال به xAiApi

+

مبتنی بر ساختار پروژه xSaherelmWorkspace

+
+
+ +
+ +
+ هدف مستند:
+ این مستند به‌عنوان یک راهنمای فنی عملی، نحوه‌ی تعریف و ایجاد یک تولز (Tool) در MCP Server پروژه و سپس اتصال این سرور به سرویس xAiApi را بر اساس ساختار کد موجود تشریح می‌نماید. تمامی نمونه‌کدها و مسیرهای فایل بر اساس پیاده‌سازی فعلی پروژه استخراج شده‌اند. +
+ + +
+
+
۱
+
+

ایجاد یک تولز (Tool) در MCP Server

+
Creating a Tool in xAiMcpServer
+
+
+
+ +

پروژه xAiMcpServer از کتابخانه‌ی ModelContextProtocol.Server استفاده می‌کند و بر پایه‌ی سرور Grapevine پیاده‌سازی شده است. برای تعریف تولز، دو رویکرد موجود است که در ادامه هر دو تشریح می‌شود:

+ +
+ + +
+

روش Custom Handler

+
    +
  • پیاده‌سازی IXAiMcpHandler
  • +
  • استفاده از XAiMcpToolDescriptor
  • +
  • مدیریت دستی JSON-RPC
  • +
  • انعطاف بیشتر در کنترل
  • +
  • مناسب برای Register پویا
  • +
+
+
+ +
+

۱-۱. روش اول: Attribute-Based (روش توصیه‌شده)

+

در این روش کافی است یک کلاس Static تعریف کرده و متدهای آن را با اتریبیوت‌های مربوطه تزئین کنید. نمونه‌ی موجود در پروژه:

+ +
Tools/XEchoTools.cs
+
// File: xAiMcpServer/Tools/XEchoTools.cs +using System.ComponentModel; +using ModelContextProtocol.Server; + +namespace xAiMcpServer.Tools +{ + [McpServerToolType] + public static class XEchoTools + { + [McpServerTool, + Description("Echoes the message back to the client.")] + public static string Echo(string message) + { + // + var result = $"hello {message}"; + return result; + } + } +}
+ +

برای افزودن تولز جدید، کافی است یک متد جدید با اتریبیوت [McpServerTool] و توضیح مناسب [Description(...)] به همین کلاس (یا کلاس جدید با [McpServerToolType]) اضافه کنید:

+ +
نمونه تولز جدید
+
using System.ComponentModel; +using ModelContextProtocol.Server; + +namespace xAiMcpServer.Tools +{ + [McpServerToolType] + public static class XEchoTools + { + [McpServerTool, + Description("Echoes the message back to the client.")] + public static string Echo(string message) + => $"hello {message}"; + + // --- تولز جدید: جمع دو عدد --- + [McpServerTool, + Description("Adds two numbers and returns the sum.")] + public static int Add( + [Description("First number")] int a, + [Description("Second number")] int b) + => a + b; + } +}
+ +
+ ✓ کشف خودکار: در Startup.cs از طریق WithToolsFromAssembly() تمام کلاس‌های دارای [McpServerToolType] در اسمبلی جاری به‌صورت خودکار شناسایی و ثبت می‌شوند. +
+
+ +
+

۱-۲. روش دوم: Custom Handler با XAiMcpToolDescriptor

+

در این روش از مکانیزم داخلی XAiMcpHandler استفاده می‌شود. تولزها در یک دیکشنری به نام tools از نوع Dictionary<string, XAiMcpToolDescriptor> نگهداری می‌شوند.

+ +
xAiService/Services/XAiMcpHandler.cs
+
private void RegisterTools() +{ + // + tools["search_knowledge"] = new XAiMcpToolDescriptor + { + Name = "search_knowledge", + Description = "Search in knowledge base", + InputSchema = new JObject + { + ["type"] = "object", + ["properties"] = new JObject + { + ["query"] = new JObject { ["type"] = "string" } + }, + ["required"] = new JArray("query") + }, + Execute = async (args, ct) => + { + var query = args?["query"]?.ToString() ?? ""; + return $"Results for: {query}"; + } + }; +}
+ +

ساختار XAiMcpToolDescriptor در xAiModels/Models/XAiMcpToolDescriptor.cs تعریف شده است:

+ +
Models/XAiMcpToolDescriptor.cs
+
public class XAiMcpToolDescriptor +{ + public string Name { get; set; } + public string Description { get; set; } + public JObject InputSchema { get; set; } + public Func<JObject, CancellationToken, Task<string>> Execute { get; set; } +}
+
+ +
+

۱-۳. ثبت و پیکربندی در DI و Startup

+

در فایل Startup.cs پروژه xAiMcpServer، دو ثبت اصلی مورد نیاز است:

+ +
Startup.cs - ConfigureServices
+
// +// Register MCP Handler (for Custom Handler approach) +services.AddXAiMcpHandler(); + +// ... سایر سرویس‌ها ... + +// +// Register MCP Server with Http Transport and Assembly Tool Discovery +services + .AddMcpServer() + .WithHttpTransport() + .WithToolsFromAssembly();
+ +
+ 💡 نکته: تزریق WithToolsFromAssembly() باعث می‌شود تمام کلاس‌های دارای [McpServerToolType] در اسمبلی جاری اسکن شده و متدهای دارای [McpServerTool] به‌عنوان تولز ثبت شوند. +
+
+ +
+

۱-۴. کنترلر MCP

+

کنترلر McpController وظیفه‌ی پردازش درخواست‌های JSON-RPC در مسیر /mcp را بر عهده دارد:

+ +
Controllers/McpController.cs
+
public class McpController : XAiMcpControllerBase +{ + public McpController( + IXAiMcpHandler mcpHandler, + ILogger<McpController> logger, + XAppConfiguration appConfiguration, + IXIdentityProvider identityProvider, + XValidationProvider validationProvider + ) : base(mcpHandler, appConfiguration, identityProvider, logger, validationProvider) + { } +}
+ +

مسیرهای در دسترس:

+ + + + + + + + + + + + + + + + + + + + + +
متدمسیرتوضیح
POST/mcpپردازش JSON-RPC (initialize, tools/list, tools/call, ping)
GET/mcp/sseEndpoint مربوط به Server-Sent Events (SSE)
+
+ +
+

۱-۵. نکات مهم در تعریف تولز

+
    +
  • نام منحصربه‌فرد: نام متد/تولز در سطح سرور باید یکتا باشد.
  • +
  • توضیح شفاف: فیلد Description مستقیماً به LLM ارسال می‌شود؛ لذا توضیح دقیق پارامترها ضروری است.
  • +
  • Schema ورودی: در روش Descriptor، فیلد InputSchema باید یک JSON Schema معتبر باشد.
  • +
  • Thread-Safety: متدهای تولز ممکن است هم‌زمان فراخوانی شوند؛ از State سراسری پرهیز کنید.
  • +
  • Exception Handling: خطاها را به‌صورت پیام متنی برگردانید تا به‌درستی به کلاینت منتقل شوند.
  • +
+
+ +
+
+ + +
+
+
۲
+
+

اتصال MCP Server به xAiApi

+
Connecting xAiMcpServer to xAiApi
+
+
+
+ +

پس از آماده‌سازی تولزها، نوبت به ثبت MCP Server در سرویس xAiApi و برقراری اتصال می‌رسد. جریان کلی به‌صورت زیر است:

+ +
+
ثبت سرور
در دیتابیس
+ ← +
اتصال
XAiMcpServerProvider
+ ← +
دریافت لیست
تولزها
+ ← +
افزودن به
ChatOptions
+
+ +
+

۲-۱. ساختار مدل XAiMcpServer

+

موجودیت MCP Server در xAiModels/Models/Entities/XAiMcpServer.cs تعریف شده است:

+ +
Models/Entities/XAiMcpServer.cs
+
public class XAiMcpServer : XBaseGuidIDEntity +{ + [Required] public string OwnerId { get; set; } + public XAiMcpServerUsageScope Scope { get; set; } = XAiMcpServerUsageScope.Owner; + + [Required] public string Name { get; set; } + public string Description { get; set; } + public bool Enabled { get; set; } = true; + public string EnvironmentVariables { get; set; } + public string Endpoint { get; set; } + public string Headers { get; set; } + public int TimeoutSeconds { get; set; } = 30; +}
+
+ +
+

۲-۲. ثبت سرور از طریق API

+

کنترلر McpServerController در xAiApi عملیات CRUD کامل را ارائه می‌دهد. برای ثبت یک MCP Server کافی است درخواست زیر را ارسال کنید:

+ +
POST /api/v1/mcpServer
+
{ + "name": "xAiMcpServer", + "description": "AI MCP Server for xAiApi", + "endpoint": "https://localhost:7001/mcp", + "enabled": true, + "scope": "Owner", + "timeoutSeconds": 30, + "headers": "{\"Authorization\":\"Bearer YOUR_TOKEN\"}" +}
+ +
+ 💡 نکته درباره فیلد Endpoint: مقدار باید مسیر دقیق /mcp سرور را مشخص کند؛ مثلاً https://localhost:7001/mcp که در XAiMcpControllerBase با [Route("mcp")] تعریف شده است. +
+
+ +
+

۲-۳. مکانیزم اتصال (XAiMcpServerProvider)

+

کلاس XAiMcpServerProvider وظیفه‌ی برقراری اتصال و مدیریت طول‌عمر McpClient را بر عهده دارد. فرآیند اتصال به شرح زیر است:

+ +
    +
  1. دریافت لیست سرورهای فعال: از جدول AiMcpServers، سرورهایی که Enabled == true هستند خوانده می‌شوند.
  2. +
  3. ساخت Client Transport: با استفاده از HttpClientTransport و تنظیم Endpoint و Headers.
  4. +
  5. Ping و دریافت تولزها: با PingAsync و ListToolsAsync.
  6. +
  7. ذخیره در کش: نتایج در دیکشنری‌های clients، tools و mcpServers ذخیره می‌شوند.
  8. +
+ +
Providers/XAiMcpServerProvider.cs - CreateClientAsync
+
private static async Task<McpClient> CreateClientAsync( + XAiMcpServerDto s, + CancellationToken cancellationToken) +{ + // + IClientTransport transport = new HttpClientTransport(new HttpClientTransportOptions + { + Endpoint = new Uri(s.Endpoint!), + AdditionalHeaders = ParseJsonDict(s.Headers), + TransportMode = HttpTransportMode.AutoDetect + }); + + // + return await McpClient + .CreateAsync( + transport, + cancellationToken: cancellationToken + ); +}
+ +
Providers/XAiMcpServerProvider.cs - ConnectAndValidateAsync
+
private async Task ConnectAndValidateAsync( + XAiMcpServerDto descriptor, + CancellationToken cancellationToken) +{ + try + { + using var cts = CancellationTokenSource + .CreateLinkedTokenSource(cancellationToken); + cts.CancelAfter(TimeSpan.FromSeconds(descriptor.TimeoutSeconds)); + + // + var client = await CreateClientAsync(descriptor, cts.Token); + await client.PingAsync(cancellationToken: cts.Token); + var serverTools = await client + .ListToolsAsync(cancellationToken: cts.Token); + + // + clients[descriptor.Id] = client; + tools[descriptor.Id] = serverTools; + mcpServers[descriptor.Id] = descriptor; + } + catch (Exception ex) + { + logger.LogWarning(ex, + "MCP '{Name}': Connection Established Failed, Ignored ...", + descriptor.Name); + } +}
+ +
+ ✓ نکته: در صورت عدم موفقیت اتصال، خطا فقط Log شده و سایر سرورها تحت تأثیر قرار نمی‌گیرند (Fail-Safe). +
+
+ +
+

۲-۴. دریافت تولزهای در دسترس

+

متد GetAvailableToolsAsync بر اساس Scope کاربر، لیست تولزهای مجاز را برمی‌گرداند:

+ +
Providers/XAiMcpServerProvider.cs - GetAvailableToolsAsync
+
public async Task<IList<McpClientTool>> GetAvailableToolsAsync( + bool forceOwner = false, + XUserClaimsInfoDto userInfo = null, + CancellationToken cancellationToken = default) +{ + // ... + if (!userInfo.IsAdmin()) + { + forceOwner = true; + } + + // + var selectedServers = mcpServers + .Where(s => + s.Value.OwnerId == userInfo.UserId || + s.Value.Scope == XAiMcpServerUsageScope.All + ) + .Select(s => s.Key); + + // + var result = tools + .Where(c => selectedServers.Contains(c.Key)) + .SelectMany(c => c.Value); + + return [.. result]; +}
+
+ +
+

۲-۵. استفاده از تولزها در XAiService

+

در سرویس XAIServiceBase، ویژگی Options از نوع ChatOptions وجود دارد که می‌توان تولزهای MCP را به آن افزود:

+ +
Providers/XAIServiceBase.cs (الگوی استفاده)
+
// داخل یکی از متدهای XAIServiceBase +var tools = await mcpServerProvider.GetAvailableToolsAsync( + userInfo: userInfo, + cancellationToken: cancellationToken +); +if (tools.HasChild()) +{ + Options.Tools = [.. tools]; +} + +// +using var client = Descriptor.GetClient(); +var response = await client.GetResponseAsync( + options: Options, + messages: history, + cancellationToken: cancellationToken +);
+
+ +
+

۲-۶. مدیریت چرخه‌ی حیات سرور

+

سرویس XAiMcpServerProvider متدهایی برای مدیریت پویا ارائه می‌دهد:

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
متدوظیفهتأثیر بر کش
AddMcpServerافزودن سرور جدیداتصال و افزودن به کش
UpdateMcpServerبروزرسانی تنظیماتحذف و اتصال مجدد
RemoveMcpServerحذف نرم سرورحذف از کش
EnableMcpServerفعال‌سازیاتصال و افزودن
RefreshAsyncبازسازی کامل کشDispose همه و اتصال مجدد
+
+ +
+

۲-۷. کنترل دسترسی (Scope)

+

هر سرور MCP دارای یک فیلد Scope است که تعیین می‌کند چه کاربرانی می‌توانند از تولزهای آن استفاده کنند:

+ +
+
+

Scope = Owner

+
    +
  • فقط صاحب سرور به تولزها دسترسی دارد
  • +
  • پیش‌فرض برای کاربران عادی
  • +
  • مناسب اطلاعات حساس
  • +
+
+ + +
+
+ +
+

۲-۸. چک‌لیست اتصال موفق

+
    +
  • سرور MCP در حال اجرا روی Endpoint مشخص باشد (مثلاً https://localhost:7001/mcp).
  • +
  • گواهی SSL در محیط توسعه پذیرفته شده باشد (در Startup.cs تنظیم شده است).
  • +
  • فیلد Endpoint دقیقاً به مسیر /mcp اشاره کند.
  • +
  • در صورت نیاز به احراز هویت، Headers به فرمت JSON معتبر تنظیم شود.
  • +
  • مقدار TimeoutSeconds حداقل ۳۰ ثانیه باشد.
  • +
  • سرور در وضعیت Enabled = true قرار داشته باشد.
  • +
  • Scope به‌درستی تنظیم شده باشد (Owner برای خصوصی، All برای اشتراکی).
  • +
+
+ +
+ ⚠ هشدار امنیتی: هرگز توکن‌های حساس را در فیلد Headers به‌صورت plain-text ذخیره نکنید. از EnvironmentVariables یا سیستم مدیریت Secrets استفاده نمایید. +
+ +
+
+ + +
+
+
۳
+
+

جمع‌بندی و نقشه‌ی راه

+
Summary & Roadmap
+
+
+
+ +

فرآیند کلی از تعریف تولز تا استفاده در xAiApi شامل مراحل زیر است:

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
مرحلهمسئولفایل/ماژولخروجی
۱. تعریف تولزتوسعه‌دهندهxAiMcpServer/Tools/متد با [McpServerTool]
۲. ثبت در DIتوسعه‌دهندهStartup.csثبت خودکار تولز
۳. اجرای سرورDevOpsProgram.csسرور روی Port فعال
۴. ثبت سرور در xAiApiکاربر/ادمینMcpServerControllerرکورد در جدول
۵. اتصال خودکارXAiMcpServerProviderProviders/کش تولزها
۶. استفاده در ChatXAIServiceBaseProviders/XAIServiceBase.csافزودن به ChatOptions
+ +
+

🎯 نتیجه نهایی

+

با پیروی از ساختار موجود، افزودن یک تولز جدید در سمت MCP Server تنها نیازمند یک متد با اتریبیوت [McpServerTool] است و اتصال آن به xAiApi به‌صورت خودکار از طریق XAiMcpServerProvider مدیریت می‌شود.

+
+ 💎 نکته کلیدی:
+ معماری موجود به‌گونه‌ای طراحی شده که توسعه‌ی تولزهای جدید بدون نیاز به تغییر در xAiApi انجام شود؛ کافی است سرور MCP مجدداً اجرا و در صورت نیاز از طریق RefreshAsync بازخوانی شود. +
+
+ +
+
+ +
+ این مستند فنی برای استفاده‌ی تیم توسعه‌ی xSaherelmWorkspace تهیه شده است. آخرین بروزرسانی بر اساس ساختار کد فعلی پروژه انجام شده است. +
+ +
+ +
+ + +
تاریخ تهیه: آبان ۱۴۰۵  |  نسخه: ۱.۰  |  طبقه‌بندی: فنی
+
+ +
+ + + \ No newline at end of file diff --git a/Documents/Docs/Developer/MCP Server HttpTransport 9.html b/Documents/Docs/Developer/MCP Server HttpTransport 9.html new file mode 100644 index 0000000..e0d3224 --- /dev/null +++ b/Documents/Docs/Developer/MCP Server HttpTransport 9.html @@ -0,0 +1,1246 @@ + + + + + +راهنمای گام‌به‌گام رویکرد Custom Handler در MCP Server + + + + +
+ +
+
+
+ +
+
+
شماره مستند: TECH-1405-003
+
نسخه: ۱.۰
+
تاریخ تهیه: آبان ۱۴۰۵
+
طبقه‌بندی: فنی
+
+
+ +
+ STEP-BY-STEP GUIDE +

رویکرد Custom Handler در MCP Server

+

راهنمای گام‌به‌گام ایجاد تولز با XAiMcpHandler

+
+
+ +
+ +
+ مخاطب این مستند:
+ این راهنما برای توسعه‌دهندگانی تهیه شده که قصد دارند بدون استفاده از اتریبیوت‌های SDK، یک تولز (Tool) جدید را از طریق مکانیزم داخلی XAiMcpHandler تعریف و به MCP Server اضافه کنند. تمامی گام‌ها بر اساس ساختار فعلی پروژه xSaherelmWorkspace است. +
+ + +
+
+
۱
+
+

شناخت اجزای رویکرد Custom Handler

+
Understanding the Custom Handler Components
+
+
+
+ +

پیش از شروع پیاده‌سازی، باید بدانید که چهار جزء اصلی در این رویکرد نقش دارند:

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
جزءنوعمسیرنقش
IXAiMcpHandlerInterfacexAiService/Interfaces/IXAiMcpHandler.csقرارداد پردازش JSON-RPC
XAiMcpHandlerClassxAiService/Services/XAiMcpHandler.csپیاده‌سازی و نگهداری دیکشنری تولزها
XAiMcpToolDescriptorModelxAiModels/Models/XAiMcpToolDescriptor.csتوصیف‌گر هر تولز
XAiMcpControllerBaseControllerxAiService/Controllers/XAiMcpControllerBase.csEndpoint دریافت درخواست
+ +

جریان کلی کار به شکل زیر است:

+ +
+
کلاینت
(POST /mcp)
+ ← +
McpController
(Endpoint)
+ ← +
XAiMcpHandler
.ProcessAsync
+ ← +
tools/call
Execute()
+
+ +
+ 💡 نکته: دیکشنری tools در XAiMcpHandler یک عضو Private از نوع Dictionary<string, XAiMcpToolDescriptor> است که در سازنده‌ی کلاس و از طریق متد RegisterTools() پر می‌شود. +
+ +
+
+ + +
+
+
۲
+
+

گام به گام پیاده‌سازی یک تولز جدید

+
Step-by-Step Tool Implementation
+
+
+
+ + +
+ گام ۱ +
تعیین شناسه و اطلاعات پایه‌ی تولز
+ +

ابتدا یک نام یکتا و توضیح شفاف برای تولز در نظر بگیرید. نام باید با الگوی Snake_Case و ترجیحاً انگلیسی باشد؛ زیرا LLM بر اساس همین نام، تولز را فراخوانی می‌کند.

+ +
// مشخصات پیشنهادی +Name = "calculate_bmi" +Description = "Calculates Body Mass Index given weight (kg) and height (m)."
+ +
+ ⚠ توجه: نام‌های تکراری باعث بازنویسی تولز قبلی در دیکشنری می‌شوند و بدون هیچ خطایی، تولز قدیمی حذف خواهد شد. +
+
+ + +
+ گام ۲ +
ساخت InputSchema به فرمت JSON Schema
+ +

فیلد InputSchema از نوع JObject است و باید یک JSON Schema معتبر باشد. ساختار استاندارد شامل type، properties و required است:

+ +
Schema نمونه
+
new JObject +{ + ["type"] = "object", + ["properties"] = new JObject + { + ["weight"] = new JObject + { + ["type"] = "number", + ["description"] = "Weight in kilograms" + }, + ["height"] = new JObject + { + ["type"] = "number", + ["description"] = "Height in meters" + } + }, + ["required"] = new JArray("weight", "height") +}
+ + + + + + + + + + + + + + + + + + + + + + + + + + +
کلیدتوضیحالزامی
typeهمیشه "object"✓
propertiesتعریف هر پارامتر با نوع و توضیح✓
requiredآرایه‌ای از نام پارامترهای الزامی✓
+
+ + +
+ گام ۳ +
پیاده‌سازی تابع Execute
+ +

تابع Execute یک Func<JObject, CancellationToken, Task<string>> است. ورودی اول (args) شامل آرگومان‌های ارسال‌شده از سوی کلاینت است و خروجی آن همیشه یک string خواهد بود که به‌صورت text در پاسخ JSON-RPC بازگردانده می‌شود.

+ +
Execute Function
+
Execute = async (args, ct) => +{ + // 1. استخراج و اعتبارسنجی ورودی‌ها + var weight = args?["weight"]?.Value<double>() ?? 0; + var height = args?["height"]?.Value<double>() ?? 0; + + if (weight <= 0 || height <= 0) + { + return "Error: weight and height must be positive numbers."; + } + + // 2. منطق اصلی تولز + var bmi = weight / (height * height); + + // 3. ساخت خروجی متنی + var category = bmi < 18.5 ? "Underweight" + : bmi < 25 ? "Normal" + : bmi < 30 ? "Overweight" + : "Obese"; + + return $"BMI = {bmi:F2} ({category})"; +}
+ +
+ 💡 نکته: در پیاده‌سازی فعلی HandleToolCallAsync، خروجی همیشه به‌صورت content: [{ type: "text", text: result }] بازگردانده می‌شود؛ لذا Execute فقط می‌تواند یک رشته تولید کند. برای خروجی‌های ساختاریافته‌تر (تصویر، فایل و ...) لازم است HandleToolCallAsync سفارشی‌سازی شود. +
+
+ + +
+ گام ۴ +
ثبت تولز در متد RegisterTools()
+ +

کل فایل xAiService/Services/XAiMcpHandler.cs را باز کرده و متد RegisterTools() را ویرایش کنید. تولز جدید را به‌عنوان یک عضو جدید به دیکشنری tools اضافه کنید:

+ +
xAiService/Services/XAiMcpHandler.cs
+
private void RegisterTools() +{ + // تولز موجود + tools["search_knowledge"] = new XAiMcpToolDescriptor + { + Name = "search_knowledge", + Description = "Search in knowledge base", + InputSchema = new JObject { /* ... */ }, + Execute = async (args, ct) => $"Results for: {args?["query"]}" + }; + + // 🆕 تولز جدید: calculate_bmi + tools["calculate_bmi"] = new XAiMcpToolDescriptor + { + Name = "calculate_bmi", + Description = "Calculates Body Mass Index given weight (kg) and height (m).", + InputSchema = new JObject + { + ["type"] = "object", + ["properties"] = new JObject + { + ["weight"] = new JObject { ["type"] = "number" }, + ["height"] = new JObject { ["type"] = "number" } + }, + ["required"] = new JArray("weight", "height") + }, + Execute = async (args, ct) => + { + var weight = args?["weight"]?.Value<double>() ?? 0; + var height = args?["height"]?.Value<double>() ?? 0; + if (weight <= 0 || height <= 0) + return "Error: weight and height must be positive numbers."; + + var bmi = weight / (height * height); + return $"BMI = {bmi:F2}"; + } + }; +}
+ +
+ ✓ همین! با افزودن این بلوک، تولز جدید در اولین درخواست بعدی کلاینت (پس از اجرای مجدد سرور) در tools/list قابل مشاهده و در tools/call قابل فراخوانی خواهد بود. +
+
+ +
+
+ + +
+
+
۳
+
+

درک جریان JSON-RPC در زمان اجرا

+
Understanding the JSON-RPC Runtime Flow
+
+
+
+ +

برای اطمینان از صحت کار تولز، باید بدانید که XAiMcpHandler.ProcessAsync چگونه درخواست‌ها را پردازش می‌کند:

+ +
xAiService/Services/XAiMcpHandler.cs - ProcessAsync
+
public async Task<JObject> ProcessAsync( + JObject request, + CancellationToken cancellationToken = default) +{ + var method = request["method"]?.ToString(); + var id = request["id"]; + + return method switch + { + "initialize" => HandleInitialize(id), + "tools/list" => HandleToolsList(id), + "tools/call" => await HandleToolCallAsync(request, id, cancellationToken), + "ping" => HandlePing(id), + _ => CreateError(id, -32601, $"Method not found: {method}") + }; +}
+ +

چرخه‌ی سه‌مرحله‌ای فراخوانی تولز

+ +
    +
  1. + initialize (یک‌بار): + کلاینت لیست capabilities را دریافت می‌کند. پاسخ شامل protocolVersion، serverInfo و capabilities است. +
  2. +
  3. + tools/list (اختیاری، پس از initialize): + کلاینت لیست تمام تولزهای موجود را دریافت می‌کند. HandleToolsList روی دیکشنری tools پیمایش کرده و برای هر عضو، Name، Description و InputSchema را برمی‌گرداند. +
  4. +
  5. + tools/call (به تعداد نیاز): + کلاینت با ارسال { "name": "calculate_bmi", "arguments": {...} } تولز مورد نظر را فراخوانی می‌کند. HandleToolCallAsync تولز را از دیکشنری پیدا کرده، Execute را فراخوانی و نتیجه را در قالب content: [{ type: "text", text: "..." }] برمی‌گرداند. +
  6. +
+ +

نمونه‌ی Request/Response واقعی

+ +
tools/list → Request
+
{ + "jsonrpc": "2.0", + "id": 2, + "method": "tools/list" +}
+ +
tools/list → Response
+
{ + "jsonrpc": "2.0", + "id": 2, + "result": { + "tools": [ + { + "name": "search_knowledge", + "description": "Search in knowledge base", + "inputSchema": { /* ... */ } + }, + { + "name": "calculate_bmi", + "description": "Calculates Body Mass Index...", + "inputSchema": { /* ... */ } + } + ] + } +}
+ +
tools/call → Request
+
{ + "jsonrpc": "2.0", + "id": 3, + "method": "tools/call", + "params": { + "name": "calculate_bmi", + "arguments": { + "weight": 75, + "height": 1.78 + } + } +}
+ +
tools/call → Response
+
{ + "jsonrpc": "2.0", + "id": 3, + "result": { + "content": [ + { + "type": "text", + "text": "BMI = 23.67" + } + ] + } +}
+ +
+
+ + +
+
+
۴
+
+

الگوهای پیشرفته و بهترین شیوه‌ها

+
Advanced Patterns & Best Practices
+
+
+
+ +
+

۴-۱. تزریق وابستگی به تولزها

+

اگر تولز شما نیاز به سرویس دیگری دارد (مثلاً دیتابیس یا HttpClient)، می‌توانید آن را به‌صورت Closure داخل RegisterTools تزریق کنید. کافی است سازنده‌ی XAiMcpHandler را تغییر دهید:

+ +
xAiService/Services/XAiMcpHandler.cs
+
public class XAiMcpHandler : IXAiMcpHandler +{ + private readonly Dictionary<string, XAiMcpToolDescriptor> tools = new(); + private readonly IMyService myService; + + public XAiMcpHandler(IMyService myService) + { + this.myService = myService; + RegisterTools(); + } + + private void RegisterTools() + { + tools["my_tool"] = new XAiMcpToolDescriptor + { + Name = "my_tool", + Description = "...", + InputSchema = new JObject { /* ... */ }, + Execute = async (args, ct) => + { + // استفاده از سرویس تزریق‌شده + var result = await myService.DoSomethingAsync( + args?["input"]?.ToString(), ct); + return result; + } + }; + } +}
+ +

و ثبت DI را در xAiService/Extensions/DIExtensions.cs بروزرسانی کنید تا سازنده‌ی جدید را بشناسد:

+ +
xAiService/Extensions/DIExtensions.cs
+
public static void AddXAiMcpHandler(this IServiceCollection source) +{ + source.AddScoped<IXAiMcpHandler, XAiMcpHandler>(); +}
+ +
+ 💡 نکته: XAiMcpHandler در حالت Scoped ثبت شده؛ یعنی برای هر درخواست HTTP یک نمونه‌ی جدید ساخته می‌شود و RegisterTools از نو اجرا می‌شود. این رفتار برای تولزهای Stateless مناسب است، اما اگر تعداد تولزها زیاد شود، می‌توانید آن را به Singleton تغییر دهید (به شرط رعایت Thread-Safety). +
+
+ +
+

۴-۲. مدیریت خطا

+

در HandleToolCallAsync، اگر تولز پیدا نشود یا اجرا با خطا مواجه شود، پاسخ JSON-RPC مناسب تولید می‌شود. اما خطاهای داخلی Execute خودتان را باید مدیریت کنید:

+ +
Execute = async (args, ct) => +{ + try + { + // منطق تولز + } + catch (Exception ex) + { + // خطا را به‌صورت متن برگردانید تا کلاینت متوجه شود + return $"Tool execution failed: {ex.Message}"; + } +}
+ +
+ ⚠ هشدار: اگر Exception پرتاب شود و مدیریت نشود، HandleToolCallAsync آن را به‌صورت یک خطای 500 به کلاینت برمی‌گرداند. بهتر است در Execute همه‌ی خطاها را به پیام متنی تبدیل کنید. +
+
+ +
+

۴-۳. اعتبارسنجی ورودی‌ها

+

SDK به‌صورت خودکار ورودی‌ها را طبق InputSchema اعتبارسنجی نمی‌کند. بنابراین مسئولیت اعتبارسنجی بر عهده‌ی Execute است:

+ +
Execute = async (args, ct) => +{ + // اعتبارسنجی نوع و محدوده + var query = args?["query"]?.ToString(); + if (string.IsNullOrWhiteSpace(query)) + return "Error: 'query' is required and cannot be empty."; + + if (query.Length > 500) + return "Error: 'query' must be at most 500 characters."; + + // ادامه‌ی منطق +}
+
+ +
+

۴-۴. استفاده از CancellationToken

+

پارامتر ct از سمت کلاینت/سرور ارسال می‌شود و با قطع ارتباط، لغو می‌گردد. همیشه آن را به عملیات طولانی‌مدت پاس دهید:

+ +
Execute = async (args, ct) => +{ + // پاس دادن ct به عملیات async + var data = await httpClient.GetStringAsync(url, ct); + return data; +}
+
+ +
+

۴-۵. ثبت پویا (Dynamic Registration)

+

اگر تعداد تولزها زیاد است یا می‌خواهید از خارج از کلاس ثبت شوند، می‌توانید متد RegisterTools را عمومی کرده یا یک متد RegisterTool(XAiMcpToolDescriptor) اضافه کنید:

+ +
public void RegisterTool(XAiMcpToolDescriptor descriptor) +{ + if (descriptor == null || string.IsNullOrWhiteSpace(descriptor.Name)) + throw new ArgumentException("Invalid tool descriptor."); + + tools[descriptor.Name] = descriptor; +}
+ +

سپس در Startup.cs یا هر جای دیگری که به IXAiMcpHandler دسترسی دارید، تولزها را ثبت کنید.

+
+ +
+
+ + +
+
+
۵
+
+

محدودیت‌های فعلی و راهکارها

+
Current Limitations & Workarounds
+
+
+
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
محدودیتتأثیرراهکار
خروجی فقط text استنمی‌توان تصویر یا فایل برگرداندسفارشی‌سازی HandleToolCallAsync برای پشتیبانی از انواع دیگر
ثبت Statically در Constructorامکان تعریف تولز بر اساس کانفیگ وجود نداردتزریق IConfiguration و خواندن تولزها از کانفیگ
بدون اعتبارسنجی خودکار InputSchemaخطاهای ورودی به LLM برمی‌گردداعتبارسنجی دستی در Execute یا افزودن Fluent Validation
XAiMcpHandler به‌صورت Scopedهر درخواست، ثبت تولز را دوباره انجام می‌دهدتغییر به Singleton با رعایت Thread-Safety (استفاده از ConcurrentDictionary)
عدم پشتیبانی از Streamingخروجی یکجا برگردانده می‌شوددر صورت نیاز، HandleToolCallAsync را برای SSE تغییر دهید
+ +
+
+ + +
+
+
۶
+
+

چک‌لیست پیاده‌سازی و تست

+
Implementation & Testing Checklist
+
+
+
+ +
+ ✓ قبل از اجرا +
موارد ضروری
+
    +
  • نام تولز یکتاست و با نام‌های قبلی تداخل ندارد.
  • +
  • Description واضح و کوتاه نوشته شده (زیر ۲۰۰ کاراکتر).
  • +
  • InputSchema شامل type، properties و required است.
  • +
  • همه‌ی پارامترهای الزامی در required ذکر شده‌اند.
  • +
  • Execute همه‌ی خطاها را با try/catch مدیریت می‌کند.
  • +
  • CancellationToken به عملیات طولانی‌مدت پاس داده می‌شود.
  • +
  • ورودی‌ها با args?["..."]?.Value<T>() استخراج می‌شوند.
  • +
+
+ +
+ 🧪 تست +
سناریوهای تست
+
    +
  • تست initialize: ارسال {"method":"initialize","id":1} و دریافت protocolVersion.
  • +
  • تست tools/list: باید تولز جدید در لیست دیده شود.
  • +
  • تست tools/call با ورودی معتبر: نتیجه‌ی درست دریافت شود.
  • +
  • تست tools/call با پارامتر ناموجود: خطای مناسب برگردد.
  • +
  • تست tools/call با پارامتر نامعتبر (مثلاً weight منفی): پیام خطای واضح برگردد.
  • +
  • تست تولز ناموجود: پاسخ -32602 (Invalid params) دریافت شود.
  • +
  • تست قطع ارتباط: CancellationToken به‌درستی فعال شود.
  • +
+
+ +
تست با cURL
+
curl -X POST https://localhost:7001/mcp \ + -H "Content-Type: application/json" \ + -d '{ + "jsonrpc": "2.0", + "id": 1, + "method": "tools/call", + "params": { + "name": "calculate_bmi", + "arguments": { "weight": 75, "height": 1.78 } + } + }'
+ +
+
+ + +
+
+
۷
+
+

نمونه‌ی کامل یک تولز واقعی

+
Complete Real-World Example
+
+
+
+ +

در این بخش یک تولز کامل با نام get_current_time که زمان فعلی یک منطقه‌ی زمانی را برمی‌گرداند، ارائه می‌شود:

+ +
xAiService/Services/XAiMcpHandler.cs
+
// اضافه کردن using در بالای فایل +using System; + +// داخل متد RegisterTools(): +tools["get_current_time"] = new XAiMcpToolDescriptor +{ + Name = "get_current_time", + Description = "Returns the current date and time for a given timezone offset (in hours, e.g. 3.5 for Iran).", + InputSchema = new JObject + { + ["type"] = "object", + ["properties"] = new JObject + { + ["offsetHours"] = new JObject + { + ["type"] = "number", + ["description"] = "Timezone offset in hours from UTC (e.g. 3.5 for Iran)." + } + }, + ["required"] = new JArray("offsetHours") + }, + Execute = async (args, ct) => + { + var offset = args?["offsetHours"]?.Value<double>() ?? 0; + + // اعتبارسنجی محدوده + if (offset < -12 || offset > 14) + return "Error: offsetHours must be between -12 and 14."; + + // محاسبه‌ی زمان محلی + var utcNow = DateTime.UtcNow; + var local = utcNow.AddHours(offset); + + return $"Current time (UTC{offset:+0.0;-0.0}): {local:yyyy-MM-dd HH:mm:ss}"; + } +};
+ +
+ ✓ تست سریع: کافی است سرور را ری‌استارت کرده و با curl درخواست tools/call با نام get_current_time و {"offsetHours": 3.5} ارسال کنید. +
+ +
+
+ + +
+
+
۸
+
+

مقایسه‌ی نهایی: Custom Handler در برابر Attribute-Based

+
Final Comparison
+
+
+
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
ویژگیCustom HandlerAttribute-Based
محل تعریف تولزدر متد RegisterToolsدر کلاس‌های دارای [McpServerToolType]
نحوه‌ی کشفدستی در دیکشنری toolsخودکار با WithToolsFromAssembly()
کنترل روی Schemaکامل (JObject دستی)خودکار از امضای متد
پشتیبانی از DI در تولزبا تزریق در Constructorاز طریق پارامتر متد (در صورت پشتیبانی SDK)
پشتیبانی از خروجی غنیمحدود (فقط text)وابسته به SDK (معمولاً کامل)
کاربرد مناسبتولزهای ساده و سریعتولزهای پیچیده با خروجی متنوع
+ +
+

🎯 جمع‌بندی

+

رویکرد Custom Handler برای سناریوهایی مناسب است که می‌خواهید کنترل کامل روی تعریف تولز، Schema و منطق اجرا داشته باشید و تعداد تولزها محدود است.

+

برای پروژه‌های بزرگ‌تر یا زمانی که به خروجی غنی (تصویر، فایل و ...) نیاز دارید، رویکرد Attribute-Based توصیه می‌شود.

+
+ 💎 نکته نهایی:
+ در پروژه‌ی فعلی هر دو رویکرد ثبت شده‌اند؛ برای شروع سریع با Custom Handler، تنها کافی است یک بلوک جدید به RegisterTools() اضافه کنید و سپس سرور را ری‌استارت نمایید. +
+
+ +
+
+ +
+ این مستند فنی برای استفاده‌ی تیم توسعه‌ی xSaherelmWorkspace تهیه شده است. آخرین بروزرسانی بر اساس ساختار کد فعلی پروژه انجام شده است. +
+ +
+ +
+ + +
تاریخ تهیه: آبان ۱۴۰۵  |  نسخه: ۱.۰  |  طبقه‌بندی: فنی
+
+ +
+ + + \ No newline at end of file diff --git a/Documents/GeneratedContext/xDashboard-xAiApi-20261104_113310.txt b/Documents/GeneratedContext/xDashboard-xAiApi-20261104_113310.txt deleted file mode 100644 index 3f512b7..0000000 --- a/Documents/GeneratedContext/xDashboard-xAiApi-20261104_113310.txt +++ /dev/null @@ -1,38276 +0,0 @@ - -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\xAiApi\Program.cs - -using System.Text; -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) - .ConfigureWebHostDefaults(webBuilder => - { - webBuilder.UseStartup(); - }); - - // - return result; - } - } -} - -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\xAiApi\Startup.cs - -using System; -using System.IO; -using xAiApi.DI; -using System.Linq; -using xAiModels.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 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 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 - { - 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(); - - // - // 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( - lifeTime: lifeTime, - repositoryType: repositoryType - ); - - // - // Register Tag Service ... - services.AddXTagService( - lifeTime: lifeTime, - repositoryType: repositoryType - ); - - // - // Register File Service ... - services.AddXFileService( - lifeTime: lifeTime, - repositoryType: repositoryType - ); - - // - // Register AiApi Data Service ... - services.AddXAiDataService( - lifeTime: lifeTime, - repositoryType: repositoryType - ); - - // - // Register XAiApi Configuration ... - services.AddXAiApiConfiguration(Configuration); - - // - // 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(); - - // - // 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(); - } - - // - // 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(); - - // - // 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\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\xAiApi\Configurations\XAiApiConfiguration.cs - -using xAiApi.Models; -using xAiModels.Models; - -namespace xAiApi.Configurations -{ - public class XAiApiConfiguration - { - /// - /// Allowed Models to Use ... - /// - public XAiModelDescriptor[] Models { get; set; } = []; - - /// - /// Allowed Prompts to Use ... - /// - public XAiPromptDescriptor[] Prompts { get; set; } = []; - - /// - /// OCR Configuration ... - /// - public XAiOCRDescriptor OCR { get; set; } = new(); - - /// - /// Transcript Configuration ... - /// - public XAiTransciptDescriptor Transcript { get; set; } = new(); - - /// - /// PDF To Image Configuration ... - /// - public XPDFToImageDescriptor PDFToImageDescriptor { get; set; } = new(); - - /// - /// Proxy Configuration ... - /// - /// - public XAiModelProxyConfiguration ProxyConfiguration { get; set; } = new(); - - /// - /// Text Chunker Configuration ... - /// - public XTextChunkerDescriptor TextChunker { get; set; } = new(); - - /// - /// RAG Configuration ... - /// - public XAiDocumentRAGDescriptor RAGDescriptor {get; set;} = new(); - } -} - -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\xAiApi\Constants\ConfigurationNodeNames.cs - -namespace xAiApi.Constants -{ - public partial struct ConfigurationNodeNames - { - public const string AI_API_NODE = "AiApiConfiguration"; - } -} - -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\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 = "Gemma"; - public const string XAiEmbeddingModelName = "Embed"; - public const string XAiDefaultVisionModelName = "Qwen"; - public const string XAiDefaultThinkingModelName = "Qwen"; - public const string XAiEmbeddingPromptName = "Embedding"; - } -} - -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\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 logger, - XAppConfiguration appConfiguration, - IXIdentityProvider identityProvider, - XValidationProvider validationProvider - ) : base( - logger, - appConfiguration, - identityProvider, - validationProvider - ) - { } - #endregion - } -} - -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\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 -{ - /// - /// Chat With Documents (In-Memory RAG) Controller ... - /// Flow: Ingest Files -> SessionId -> Ask / AskStream -> Delete Session - /// - [Authorize] - public class ChatWithDocumentsController : XBaseIdentityApiV1Controller - { - /// - /// Default AI Service ... - /// - private readonly IXAiService aiService; - - /// - /// Text Chunker Service ... - /// - private readonly IXTextChunker textChunker; - - /// - /// In Memory Vector Store ... - /// - private readonly IXInMemoryVectorStore vectorStore; - - /// - /// XAiApi Configuration ... - /// - private readonly XAiApiConfiguration apiConfiguration; - - /// - /// Embedding Service ... - /// - private readonly IXAiEmbeddingService embeddingService; - - /// - /// File Context Extractor Service ... - /// - private readonly IXFileContentExtractor fileContentExtractor; - - public ChatWithDocumentsController( - IXAiService aiService, - IXTextChunker textChunker, - IXInMemoryVectorStore vectorStore, - XAppConfiguration appConfiguration, - IXIdentityProvider identityProvider, - XAiApiConfiguration apiConfiguration, - IXAiEmbeddingService embeddingService, - XValidationProvider validationProvider, - ILogger 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 ... - /// - /// Ingest Files into a (new or existing) In-Memory Session: - /// Extract -> Chunk -> Embed -> Store ... - /// - /// - /// Optional: Add to an Existing Session - /// Optional: Session TTL in Minutes (only for new Session) - /// - /// - [HttpPost("Ingest")] - [Consumes("multipart/form-data")] - public async Task> 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(); - 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 ... - /// - /// Ask a Question over Ingested Documents ... - /// - /// - /// - /// - [HttpPost("Ask")] - public async Task> 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; - } - } - - /// - /// Ask a Question over Ingested Documents and Stream Response (SSE) ... - /// First Event Carries Sources, Next Events Carry Text Deltas, Last Event has IsFinal = true ... - /// - /// - /// - /// - [HttpPost("AskStream")] - public async Task AskStream( - [FromBody] 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 ... - /// - /// Retrieve Session Info (without Embeddings) ... - /// - /// - /// - [HttpGet("Session/{id:guid}")] - public async Task> GetSession(Guid id) - { - // - try - { - // - var userInfo = await GetUserInfo(); - if (!vectorStore.TryGet(id, out var session, userInfo.UserId)) - { - XException.NotFound.Throw(); - } - - // - IList 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; - } - } - - /// - /// Remove a Session and Free Memory ... - /// - /// - /// - [HttpDelete("Session/{id:guid}")] - public async Task> 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 ... - /// - /// Extract Plain Text of a File (Text or Audio Transcript) ... - /// - private async Task ExtractText( - IFormFile file, - string mimeType, - CancellationToken cancellationToken - ) - { - // - try - { - // - using var stream = file.OpenReadStream(); - var extraction = await fileContentExtractor.ExtractRichAsync( - fileStream: stream, - mimeType: mimeType, - fileName: file.FileName, - cancellationToken: cancellationToken - ); - - // - var result = extraction?.Text; - if (string.IsNullOrWhiteSpace(result)) - { - result = extraction?.AudioTranscript; - } - - // - return result; - } - catch (OperationCanceledException) - { - throw; - } - catch (Exception ex) - { - Logger.LogWarning(ex, "ChatWithDocuments: Extraction Failed for {FileName}", file.FileName); - return null; - } - } - - /// - /// Embed Chunks in Batches and Build Vectors ... - /// - private async Task> EmbedChunks( - IList chunks, - string fileName, - string mimeType, - CancellationToken cancellationToken - ) - { - // - var result = new List(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 - { - [apiConfiguration.RAGDescriptor.MetadataFileName] = fileName, - [apiConfiguration.RAGDescriptor.MetadataMimeType] = mimeType, - [apiConfiguration.RAGDescriptor.MetadataChunkIndex] = chunk.Index.ToString() - } - }); - } - } - - // - return result; - } - - /// - /// Embed Prompt and Search Session ... - /// - private async Task> 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 ?? []; - } - - /// - /// Map Search Results to Public Sources ... - /// - private IList ToSources( - IEnumerable 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; - } - - /// - /// Write a SSE Event ... - /// - private Task WriteChunk( - XAiDocumentAnswerChunk chunk, - CancellationToken cancellationToken - ) - { - // - return Response.WriteSseEventAsync( - data: chunk, - cancellationToken: cancellationToken - ); - } - #endregion - } -} - -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\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 -{ - /// - /// Knowledge (Persistent RAG over XAiVector Table) Controller ... - /// Flow: Ingest Files -> Ask / AskStream (Retrieve from DB -> Generate) -> Documents / Delete - /// - [Authorize] - public class KnowledgeController : XBaseIdentityApiV1Controller - { - /// - /// Persistent RAG Service ... - /// - private readonly IXAiRAGService ragService; - - public KnowledgeController( - IXAiRAGService ragService, - XAppConfiguration appConfiguration, - IXIdentityProvider identityProvider, - ILogger logger, - XValidationProvider validationProvider - ) : base(logger, appConfiguration, identityProvider, validationProvider) - { - this.ragService = ragService; - } - - // - #region Ingest ... - /// - /// Ingest Files into a Knowledge Scope: - /// Extract -> Chunk -> Embed -> Store in XAiVector Table ... - /// - /// - /// Target Scope: User (default) / Project / Conversation / Global (Admin) - /// ProjectId or ConversationId (Required for Project / Conversation) - /// Optional Knowledge Type / Domain - /// Replace Previously Stored Vectors of Same File (default true) - /// - /// - [HttpPost("Ingest")] - [Consumes("multipart/form-data")] - [Authorize(Policy = XPolicies.EnabledAdmin)] - public async Task> Ingest( - [FromForm] IFormFileCollection files, - [FromForm] XAiKnowledgeScope? scope = XAiKnowledgeScope.Global, - [FromForm] Guid? scopeId = null, - [FromForm] string knowledgeType = null, - [FromForm] bool replaceExisting = true, - CancellationToken cancellationToken = default - ) - { - // - try - { - // - // Validate ... - if (!files.HasChild()) - { - XException.InvalidArgs.Throw(); - } - - // - var userInfo = await GetUserInfo(); - var connectionId = GetConnectionId(); - - // - var result = await ragService.IngestAsync( - files: files, - userInfo: userInfo, - connectionId: connectionId, - replaceExisting: replaceExisting, - cancellationToken: cancellationToken, - scope: BuildScope(scope, scopeId, knowledgeType) - ); - - // - return Ok(result); - } - catch (Exception ex) - { - // - var result = GetExceptionActionResult(ex); - return result; - } - } - #endregion - - // - #region Documents ... - /// - /// List Ingested Documents of a Knowledge Scope ... - /// - /// User (default) / Project / Conversation / Global - /// ProjectId or ConversationId (Required for Project / Conversation) - /// Optional Knowledge Type Filter - /// - /// - [HttpGet("Documents")] - [Authorize(Policy = XPolicies.EnabledAdmin)] - public async Task>> 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; - } - } - - /// - /// Remove All Vectors of a Document in a Knowledge Scope ... - /// - /// - /// User (default) / Project / Conversation / Global (Admin) - /// ProjectId or ConversationId (Required for Project / Conversation) - /// - /// Count of Removed Vectors - [HttpDelete("Documents")] - [Authorize(Policy = XPolicies.EnabledAdmin)] - public async Task> 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 ... - /// - /// Build Scope Descriptor from Request Params ... - /// - 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; - } - - /// - /// Write a SSE Event ... - /// - private Task WriteChunk( - XAiDocumentAnswerChunk chunk, - CancellationToken cancellationToken - ) - { - // - return Response.WriteSseEventAsync( - data: chunk, - cancellationToken: cancellationToken - ); - } - #endregion - } -} - - -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\xAiApi\Controllers\McpServerController.cs - -using System; -using System.Linq; -using xModels.Dtos; -using xModels.Base; -using xIdentityHelper; -using System.Threading; -using xCommons.Providers; -using xAiModels.Models.Dtos; -using xAiModels.Controllers; -using System.Threading.Tasks; -using xCommons.Configurations; -using Microsoft.AspNetCore.Mvc; -using xAiModels.Interfaces.Dtos; -using xAiModels.Models.Entities; -using System.Collections.Generic; -using Microsoft.Extensions.Logging; -using Microsoft.AspNetCore.Authorization; -using Microsoft.EntityFrameworkCore.Query; - -namespace xAiApi.Controllers -{ - [Authorize] - public class McpServerController : XAiMcpServerControllerBase - { - public McpServerController( - ILogger logger, - XAppConfiguration appConfiguration, - XValidationProvider validationProvider, - IXAiMcpServerRepositoryService repositoryService, - Func, IOrderedQueryable> defaultOrderBuilder = null, - Func, IIncludableQueryable> defaultIncludeBuilder = null - ) : base( - logger, - appConfiguration, - validationProvider, - repositoryService, - defaultOrderBuilder, - defaultIncludeBuilder - ) - { } - - // - #region Actions ... - // - #region Add ... - /// - /// Add Specified Item ... - /// - /// - /// - /// - /// - /// - [HttpPost] - [Authorize(Policy = XPolicies.EnabledAdmin)] - public override async Task> Add( - [FromBody] XAiMcpServerDto item, - CancellationToken cancellationToken = default - ) - { - // - var result = await base.Add( - item: item, - cancellationToken: cancellationToken - ); - - // - return result; - } - - /// - /// Add or Update Specified Item ... - /// - /// - /// - /// - /// - /// - [HttpPost("AddOrUpdate")] - [Authorize(Policy = XPolicies.EnabledAdmin)] - public override async Task> AddOrUpdate( - [FromBody] XAiMcpServerDto item, - CancellationToken cancellationToken = default - ) - { - // - var result = await base.AddOrUpdate( - item: item, - cancellationToken: cancellationToken - ); - - // - return result; - } - - /// - /// Add a Collection of Items ... - /// - /// - /// - /// - /// - /// - [HttpPost("AddMany")] - [Authorize(Policy = XPolicies.EnabledAdmin)] - public override async Task AddMany( - [FromBody] XBaseRangeRequest request, - CancellationToken cancellationToken = default - ) - { - // - var result = await base.AddMany( - request: request, - cancellationToken: cancellationToken - ); - - // - return result; - } - #endregion - - // - #region Retrieve ... - /// - /// Get Specified Item ... - /// - /// - /// - /// - /// - /// - /// - /// - [HttpGet("{id}")] - [Authorize(Policy = XPolicies.EnabledAdmin)] - public override async Task> Get( - [FromRoute] Guid id, - [FromQuery] bool ignoreSoftDeleteds = true, - [FromQuery] bool useDefaultIncludes = false, - CancellationToken cancellationToken = default - ) - { - // - var result = await base.Get( - id: id, - cancellationToken: cancellationToken, - ignoreSoftDeleteds: ignoreSoftDeleteds, - useDefaultIncludes: useDefaultIncludes - ); - - // - return result; - } - - /// - /// Get All Items ... - /// - /// - /// - /// - /// - /// - /// - /// - [HttpGet] - [Authorize(Policy = XPolicies.EnabledAdmin)] - public override async Task>> GetAll( - [FromQuery] bool ignoreSoftDeleteds = true, - [FromQuery] bool useDefaultOrders = false, - [FromQuery] bool useDefaultIncludes = false, - CancellationToken cancellationToken = default - ) - { - // - var result = await base.GetAll( - useDefaultOrders: useDefaultOrders, - cancellationToken: cancellationToken, - ignoreSoftDeleteds: ignoreSoftDeleteds, - useDefaultIncludes: useDefaultIncludes - ); - - // - return result; - } - - /// - /// Find Specified Item ... - /// - /// - /// - /// - /// - /// - /// - /// - [HttpGet("FindOne/{query}")] - [Authorize(Policy = XPolicies.EnabledAdmin)] - public override async Task> FindOne( - [FromRoute] string query, - [FromQuery] bool ignoreSoftDeleteds = true, - [FromQuery] bool useDefaultIncludes = false, - CancellationToken cancellationToken = default - ) - { - // - var result = await base.FindOne( - query: query, - cancellationToken: cancellationToken, - ignoreSoftDeleteds: ignoreSoftDeleteds, - useDefaultIncludes: useDefaultIncludes - ); - - // - return result; - } - - /// - /// Find Many Items ... - /// - /// - /// - /// - /// - /// - /// - /// - /// - [HttpGet("FindMany/{query}")] - [Authorize(Policy = XPolicies.EnabledAdmin)] - public override async Task>> FindMany( - [FromRoute] string query, - [FromQuery] bool ignoreSoftDeleteds = true, - [FromQuery] bool useDefaultOrders = false, - [FromQuery] bool useDefaultIncludes = false, - CancellationToken cancellationToken = default - ) - { - // - var result = await base.FindMany( - query: query, - useDefaultOrders: useDefaultOrders, - cancellationToken: cancellationToken, - ignoreSoftDeleteds: ignoreSoftDeleteds, - useDefaultIncludes: useDefaultIncludes - ); - - // - return result; - } - - /// - /// Retrieve Items Based on Query Mechanism ... - /// - /// - /// - /// - /// - /// - /// - /// - /// - [HttpGet("Query")] - [Authorize(Policy = XPolicies.EnabledAdmin)] - public override async Task>> Query( - [FromQuery] XQuery query, - [FromQuery] bool ignoreSoftDeleteds = true, - [FromQuery] bool useDefaultOrders = false, - [FromQuery] bool useDefaultIncludes = false, - CancellationToken cancellationToken = default - ) - { - // - var result = await base.Query( - query: query, - useDefaultOrders: useDefaultOrders, - cancellationToken: cancellationToken, - ignoreSoftDeleteds: ignoreSoftDeleteds, - useDefaultIncludes: useDefaultIncludes - ); - - // - return result; - } - #endregion - - // - #region Update ... - /// - /// Update Item ... - /// - /// - /// - /// - /// - /// - /// - [HttpPut("{id}")] - [Authorize(Policy = XPolicies.EnabledAdmin)] - public override async Task> Update( - [FromRoute] Guid id, - [FromBody] XAiMcpServerDto item, - CancellationToken cancellationToken = default - ) - { - // - var result = await base.Update( - id: id, - item: item, - cancellationToken: cancellationToken - ); - - // - return result; - } - - /// - /// Update a Collection of items ... - /// - /// - /// - /// - /// - /// - [HttpPost("UpdateMany")] - [Authorize(Policy = XPolicies.EnabledAdmin)] - public override async Task> UpdateMany( - [FromBody] XBaseRangeRequest request, - CancellationToken cancellationToken = default - ) - { - // - var result = await base.UpdateMany( - request: request, - cancellationToken: cancellationToken - ); - - // - return result; - } - #endregion - - // - #region Exists ... - /// - ///Check an Item Exists or not ... - /// - /// - /// - /// - /// - /// - /// - [HttpGet("{id}/IsExists")] - [Authorize(Policy = XPolicies.EnabledAdmin)] - public override async Task> IsExists( - [FromRoute] Guid id, - [FromQuery] bool ignoreSoftDeleteds = true, - CancellationToken cancellationToken = default - ) - { - // - var result = await base.IsExists( - id: id, - cancellationToken: cancellationToken, - ignoreSoftDeleteds: ignoreSoftDeleteds - ); - - // - return result; - } - #endregion - - // - #region Remove ... - /// - /// Remove an Items ... - /// - /// - /// - /// - /// - /// - /// - [HttpDelete("{id}")] - [Authorize(Policy = XPolicies.EnabledAdmin)] - public override async Task> Remove( - [FromRoute] Guid id, - [FromQuery] bool softDelete = false, - CancellationToken cancellationToken = default - ) - { - // - var result = await base.Remove( - id: id, - softDelete: softDelete, - cancellationToken: cancellationToken - ); - - // - return result; - } - - /// - /// Remove Many Items ... - /// - /// - /// - /// - /// - /// - /// - [HttpPost("RemoveMany")] - [Authorize(Policy = XPolicies.EnabledAdmin)] - public override async Task RemoveMany( - [FromBody] XBaseRangeRequest request, - [FromQuery] bool softDelete = false, - CancellationToken cancellationToken = default - ) - { - // - var result = await base.RemoveMany( - request: request, - softDelete: softDelete, - cancellationToken: cancellationToken - ); - - // - return result; - } - #endregion - #endregion - } -} - -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\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 -{ - /// - /// Runing when application start ... - /// - [Route("")] - [AllowAnonymous] - public class StartupController : XBaseController - { - - public StartupController( - ILogger logger, - XAppConfiguration appConfiguration, - XValidationProvider validationProvider - ) : base( - logger, - appConfiguration, - validationProvider - ) - { } - - /// - /// Show Configured Welcome Message - /// - /// - [HttpGet("")] - [AllowAnonymous] - public virtual ActionResult Index() - { - // - var controllerName = GetControllerName(); - var message = $"{AppConfiguration.WelcomeMessage}"; - - // - return Ok(message); - } - - /// - /// Global Exception Handler Endpoint (Production) ... - /// Returns a Generic Error without Leaking Exception Details ... - /// - /// - [AllowAnonymous] - [Route("error")] - [ApiExplorerSettings(IgnoreApi = true)] - public virtual ActionResult Error() - { - // - var error = XException.ActionFailed.ToXError(); - return StatusCode(StatusCodes.Status500InternalServerError, error); - } - } -} - -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\xAiApi\Controllers\TestIdentity.cs - -using xCommons.Providers; -using xCommons.Configurations; -using xIdentityService.Interfaces; -using xIdentityHelper.Controllers; -using Microsoft.Extensions.Logging; - -namespace xAiApi.Controllers { - /// - /// Test all Authentication Policies ... - /// - public class TestIdentity : XTestIdentityControllerBase { - public TestIdentity ( - ILogger logger, - XAppConfiguration appConfiguration, - IXIdentityProvider identityProvider, - XValidationProvider validationProvider - ) : base ( - logger, - appConfiguration, - identityProvider, - validationProvider - ) { } - } -} - -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\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 - { - public XAiController( - ILogger logger, - IXAiService aiService, - XAppConfiguration appConfiguration, - IXIdentityProvider identityProvider, - XValidationProvider validationProvider - ) : base( - logger, - aiService, - appConfiguration, - identityProvider, - validationProvider - ) - { } - } -} - -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\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 : 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 ... - /// - /// Ask Question and Get Response ... - /// - /// - /// - /// - [HttpGet("AskText")] - [Authorize(Policy = XPolicies.EnabledUser)] - public virtual async Task> AskText( - [FromQuery] string question, - CancellationToken cancellationToken = default - ) - { - // - try - { - // - // Validate ... - ValidationProvider.NotEmpty(question); - - // - var result = await aiService.AskTextAsync( - prompt: question, - cancellationToken: cancellationToken - ); - - // - return Ok(result); - } - catch (Exception ex) - { - // - var result = GetExceptionActionResult(ex); - return result; - } - } - - /// - /// Ask Question and Get Response Stream ... - /// - /// - /// - /// - [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 enumerable = aiService.AskTextAsEnumerable( - prompt: question, - 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); - } - } - - /// - /// Ask a Question By Rag Retrive From Knowledge ... - /// - /// - /// - /// - [HttpGet("AskTextFromKnowledge")] - [Authorize(Policy = XPolicies.EnabledUser)] - public virtual async Task> 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; - } - } - - /// - /// Ask a Question By Rag Retrive From Knowledge and Stream Response ... - /// - /// - /// - /// - [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); - } - } - - /// - /// Ask Question and Get Response ... - /// - /// - /// - /// - [HttpPost("Ask")] - [Authorize(Policy = XPolicies.EnabledUser)] - public virtual async Task> 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; - } - } - - /// - /// Ask Question and Get Response Stream ... - /// - /// - /// - /// - [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); - } - } - - /// - /// Ask Question with Files and Get Response ... - /// - /// - /// - /// - [HttpPost("AskWithFiles")] - [Consumes("multipart/form-data")] - [Authorize(Policy = XPolicies.EnabledUser)] - public virtual async Task> AskWithFiles( - [FromForm] XAiResponseRequest request, - [FromForm] IFormFileCollection files, - CancellationToken cancellationToken = default - ) - { - // - try - { - // - // Validate ... - if (!request.IsValid()) - { - XException.InvalidArgs.Throw(); - } - - // - var userInfo = await GetUserInfo(); - var connectionId = GetConnectionId(); - - // - var result = await aiService.AskAsync( - files: files, - 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; - } - } - - /// - /// Ask Question with Files and Get Response Stream ... - /// - /// - /// - /// - [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, - 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 ... - /// - /// Retrieve AI Projects ... - /// - /// - /// - /// - [HttpGet("Projects")] - [Authorize(Policy = XPolicies.EnabledUser)] - public async Task>> 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; - } - } - - /// - /// Retrieve Specified AI Project's Conversations ... - /// - /// - /// - /// - [Authorize(Policy = XPolicies.EnabledUser)] - [HttpGet("Projects/{projectId}/Conversations")] - public async Task>> LoadConversations( - [FromRoute] Guid projectId, - CancellationToken cancellationToken = default - ) - { - // - try - { - // - // Validate ... - if (projectId.IsDefaultGuid()) - { - XException.InvalidArgs.Throw(); - } - - // - var userInfo = await GetUserInfo(); - var connectionId = GetConnectionId(); - - // - var result = await aiService.LoadConversations( - projectId: projectId, - connectionId: connectionId, - cancellationToken: cancellationToken - ); - - // - return Ok(result); - } - catch (Exception ex) - { - // - var result = GetExceptionActionResult(ex); - return result; - } - } - - /// - /// Retrieve Specified AI Conversation's Messages ... - /// - /// - /// - /// - [Authorize(Policy = XPolicies.EnabledUser)] - [HttpGet("Conversations/{conversationId}/Messages")] - public async Task>> LoadMessages( - [FromRoute] Guid conversationId, - CancellationToken cancellationToken = default - ) - { - // - try - { - // - // Validate ... - if (conversationId.IsDefaultGuid()) - { - XException.InvalidArgs.Throw(); - } - - // - var result = await aiService.LoadMessages( - conversationId: conversationId, - cancellationToken: cancellationToken - ); - - // - return Ok(result); - } - catch (Exception ex) - { - // - var result = GetExceptionActionResult(ex); - return result; - } - } - #endregion - - // - #region Queries ... - /// - /// Query Projects ... - /// - /// - /// - /// - /// - /// - [HttpGet("Projects/Query")] - [Authorize(Policy = XPolicies.EnabledUser)] - public async Task>> 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; - } - } - - /// - /// Query Conversations ... - /// - /// - /// - /// - /// - [Authorize(Policy = XPolicies.EnabledUser)] - [HttpGet("Projects/{projectId}/Conversations/Query")] - public async Task>> 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; - } - } - - /// - /// Query Messages ... - /// - /// - /// - /// - /// - [Authorize(Policy = XPolicies.EnabledUser)] - [HttpGet("Conversations/{conversationId}/Messages/Query")] - public async Task>> 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 ... - /// - /// Create an AI Project ... - /// - /// - /// - /// - [HttpPost("Projects")] - [Authorize(Policy = XPolicies.EnabledUser)] - public async Task> 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; - } - } - - /// - /// Create an AI Conversation ... - /// - /// - /// - /// - /// - [Authorize(Policy = XPolicies.EnabledUser)] - [HttpPost("Projects/{projectId}/Conversations")] - public async Task> 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; - } - } - #endregion - - // - #region Content Extraction ... - /// - /// Extract Files Content ... - /// - /// - /// - /// - /// - [HttpPost("ExtractContent")] - [Consumes("multipart/form-data")] - [Authorize(Policy = XPolicies.EnabledUser)] - public async Task> 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()]; - } - - // - 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 ... - /// - /// Write Validation Error for Streaming Endpoints (before Stream Starts) ... - /// - /// - [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\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\xAiApi\Database\XAiApiDatabaseDescriptor.cs - -using xAiApi.Constants; -using xDataService.Interfaces; -using xDataService.Models; - -namespace xAiApi.Database -{ - /// - /// Ai Api Database Descriptor ... - /// - public class XAiApiDatabaseDescriptor : XDatabaseDescriptor, IXDatabaseDescriptor - { - public XAiApiDatabaseDescriptor() : base( - name: XAiApiConstants.XAiApiDbIdentifier, - repositories: [] - ) - { - OptionsBuilder = b => b.MigrationsAssembly(XAiApiConstants.XAiApiMigrationsAssemblyIdentifier); - } - } -} - -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\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 -{ - /// - /// Db Context of AiApi ... - /// - 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\hkhazaeeasl\Documents\Projets\XProjects\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 - { - /// - /// Extract AI Configuration ... - /// - /// - /// - public static XAiApiConfiguration GetXAiApiConfiguration(this IConfiguration source) - { - // - XAiApiConfiguration result = null; - - // - var section = source.GetSection(ConfigurationNodeNames.AI_API_NODE); - if (!section.IsNull()) - { - result = section.Get(); - } - - // - return result; - } - - /// - /// Register AiApi Configuration ... - /// - /// - /// - public static void AddXAiApiConfiguration( - this IServiceCollection source, - IConfiguration configuration - ) - { - // - var apiConfig = configuration.GetXAiApiConfiguration(); - source.AddXAiApiConfiguration(apiConfig); - } - - /// - /// Register AiApi Configuration ... - /// - /// - /// - public static void AddXAiApiConfiguration( - this IServiceCollection source, - XAiApiConfiguration configuration - ) - { - // - if (!configuration.IsValid()) - { - XException.InvalidConfiguration.Throw(); - } - - // - source.AddSingleton(configuration); - } - - /// - /// Register Rag Service ... - /// - /// - public static void AddXRagService( - this IServiceCollection source - ) - { - // - // Persistent RAG (Knowledge over XAiVector Table) ... - source.AddScoped(); - source.AddScoped(); - } - - /// - /// Register Ai Services ... - /// - /// - public static void AddXAiServices( - this IServiceCollection source - ) - { - // - source.AddScoped(); - source.AddScoped(); - } - - /// - /// Register AiApi File Content Extractor Services ... - /// - /// - public static void AddXAiFileContentExtractors( - this IServiceCollection source - ) - { - // - // Register File Content Extractors ... - source.AddSingleton(); - source.AddSingleton(); - source.AddSingleton(); - source.AddSingleton(); - source.AddSingleton(); - source.AddSingleton(); - source.AddSingleton(); - source.AddSingleton(); - source.AddSingleton(); - source.AddSingleton(); - source.AddSingleton(); - source.AddSingleton(); - source.AddSingleton(); - - // - source.AddSingleton(); - } - - /// - /// Register AiApi Text Chunker Service ... - /// - /// - public static void AddXAiTextChunker( - this IServiceCollection source - ) - { - // - // Stateless -> Singleton ... - source.AddSingleton(); - } - - /// - /// Register In-Memory Vector Store Service ... - /// - public static void AddXAiInMemoryVectorStore(this IServiceCollection source) - { - source.AddSingleton(); - source.AddHostedService(); - } - - /// - /// Register all Services Required for Chat With Documents (In-Memory RAG): - /// Text Chunker + In-Memory Vector Store (+ Cleanup) ... - /// - /// - public static void AddXAiChatWithDocuments(this IServiceCollection source) - { - source.AddXAiInMemoryVectorStore(); - } - - /// - /// Use Model Proxy Provider ... - /// - /// - /// - public static IApplicationBuilder UseXAiModelProxy( - this IApplicationBuilder source - ) - { - return source.UseMiddleware(); - } - - // - #region Private ... - /// - /// a LogTag for Service ... - /// - private static string XLogTag = XAiApiConstants.XDILogTag; - - /// - /// print a log in Console ... - /// - /// - private static void Log(string message) - { - Console.WriteLine($"{XLogTag} => {message}"); - } - #endregion - } -} - -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\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 - { - /// - /// Validate Configurations ... - /// - /// - /// - 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; - } - - /// - /// Check TextChunker Descriptor is Valid or not ... - /// - /// - /// - 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; - } - - /// - /// Check Document Ask Request is Valid or not ... - /// - /// - /// - public static bool IsValid(this XAiDocumentAskRequest source) - { - // - var result = - !source.IsNullOrDefault() && - !source.Prompt.IsNullOrEmpty() && - !source.SessionId.IsDefaultGuid(); - - // - return result; - } - - /// - /// Extract Default Model Descriptor ... - /// - /// - /// - public static XAiModelDescriptor GetDefaultModel(this XAiApiConfiguration source) - { - // - XAiModelDescriptor result = null; - - // - if (source.IsValid()) - { - result = source.Models[0]; - } - - // - return result; - } - - /// - /// Retrieve Specified Model from Config ... - /// - /// - /// - /// - 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; - } - - /// - /// Retrieve Introduction Prompt ... - /// - /// - /// - 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; - } - - /// - /// Select Specified Prompts and Parse it's Template - /// and Generate Message ... - /// - /// - /// - /// - /// - public static string GetPrompt( - this XAiApiConfiguration source, - string name = null, - IDictionary @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; - } - - /// - /// Provide HttpClient for Common Usages ... - /// - /// - /// - 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; - } - - /// - /// Instance and Retrieve Chat Client ... - /// - /// - /// - 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; - } - - } -} - -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\xAiApi\Extensions\XProgramExtensions.cs - -using xIdentityHelper; -using xCommons.Extensions; -using xCommons.Authorization; -using System.Collections.Generic; -using Microsoft.AspNetCore.Builder; -using Microsoft.AspNetCore.Authorization; -using Microsoft.AspNetCore.HttpOverrides; -using Microsoft.Extensions.DependencyInjection; - -namespace xAiApi.Extensions -{ - public static class XProgramExtensions - { - /// - /// Register Authorization Policies - /// - /// - /// - public static void AddXAuthorization( - this IServiceCollection services, - IDictionary policies = null - ) - { - // - 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); - } - } - } - - // - var xPolicies = XAuthorizationHelper.GetXAuthorizationPolicies(); - if (!xPolicies.IsNull()) - { - // - // Fill Policies ... - using (var policiesEnumerator = xPolicies.GetEnumerator()) - { - while (policiesEnumerator.MoveNext()) - { - var policyDescriptor = policiesEnumerator.Current; - options.AddPolicy(policyDescriptor.Key, policyDescriptor.Value); - } - } - } - }); - - // - services.AddSingleton(); - } - - /// - /// Use Forward Headers Options for resolving behind a proxy issues ... - /// - /// - /// - 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\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\xAiApi\Interfaces\IXAiEmbeddingService.cs - -namespace xAiApi.Interfaces -{ - public interface IXAiEmbeddingService : IXAiEmbeddingServiceBase - { } -} - -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\xAiApi\Interfaces\IXAiEmbeddingServiceBase.cs - -using System.Threading; -using System.Threading.Tasks; -using Microsoft.Extensions.AI; -using System.Collections.Generic; - -namespace xAiApi.Interfaces -{ - /// - /// Base Embedding Provider Service ... - /// - public interface IXAiEmbeddingServiceBase // : IXAiServiceBase - { - /// - /// Embedding Specified String ... - /// - /// - /// - /// - Task Embedding( - string content, - CancellationToken cancellationToken = default - ); - - /// - /// Embedding Specified Batch ... - /// - /// - /// - /// - Task> Embeddings( - string[] batch, - CancellationToken cancellationToken = default - ); - - /// - /// Embedding Generator ... - /// - /// - IEmbeddingGenerator> GetEmbeddingGenerator(); - } -} - -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\xAiApi\Interfaces\IXAiMcpServerProvider.cs - -using System; -using System.Collections.Generic; -using System.Linq; -using System.Linq.Expressions; -using System.Threading; -using System.Threading.Tasks; -using ModelContextProtocol.Client; -using xAiModels.Models.Dtos; -using xAiModels.Models.Entities; -using xIdentityModels.Models; -using xModels.Dtos; - -namespace xAiApi.Interfaces -{ - public interface IXAiMcpServerProvider - { - // - #region Manager ... - /// - /// Get a List Of Available Tools which Provided using registered Mcp Servers ... - /// - /// - /// - /// - /// - Task> GetAvailableToolsAsync( - bool forceOwner = false, - XUserClaimsInfoDto userInfo = null, - CancellationToken cancellationToken = default - ); - - /// - /// Test Specified Mcp Server ... - /// - /// - /// - /// - Task TestServerAsync( - XAiMcpServerDto server, - CancellationToken cancellationToken = default - ); - - /// - /// Force Refresh Mcp Servers ... - /// - /// - Task RefreshAsync(); - #endregion - - // - #region Actions ... - /// - /// Add an Mcp Server ... - /// - /// - /// - /// - /// - /// - Task AddMcpServer( - XAiMcpServerDto item, - string connectionId = null, - XUserClaimsInfoDto userInfo = null, - CancellationToken cancellationToken = default - ); - - /// - /// Update Specified Mcp Server ... - /// - /// - /// - /// - /// - /// - /// - Task UpdateMcpServer( - Guid id, - XAiMcpServerDto item, - string connectionId = null, - XUserClaimsInfoDto userInfo = null, - CancellationToken cancellationToken = default - ); - - /// - /// Remove Specified Mcp Server ... - /// - /// - /// - /// - /// - /// - Task RemoveMcpServer( - Guid id, - string connectionId = null, - XUserClaimsInfoDto userInfo = null, - CancellationToken cancellationToken = default - ); - - /// - /// Disable Specified Mcp Server ... - /// - /// - /// - /// - /// - /// - Task DisableMcpServer( - Guid id, - string connectionId = null, - XUserClaimsInfoDto userInfo = null, - CancellationToken cancellationToken = default - ); - - /// - /// Enable Specified Mcp Server ... - /// - /// - /// - /// - /// - /// - Task EnableMcpServer( - Guid id, - string connectionId = null, - XUserClaimsInfoDto userInfo = null, - CancellationToken cancellationToken = default - ); - - /// - /// Toggle Specified Mcp Server ... - /// - /// - /// - /// - /// - /// - Task ToggleMcpServer( - Guid id, - string connectionId = null, - XUserClaimsInfoDto userInfo = null, - CancellationToken cancellationToken = default - ); - - /// - /// Retrieve all Mcp Server ... - /// - /// - /// - /// - /// - Task> GetAll( - bool forceOwner = false, - XUserClaimsInfoDto userInfo = null, - CancellationToken cancellationToken = default - ); - - /// - /// Find Specified Mcp Server ... - /// - /// - /// - /// - /// - /// - Task FindOne( - Expression> predicate, - bool forceOwner = false, - XUserClaimsInfoDto userInfo = null, - CancellationToken cancellationToken = default - ); - - /// - /// Find a Collection of Specified Mcp Servers ... - /// - /// - /// - /// - /// - /// - Task> FindMany( - Expression> predicate, - bool forceOwner = false, - XUserClaimsInfoDto userInfo = null, - CancellationToken cancellationToken = default - ); - - /// - /// Query Registered Mcp Servers ... - /// - /// - /// - /// - /// - /// - Task> Query( - XQuery query, - bool forceOwner = false, - XUserClaimsInfoDto userInfo = null, - CancellationToken cancellationToken = default - ); - #endregion - } -} - -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\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 -{ - /// - /// Persistent RAG Service over XAiVector Table: - /// Ingest (Extract -> Chunk -> Embed -> Store) and Ask (Embed -> Search -> Generate) ... - /// Isolation is Scope Based (Conversation / Project / User / Global) ... - /// - public interface IXAiRAGService - { - /// - /// Ingest Files into Specified Knowledge Scope: - /// Extract -> Chunk -> Embed -> Store (XAiVector) ... - /// - /// - /// Target Scope (Null = User Scope) - /// - /// - /// - /// - /// - Task IngestAsync( - IFormFileCollection files, - XAiKnowledgeScopeDescriptor scope = null, - XUserClaimsInfoDto userInfo = null, - string connectionId = null, - bool replaceExisting = true, - CancellationToken cancellationToken = default - ); - - /// - /// Embed Prompt and Retrieve Relevant Chunks (Tiered: Conversation -> Project -> User -> Global) ... - /// - /// - /// - /// - /// - Task> RetrieveAsync( - XAiKnowledgeAskRequest request, - XUserClaimsInfoDto userInfo = null, - CancellationToken cancellationToken = default - ); - - /// - /// List Ingested Documents of Specified Scope ... - /// - /// Target Scope (Null = User Scope) - /// - /// - /// - Task> LoadDocumentsAsync( - XAiKnowledgeScopeDescriptor scope = null, - XUserClaimsInfoDto userInfo = null, - CancellationToken cancellationToken = default - ); - - /// - /// Remove All Vectors of a Document in Specified Scope ... - /// - /// - /// Target Scope (Null = User Scope) - /// - /// - /// - /// Count of Removed Vectors - Task RemoveDocumentAsync( - string fileName, - XAiKnowledgeScopeDescriptor scope = null, - XUserClaimsInfoDto userInfo = null, - string connectionId = null, - CancellationToken cancellationToken = default - ); - - /// - /// Migrate Legacy Vectors of Owner ("{ownerId}/{fileName}#i") into User Scope ("user/{ownerId}/{fileName}#i") ... - /// Idempotent: Returns 0 when Nothing Left to Migrate ... - /// - /// - /// - /// Count of Migrated Vectors - Task MigrateLegacyVectorsAsync( - XUserClaimsInfoDto userInfo = null, - CancellationToken cancellationToken = default - ); - - /// - /// Map Search Results to Public Sources ... - /// - /// - /// - IList ToSources( - IEnumerable context - ); - } -} - -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\xAiApi\Interfaces\IXAiService.cs - -namespace xAiApi.Interfaces -{ - public interface IXAiService : IXAiServiceBase - { } -} - -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\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 -{ - /// - /// Describe a Base Service Actions of any Ai Based Services ... - /// - public interface IXAiServiceBase : IDisposable - { - /// - /// Chat Options ... - /// - ChatOptions Options { get; } - - /// - /// Descriptor of Models which used in Service ... - /// - XAiModelDescriptor Descriptor { get; } - - // - #region Actions ... - /// - /// Base Method for Communicate with LLM ... - /// - /// - /// - /// - Task AskTextAsync( - string prompt, - CancellationToken cancellationToken = default - ); - - /// - /// Base Method for Communicate with LLM ... - /// - /// - /// - /// - IAsyncEnumerable AskTextAsEnumerable( - string prompt, - CancellationToken cancellationToken = default - ); - - /// - /// Ask a Question By Providing Vector Search Result ... - /// - /// - /// - /// - /// - /// - Task AskTextByContextAsync( - string prompt, - IList context = null, - XUserClaimsInfoDto userInfo = null, - CancellationToken cancellationToken = default - ); - - /// - /// Ask a Question By By Providing Vector Search Result and Stream Response ... - /// - /// - /// - /// - /// - /// - IAsyncEnumerable AskTextByContextAsEnumerable( - string prompt, - IList context = null, - XUserClaimsInfoDto userInfo = null, - CancellationToken cancellationToken = default - ); - - /// - /// Ask a Question By Rag Retrive From Knowledge ... - /// - /// - /// - /// - /// - /// - /// - /// - Task AskTextFromKnowledgeAsync( - string prompt, - string type = null, - int? topK = null, - float? minScore = null, - XUserClaimsInfoDto userInfo = null, - CancellationToken cancellationToken = default - ); - - /// - /// Ask a Question By Rag Retrive From Knowledge and Stream Response ... - /// - /// - /// - /// - /// - /// - /// - /// - IAsyncEnumerable AskTextFromKnowledgeAsEnumerable( - string prompt, - string type = null, - int? topK = null, - float? minScore = null, - XUserClaimsInfoDto userInfo = null, - CancellationToken cancellationToken = default - ); - - /// - /// Ask a Question as Prompt and Retrieve Response ... - /// - /// - /// - /// - /// - /// - /// - /// - /// - /// - /// - /// - Task AskAsync( - string prompt, - string type = null, - int? topK = null, - float? minScore = null, - Guid? projectId = null, - Guid? conversationId = null, - string connectionId = null, - IFormFileCollection files = null, - XUserClaimsInfoDto userInfo = null, - CancellationToken cancellationToken = default - ); - - /// - /// Ask a Question as Prompt and Retrieve Response as Async Enumerable ... - /// - /// - /// - /// - /// - /// - /// - /// - /// - /// - /// - /// - IAsyncEnumerable AskAsEnumerable( - string prompt, - string type = null, - int? topK = null, - float? minScore = null, - Guid? projectId = null, - Guid? conversationId = null, - string connectionId = null, - IFormFileCollection files = null, - XUserClaimsInfoDto userInfo = null, - CancellationToken cancellationToken = default - ); - #endregion - - // - #region Loaders ... - /// - /// Load AI Projects ... - /// - /// - /// - /// - /// - /// - Task> LoadProjects( - string ownerId, - string connectionId = null, - bool includeDefaults = false, - CancellationToken cancellationToken = default - ); - - /// - /// Load Conversations of Specified AI Project ... - /// - /// - /// - /// - /// - Task> LoadConversations( - Guid projectId, - string connectionId = null, - CancellationToken cancellationToken = default - ); - - /// - /// Load Messages of Specified Conversation ... - /// - /// - /// - /// - Task> LoadMessages( - Guid conversationId, - CancellationToken cancellationToken = default - ); - #endregion - - // - #region Queries ... - /// - /// Query Projects ... - /// - /// - /// - /// - /// - Task> QueryProjects( - string ownerId, - XQuery query, - CancellationToken cancellationToken = default - ); - - /// - /// Query Conversations ... - /// - /// - /// - /// - /// - /// - Task> QueryConversations( - string ownerId, - Guid projectId, - XQuery query, - CancellationToken cancellationToken = default - ); - - /// - /// Query Messages ... - /// - /// - /// - /// - /// - /// - Task> QueryMessages( - string ownerId, - Guid conversationId, - XQuery query, - CancellationToken cancellationToken = default - ); - #endregion - - // - #region Creators ... - /// - /// Create an AI Project ... - /// - /// - /// - /// - /// - /// - Task CreateProject( - string ownerId, - XAiProjectDto item, - string connectionId = null, - CancellationToken cancellationToken = default - ); - - /// - /// Create an AI Conversation ... - /// - /// - /// - /// - /// - /// - /// - Task CreateConversation( - string ownerId, - Guid projectId, - XAiConversationDto item, - string connectionId = null, - CancellationToken cancellationToken = default - ); - #endregion - - // - #region Content Extraction ... - /// - /// Try to Extract Files Content ... - /// - /// - /// - /// - /// - Task ExtractContent( - IFormFileCollection files, - string[] extractors = null, - CancellationToken cancellationToken = default - ); - #endregion - } -} - -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\xAiApi\Interfaces\IXDefaultThinkingAiService.cs - -namespace xAiApi.Interfaces -{ - public interface IXDefaultThinkingAiService: IXAiServiceBase - { } -} - -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\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 vectors, - string ownerId = null, - TimeSpan? ttl = null - ); - bool Replace( - Guid sessionId, - IEnumerable vectors, - string ownerId = null - ); - bool Add( - Guid sessionId, - IEnumerable vectors, - string ownerId = null - ); - IList Search( - Guid sessionId, - ReadOnlyMemory 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\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\xAiApi\Interfaces\IXTextChunker.cs - -using xAiApi.Models; -using System.Collections.Generic; - -namespace xAiApi.Interfaces -{ - /// - /// a Service for Splitting Long Texts into Overlapping Chunks - /// which Suitable for Embedding ... - /// - public interface IXTextChunker - { - /// - /// Split Text into Chunks ... - /// - /// Source Text - /// Source Name (e.g. File Name) used for Identifier - /// - IList Chunk( - string text, - string source = null - ); - - /// - /// Split Text into Chunks and Return only Texts ... - /// - /// - /// - IList ChunkTexts( - string text - ); - } -} - -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\xAiApi\Interfaces\Extractors\IXAudioFileContentExtractor.cs - -namespace xAiApi.Interfaces.Extractors -{ - public interface IXAudioFileContentExtractor : IXFileContentExtractorBase - { } -} - -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\xAiApi\Interfaces\Extractors\IXCodeFileContentExtractor.cs - -namespace xAiApi.Interfaces.Extractors -{ - /// - /// Extractor for source code files ... - /// (C#, Python, JavaScript, TypeScript, Java, Go, Rust, ...) - /// - public interface IXCodeFileContentExtractor : IXFileContentExtractorBase - { } -} - -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\xAiApi\Interfaces\Extractors\IXDocxFileContentExtractor.cs - -namespace xAiApi.Interfaces.Extractors -{ - public interface IXDocxFileContentExtractor : IXFileContentExtractorBase - { } -} - -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\xAiApi\Interfaces\Extractors\IXEpubFileContentExtractor.cs - -namespace xAiApi.Interfaces.Extractors -{ - /// - /// Extractor for EPUB electronic publication format - /// (application/epub+zip) - /// - public interface IXEpubFileContentExtractor : IXFileContentExtractorBase - { } -} - -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\xAiApi\Interfaces\Extractors\IXExcelFileContentExtractor.cs - -namespace xAiApi.Interfaces.Extractors -{ - public interface IXExcelFileContentExtractor : IXFileContentExtractorBase - { } -} - -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\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 -{ - /// - /// a Base Service for Extracting File Content ... - /// - public interface IXFileContentExtractorBase - { - /// - /// Check if this extractor supports the specified MIME type ... - /// - bool CanExtract(string mimeType); - - /// - /// Extract text content from file stream ... - /// - Task ExtractAsync( - Stream fileStream, - string mimeType, - CancellationToken cancellationToken = default - ); - - /// - /// Extract content from stream as Rich Result ... - /// - /// - /// - /// - /// - /// - Task ExtractRichAsync( - Stream fileStream, - string fileName, - string mimeType, - CancellationToken cancellationToken = default - ); - } - - /// - /// a Service for Extracting File Content ... - /// - public interface IXFileContentExtractor - { - /// - /// Check if this extractor supports the specified MIME type ... - /// - /// - /// - /// - bool CanExtract( - string mimeType, - string[] extractors = null - ); - - /// - /// Extract text content from file stream ... - /// - /// - /// - /// - /// - /// - Task ExtractAsync( - Stream fileStream, - string mimeType, - string[] extractors = null, - CancellationToken cancellationToken = default - ); - - /// - /// Extract content from stream as Rich Result ... - /// - /// - /// - /// - /// - /// - /// - Task ExtractRichAsync( - Stream fileStream, - string fileName, - string mimeType, - string[] extractors = null, - CancellationToken cancellationToken = default - ); - - } -} - -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\xAiApi\Interfaces\Extractors\IXHtmlFileContentExtractor.cs - -namespace xAiApi.Interfaces.Extractors -{ - /// - /// Extractor for HTML documents (text/html, application/xhtml+xml) - /// - public interface IXHtmlFileContentExtractor : IXFileContentExtractorBase - { } -} - -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\xAiApi\Interfaces\Extractors\IXImageFileContentExtractor.cs - -namespace xAiApi.Interfaces.Extractors -{ - public interface IXImageFileContentExtractor : IXFileContentExtractorBase - { } -} - -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\xAiApi\Interfaces\Extractors\IXOpenDocumentFileContentExtractor.cs - -namespace xAiApi.Interfaces.Extractors -{ - /// - /// Extractor for OpenDocument Format (ODF) documents - /// (ODT: OpenDocument Text, ODS: OpenDocument Spreadsheet, ODP: OpenDocument Presentation) - /// - public interface IXOpenDocumentFileContentExtractor : IXFileContentExtractorBase - { } -} - -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\xAiApi\Interfaces\Extractors\IXPdfFileContentExtractor.cs - -namespace xAiApi.Interfaces.Extractors -{ - public interface IXPdfFileContentExtractor : IXFileContentExtractorBase - { } -} - -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\xAiApi\Interfaces\Extractors\IXPlainTextFileContentExtractor.cs - -namespace xAiApi.Interfaces.Extractors -{ - public interface IXPlainTextFileContentExtractor : IXFileContentExtractorBase - { } -} - -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\xAiApi\Interfaces\Extractors\IXPowerPointFileContentExtractor.cs - -namespace xAiApi.Interfaces.Extractors -{ - /// - /// Extractor for all PowerPoint Presentation formats - /// (OpenXML: pptx, ppsx, potx, pptm, ppsm, potm | Legacy Binary: ppt, pps, pot) - /// - public interface IXPowerPointFileContentExtractor : IXFileContentExtractorBase - { } -} - -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\xAiApi\Interfaces\Extractors\IXRtfFileContentExtractor.cs - -namespace xAiApi.Interfaces.Extractors -{ - /// - /// Extractor for Rich Text Format (RTF) documents - /// (application/rtf, text/rtf) - /// - public interface IXRtfFileContentExtractor : IXFileContentExtractorBase - { } -} - -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\xAiApi\Interfaces\Extractors\IXVisionFileContentExtractor.cs - -namespace xAiApi.Interfaces.Extractors -{ - public interface IXVisionFileContentExtractor : IXFileContentExtractorBase - { } -} - -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\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 logger; - - public XAiModelProxyMiddleware( - RequestDelegate next, - XAiApiConfiguration configuration, - IHttpClientFactory httpClientFactory, - ILogger logger - ) - { - // - this.next = next; - this.logger = logger; - this.configuration = configuration; - this.httpClientFactory = httpClientFactory; - } - - /// - /// Handle Routing ... - /// - /// - /// - 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\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\xAiApi\Migrations\20261104052650_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(nullable: false), - Deleted = table.Column(nullable: false), - OwnerId = table.Column(maxLength: 255, nullable: false), - Title = table.Column(maxLength: 255, nullable: false), - CreatedOn = table.Column(nullable: false), - UpdatedAt = table.Column(nullable: false), - ProjectId = table.Column(nullable: false) - }, - constraints: table => - { - table.PrimaryKey("PK_AiConversations", x => x.Id); - }); - - migrationBuilder.CreateTable( - name: "AiMcpServers", - columns: table => new - { - Id = table.Column(nullable: false), - Deleted = table.Column(nullable: false), - OwnerId = table.Column(maxLength: 255, nullable: false), - Scope = table.Column(nullable: false), - Name = table.Column(maxLength: 255, nullable: false), - Description = table.Column(maxLength: 1000, nullable: true), - Enabled = table.Column(nullable: false), - EnvironmentVariables = table.Column(nullable: true), - Endpoint = table.Column(maxLength: 1000, nullable: true), - Headers = table.Column(nullable: true), - TimeoutSeconds = table.Column(nullable: false), - CreatedOn = table.Column(nullable: false), - UpdatedAt = table.Column(nullable: false) - }, - constraints: table => - { - table.PrimaryKey("PK_AiMcpServers", x => x.Id); - }); - - migrationBuilder.CreateTable( - name: "AiMessages", - columns: table => new - { - Id = table.Column(nullable: false), - Deleted = table.Column(nullable: false), - OwnerId = table.Column(maxLength: 255, nullable: false), - Content = table.Column(nullable: false), - Role = table.Column(nullable: false), - CreatedOn = table.Column(nullable: false), - UpdatedAt = table.Column(nullable: false), - ConversationId = table.Column(maxLength: 255, nullable: false), - MetaDatas = table.Column(nullable: true) - }, - constraints: table => - { - table.PrimaryKey("PK_AiMessages", x => x.Id); - }); - - migrationBuilder.CreateTable( - name: "AiProjects", - columns: table => new - { - Id = table.Column(nullable: false), - Deleted = table.Column(nullable: false), - OwnerId = table.Column(maxLength: 255, nullable: false), - Title = table.Column(maxLength: 255, nullable: false), - Description = table.Column(maxLength: 1000, nullable: true), - Prompt = table.Column(nullable: true), - CreatedOn = table.Column(nullable: false), - UpdatedAt = table.Column(nullable: false) - }, - constraints: table => - { - table.PrimaryKey("PK_AiProjects", x => x.Id); - }); - - migrationBuilder.CreateTable( - name: "AiVectors", - columns: table => new - { - Id = table.Column(nullable: false), - Deleted = table.Column(nullable: false), - Text = table.Column(nullable: true), - Identifier = table.Column(nullable: true), - Type = table.Column(maxLength: 100, nullable: true), - Embedding = table.Column(nullable: true), - Metadata = table.Column(nullable: true) - }, - constraints: table => - { - table.PrimaryKey("PK_AiVectors", x => x.Id); - }); - - migrationBuilder.CreateTable( - name: "Files", - columns: table => new - { - Id = table.Column(nullable: false), - Deleted = table.Column(nullable: false), - Type = table.Column(nullable: false), - OwnerId = table.Column(maxLength: 255, nullable: false), - Name = table.Column(maxLength: 255, nullable: false), - Path = table.Column(nullable: false), - Thumb = table.Column(nullable: true), - ThumbPath = table.Column(nullable: true), - UploadedOn = table.Column(nullable: false), - FileName = table.Column(nullable: true), - References = table.Column(nullable: true) - }, - constraints: table => - { - table.PrimaryKey("PK_Files", x => x.Id); - }); - - migrationBuilder.CreateTable( - name: "Strings", - columns: table => new - { - Id = table.Column(nullable: false) - .Annotation("Sqlite:Autoincrement", true), - Deleted = table.Column(nullable: false), - Language = table.Column(maxLength: 10, nullable: false), - ResourceTitle = table.Column(maxLength: 255, nullable: false), - TranslatedValue = table.Column(nullable: false) - }, - constraints: table => - { - table.PrimaryKey("PK_Strings", x => x.Id); - }); - - migrationBuilder.CreateTable( - name: "Tags", - columns: table => new - { - Id = table.Column(nullable: false) - .Annotation("Sqlite:Autoincrement", true), - Deleted = table.Column(nullable: false), - Tag = table.Column(maxLength: 255, nullable: false), - References = table.Column(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\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\xAiApi\Migrations\20261104052650_InitialMigrationAiApi.Designer.cs - -// -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("20261104052650_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("Id") - .ValueGeneratedOnAdd() - .HasColumnType("TEXT"); - - b.Property("CreatedOn") - .HasColumnType("TEXT"); - - b.Property("Deleted") - .HasColumnType("INTEGER"); - - b.Property("OwnerId") - .IsRequired() - .HasColumnType("TEXT") - .HasMaxLength(255); - - b.Property("ProjectId") - .HasColumnType("TEXT"); - - b.Property("Title") - .IsRequired() - .HasColumnType("TEXT") - .HasMaxLength(255); - - b.Property("UpdatedAt") - .HasColumnType("TEXT"); - - b.HasKey("Id"); - - b.ToTable("AiConversations"); - }); - - modelBuilder.Entity("xAiModels.Models.Entities.XAiMcpServer", b => - { - b.Property("Id") - .ValueGeneratedOnAdd() - .HasColumnType("TEXT"); - - b.Property("CreatedOn") - .HasColumnType("TEXT"); - - b.Property("Deleted") - .HasColumnType("INTEGER"); - - b.Property("Description") - .HasColumnType("TEXT") - .HasMaxLength(1000); - - b.Property("Enabled") - .HasColumnType("INTEGER"); - - b.Property("Endpoint") - .HasColumnType("TEXT") - .HasMaxLength(1000); - - b.Property("EnvironmentVariables") - .HasColumnType("TEXT"); - - b.Property("Headers") - .HasColumnType("TEXT"); - - b.Property("Name") - .IsRequired() - .HasColumnType("TEXT") - .HasMaxLength(255); - - b.Property("OwnerId") - .IsRequired() - .HasColumnType("TEXT") - .HasMaxLength(255); - - b.Property("Scope") - .HasColumnType("INTEGER"); - - b.Property("TimeoutSeconds") - .HasColumnType("INTEGER"); - - b.Property("UpdatedAt") - .HasColumnType("TEXT"); - - b.HasKey("Id"); - - b.ToTable("AiMcpServers"); - }); - - modelBuilder.Entity("xAiModels.Models.Entities.XAiMessage", b => - { - b.Property("Id") - .ValueGeneratedOnAdd() - .HasColumnType("TEXT"); - - b.Property("Content") - .IsRequired() - .HasColumnType("TEXT"); - - b.Property("ConversationId") - .HasColumnType("TEXT") - .HasMaxLength(255); - - b.Property("CreatedOn") - .HasColumnType("TEXT"); - - b.Property("Deleted") - .HasColumnType("INTEGER"); - - b.Property("MetaDatas") - .HasColumnType("TEXT"); - - b.Property("OwnerId") - .IsRequired() - .HasColumnType("TEXT") - .HasMaxLength(255); - - b.Property("Role") - .HasColumnType("INTEGER"); - - b.Property("UpdatedAt") - .HasColumnType("TEXT"); - - b.HasKey("Id"); - - b.ToTable("AiMessages"); - }); - - modelBuilder.Entity("xAiModels.Models.Entities.XAiProject", b => - { - b.Property("Id") - .ValueGeneratedOnAdd() - .HasColumnType("TEXT"); - - b.Property("CreatedOn") - .HasColumnType("TEXT"); - - b.Property("Deleted") - .HasColumnType("INTEGER"); - - b.Property("Description") - .HasColumnType("TEXT") - .HasMaxLength(1000); - - b.Property("OwnerId") - .IsRequired() - .HasColumnType("TEXT") - .HasMaxLength(255); - - b.Property("Prompt") - .HasColumnType("TEXT"); - - b.Property("Title") - .IsRequired() - .HasColumnType("TEXT") - .HasMaxLength(255); - - b.Property("UpdatedAt") - .HasColumnType("TEXT"); - - b.HasKey("Id"); - - b.ToTable("AiProjects"); - }); - - modelBuilder.Entity("xAiModels.Models.Entities.XAiVector", b => - { - b.Property("Id") - .ValueGeneratedOnAdd() - .HasColumnType("TEXT"); - - b.Property("Deleted") - .HasColumnType("INTEGER"); - - b.Property("Embedding") - .HasColumnType("TEXT"); - - b.Property("Identifier") - .HasColumnType("TEXT"); - - b.Property("Metadata") - .HasColumnType("TEXT"); - - b.Property("Text") - .HasColumnType("TEXT"); - - b.Property("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("Id") - .ValueGeneratedOnAdd() - .HasColumnType("TEXT"); - - b.Property("Deleted") - .HasColumnType("INTEGER"); - - b.Property("FileName") - .HasColumnType("TEXT"); - - b.Property("Name") - .IsRequired() - .HasColumnType("TEXT") - .HasMaxLength(255); - - b.Property("OwnerId") - .IsRequired() - .HasColumnType("TEXT") - .HasMaxLength(255); - - b.Property("Path") - .IsRequired() - .HasColumnType("TEXT"); - - b.Property("References") - .HasColumnType("TEXT"); - - b.Property("Thumb") - .HasColumnType("TEXT"); - - b.Property("ThumbPath") - .HasColumnType("TEXT"); - - b.Property("Type") - .HasColumnType("INTEGER"); - - b.Property("UploadedOn") - .HasColumnType("TEXT"); - - b.HasKey("Id"); - - b.ToTable("Files"); - }); - - modelBuilder.Entity("xStringService.Models.Entities.XString", b => - { - b.Property("Id") - .ValueGeneratedOnAdd() - .HasColumnType("INTEGER"); - - b.Property("Deleted") - .HasColumnType("INTEGER"); - - b.Property("Language") - .IsRequired() - .HasColumnType("TEXT") - .HasMaxLength(10); - - b.Property("ResourceTitle") - .IsRequired() - .HasColumnType("TEXT") - .HasMaxLength(255); - - b.Property("TranslatedValue") - .IsRequired() - .HasColumnType("TEXT"); - - b.HasKey("Id"); - - b.ToTable("Strings"); - }); - - modelBuilder.Entity("xTagService.Models.Entities.XTag", b => - { - b.Property("Id") - .ValueGeneratedOnAdd() - .HasColumnType("INTEGER"); - - b.Property("Deleted") - .HasColumnType("INTEGER"); - - b.Property("References") - .HasColumnType("TEXT"); - - b.Property("Tag") - .IsRequired() - .HasColumnType("TEXT") - .HasMaxLength(255); - - b.HasKey("Id"); - - b.ToTable("Tags"); - }); -#pragma warning restore 612, 618 - } - } -} - -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\xAiApi\Migrations\XAiApiDbContextModelSnapshot.cs - -// -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("Id") - .ValueGeneratedOnAdd() - .HasColumnType("TEXT"); - - b.Property("CreatedOn") - .HasColumnType("TEXT"); - - b.Property("Deleted") - .HasColumnType("INTEGER"); - - b.Property("OwnerId") - .IsRequired() - .HasColumnType("TEXT") - .HasMaxLength(255); - - b.Property("ProjectId") - .HasColumnType("TEXT"); - - b.Property("Title") - .IsRequired() - .HasColumnType("TEXT") - .HasMaxLength(255); - - b.Property("UpdatedAt") - .HasColumnType("TEXT"); - - b.HasKey("Id"); - - b.ToTable("AiConversations"); - }); - - modelBuilder.Entity("xAiModels.Models.Entities.XAiMcpServer", b => - { - b.Property("Id") - .ValueGeneratedOnAdd() - .HasColumnType("TEXT"); - - b.Property("CreatedOn") - .HasColumnType("TEXT"); - - b.Property("Deleted") - .HasColumnType("INTEGER"); - - b.Property("Description") - .HasColumnType("TEXT") - .HasMaxLength(1000); - - b.Property("Enabled") - .HasColumnType("INTEGER"); - - b.Property("Endpoint") - .HasColumnType("TEXT") - .HasMaxLength(1000); - - b.Property("EnvironmentVariables") - .HasColumnType("TEXT"); - - b.Property("Headers") - .HasColumnType("TEXT"); - - b.Property("Name") - .IsRequired() - .HasColumnType("TEXT") - .HasMaxLength(255); - - b.Property("OwnerId") - .IsRequired() - .HasColumnType("TEXT") - .HasMaxLength(255); - - b.Property("Scope") - .HasColumnType("INTEGER"); - - b.Property("TimeoutSeconds") - .HasColumnType("INTEGER"); - - b.Property("UpdatedAt") - .HasColumnType("TEXT"); - - b.HasKey("Id"); - - b.ToTable("AiMcpServers"); - }); - - modelBuilder.Entity("xAiModels.Models.Entities.XAiMessage", b => - { - b.Property("Id") - .ValueGeneratedOnAdd() - .HasColumnType("TEXT"); - - b.Property("Content") - .IsRequired() - .HasColumnType("TEXT"); - - b.Property("ConversationId") - .HasColumnType("TEXT") - .HasMaxLength(255); - - b.Property("CreatedOn") - .HasColumnType("TEXT"); - - b.Property("Deleted") - .HasColumnType("INTEGER"); - - b.Property("MetaDatas") - .HasColumnType("TEXT"); - - b.Property("OwnerId") - .IsRequired() - .HasColumnType("TEXT") - .HasMaxLength(255); - - b.Property("Role") - .HasColumnType("INTEGER"); - - b.Property("UpdatedAt") - .HasColumnType("TEXT"); - - b.HasKey("Id"); - - b.ToTable("AiMessages"); - }); - - modelBuilder.Entity("xAiModels.Models.Entities.XAiProject", b => - { - b.Property("Id") - .ValueGeneratedOnAdd() - .HasColumnType("TEXT"); - - b.Property("CreatedOn") - .HasColumnType("TEXT"); - - b.Property("Deleted") - .HasColumnType("INTEGER"); - - b.Property("Description") - .HasColumnType("TEXT") - .HasMaxLength(1000); - - b.Property("OwnerId") - .IsRequired() - .HasColumnType("TEXT") - .HasMaxLength(255); - - b.Property("Prompt") - .HasColumnType("TEXT"); - - b.Property("Title") - .IsRequired() - .HasColumnType("TEXT") - .HasMaxLength(255); - - b.Property("UpdatedAt") - .HasColumnType("TEXT"); - - b.HasKey("Id"); - - b.ToTable("AiProjects"); - }); - - modelBuilder.Entity("xAiModels.Models.Entities.XAiVector", b => - { - b.Property("Id") - .ValueGeneratedOnAdd() - .HasColumnType("TEXT"); - - b.Property("Deleted") - .HasColumnType("INTEGER"); - - b.Property("Embedding") - .HasColumnType("TEXT"); - - b.Property("Identifier") - .HasColumnType("TEXT"); - - b.Property("Metadata") - .HasColumnType("TEXT"); - - b.Property("Text") - .HasColumnType("TEXT"); - - b.Property("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("Id") - .ValueGeneratedOnAdd() - .HasColumnType("TEXT"); - - b.Property("Deleted") - .HasColumnType("INTEGER"); - - b.Property("FileName") - .HasColumnType("TEXT"); - - b.Property("Name") - .IsRequired() - .HasColumnType("TEXT") - .HasMaxLength(255); - - b.Property("OwnerId") - .IsRequired() - .HasColumnType("TEXT") - .HasMaxLength(255); - - b.Property("Path") - .IsRequired() - .HasColumnType("TEXT"); - - b.Property("References") - .HasColumnType("TEXT"); - - b.Property("Thumb") - .HasColumnType("TEXT"); - - b.Property("ThumbPath") - .HasColumnType("TEXT"); - - b.Property("Type") - .HasColumnType("INTEGER"); - - b.Property("UploadedOn") - .HasColumnType("TEXT"); - - b.HasKey("Id"); - - b.ToTable("Files"); - }); - - modelBuilder.Entity("xStringService.Models.Entities.XString", b => - { - b.Property("Id") - .ValueGeneratedOnAdd() - .HasColumnType("INTEGER"); - - b.Property("Deleted") - .HasColumnType("INTEGER"); - - b.Property("Language") - .IsRequired() - .HasColumnType("TEXT") - .HasMaxLength(10); - - b.Property("ResourceTitle") - .IsRequired() - .HasColumnType("TEXT") - .HasMaxLength(255); - - b.Property("TranslatedValue") - .IsRequired() - .HasColumnType("TEXT"); - - b.HasKey("Id"); - - b.ToTable("Strings"); - }); - - modelBuilder.Entity("xTagService.Models.Entities.XTag", b => - { - b.Property("Id") - .ValueGeneratedOnAdd() - .HasColumnType("INTEGER"); - - b.Property("Deleted") - .HasColumnType("INTEGER"); - - b.Property("References") - .HasColumnType("TEXT"); - - b.Property("Tag") - .IsRequired() - .HasColumnType("TEXT") - .HasMaxLength(255); - - b.HasKey("Id"); - - b.ToTable("Tags"); - }); -#pragma warning restore 612, 618 - } - } -} - -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\xAiApi\Models\XAiDocumentModels.cs - -using System; -using System.Collections.Generic; - -namespace xAiApi.Models -{ - /// - /// Result of Ingesting Documents into an In-Memory Session ... - /// - public class XAiDocumentIngestResult - { - /// - /// Session Identifier which must be used in Ask Requests ... - /// - public Guid SessionId { get; set; } - - /// - /// Count of Successfully Processed Files ... - /// - public int FilesCount { get; set; } - - /// - /// Count of Chunks (Vectors) Added to Session ... - /// - public int ChunksCount { get; set; } - - /// - /// Total Vectors Count in Session after Ingest ... - /// - public int TotalVectorsCount { get; set; } - - /// - /// Files which Skipped (Unsupported / Empty / Failed) ... - /// - public IList SkippedFiles { get; set; } = new List(); - - /// - /// Session Expiration Time (UTC) based on Last Access ... - /// - public DateTime ExpiresAtUtc { get; set; } - } - - /// - /// Request for Asking a Question over Ingested Documents ... - /// - public class XAiDocumentAskRequest - { - /// - /// Session Identifier ... - /// - public Guid SessionId { get; set; } - - /// - /// User Question ... - /// - public string Prompt { get; set; } - - /// - /// Count of Top Chunks used as Context (Optional) ... - /// - public int? TopK { get; set; } - - /// - /// Minimum Similarity Score of Chunks (Optional) ... - /// - public float? MinScore { get; set; } - } - - /// - /// a Source Chunk which used for Generating Answer ... - /// - public class XAiDocumentSource - { - /// - /// Doc and Chunk Identifier (e.g. "file.pdf#3") ... - /// - public string Identifier { get; set; } - - /// - /// Source File Name ... - /// - public string FileName { get; set; } - - /// - /// Chunk Index in Source File ... - /// - public int? ChunkIndex { get; set; } - - /// - /// Similarity Score ... - /// - public float Score { get; set; } - - /// - /// Short Snippet of Chunk Text ... - /// - public string Snippet { get; set; } - - /// - /// Knowledge Scope the Chunk Retrieved from (Null for Session Based Documents) ... - /// - public string Scope { get; set; } - - /// - /// Knowledge Type of the Chunk ... - /// - public string Type { get; set; } - } - - /// - /// Answer of a Chat With Documents Request ... - /// - public class XAiDocumentAnswer - { - /// - /// Session Identifier ... - /// - public Guid SessionId { get; set; } - - /// - /// Generated Answer ... - /// - public string Answer { get; set; } - - /// - /// True when no Relevant Chunk Found in Session ... - /// - public bool NoContextFound { get; set; } - - /// - /// Sources used for Generating Answer ... - /// - public IList Sources { get; set; } = new List(); - } - - /// - /// Streaming Chunk of a Chat With Documents Answer ... - /// - public class XAiDocumentAnswerChunk - { - /// - /// Text Delta ... - /// - public string Text { get; set; } - - /// - /// True for Last Chunk ... - /// - public bool IsFinal { get; set; } - - /// - /// True when no Relevant Chunk Found in Session ... - /// - public bool NoContextFound { get; set; } - - /// - /// Sources (Only Filled in First Chunk) ... - /// - public IList Sources { get; set; } - } - - /// - /// Public Info of a Document Session (without Embeddings) ... - /// - 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 Files { get; set; } = new List(); - } - - /// - /// Document RAG Configuration ... - /// - 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 ... - /// - /// Max Files Accepted in a Single Ingest Request (0 = Unlimited) ... - /// - public int MaxFilesPerIngest { get; set; } = 20; - - /// - /// Max Size of a Single File in Bytes (0 = Unlimited) ... - /// - public long MaxFileSizeBytes { get; set; } = 25 * 1024 * 1024; - - /// - /// Max Distinct Documents Allowed in a Non-Global Scope (0 = Unlimited) ... - /// - public int MaxDocumentsPerScope { get; set; } = 50; - } -} - -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\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 Vectors { get; set; } = new List(); - public bool IsExpired(DateTime utcNow) { return utcNow - LastAccessAtUtc >= Ttl; } - } -} - -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\xAiApi\Models\XAiKnowledgeModels.cs - -using System; -using xAiModels.Constants; -using System.Collections.Generic; - -namespace xAiApi.Models -{ - /// - /// Describes Target Knowledge Base Scope of an Operation ... - /// - public class XAiKnowledgeScopeDescriptor - { - /// - /// Scope Kind ... - /// - public XAiKnowledgeScope Scope { get; set; } = XAiKnowledgeScope.User; - - /// - /// Scope Identifier (ProjectId / ConversationId) - Null for Global and User ... - /// - public Guid? ScopeId { get; set; } - - /// - /// Optional Knowledge Type / Domain Filter ... - /// - public string Type { get; set; } - - /// - /// Create User Scope Knowledge Descriptor ... - /// - /// - /// - public static XAiKnowledgeScopeDescriptor User( - string type = null - ) => new() - { - // - Type = type ?? XAiModelsConstants.XAiDefaultKnowledgeType, - ScopeId = null, - Scope = XAiKnowledgeScope.User, - }; - - /// - /// Create Global Scope Knowledge Descriptor ... - /// - /// - /// - public static XAiKnowledgeScopeDescriptor Global( - string type = null - ) => new() - { - Type = type ?? XAiModelsConstants.XAiDefaultKnowledgeType, - ScopeId = null, - Scope = XAiKnowledgeScope.Global, - }; - - /// - /// Create Project Scope Knowledge Descriptor ... - /// - /// - /// - /// - public static XAiKnowledgeScopeDescriptor Project( - Guid projectId, - string type = null - ) => new() - { - Type = type ?? XAiModelsConstants.XAiDefaultKnowledgeType, - ScopeId = projectId, - Scope = XAiKnowledgeScope.Project, - }; - - /// - /// Create Conversational Scope Knowledge Descriptor ... - /// - /// - /// - /// - public static XAiKnowledgeScopeDescriptor Conversation( - Guid conversationId, - string type = null - ) => new() - { - Type = type ?? XAiModelsConstants.XAiDefaultKnowledgeType, - ScopeId = conversationId, - Scope = XAiKnowledgeScope.Conversation, - }; - } - - /// - /// Result of Ingesting Files into Persistent Knowledge Base (XAiVector Table) ... - /// - public class XAiKnowledgeIngestResult - { - /// - /// Target Scope ... - /// - public XAiKnowledgeScope Scope { get; set; } - - /// - /// Target Scope Identifier (Null for Global) ... - /// - public Guid? ScopeId { get; set; } - - /// - /// Knowledge Type of Ingested Vectors ... - /// - public string Type { get; set; } - - /// - /// Count of Successfully Ingested Files ... - /// - public int FilesCount { get; set; } - - /// - /// Count of Stored Chunks (Vectors) in this Request ... - /// - public int ChunksCount { get; set; } - - /// - /// Count of Removed Stale Vectors (Re-Ingest) ... - /// - public int ReplacedCount { get; set; } - - /// - /// Skipped Files (Empty, Unsupported or Extraction Failed) ... - /// - public IList SkippedFiles { get; set; } = new List(); - - /// - /// Ingested Documents Info ... - /// - public IList Documents { get; set; } = new List(); - } - - /// - /// Ask Request over Persistent Knowledge Base ... - /// Retrieval is Tiered: Conversation -> Project -> User -> Global (Each Tier Fills Remaining TopK) ... - /// - public class XAiKnowledgeAskRequest - { - /// - /// Question ... - /// - public string Prompt { get; set; } - - /// - /// Optional: Conversation Scope (Caller must be Conversation Owner) ... - /// When Provided, Conversation's Project is used for Second Tier Automatically ... - /// - public Guid? ConversationId { get; set; } - - /// - /// Optional: Project Scope (Caller must be Project Owner) ... - /// - public Guid? ProjectId { get; set; } - - /// - /// Include Personal (User) Knowledge Tier (default true) ... - /// - public bool IncludeUser { get; set; } = true; - - /// - /// Include Global Knowledge Tier (default true) ... - /// - public bool IncludeGlobal { get; set; } = true; - - /// - /// Optional: Restrict Retrieval to a Knowledge Type / Domain ... - /// - public string Type { get; set; } - - /// - /// Optional: Restrict Retrieval to a Specific File Name ... - /// - public string FileName { get; set; } - - /// - /// Optional: Max Retrieved Chunks ... - /// - public int? TopK { get; set; } - - /// - /// Optional: Minimum Cosine Similarity Score ... - /// - public float? MinScore { get; set; } - } - - /// - /// Ingested Document Info ... - /// - public class XAiKnowledgeDocumentInfo - { - /// - /// Scope ... - /// - public XAiKnowledgeScope Scope { get; set; } - - /// - /// Scope Identifier (Null for Global) ... - /// - public Guid? ScopeId { get; set; } - - /// - /// Knowledge Type ... - /// - public string Type { get; set; } - - /// - /// File Name ... - /// - public string FileName { get; set; } - - /// - /// Mime Type ... - /// - public string MimeType { get; set; } - - /// - /// Ingesting User Identifier ... - /// - public string OwnerId { get; set; } - - /// - /// Count of Stored Chunks ... - /// - public int ChunksCount { get; set; } - - /// - /// Ingestion Time (UTC) ... - /// - public DateTime? IngestedAtUtc { get; set; } - } - - /// - /// Public Vector Info (Export) ... - /// - 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 Metadata { get; set; } - - /// - /// Embedding (Only Filled when Requested) ... - /// - public float[] Embedding { get; set; } - } -} - - -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\xAiApi\Models\XAiMcpServerDescriptor.cs - -namespace xAiApi.Models -{ - /// - /// Describe an Mcp Server for Seeding ... - /// - 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\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\xAiApi\Models\XAiModelProxyConfiguration.cs - -namespace xAiApi.Models -{ - public class XAiModelProxyConfiguration - { - /// - /// Enable Proxy or not ... - /// - /// - public bool Enabled { get; set; } = false; - - /// - /// Proxy Prefix ... - /// - /// - public string RoutePrefix { get; set; } = "ai-model"; - } -} - -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\xAiApi\Models\XAiOCRDescriptor.cs - -using Tesseract; - -namespace xAiApi.Models -{ - public class XAiOCRDescriptor - { - /// - /// Provides Trained Data Path ... - /// - public string DataPath { get; set; } - - /// - /// The Engine for Doing OCR ... - /// - public EngineMode EngineMode { get; set; } - - /// - /// Enable OCR Fallback using Model ... - /// - public bool EnableOcrFallback { get; set; } - - /// - /// Default OCR Language ... - /// - public string DefaultLanguage { get; set; } - } -} - -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\xAiApi\Models\XAiTransciptDescriptor.cs - -namespace xAiApi.Models -{ - public class XAiTransciptDescriptor - { - public string Language { get; set; } - public string ModelsPath { get; set; } - } -} - -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\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\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\xAiApi\Models\XPreparedChatContext.cs - -using xAiModels.Models.Dtos; -using Microsoft.Extensions.AI; -using System.Collections.Generic; - -namespace xAiApi.Models -{ - /// - /// a Shared Context Between Actions for Generation ... - /// - public class XPreparedChatContext - { - /// - /// Specified Related Project, if Exists ... - /// - public XAiProjectDto Project { get; set; } = null; - - /// - /// Specified Related Conversation, if Exists ... - /// - public XAiConversationDto Conversation { get; set; } = null; - - /// - /// Specified Message History, if Exists ... - /// - public IList History { get; set; } = []; - - /// - /// Specified Vector Search Conext, if Exists ... - /// - public IList Context { get; set; } = []; - - /// - /// Specified Persisted Prompt, if Exists ... - /// - public XAiMessageDto PersistedPromptMessage { get; set; } = null; - } -} - -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\xAiApi\Models\XTextChunk.cs - -namespace xAiApi.Models -{ - /// - /// Represents a Chunk of a Text which Produced by Text Chunker ... - /// - public class XTextChunk - { - /// - /// Zero Based Index of Chunk in Source Text ... - /// - public int Index { get; set; } - - /// - /// Chunk Text Content ... - /// - public string Text { get; set; } = string.Empty; - - /// - /// Source Name (e.g. File Name) which Chunk Extracted From ... - /// - public string Source { get; set; } - - /// - /// Doc and Chunk Identifier (e.g. "file.pdf#3") ... - /// - public string Identifier { get; set; } - - /// - /// Start Offset of Chunk in Normalized Source Text ... - /// - public int StartOffset { get; set; } - - /// - /// Length of Chunk Text ... - /// - public int Length => Text?.Length ?? 0; - } -} - -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\xAiApi\Models\XTextChunkerDescriptor.cs - -namespace xAiApi.Models -{ - /// - /// Text Chunker Descriptor ... - /// - public class XTextChunkerDescriptor - { - /// - /// Maximum Characters Count of each Chunk ... - /// - public int ChunkSize { get; set; } = 800; - - /// - /// Characters Count which Shared between two Consecutive Chunks ... - /// - public int ChunkOverlap { get; set; } = 150; - - /// - /// Chunks Smaller than this Size will be Merged into Previous Chunk ... - /// - public int MinChunkSize { get; set; } = 50; - - /// - /// Chunck Identifier Separator ... - /// - public string ChunkIdentifierSeparator { get; set; } = "#"; - - /// - /// Normalize Line Endings and Repeated Whitespaces before Chunking ... - /// - public bool NormalizeWhitespace { get; set; } = true; - } -} - -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\xAiApi\Providers\XAiEmbeddingService.cs - -using xAiApi.Constants; -using xAiApi.Interfaces; -using xCommons.Providers; -using xAiModels.Interfaces; -using xAiApi.Configurations; -using Microsoft.Extensions.Logging; -using xAiApi.Interfaces.Extractors; - -namespace xAiApi.Providers -{ - public class XAiEmbeddingService : XAiEmbeddingServiceBase, IXAiEmbeddingService - { - public XAiEmbeddingService( - IXAiDataProvider dataProvider, - XAiApiConfiguration configuration, - ILogger logger, - XValidationProvider validationProvider, - IXFileContentExtractor fileContentExtractor - ) : base( - dataProvider, - configuration, - validationProvider, - logger, - fileContentExtractor, - XAiApiConstants.XAiEmbeddingModelName - ) - { } - } -} - -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\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 -{ - /// - /// Base Embedding Provider Service ... - /// - 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 logger; - private readonly IXFileContentExtractor fileContentExtractor; - - protected XAiEmbeddingServiceBase( - IXAiDataProvider dataProvider, - XAiApiConfiguration configuration, - XValidationProvider validationProvider, - ILogger 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; - } - - /// - /// Embedding Specified String ... - /// - /// - /// - /// - public virtual async Task Embedding( - string content, - CancellationToken cancellationToken = default - ) - { - // - // Validate ... - if (content.IsNullOrEmpty()) - { - XException.InvalidArgs.Throw(); - } - - // - var generator = GetEmbeddingGenerator(); - - // - GeneratedEmbeddings> 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; - } - - /// - /// Embedding Specified Batch ... - /// - /// - /// - /// - public virtual async Task> Embeddings( - string[] batch, - CancellationToken cancellationToken = default - ) - { - // - // Validate ... - if (!batch.HasChild() || - !batch.All(x => !x.IsNullOrEmpty()) - ) - { - XException.InvalidArgs.Throw(); - } - - // - using var generator = GetEmbeddingGenerator(); - - // - GeneratedEmbeddings> 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; - } - - /// - /// Embedding Generator ... - /// - /// - public IEmbeddingGenerator> GetEmbeddingGenerator() - { - // - IEmbeddingGenerator> 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\hkhazaeeasl\Documents\Projets\XProjects\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 xAiModels.Extensions; -using xExceptions.Constants; -using xAiModels.Models.Dtos; -using xIdentityModels.Models; -using System.Threading.Tasks; -using System.Linq.Expressions; -using xAiModels.Models.Entities; -using xAiModels.Interfaces.Dtos; -using xIdentityHelper.Extensions; -using System.Collections.Generic; -using xIdentityService.Interfaces; -using ModelContextProtocol.Client; -using Microsoft.Extensions.Logging; -using xAiModels.Interfaces.Entities; -using xAiModels.Interfaces.Enrichers; - -namespace xAiApi.Providers -{ - /// - /// MCP Manager / Provider ... - /// - public class XAiMcpServerProvider : IXAiMcpServerProvider, IAsyncDisposable - { - private readonly IXIdentityProvider identityProvider; - private readonly ILogger logger; - private readonly XValidationProvider validationProvider; - private readonly IXAiMcpServerEnricher mcpServerEnricher; - private readonly IXAiMcpServerServiceProvider mcpServerServiceProvider; - private readonly IXAiMcpServerRepositoryProvider mcpServerRepositoryProvider; - - private readonly Dictionary clients = []; - private readonly Dictionary mcpServers = []; - private readonly Dictionary> tools = []; - private readonly SemaphoreSlim initLock = new(1, 1); - private bool isInitialized = false; - - public XAiMcpServerProvider( - IXIdentityProvider identityProvider, - ILogger logger, - XValidationProvider validationProvider, - IXAiMcpServerEnricher mcpServerEnricher, - IXAiMcpServerServiceProvider mcpServerServiceProvider, - IXAiMcpServerRepositoryProvider mcpServerRepositoryProvider - ) - { - // - this.logger = logger; - 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 ... - /// - /// Get a List Of Available Tools which Provided using registered Mcp Servers ... - /// - /// - /// - /// - /// - public async Task> 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; - } - - // - // Check Initialization ... - if (isInitialized) - { - // - var selectedServers = mcpServers - .Where(s => - s.Value.OwnerId == userInfo.UserId || - s.Value.Scope == XAiMcpServerUsageScope.All - ) - .Select(s => s.Key); - var result = tools - .Where(c => selectedServers.Contains(c.Key)) - .SelectMany(c => c.Value); - return [.. result]; - } - - // - await initLock.WaitAsync(cancellationToken); - try - { - // - if (isInitialized) - { - // - var selectedServers = mcpServers - .Where(s => - s.Value.OwnerId == userInfo.UserId || - s.Value.Scope == XAiMcpServerUsageScope.All - ) - .Select(s => s.Key); - var result = tools - .Where(c => selectedServers.Contains(c.Key)) - .SelectMany(c => c.Value); - return [.. result]; - } - - // - var servers = await mcpServerServiceProvider - .FindManyAsync( - orderBuilder: null, - includeBuilder: null, - ignoreSoftDeleteds: true, - predicate: x => x.Enabled, - cancellationToken: cancellationToken - ); - if (servers.HasChild()) - { - // - var tasks = servers - .Select(s => - ConnectAndValidateAsync(s, cancellationToken)); - await Task.WhenAll(tasks); - } - - // - isInitialized = true; - return [.. tools.Values.SelectMany(t => t)]; - } - finally - { - initLock.Release(); - } - } - - /// - /// Test Specified Mcp Server ... - /// - /// - /// - /// - public async Task TestServerAsync( - XAiMcpServerDto server, - CancellationToken cancellationToken = default - ) - { - // - try - { - // - using var cts = CancellationTokenSource.CreateLinkedTokenSource(cancellationToken); - cts.CancelAfter(TimeSpan.FromSeconds(server.TimeoutSeconds)); - - // - var client = await CreateClientAsync(server, cts.Token); - 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} ..."; - } - } - - /// - /// Force Refresh Mcp Servers ... - /// - /// - public async Task RefreshAsync() - { - // - 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(cancellationToken: CancellationToken.None); - } - #endregion - - // - #region Actions ... - /// - /// Add an Mcp Server ... - /// - /// - /// - /// - /// - /// - public async Task 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 - ); - - // - await initLock.WaitAsync(cancellationToken); - try - { - await ConnectAndValidateAsync(result, cancellationToken); - } - finally - { - initLock.Release(); - } - } - - // - return result; - } - - /// - /// Update Specified Mcp Server ... - /// - /// - /// - /// - /// - /// - /// - public async Task 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 - ); - - // - await initLock.WaitAsync(cancellationToken); - try - { - // - // Remove Exists ... - tools.Remove(result.Id); - clients.Remove(result.Id); - mcpServers.Remove(result.Id); - - // - // Update ... - await ConnectAndValidateAsync(result, cancellationToken); - } - finally - { - initLock.Release(); - } - } - - // - return result; - } - - /// - /// Remove Specified Mcp Server ... - /// - /// - /// - /// - /// - /// - public async Task 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 - ); - - // - await initLock.WaitAsync(cancellationToken); - try - { - // - // Remove Exists ... - tools.Remove(result.Id); - clients.Remove(result.Id); - mcpServers.Remove(result.Id); - } - finally - { - initLock.Release(); - } - } - - // - return result; - } - - /// - /// Disable Specified Mcp Server ... - /// - /// - /// - /// - /// - /// - public async Task 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) - { - // - await initLock.WaitAsync(cancellationToken); - try - { - // - // Remove Exists ... - tools.Remove(exists.Id); - clients.Remove(exists.Id); - mcpServers.Remove(exists.Id); - } - finally - { - initLock.Release(); - } - } - - // - return result; - } - - /// - /// Enable Specified Mcp Server ... - /// - /// - /// - /// - /// - /// - public async Task 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) - { - // - await initLock.WaitAsync(cancellationToken); - try - { - await ConnectAndValidateAsync(exists, cancellationToken); - } - finally - { - initLock.Release(); - } - } - - // - return result; - } - - /// - /// Toggle Specified Mcp Server ... - /// - /// - /// - /// - /// - /// - public async Task 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) - { - // - await initLock.WaitAsync(cancellationToken); - try - { - if (exists.Enabled) - { - await ConnectAndValidateAsync(exists, cancellationToken); - } - else - { - // - // Remove Exists ... - tools.Remove(exists.Id); - clients.Remove(exists.Id); - mcpServers.Remove(exists.Id); - } - } - finally - { - initLock.Release(); - } - } - - // - return result; - } - - /// - /// Retrieve all Mcp Server ... - /// - /// - /// - /// - /// - public async Task> 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(); - Func, IOrderedQueryable> 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; - } - - /// - /// Find Specified Mcp Server ... - /// - /// - /// - /// - /// - /// - public async Task FindOne( - Expression> 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> 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; - } - - /// - /// Find a Collection of Specified Mcp Servers ... - /// - /// - /// - /// - /// - /// - public async Task> FindMany( - Expression> 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> 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; - } - - /// - /// Query Registered Mcp Servers ... - /// - /// - /// - /// - /// - /// - public async Task> 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> 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 ParseJsonDict(string json) - => json.IsNullOrEmpty() ? null - : JsonSerializer.Deserialize>(json); - - private static List ParseJsonList(string json) - => json.IsNullOrEmpty() ? null - : JsonSerializer.Deserialize>(json); - - private static async Task CreateClientAsync( - XAiMcpServerDto s, - CancellationToken cancellationToken - ) - { - // - IClientTransport transport = new HttpClientTransport(new HttpClientTransportOptions - { - Endpoint = new Uri(s.Endpoint!), - AdditionalHeaders = ParseJsonDict(s.Headers), - TransportMode = HttpTransportMode.AutoDetect - }); - - // - return await McpClient - .CreateAsync( - transport, - cancellationToken: cancellationToken - ); - } - - private async Task ConnectAndValidateAsync( - XAiMcpServerDto descriptor, - CancellationToken cancellationToken - ) - { - // - try - { - // - using var cts = CancellationTokenSource.CreateLinkedTokenSource(cancellationToken); - cts.CancelAfter(TimeSpan.FromSeconds(descriptor.TimeoutSeconds)); - - // - var client = await CreateClientAsync(descriptor, cts.Token); - await client.PingAsync(cancellationToken: cts.Token); - var serverTools = await client - .ListToolsAsync(cancellationToken: cts.Token); - - // - clients[descriptor.Id] = client; - tools[descriptor.Id] = serverTools; - mcpServers[descriptor.Id] = descriptor; - - // - logger.LogInformation( - "MCP '{Name}': {Count} Tools Detected ...", - descriptor.Name, - serverTools.Count - ); - } - catch (Exception ex) - { - // - logger.LogWarning(ex, - "MCP '{Name}': Connection Established Failed, Ignored ...", - descriptor.Name - ); - } - } - #endregion - } -} - -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\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 -{ - /// - /// 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 ... - /// - public class XAiRAGService : IXAiRAGService - { - private readonly IXTextChunker textChunker; - private readonly IXFileProvider fileProvider; - private readonly IXAiDataProvider dataProvider; - private readonly ILogger logger; - private readonly XAiApiConfiguration configuration; - private readonly IXAiEmbeddingService embeddingService; - private readonly IXFileContentExtractor fileContentExtractor; - - /// - /// Characters which are not Allowed in File Name Part of Identifier ... - /// - private static readonly char[] UnsafeFileNameChars = ['/', '\\', '#']; - - public XAiRAGService( - IXTextChunker textChunker, - IXFileProvider fileProvider, - IXAiDataProvider dataProvider, - ILogger 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 ... - /// - /// Ingest Files into Specified Knowledge Scope: - /// Extract -> Chunk -> Embed -> Store (XAiVector) ... - /// - /// - /// - /// - /// - /// - /// - /// - public async Task 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 ... - /// - /// Embed Prompt and Retrieve Relevant Chunks (Tiered: Conversation -> Project -> User -> Global) ... - /// Each Tier Fills Remaining TopK; Duplicates are Removed ... - /// - /// - /// - /// - /// - public async Task> 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(); - var seen = new HashSet(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 ... - /// - /// List Ingested Documents of Specified Scope ... - /// - /// - /// - /// - /// - public async Task> 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; - } - - /// - /// Remove All Vectors of a Document in Specified Scope ... - /// - /// - /// - /// - /// - /// - /// Count of Removed Vectors - public async Task 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; - } - - /// - /// 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 ... - /// - /// - /// - /// Count of Migrated Vectors - public async Task 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(); - 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; - } - - /// - /// Map Search Results to Public Sources ... - /// - /// - /// - public IList ToSources( - IEnumerable 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 ... - /// - /// Extract Plain Text of a File (Text or Audio Transcript) ... - /// - private async Task ExtractText( - IFormFile file, - string mimeType, - CancellationToken cancellationToken - ) - { - // - try - { - // - using var stream = file.OpenReadStream(); - var extraction = await fileContentExtractor.ExtractRichAsync( - fileStream: stream, - mimeType: mimeType, - fileName: file.FileName, - cancellationToken: cancellationToken - ); - - // - var result = extraction?.Text; - if (string.IsNullOrWhiteSpace(result)) - { - result = extraction?.AudioTranscript; - } - - // - return result; - } - catch (OperationCanceledException) - { - throw; - } - catch (Exception ex) - { - logger.LogWarning(ex, "Knowledge: Extraction Failed for {FileName}", file.FileName); - return null; - } - } - - /// - /// Embed Chunks in Batches and Build Vectors (with Scope Metadata) ... - /// - private async Task> EmbedChunks( - XAiKnowledgeScopeDescriptor scope, - IList chunks, - string type, - string ownerId, - string fileName, - string mimeType, - string ingestedAtUtc, - CancellationToken cancellationToken - ) - { - // - var rag = configuration.RAGDescriptor; - var batchSize = Math.Max(1, rag.EmbeddingBatchSize); - var result = new List(chunks.Count); - - // - for (var offset = 0; offset < chunks.Count; offset += batchSize) - { - // - cancellationToken.ThrowIfCancellationRequested(); - - // - var batch = chunks.Skip(offset).Take(batchSize).ToList(); - var embeddings = await embeddingService.Embeddings( - batch: batch.Select(c => c.Text).ToArray(), - cancellationToken: cancellationToken - ); - - // - if (embeddings.IsNullOrDefault() || embeddings.Count != batch.Count) - { - XException.ActionFailed.Throw(); - } - - // - for (var i = 0; i < batch.Count; i++) - { - // - var chunk = batch[i]; - result.Add(new XAiVectorDto - { - // - Type = type, - Text = chunk.Text, - Embedding = embeddings[i], - Identifier = chunk.Identifier, - Metadata = new Dictionary - { - [rag.MetadataFileName] = fileName, - [rag.MetadataMimeType] = mimeType, - [rag.MetadataChunkIndex] = chunk.Index.ToString(), - [XAiModelsConstants.XAiKnowledgeMetadataType] = type, - [XAiModelsConstants.XAiKnowledgeMetadataOwnerId] = ownerId, - [XAiModelsConstants.XAiKnowledgeMetadataScope] = scope.Scope.ToString(), - [XAiModelsConstants.XAiKnowledgeMetadataScopeId] = scope.ScopeId?.ToString("D") ?? string.Empty, - [XAiModelsConstants.XAiKnowledgeMetadataIngestedAtUtc] = ingestedAtUtc - } - }); - } - } - - // - return result; - } - - // - #region Scope ... - /// - /// Normalize Scope (Null => User, Clear ScopeId for User/Global, Require ScopeId for Project/Conversation) ... - /// - private 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; - } - - /// - /// Ensure Caller has Access to Scope: - /// User: Own Data | Global: Read = Everyone, Write = Admin - /// Project / Conversation: Caller must be Owner ... - /// - 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; - } - } - - /// - /// Ensure Caller Owns Project ... - /// - private async Task 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; - } - - /// - /// Ensure Caller Owns Conversation ... - /// - private async Task 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; - } - - /// - /// Resolve Retrieval Tiers (Ordered): Conversation -> Project -> User -> Global ... - /// - private async Task> ResolveTiers( - XAiKnowledgeAskRequest request, - XUserClaimsInfoDto userInfo, - CancellationToken cancellationToken - ) - { - // - var result = new List(); - 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; - } - - /// - /// Scope Prefix (Always Ends with Separator so "a" never Matches "ab"): - /// "conversation/{id}/" | "project/{id}/" | "user/{ownerId}/" | "global/" ... - /// - 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; - } - - /// - /// Document Chunk Prefix: "{scopePrefix}{fileName}#" ... - /// Separator Suffix Prevents "a.pdf" from Matching "a.pdf.bak" ... - /// - private string GetDocumentChunkPrefix( - string scopePrefix, - string fileName - ) - { - return $"{scopePrefix}{fileName}{configuration.TextChunker.ChunkIdentifierSeparator}"; - } - - /// - /// Normalize File Name for Identifier (Strip Client Path, Replace Separators) ... - /// - 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; - } - - /// - /// Load Distinct Document Names of a Scope ... - /// - private async Task> LoadDocumentNames( - string scopePrefix, - CancellationToken cancellationToken - ) - { - // - var vectors = await dataProvider.LoadVectorsAsync( - includeEmbedding: false, - identifierPrefix: scopePrefix, - cancellationToken: cancellationToken - ); - - // - var rag = configuration.RAGDescriptor; - var result = new HashSet( - (vectors ?? []) - .Select(v => v.Metadata.GetMetadata(rag.MetadataFileName)) - .Where(n => !n.IsNullOrEmpty()), - StringComparer.Ordinal - ); - - // - return result; - } - - /// - /// Is Valid User ... - /// - private static bool IsValidUser(XUserClaimsInfoDto userInfo) - { - return !userInfo.IsNullOrDefault() && !userInfo.UserId.IsNullOrEmpty(); - } - - /// - /// Is Caller Admin ... - /// - 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\hkhazaeeasl\Documents\Projets\XProjects\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 logger, - XAiApiConfiguration configuration, - XValidationProvider validationProvider, - IXFileContentExtractor fileContentExtractor - ) : base( - ragProvider, - dataProvider, - logger, - configuration, - validationProvider, - fileContentExtractor, - XAiApiConstants.XAiDefaultModelName - ) - { } - } -} - -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\xAiApi\Providers\XAIServiceBase.cs - -using System; -using System.Linq; -using xModels.Dtos; -using xAiApi.Models; -using System.Threading; -using xAiApi.Constants; -using xAiModels.Models; -using xAiApi.Interfaces; -using xAiApi.Extensions; -using xCommons.Providers; -using xCommons.Extensions; -using xAiModels.Constants; -using xAiModels.Interfaces; -using xAiModels.Extensions; -using xAiApi.Configurations; -using xExceptions.Constants; -using xAiModels.Models.Dtos; -using xAiService.Extensions; -using System.Threading.Tasks; -using xIdentityModels.Models; -using Microsoft.Extensions.AI; -using Microsoft.AspNetCore.Http; -using System.Collections.Generic; -using Microsoft.Extensions.Logging; -using xAiApi.Interfaces.Extractors; -using System.Runtime.CompilerServices; - -namespace xAiApi.Providers -{ - /// - /// Base Ai Service ... - /// - public abstract class XAIServiceBase : IXAiServiceBase - { - /// - /// Chat Options ... - /// - public ChatOptions Options { get; } - - /// - /// Descriptor of Models which used in Service ... - /// - public XAiModelDescriptor Descriptor { get; } - - private readonly IXAiRAGService ragProvider; - private readonly IXAiDataProvider dataProvider; - private readonly ILogger logger; - private readonly XAiApiConfiguration configuration; - private readonly XValidationProvider validationProvider; - private readonly IXFileContentExtractor fileContentExtractor; - - protected XAIServiceBase( - IXAiRAGService ragProvider, - IXAiDataProvider dataProvider, - ILogger logger, - XAiApiConfiguration configuration, - XValidationProvider validationProvider, - IXFileContentExtractor fileContentExtractor, - string model = null - ) - { - // - this.logger = logger; - this.ragProvider = ragProvider; - this.dataProvider = dataProvider; - this.configuration = configuration; - this.validationProvider = validationProvider; - this.fileContentExtractor = fileContentExtractor; - - // - // Prepare Embedding Model Descriptor ... - Descriptor = configuration.GetModel(model); - if (!Descriptor.IsValid()) - { - XException.InvalidConfiguration.Throw(); - } - - // - // Prepare Chat Options based On Tools ... - Options = new ChatOptions(); - } - - // - #region Actions ... - /// - /// Base Method for Communicate with LLM ... - /// - /// - /// - /// - public virtual async Task AskTextAsync( - string prompt, - CancellationToken cancellationToken = default - ) - { - // - // Check Prompt Exists ... - if (prompt.IsNullOrEmpty()) - { - XException.InvalidArgs.Throw(); - } - - // - using var client = Descriptor.GetClient(); - var history = GetHistory(prompt); - var response = await client.GetResponseAsync( - 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; - } - - /// - /// Base Method for Communicate with LLM ... - /// - /// - /// - /// - public virtual async IAsyncEnumerable AskTextAsEnumerable( - string prompt, - [EnumeratorCancellation] - CancellationToken cancellationToken = default - ) - { - // - // Check Prompt Exists ... - if (prompt.IsNullOrEmpty()) - { - XException.InvalidArgs.Throw(); - } - - // - using var client = Descriptor.GetClient(); - var history = GetHistory(prompt); - var enumerable = client.GetStreamingResponseAsync( - options: Options, - messages: history - ); - - // - await foreach (var res in enumerable) - { - // - // Cancellation Token ... - if (cancellationToken.IsCancellationRequested) - { - yield break; - } - - // - yield return res.Text; - } - } - - /// - /// Ask a Question By Providing Vector Search Result ... - /// - /// - /// - /// - /// - /// - public virtual async Task AskTextByContextAsync( - string prompt, - IList 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); - 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; - } - - /// - /// Ask a Question By By Providing Vector Search Result and Stream Response ... - /// - /// - /// - /// - /// - /// - public virtual async IAsyncEnumerable AskTextByContextAsEnumerable( - string prompt, - IList 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); - 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; - } - } - - /// - /// Ask a Question By Rag Retrive From Knowledge ... - /// - /// - /// - /// - /// - /// - /// - /// - public virtual async Task 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, - resolveConversation: false, - cancellationToken: cancellationToken - ); - - // - using var client = Descriptor.GetClient(); - var response = await client - .GetResponseAsync( - options: Options, - messages: prep.History, - cancellationToken: cancellationToken - ); - if (!response.IsValid()) - { - client.Dispose(); - XException.ActionFailed.Throw(); - } - - // - return response.Text; - } - - /// - /// Ask a Question By Rag Retrive From Knowledge and Stream Response ... - /// - /// - /// - /// - /// - /// - /// - /// - public virtual async IAsyncEnumerable 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, - resolveConversation: false, - cancellationToken: cancellationToken - ); - - // - using var client = Descriptor.GetClient(); - 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; - } - } - - /// - /// Ask a Question as Prompt and Retrieve Response ... - /// - /// - /// - /// - /// - /// - /// - /// - /// - /// - /// - /// - public virtual async Task AskAsync( - string prompt, - string type = null, - int? topK = null, - float? minScore = null, - Guid? projectId = null, - Guid? conversationId = null, - string connectionId = null, - IFormFileCollection files = null, - XUserClaimsInfoDto userInfo = null, - CancellationToken cancellationToken = default - ) - { - // - // Validate Args ... - validationProvider - .GroupValidationBuilder() - .AddNotEmpty(prompt) - .AddNotNull(userInfo) - .AddNotEmpty(userInfo.UserId) - .ValidateGroup(); - - // - var prep = await PrepareChatRequirementsAsync( - type: type, - topK: topK, - files: files, - prompt: prompt, - minScore: minScore, - userInfo: userInfo, - persistPrompt: true, - projectId: projectId, - resolveConversation: true, - connectionId: connectionId, - conversationId: conversationId, - cancellationToken: cancellationToken - ); - - // - using var client = Descriptor.GetClient(); - 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; - } - - /// - /// Ask a Question as Prompt and Retrieve Response as Async Enumerable ... - /// - /// - /// - /// - /// - /// - /// - /// - /// - /// - /// - /// - public virtual async IAsyncEnumerable AskAsEnumerable( - string prompt, - string type = null, - int? topK = null, - float? minScore = null, - Guid? projectId = null, - Guid? conversationId = null, - string connectionId = null, - IFormFileCollection files = null, - XUserClaimsInfoDto userInfo = null, - [EnumeratorCancellation] - CancellationToken cancellationToken = default - ) - { - // - // Validate Args ... - validationProvider - .GroupValidationBuilder() - .AddNotEmpty(prompt) - .AddNotNull(userInfo) - .AddNotEmpty(userInfo.UserId) - .ValidateGroup(); - - // - var prep = await PrepareChatRequirementsAsync( - type: type, - topK: topK, - files: files, - prompt: prompt, - minScore: minScore, - userInfo: userInfo, - persistPrompt: true, - projectId: projectId, - resolveConversation: true, - connectionId: connectionId, - conversationId: conversationId, - cancellationToken: cancellationToken - ); - - // - using var client = Descriptor.GetClient(); - 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 ... - /// - /// Load AI Projects ... - /// - /// - /// - /// - /// - /// - public virtual async Task> LoadProjects( - string ownerId, - string connectionId = null, - bool includeDefaults = false, - CancellationToken cancellationToken = default - ) - { - // - // Validate Args ... - if (ownerId.IsNullOrEmpty()) - { - XException.InvalidArgs.Throw(); - } - - // - var result = await dataProvider.LoadProjects( - ownerId: ownerId, - fillConversations: false, - connectionId: connectionId, - fillConversationMessages: false, - cancellationToken: cancellationToken - ); - - // - // Handle Defaults Including ... - if (includeDefaults) - { - // - // Here we have to fill Conversations of Default Project ... - var defaultProjectId = result.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; - } - - /// - /// Load Conversations of Specified AI Project ... - /// - /// - /// - /// - /// - public virtual async Task> LoadConversations( - Guid projectId, - string connectionId = null, - CancellationToken cancellationToken = default - ) - { - // - // Validate Args ... - if (projectId.IsDefaultGuid()) - { - XException.InvalidArgs.Throw(); - } - - // - var result = await dataProvider.LoadConversations( - fillMessages: false, - projectId: projectId, - connectionId: connectionId, - cancellationToken: cancellationToken - ); - - // - return result; - } - - /// - /// Load Messages of Specified Conversation ... - /// - /// - /// - /// - public virtual async Task> LoadMessages( - Guid conversationId, - CancellationToken cancellationToken = default - ) - { - // - // Validate Args ... - if (conversationId.IsDefaultGuid()) - { - XException.InvalidArgs.Throw(); - } - - // - var result = await dataProvider.LoadMessages( - conversationId: conversationId, - cancellationToken: cancellationToken - ); - - // - return result; - } - #endregion - - // - #region Queries ... - /// - /// Query Projects ... - /// - /// - /// - /// - /// - public virtual async Task> QueryProjects( - string ownerId, - XQuery query, - CancellationToken cancellationToken = default - ) - { - // - // Validate ... - if (ownerId.IsNullOrEmpty()) - { - XException.InvalidArgs.Throw(); - } - - // - var result = await dataProvider.QueryProjects( - query: query, - ownerId: ownerId, - cancellationToken: cancellationToken - ); - - // - return result; - } - - /// - /// Query Conversations ... - /// - /// - /// - /// - /// - /// - public virtual async Task> QueryConversations( - string ownerId, - Guid projectId, - XQuery query, - CancellationToken cancellationToken = default - ) - { - // - // Validate ... - if (ownerId.IsNullOrEmpty() || - projectId.IsDefaultGuid()) - { - XException.InvalidArgs.Throw(); - } - - // - // Retrieve Project ... - var project = await dataProvider.GetProject( - id: projectId, - fillConversations: false, - fillConversationMessages: false, - cancellationToken: cancellationToken - ); - if (project.IsNullOrDefault()) - { - XException.NotFound.Throw(); - } - - // - // Validate Owner ... - if (ownerId != project.OwnerId) - { - XException.NotAllowed.Throw(); - } - - // - var result = await dataProvider.QueryConversations( - query: query, - ownerId: ownerId, - projectId: projectId, - cancellationToken: cancellationToken - ); - - // - return result; - } - - /// - /// Query Messages ... - /// - /// - /// - /// - /// - /// - public virtual async Task> QueryMessages( - string ownerId, - Guid conversationId, - XQuery query, - CancellationToken cancellationToken = default - ) - { - // - // Validate ... - if (ownerId.IsNullOrEmpty() || - conversationId.IsDefaultGuid()) - { - XException.InvalidArgs.Throw(); - } - - // - // Retrieve Conversation ... - var conversation = await dataProvider.GetConversation( - id: conversationId, - fillMessages: false, - cancellationToken: cancellationToken - ); - if (conversation.IsNullOrDefault()) - { - XException.NotFound.Throw(); - } - - // - // Validate Owner ... - if (ownerId != conversation.OwnerId) - { - XException.NotAllowed.Throw(); - } - - // - var result = await dataProvider.QueryMessages( - query: query, - ownerId: ownerId, - conversationId: conversationId, - cancellationToken: cancellationToken - ); - - // - return result; - } - #endregion - - // - #region Creators ... - /// - /// Create an AI Project ... - /// - /// - /// - /// - /// - /// - public virtual async Task CreateProject( - string ownerId, - XAiProjectDto item, - string connectionId = null, - CancellationToken cancellationToken = default - ) - { - // - var result = await dataProvider.CreateProject( - item: item, - ownerId: ownerId, - connectionId: connectionId, - cancellationToken: cancellationToken - ); - - // - return result; - } - - /// - /// Create an AI Conversation ... - /// - /// - /// - /// - /// - /// - /// - public virtual async Task CreateConversation( - string ownerId, - Guid projectId, - XAiConversationDto item, - string connectionId = null, - CancellationToken cancellationToken = default - ) - { - // - var result = await dataProvider.CreateConversation( - item: item, - ownerId: ownerId, - projectId: projectId, - connectionId: connectionId, - cancellationToken: cancellationToken - ); - - // - return result; - } - #endregion - - // - #region Content Extraction ... - /// - /// Try to Extract Files Content ... - /// - /// - /// - /// - /// - public async Task ExtractContent( - IFormFileCollection files, - string[] extractors = null, - CancellationToken cancellationToken = default - ) - { - // - if (!files.HasChild()) - { - XException.InvalidArgs.Throw(); - } - - // - var extractionResults = new List(); - foreach (var file in files) - { - // - if (file.IsNull() || file.Length == 0) - { - continue; - } - - // - var mimeType = file.ContentType?.ToLowerInvariant() ?? string.Empty; - if (!fileContentExtractor.CanExtract(mimeType, extractors)) - { - continue; - } - - // - try - { - // - using var stream = file.OpenReadStream(); - - // - var fr = await fileContentExtractor.ExtractRichAsync( - fileStream: stream, - mimeType: mimeType, - extractors: extractors, - fileName: file.FileName, - cancellationToken: cancellationToken - ); - - // - if (fr.IsValid()) - { - extractionResults.Add(fr); - } - } - catch (OperationCanceledException) - { - throw; - } - catch - { - continue; - } - - // - // TODO: Implement File Save ... - } - - // - var result = string.Empty; - if (extractionResults.HasChild()) - { - // - extractionResults.ForEach(er => - { - result += $"File {er.FileName} Content:{Environment.NewLine}{er.Text ?? er.AudioTranscript}{Environment.NewLine}----"; - }); - } - - // - return result; - } - #endregion - - /// - /// Base Dispose Action ... - /// - /// - public virtual void Dispose() - { } - - // - #region Private ... - /// - /// Prepare a Message History List for LLM Communication based on Prompt ... - /// - /// - /// - /// - private IList GetHistory( - string prompt = null, - bool forcePrompt = true - ) - { - // - // Validate Args ... - if (prompt.IsNullOrEmpty()) - { - XException.InvalidArgs.Throw(); - } - - // - // User Prompt ... - var promptMessage = new ChatMessage( - ChatRole.User, - prompt - ); - - // - // Preparing Introduction Prompt ... - var introductionPrompt = new ChatMessage( - ChatRole.System, - configuration.GetPrompt() - ); - - // - List result = - [ - introductionPrompt, - ]; - if (forcePrompt && - prompt is not null && - !string.IsNullOrWhiteSpace(prompt)) - { - result.Add(promptMessage); - } - - // - return result; - } - - /// - /// Build Chat History for RAG: - /// [System: Introduction + ChatWithDocuments Prompt + Context Block] + [User: Prompt] ... - /// - /// - /// - /// - private IList GetHistory( - string prompt, - IEnumerable context - ) - { - // - var introductionPrompt = configuration.GetPrompt(); - var ragPrompt = configuration.GetPrompt(XAiApiConstants.XAiApiRagPromptName); - if (ragPrompt.IsNullOrEmpty()) - { - XException.InvalidConfiguration.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}"; - } - - // - List result = - [ - new ChatMessage(ChatRole.System, systemText), - new ChatMessage(ChatRole.User, prompt), - ]; - - // - return result; - } - - /// - /// Implementing Memory Strategy here ... - /// - /// - /// - /// - /// - /// - private async Task> PrepareMemory( - XAiProjectDto project, - IEnumerable messages, - IEnumerable context = null, - CancellationToken cancellationToken = default - ) - { - // - var result = new List(); - - // - // Retrieve Introduction Prompt ... - var ragPrompt = configuration.GetPrompt(XAiApiConstants.XAiApiRagPromptName); - var introductionPrompt = configuration.GetPrompt(XAiApiConstants.XAiApiIntroductionPromptName); - if (ragPrompt.IsNullOrEmpty() || - introductionPrompt.IsNullOrEmpty() - ) - { - XException.InvalidData.Throw(); - } - - // - var contextBlock = BuildContextBlock(context); - var systemText = introductionPrompt; - if (context.HasChild() && - !contextBlock.IsNullOrEmpty()) - { - // - systemText = - $"{introductionPrompt}{Environment.NewLine}{Environment.NewLine}" + - $"{ragPrompt}{Environment.NewLine}{Environment.NewLine}" + - $"Context:{Environment.NewLine}{contextBlock}"; - } - - // - // Apply Project Prompt as System Text ... - if (!project.IsNullOrDefault() && - !project.Prompt.IsNullOrEmpty()) - { - systemText += $"{project.Prompt}{Environment.NewLine}"; - } - - // - // Add System Message ... - result.Add(new ChatMessage(ChatRole.System, systemText)); - - // - // Attach Message ... - if (messages.HasChild()) - { - // - // TODO: Here we can Implement Memory Management based on - // Last nth of Messages, or Summarization of Messages, etc ... - result = [..result, ..messages - .OrderBy(m => m.CreatedOn) - .Select(m => m.ToChatMessages())]; - } - - // - return result; - } - - /// - /// Convert Context Chunks to a Numbered Text Block ... - /// - /// - /// - private string BuildContextBlock( - IEnumerable context - ) - { - // - var result = "(no context)"; - - // - var items = context? - .Where(c => - !c.IsNullOrDefault() && - !c.Text.IsNullOrEmpty() - ) - .ToList() ?? []; - if (!items.HasChild()) - { - return result; - } - - // - var index = 1; - var builder = new System.Text.StringBuilder(); - foreach (var item in items) - { - // - var identifier = item.Identifier.IsNullOrEmpty() - ? item.Id.ToString() - : item.Identifier; - - // - builder.AppendLine($"[{index}] Source: [{identifier}] (score: {item.Score:0.000})"); - builder.AppendLine(item.Text.Trim()); - builder.AppendLine("----"); - - // - index++; - } - - // - result = builder.ToString(); - - // - return result; - } - - /// - /// Normalizing Rag Params ... - /// - /// - /// - /// - private void NormalizeRagParams( - ref int? topK, - ref float? minScore, - ref string type - ) - { - // - var rag = configuration.RAGDescriptor; - - // - // TopK ... - if (!topK.HasValue || topK.Value < 1) - { - topK = rag.DefaultTopK; - } - else if (topK.Value > rag.MaxTopK) - { - topK = rag.MaxTopK; - } - - // - // Min Score ... - if (!minScore.HasValue || minScore.Value < 0 || minScore.Value > 1) - { - minScore = rag.DefaultMinScore; - } - - // - // Type ... - if (type.IsNullOrEmpty()) - { - type = XAiModelsConstants.XAiDefaultKnowledgeType; - } - } - - /// - /// Retrieve Prepared Chat Context ... - /// - /// - /// - /// - /// - /// - /// - /// - /// - /// - /// - /// - /// - /// - private async Task PrepareChatRequirementsAsync( - int? topK, - string type, - string prompt, - float? minScore, - Guid? projectId, - bool persistPrompt, - string connectionId, - Guid? conversationId, - bool resolveConversation, - IFormFileCollection files, - XUserClaimsInfoDto userInfo, - IList additionalContents = null, - CancellationToken cancellationToken = default - ) - { - // - // 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 - ) - { - // - try - { - // - var ingestResult = await ragProvider - .IngestAsync( - files: files, - userInfo: userInfo, - replaceExisting: true, - connectionId: connectionId, - scope: XAiKnowledgeScopeDescriptor - .Conversation( - type: type, - conversationId: conversationId.Value - ), - cancellationToken: cancellationToken - ); - if (ingestResult.SkippedFiles.HasChild()) - { - // - logger.LogWarning( - "Ingest skipped {Count} file(s): {Files}", - ingestResult.SkippedFiles.Count, - string.Join(", ", ingestResult.SkippedFiles)); - } - } - catch (OperationCanceledException) - { - throw; - } - catch (Exception ex) - { - // - logger.LogError(ex, - "Ingest failed for prompt '{Prompt}'. Continuing without attachments.", - prompt - ); - } - } - - // - // Request Knowledge ... - var knowledgeRequest = new XAiKnowledgeAskRequest - { - TopK = topK, - Type = type, - Prompt = prompt, - IncludeUser = true, - MinScore = minScore, - IncludeGlobal = true, - ProjectId = resolveConversation ? projectId : null, - ConversationId = resolveConversation ? conversationId : null, - }; - var context = await ragProvider - .RetrieveAsync( - userInfo: userInfo, - request: knowledgeRequest, - cancellationToken: cancellationToken - ); - - // - // Prepare History and Persisted Prompt Message ... - IList 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; - } - #endregion - } -} - -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\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 logger, - XAiApiConfiguration configuration, - XValidationProvider validationProvider, - IXFileContentExtractor fileContentExtractor, - ReasoningEffort effort = ReasoningEffort.Medium, - ReasoningOutput output = ReasoningOutput.Full - ) : base( - ragProvider, - dataProvider, - logger, - configuration, - validationProvider, - fileContentExtractor, - XAiApiConstants.XAiDefaultThinkingModelName - ) - { - // - // Preparing Reasoning ... - Options.Reasoning = new ReasoningOptions - { - Output = output, - Effort = effort, - }; - } - } -} - -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\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 sessions = new ConcurrentDictionary(); - 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 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 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 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 Search( - Guid sessionId, - ReadOnlyMemory queryEmbedding, - int topK = 5, - float minScore = 0f, - string ownerId = null - ) - { - // - var result = new List(); - 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 Copy( - IEnumerable vectors - ) - { - return vectors == null ? new List() : vectors.Where(x => x != null).ToList(); - } - #endregion - } -} - -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\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 -{ - /// - /// Periodically Removes Expired Document Sessions from In-Memory Vector Store ... - /// - public class XInMemoryVectorStoreCleanupService : BackgroundService - { - /// - /// Default Cleanup Interval ... - /// - public static readonly TimeSpan DefaultInterval = TimeSpan.FromMinutes(5); - - private readonly TimeSpan interval; - private readonly IXInMemoryVectorStore vectorStore; - private readonly ILogger logger; - - public XInMemoryVectorStoreCleanupService( - IXInMemoryVectorStore vectorStore, - ILogger logger - ) - { - this.logger = logger; - this.vectorStore = vectorStore; - this.interval = DefaultInterval; - } - - /// - /// Cleanup Loop ... - /// - /// - /// - 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\hkhazaeeasl\Documents\Projets\XProjects\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 -{ - /// - /// Splits Long Texts into Overlapping Chunks using a Hierarchical Strategy: - /// Paragraphs -> Sentences -> Words -> Hard Cut ... - /// - public class XTextChunker : IXTextChunker - { - /// - /// Default Options which used when no Options Provided ... - /// - private readonly XAiApiConfiguration configuration; - - /// - /// Matches Paragraph Boundaries (two or more Line Breaks) ... - /// - private static readonly Regex ParagraphSplitter = new( - @"\n\s*\n+", - RegexOptions.Compiled - ); - - /// - /// Matches Sentence Boundaries, Supports Latin, Persian and CJK Terminators ... - /// - private static readonly Regex SentenceSplitter = new( - @"(?<=[\.\!\?؟。!?])\s+|(?<=\n)", - RegexOptions.Compiled - ); - - /// - /// Matches Repeated Horizontal Whitespaces ... - /// - private static readonly Regex HorizontalWhitespace = new( - @"[ \t\f\v\u00A0]{2,}", - RegexOptions.Compiled - ); - - /// - /// Matches Three or more Line Breaks ... - /// - 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; - } - - /// - /// Split Text into Chunks ... - /// - /// - /// - /// - public IList Chunk( - string text, - string source = null - ) - { - // - var result = new List(); - 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; - } - - /// - /// Split Text into Chunks and Return only Texts ... - /// - /// - /// - public IList ChunkTexts(string text) - { - // - var result = Chunk(text, null) - .Select(c => c.Text) - .ToList(); - - // - return result; - } - - // - #region Private ... - /// - /// Internal Text Unit with its Offset in Normalized Source ... - /// - private readonly struct Unit - { - public Unit(string text, int offset) - { - Text = text; - Offset = offset; - } - - public string Text { get; } - public int Offset { get; } - } - - /// - /// Normalize Line Endings and Whitespaces ... - /// - /// - /// - 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; - } - - /// - /// Create Chunk Model ... - /// - /// - /// - /// - /// - /// - 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; - } - - /// - /// Split Text into Atomic Units; each Unit Guaranteed to fit in ChunkSize ... - /// - /// - /// - private List BuildUnits(string text) - { - // - var result = new List(); - - // - 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; - } - - /// - /// Split Text by Regex while Tracking Offsets, Skipping Empty Parts ... - /// - /// - /// - /// - /// - private IEnumerable 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; - } - } - } - - /// - /// Trim Unit Text while Adjusting its Offset ... - /// - /// - /// - /// - 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; - } - - /// - /// Cut a Unit into Pieces no Longer than Max Size, Preferring Whitespace Boundaries ... - /// - /// - /// - /// - private IEnumerable 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++; - } - } - } - - /// - /// Accumulate Units into Chunks up to ChunkSize, Carrying Overlap to Next Chunk ... - /// - /// - /// - private List Accumulate(List units) - { - // - var result = new List(); - if (!units.HasChild()) - { - return result; - } - - // - var buffer = new StringBuilder(); - var buffered = new List(); - 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; - } - - /// - /// Map Trailing Overlap Length of Buffered Units back to Source Offset ... - /// Units Joined by Single Space Separator in Buffer ... - /// - /// - /// - /// - private int ComputeOverlapOffset( - List 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; - } - - /// - /// Take Trailing Overlap from Text, Aligned to Word Boundary ... - /// - /// - /// - /// - 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(); - } - - /// - /// Merge Chunks Smaller than MinChunkSize into their Predecessor ... - /// - /// - /// - private List MergeSmallChunks(List chunks) - { - // - if (configuration.TextChunker.MinChunkSize <= 0 || chunks.Count < 2) - { - return chunks; - } - - // - var result = new List(); - 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; - } - - /// - /// Characters Considered as Word Boundaries ... - /// - private readonly char[] WordBoundaries = [' ', '\n', '\t']; - #endregion - } -} - -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\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 -{ - /// - /// Extracts text content from Audio files ... - /// - public class XAudioFileContentExtractor : IXAudioFileContentExtractor - { - /// - /// Supported MIME Types ... - /// - 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; - } - - /// - /// Check if this extractor supports the specified MIME type ... - /// - public bool CanExtract(string mimeType) - { - // - return SupportedMimeTypes.Contains( - mimeType?.ToLowerInvariant() ?? string.Empty - ); - } - - /// - /// Extract text content from file stream ... - /// - public async Task ExtractAsync( - Stream fileStream, - string mimeType, - CancellationToken cancellationToken = default - ) - { - // - var result = await ExtractRichAsync( - fileStream, - "audio", - mimeType, - cancellationToken - ); - - // - return result.AudioTranscript; - } - - /// - /// Extract content from stream as Rich Result ... - /// - /// - /// - /// - /// - /// - public async Task 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 ... - /// - /// Audio Format Converting to WAV 16kHz Mono 16-bit PCM ... - /// - private async Task 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; - } - - /// - /// Retrieve File Extension based on mime type ... - /// - /// - /// - 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\hkhazaeeasl\Documents\Projets\XProjects\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 -{ - /// - /// Extractor for source code files ... - /// (C#, Python, JavaScript, TypeScript, Java, Go, Rust, ...) - /// - public class XCodeFileContentExtractor : IXCodeFileContentExtractor - { - /// - /// Supported MIME Types ... - /// - 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", - ]; - - /// - /// Check if this extractor supports the specified MIME type ... - /// - /// - /// - public bool CanExtract(string mimeType) - { - // - return SupportedMimeTypes.Contains( - mimeType?.ToLowerInvariant() ?? string.Empty - ); - } - - /// - /// Extract text content from file stream ... - /// - /// - /// - /// - /// - public async Task ExtractAsync( - Stream fileStream, - string mimeType, - CancellationToken cancellationToken = default - ) - { - // - var result = await ExtractRichAsync( - fileStream, - string.Empty, - mimeType, - cancellationToken - ); - - // - return result.Text; - } - - /// - /// Extract content from stream as Rich Result ... - /// - /// - /// - /// - /// - /// - public async Task 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\hkhazaeeasl\Documents\Projets\XProjects\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 -{ - /// - /// Extracts text content from DOCX files using DocumentFormat.OpenXml ... - /// - public class XDocxFileContentExtractor : IXDocxFileContentExtractor - { - /// - /// Supported MIME Types ... - /// - private static readonly string[] SupportedMimeTypes = - [ - "application/vnd.openxmlformats-officedocument.wordprocessingml.document" - ]; - - /// - /// Check if this extractor supports the specified MIME type ... - /// - public bool CanExtract(string mimeType) - { - // - return SupportedMimeTypes.Contains( - mimeType?.ToLowerInvariant() ?? string.Empty - ); - } - - /// - /// Extract text content from file stream ... - /// - public async Task 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(); - foreach (var paragraph in paragraphs) - { - // - var text = paragraph.InnerText?.Trim(); - if (!string.IsNullOrEmpty(text)) - { - stringBuilder.AppendLine(text); - } - } - } - } - - // - return stringBuilder.ToString(); - } - - /// - /// Extract content from stream as Rich Result ... - /// - /// - /// - /// - /// - /// - public async Task 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\hkhazaeeasl\Documents\Projets\XProjects\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 -{ - /// - /// Extractor for EPUB electronic publication format - /// (application/epub+zip) - /// - public class XEpubFileContentExtractor : IXEpubFileContentExtractor - { - /// - /// Supported MIME Types ... - /// - private static readonly string[] SupportedMimeTypes = - [ - "application/epub+zip" - ]; - - /// - /// Check if this extractor supports the specified MIME type ... - /// - /// - /// - public bool CanExtract(string mimeType) - { - // - return SupportedMimeTypes.Contains( - mimeType?.ToLowerInvariant() ?? string.Empty - ); - } - - /// - /// Extract text content from file stream ... - /// - /// - /// - /// - /// - public async Task ExtractAsync( - Stream fileStream, - string mimeType, - CancellationToken cancellationToken = default - ) - { - // - var result = await ExtractRichAsync( - fileStream, - "book.epub", - mimeType, - cancellationToken - ); - - // - return result.Text; - } - - /// - /// Extract content from stream as Rich Result ... - /// - /// - /// - /// - /// - /// - public async Task 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; - } - - /// - /// Extract Epub Content ... - /// - /// - /// - /// - private async Task 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; - } - - /// - /// Extract Text Content from HTML ... - /// - /// - /// - 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\hkhazaeeasl\Documents\Projets\XProjects\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 - { - /// - /// Supported MIME Types ... - /// - private static readonly string[] SupportedMimeTypes = - [ - "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet", // .xlsx - "application/vnd.ms-excel" // .xls - ]; - - /// - /// Check if this extractor supports the specified MIME type ... - /// - public bool CanExtract(string mimeType) - { - // - return SupportedMimeTypes.Contains( - mimeType?.ToLowerInvariant() ?? string.Empty - ); - } - - /// - /// Extract text content from file stream ... - /// - public async Task 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(); - } - - /// - /// Extract content from stream as Rich Result ... - /// - /// - /// - /// - /// - /// - public async Task 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\hkhazaeeasl\Documents\Projets\XProjects\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 -{ - /// - /// Composite extractor that delegates to appropriate extractor - /// based on MIME type ... - /// - public class XFileContentExtractor : IXFileContentExtractor - { - // - private readonly IList _extractors = []; - - public XFileContentExtractor( - IEnumerable availableExtractors - ) - { - // - _extractors = [.. availableExtractors - .Where(e => e.GetType() != typeof(XFileContentExtractor))]; - } - - /// - /// Check if this extractor supports the specified MIME type ... - /// - /// - /// - /// - public bool CanExtract( - string mimeType, - string[] extractors = null - ) - { - // - return GetExtractors(extractors) - .Any(e => e.CanExtract(mimeType)); - } - - /// - /// Extract text content from file stream ... - /// - /// - /// - /// - /// - /// - public async Task 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; - } - - /// - /// Extract content from stream as Rich Result ... - /// - /// - /// - /// - /// - /// - /// - public async Task 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; - } - - /// - /// Extract Provided Extractors ... - /// - /// - /// - private IList GetExtractors(string[] extractors = null) - { - // - var result = new List(); - - // - 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\hkhazaeeasl\Documents\Projets\XProjects\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 -{ - /// - /// Extractor for HTML documents (text/html, application/xhtml+xml) - /// - public class XHtmlFileContentExtractor : IXHtmlFileContentExtractor - { - /// - /// Supported MIME Types ... - /// - private static readonly string[] SupportedMimeTypes = - [ - "text/html", - "application/xhtml+xml" - ]; - - /// - /// Check if this extractor supports the specified MIME type ... - /// - /// - /// - public bool CanExtract(string mimeType) - { - // - return SupportedMimeTypes.Contains( - mimeType?.ToLowerInvariant() ?? string.Empty - ); - } - - /// - /// Extract text content from file stream ... - /// - /// - /// - /// - /// - public async Task ExtractAsync( - Stream fileStream, - string mimeType, - CancellationToken cancellationToken = default - ) - { - // - var result = await ExtractRichAsync( - fileStream, - "document.html", - mimeType, - cancellationToken - ); - - // - return result.Text; - } - - /// - /// Extract content from stream as Rich Result ... - /// - /// - /// - /// - /// - /// - public async Task 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; - } - - /// - /// Extract Html Content as Text ... - /// - /// - /// - /// - private async Task 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(); - } - - /// - /// Remove Noisy Nodes ... - /// - /// - 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(); - } - } - } - - /// - /// Extract Title ... - /// - /// - /// - private string ExtractTitle(HtmlDocument html) - { - // - var titleNode = html.DocumentNode - .SelectSingleNode("//title"); - - // - var result = titleNode?.InnerText?.Trim() ?? string.Empty; - - // - return result; - } - - /// - /// Clean Text ... - /// - /// - /// - 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\hkhazaeeasl\Documents\Projets\XProjects\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 - { - /// - /// Supported MIME Types ... - /// - private static readonly string[] SupportedMimeTypes = - [ - "image/png", - "image/jpeg", - "image/jpg", - "image/gif", - "image/webp", - "image/bmp" - ]; - - /// - /// AI Api Configuration ... - /// - 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; - } - - /// - /// Check if this extractor supports the specified MIME type ... - /// - public bool CanExtract(string mimeType) - { - // - return SupportedMimeTypes.Contains( - mimeType?.ToLowerInvariant() ?? string.Empty - ); - } - - /// - /// Extract text content from file stream ... - /// - public async Task ExtractAsync( - Stream fileStream, - string mimeType, - CancellationToken cancellationToken = default - ) - { - // - var result = await ExtractRichAsync( - fileStream, - "image", - mimeType, - cancellationToken - ); - - // - return result.Text; - } - - /// - /// Extract content from stream as Rich Result ... - /// - /// - /// - /// - /// - /// - public async Task 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; - } - - /// - /// Do OCR on Image for Text Extraction ... - /// - private async Task 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\hkhazaeeasl\Documents\Projets\XProjects\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 -{ - /// - /// Extractor for OpenDocument Format (ODF) documents - /// (ODT: OpenDocument Text, ODS: OpenDocument Spreadsheet, ODP: OpenDocument Presentation) - /// - public class XOpenDocumentFileContentExtractor : IXOpenDocumentFileContentExtractor - { - /// - /// Supported MIME Types ... - /// - private static readonly string[] SupportedMimeTypes = - [ - "application/vnd.oasis.opendocument.text", // .odt - "application/vnd.oasis.opendocument.spreadsheet", // .ods - "application/vnd.oasis.opendocument.presentation" // .odp - ]; - - /// - /// Check if this extractor supports the specified MIME type ... - /// - /// - /// - public bool CanExtract(string mimeType) - { - // - return SupportedMimeTypes.Contains( - mimeType?.ToLowerInvariant() ?? string.Empty - ); - } - - /// - /// Extract text content from file stream ... - /// - public async Task ExtractAsync( - Stream fileStream, - string mimeType, - CancellationToken cancellationToken = default - ) - { - // - var result = await ExtractRichAsync( - fileStream, - "document.rtf", - mimeType, - cancellationToken - ); - - // - return result.Text; - } - - /// - /// Extract content from stream as Rich Result ... - /// - /// - /// - /// - /// - /// - public async Task 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; - } - - /// - /// Check Mime Type ... - /// - /// - /// - private bool IsOdt(string mimeType) - { - // - var result = mimeType? - .ToLowerInvariant() == "application/vnd.oasis.opendocument.text"; - - // - return result; - } - - /// - /// Check Mime Type ... - /// - /// - /// - private bool IsOds(string mimeType) - { - // - var result = mimeType? - .ToLowerInvariant() == "application/vnd.oasis.opendocument.spreadsheet"; - - // - return result; - } - - /// - /// Check Mime Type ... - /// - /// - /// - private bool IsOdp(string mimeType) - { - // - var result = mimeType? - .ToLowerInvariant() == "application/vnd.oasis.opendocument.presentation"; - - // - return result; - } - - /// - /// Extract ODT File Content ... - /// - /// - /// - /// - private async Task 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(); - 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; - } - - /// - /// Extract ODS File Content ... - /// - /// - /// - /// - private async Task 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(); - 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; - } - - /// - /// Extract ODS File Content ... - /// - /// - /// - /// - private async Task 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(); - - // - 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\hkhazaeeasl\Documents\Projets\XProjects\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 -{ - /// - /// Extracts content from PDF files using PdfPig ... - /// - public class XPdfFileContentExtractor : IXPdfFileContentExtractor - { - /// - /// Supported MIME Types ... - /// - private static readonly string[] SupportedMimeTypes = - [ - "application/pdf" - ]; - - /// - /// Api Configuration ... - /// - private readonly XAiApiConfiguration configuration; - - public XPdfFileContentExtractor(XAiApiConfiguration configuration) - { - this.configuration = configuration; - } - - /// - /// Check if this extractor supports the specified MIME type ... - /// - /// - /// - public bool CanExtract(string mimeType) - { - // - return SupportedMimeTypes.Contains( - mimeType?.ToLowerInvariant() ?? string.Empty - ); - } - - /// - /// Extract text content from file stream ... - /// - /// - /// - /// - /// - public async Task ExtractAsync( - Stream fileStream, - string mimeType, - CancellationToken cancellationToken = default - ) - { - // - var result = await ExtractRichAsync( - fileStream, - "document.pdf", - mimeType, - cancellationToken - ); - - // - return result.Text; - } - - /// - /// Extract content from stream as Rich Result ... - /// - /// - /// - /// - /// - /// - public async Task 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; - } - - /// - /// Extract Text From PDF Files using Common way ... - /// - /// - /// - /// - private async Task 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; - } - - /// - /// Check Extracted Content is Sufficient or not ... - /// if not try to Falling Back using Images ... - /// - /// - /// - 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; - } - - /// - /// Fallback Converts PDF Pages to Images ... - /// - /// - /// - /// - /// - /// - private async Task 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\hkhazaeeasl\Documents\Projets\XProjects\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 -{ - /// - /// Extracts content from plain text files (txt, md, csv, json, xml) ... - /// - public class XPlainTextFileContentExtractor : IXPlainTextFileContentExtractor - { - /// - /// Supported MIME Types ... - /// - private static readonly string[] SupportedMimeTypes = - [ - "text/plain", - "text/markdown", - "text/csv", - "text/xml", - "application/json", - "application/xml" - ]; - - /// - /// Check if this extractor supports the specified MIME type ... - /// - /// - /// - public bool CanExtract(string mimeType) - { - // - return SupportedMimeTypes.Contains( - mimeType?.ToLowerInvariant() ?? string.Empty - ); - } - - /// - /// Extract text content from file stream ... - /// - public async Task ExtractAsync( - Stream fileStream, - string mimeType, - CancellationToken cancellationToken = default - ) - { - // - using var reader = new StreamReader(fileStream); - return await reader.ReadToEndAsync(); - } - - /// - /// Extract content from stream as Rich Result ... - /// - /// - /// - /// - /// - /// - public async Task 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\hkhazaeeasl\Documents\Projets\XProjects\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 -{ - /// - /// Extracts content from all PowerPoint formats - /// (OpenXML: pptx/ppsx/potx/pptm/ppsm/potm | Legacy Binary: ppt/pps/pot) - /// - public class XPowerPointFileContentExtractor : IXPowerPointFileContentExtractor - { - /// - /// Supported MIME Types ... - /// - 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" - ]; - - /// - /// Check if this extractor supports the specified MIME type ... - /// - public bool CanExtract(string mimeType) - { - // - return SupportedMimeTypes.Contains( - mimeType?.ToLowerInvariant() ?? string.Empty - ); - } - - /// - /// Extract text content from file stream ... - /// - public async Task ExtractAsync( - Stream fileStream, - string mimeType, - CancellationToken cancellationToken = default - ) - { - // - var result = await ExtractRichAsync( - fileStream: fileStream, - fileName: "presentation", - mimeType: mimeType, - cancellationToken: cancellationToken - ); - return result.Text; - } - - /// - /// Extract content from stream as Rich Result ... - /// - /// - /// - /// - /// - /// - public async Task 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; - } - - /// - /// Check Open XML Format ... - /// - /// - /// - 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; - } - - /// - /// Check Legacy Format ... - /// - /// - /// - private bool IsLegacyFormat(string mimeType) - { - // - var result = mimeType?.ToLowerInvariant() == "application/vnd.ms-powerpoint"; - return result; - } - - /// - /// Extract an Slide Title ... - /// - /// - /// - private string GetSlideTitle(SlidePart slidePart) - { - // - var result = string.Empty; - - // - // Title placeholder has specific type - var titleShape = slidePart.Slide - .Descendants() - .FirstOrDefault(s => s.NonVisualShapeProperties? - .NonVisualDrawingProperties? - .Name?.Value? - .StartsWith("Title", StringComparison.OrdinalIgnoreCase) == true - ); - if (titleShape != null) - { - // - var titleText = titleShape - .Descendants() - .Select(t => t.Text?.Trim()) - .Where(t => !string.IsNullOrWhiteSpace(t)); - result = string.Join(" ", titleText); - } - - // - return result; - } - - /// - /// Extract Speaker Notes ... - /// - /// - /// - private string GetSpeakerNotes(SlidePart slidePart) - { - // - var result = string.Empty; - - // - var notesSlidePart = slidePart.NotesSlidePart; - if (notesSlidePart?.NotesSlide == null) - { - return result; - } - - // - var notesTexts = notesSlidePart.NotesSlide - .Descendants() - .Select(t => t.Text?.Trim()) - .Where(t => !string.IsNullOrWhiteSpace(t)) - .ToList(); - - // - result = notesTexts.Count > 0 - ? string.Join(Environment.NewLine, notesTexts) - : null; - - // - return result; - } - - /// - /// Extract OpenXML Tables ... - /// - /// - /// - private static string ExtractOpenXmlTables(SlidePart slidePart) - { - // - var sb = new StringBuilder(); - - // - var tableElements = slidePart.Slide - .Descendants(); - - // - var tableIndex = 0; - foreach (var table in tableElements) - { - // - tableIndex++; - sb.AppendLine($" Table {tableIndex}:"); - - // - foreach (var row in table - .Descendants()) - { - // - var cells = row - .Descendants() - .Select(c => string.Join(" ", c - .Descendants() - .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; - } - - /// - /// Extract Open XML Format ... - /// - /// - /// - /// - private async Task 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() - .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; - } - - /// - /// Extract Legacy Format ... - /// - /// - /// - /// - private async Task 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(); - 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\hkhazaeeasl\Documents\Projets\XProjects\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 -{ - /// - /// Extractor for Rich Text Format (RTF) documents - /// (application/rtf, text/rtf) - /// - public class XRtfFileContentExtractor : IXRtfFileContentExtractor - { - /// - /// Supported MIME Types ... - /// - private static readonly string[] SupportedMimeTypes = - [ - "text/rtf", - "application/rtf", - ]; - - /// - /// Check if this extractor supports the specified MIME type ... - /// - /// - /// - public bool CanExtract(string mimeType) - { - // - return SupportedMimeTypes.Contains( - mimeType?.ToLowerInvariant() ?? string.Empty - ); - } - - /// - /// Extract text content from file stream ... - /// - /// - /// - /// - /// - public async Task ExtractAsync( - Stream fileStream, - string mimeType, - CancellationToken cancellationToken = default - ) - { - // - var result = await ExtractRichAsync( - fileStream, - "document.rtf", - mimeType, - cancellationToken - ); - - // - return result.Text; - } - - /// - /// Extract content from stream as Rich Result ... - /// - /// - /// - /// - /// - /// - public async Task 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; - } - - /// - /// Extract RTF Content ... - /// - /// - /// - /// - private async Task 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; - } - - /// - /// Converts Html to Text ... - /// - /// - /// - 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\hkhazaeeasl\Documents\Projets\XProjects\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 -{ - /// - /// Extracts content from files using Vision Model ... - /// - public class XVisionFileContentExtractor : IXVisionFileContentExtractor - { - /// - /// Supported MIME Types ... - /// - 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(); - } - } - - /// - /// Check if this extractor supports the specified MIME type ... - /// - public bool CanExtract(string mimeType) - { - // - return SupportedMimeTypes.Contains( - mimeType?.ToLowerInvariant() ?? string.Empty - ); - } - - /// - /// Extract text content from file stream ... - /// - public async Task ExtractAsync( - Stream fileStream, - string mimeType, - CancellationToken cancellationToken = default - ) - { - var result = await ExtractRichAsync(fileStream, "file", mimeType, cancellationToken); - return result.Text; - } - - /// - /// Extract content from stream as Rich Result ... - /// - /// - /// - /// - /// - /// - public async Task 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 ... - /// - /// Request for Doing OCR on Given Data Contents ... - /// - /// - /// - /// - public virtual async Task RequestOCRAsync( - IList 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; - } - - /// - /// Request for Doing OCR on Given Data Contents as Stream ... - /// - /// - /// - /// - public virtual async IAsyncEnumerable RequestOCRAsEnumerable( - IList 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 - } -} - -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\xAiApi\wwwroot\Storage\Uploads\Document\xSaherElm_093cc96f-7927-40f4-a61b-2cc948412f09.html - - - - - - -ثبت XAiMcpServer به عنوان Entity و مدیریت داینامیک | مستند فنی - - - - -
- -
-
-
-
-
شماره مستند: ARCH-MCP-1405-001
-
نسخه: ۱.۰
-
تاریخ تهیه: آبان ۱۴۰۵
-
طبقه‌بندی: فنی-داخلی
-
-
-
- TECHNICAL DESIGN DOCUMENT -

ثبت XAiMcpServer به‌عنوان Entity و مدیریت داینامیک

-

Seed از appSettings + CRUD API + یکپارچه‌سازی با XMcpServerConnectionManager

-
-
- -
- -
- هدف مستند:
- این مستند، مراحل دقیق و گام‌به‌گام ثبت سرورهای MCP به‌عنوان یک Entity کامل در ماژول xAiModels، همراه با لایه‌های Repository/Service/Enricher، Seeder خودکار از appSettings، کنترلرهای CRUD، و اتصال به XMcpServerConnectionManager را شرح می‌دهد. تمام الگوها دقیقاً منطبق بر کدهای موجود پروژه (مانند XAiProject و XAiConversation) پیاده‌سازی می‌شوند. -
- - - - -
-
-
۰
-
-

نمای کلی معماری و جریان داده

-
Architecture Overview
-
-
-
-

جریان کلی سیستم به این شکل خواهد بود:

- -
-┌─────────────────────────────────────────────────────────────────┐
-│  appsettings.json → "McpServers:Servers[]"                      │
-│         │                                                        │
-│         ▼                                                        │
-│  XMcpServerSeederService (IHostedService)                       │
-│         │   (در Startup اجرا می‌شود)                              │
-│         ▼                                                        │
-│  IXAiMcpServerRepositoryService → AddAsync/UpdateAsync           │
-│         │                                                        │
-│         ▼                                                        │
-│  [AiMcpServers] Table (SQL/Mongo/InMemory)                      │
-│         │                                                        │
-│         ├──→ McpServersController (CRUD API)                    │
-│         │         │                                              │
-│         │         ▼                                              │
-│         │    XMcpServerConnectionManager.RefreshAsync()          │
-│         │                                                        │
-│         ▼                                                        │
-│  XMcpServerConnectionManager                                    │
-│         │   (Ping + ListTools + Cache)                          │
-│         ▼                                                        │
-│  ChatOptions.Tools → IXDefaultAiService                         │
-└─────────────────────────────────────────────────────────────────┘
-
- -
- 💡 نکته کلیدی: appSettings فقط نقش Seed اولیه را دارد. پس از آن، مدیریت کامل از طریق API و دیتابیس انجام می‌شود. اگر سرور جدیدی به appSettings اضافه شود، Seeder در استارتاپ بعدی آن را ایجاد می‌کند و اگر UpdateExisting = true باشد، موجودیت‌های قبلی را هم به‌روزرسانی می‌کند. -
- -

ساختار فایل‌های جدید/تغییر یافته:

-
-xSaherelmWorkspace/ -├── Modules/xAiModels/ -│ ├── Models/ -│ │ ├── Entities/ -│ │ │ └── XAiMcpServer.cs [NEW] -│ │ │ ├── Dtos/ -│ │ │ │ └── XAiMcpServerDto.cs [NEW] -│ │ │ └── XMcpServerDescriptor.cs [NEW] -│ │ ├── Configurations/ -│ │ │ ├── XAiModelMappersProfile.cs [MODIFY] -│ │ │ └── Entities/ -│ │ │ └── XAiMcpServerEntityConfiguration.cs [NEW] -│ │ ├── Constants/XAiModelsConstants.cs [MODIFY] -│ │ ├── Interfaces/ -│ │ │ ├── Entities/ -│ │ │ │ ├── IXAiMcpServerKeyGenerator.cs -│ │ │ │ ├── IXAiMcpServerRepository.cs -│ │ │ │ ├── IXAiMcpServerRepositoryEvents.cs -│ │ │ │ ├── IXAiMcpServerRepositoryProvider.cs -│ │ │ │ └── IXAiMcpServerEntityHub.cs -│ │ │ ├── Dtos/ -│ │ │ │ ├── IXAiMcpServerDtoHub.cs -│ │ │ │ ├── IXAiMcpServerRepositoryService.cs -│ │ │ │ └── IXAiMcpServerServiceProvider.cs -│ │ │ └── Enrichers/ -│ │ │ └── IXAiMcpServerEnricher.cs -│ │ ├── Providers/ -│ │ │ ├── Entities/ -│ │ │ │ ├── XAiMcpServerEFRepository.cs -│ │ │ │ ├── XAiMcpServerInMemoryRepository.cs -│ │ │ │ ├── XAiMcpServerMongoRepository.cs -│ │ │ │ ├── XAiMcpServerKeyGenerator.cs -│ │ │ │ ├── XAiMcpServerRepositoryEvents.cs -│ │ │ │ ├── XAiMcpServerEntityHub.cs -│ │ │ │ ├── XAiMcpServerRepositoryProvider.cs -│ │ │ │ └── XAiMcpServerSeederBase.cs -│ │ │ ├── Dtos/ -│ │ │ │ ├── XAiMcpServerDtoHub.cs -│ │ │ │ ├── XAiMcpServerRepositoryService.cs -│ │ │ │ └── XAiMcpServerServiceProvider.cs -│ │ │ ├── Enrichers/ -│ │ │ │ └── XAiMcpServerEnricher.cs -│ │ │ └── XAiMcpServerEntityRegisterar.cs -│ │ ├── Helpers/XAiModelsHelper.cs [MODIFY] -│ │ └── DI/XDIHelperExtension.cs [MODIFY] -│ │ -├── xAiApi/ -│ ├── Configurations/ -│ │ └── XMcpServersConfiguration.cs [NEW] -│ ├── Services/ -│ │ ├── XMcpServerSeederService.cs [NEW] -│ │ └── XMcpServerConnectionManager.cs [MODIFY] -│ ├── Controllers/ -│ │ └── McpServersController.cs [NEW] -│ ├── Database/XAiApiDbContext.cs [MODIFY] -│ ├── Startup.cs [MODIFY] -│ └── appsettings.json [MODIFY] -
-
-
- - - - -
-
-
۱
-
-

تعریف Entity در xAiModels

-
Entity Layer / Models/Entities/XAiMcpServer.cs
-
-
-
-

ابتدا موجودیت اصلی را با الگوبرداری دقیق از XAiProject و XAiVector تعریف می‌کنیم. فیلدهای JSON (مانند Arguments، Headers، EnvironmentVariables) به‌صورت رشته ذخیره می‌شوند تا در هر سه Repository (EF/Mongo/InMemory) قابل نگهداری باشند.

- -
xAiModels/Models/Entities/XAiMcpServer.cs
-
using System;
-using xModels.Base;
-using System.ComponentModel.DataAnnotations;
-
-namespace xAiModels.Models.Entities
-{
-    /// <summary>
-    /// سرور MCP ثبت‌شده در دیتابیس (قابل مدیریت از طریق API) ...
-    /// </summary>
-    public class XAiMcpServer : XBaseGuidIDEntity
-    {
-        /// <summary>
-        /// شناسه مالک (کاربری که این سرور را ثبت کرده) ...
-        /// </summary>
-        [Required]
-        [StringLength(255)]
-        public string OwnerId { get; set; }
-
-        /// <summary>
-        /// نام یکتای سرور (برای هر Owner) ...
-        /// </summary>
-        [Required]
-        [StringLength(255)]
-        public string Name { get; set; }
-
-        /// <summary>
-        /// توضیحات ...
-        /// </summary>
-        [StringLength(1000)]
-        public string Description { get; set; }
-
-        /// <summary>
-        /// فعال/غیرفعال ...
-        /// </summary>
-        public bool Enabled { get; set; } = true;
-
-        /// <summary>
-        /// نوع Transport: "stdio" یا "http" ...
-        /// </summary>
-        [Required]
-        [StringLength(50)]
-        public string Transport { get; set; } = "stdio";
-
-        // --- تنظیمات Stdio ---
-        [StringLength(500)]
-        public string Command { get; set; }
-
-        /// <summary>
-        /// آرگومان‌ها به‌صورت JSON Array (مثلاً ["xAiMcpServer.dll"]) ...
-        /// </summary>
-        public string Arguments { get; set; }
-
-        [StringLength(1000)]
-        public string WorkingDirectory { get; set; }
-
-        /// <summary>
-        /// متغیرهای محیطی به‌صورت JSON Object ...
-        /// </summary>
-        public string EnvironmentVariables { get; set; }
-
-        // --- تنظیمات HTTP ---
-        [StringLength(1000)]
-        public string Endpoint { get; set; }
-
-        /// <summary>
-        /// هدرهای HTTP به‌صورت JSON Object ...
-        /// </summary>
-        public string Headers { get; set; }
-
-        /// <summary>
-        /// مهلت اتصال و اعتبارسنجی (ثانیه) ...
-        /// </summary>
-        public int TimeoutSeconds { get; set; } = 30;
-
-        // --- Audit ---
-        public DateTime CreatedOn { get; set; }
-        public DateTime UpdatedAt { get; set; }
-    }
-}
- -
xAiModels/Models/Dtos/XAiMcpServerDto.cs
-
using System;
-using xModels.Base;
-using xModels.Dtos;
-
-namespace xAiModels.Models.Dtos
-{
-    public class XAiMcpServerDto : XBaseGuidIDEntityDto
-    {
-        public string OwnerId { get; set; }
-        public virtual XPersonDto Owner { get; set; } = null;
-
-        public string Name { get; set; }
-        public string Description { get; set; }
-        public bool Enabled { get; set; }
-        public string Transport { get; set; }
-
-        public string Command { get; set; }
-        public string Arguments { get; set; }
-        public string WorkingDirectory { get; set; }
-        public string EnvironmentVariables { get; set; }
-
-        public string Endpoint { get; set; }
-        public string Headers { get; set; }
-
-        public int TimeoutSeconds { get; set; }
-
-        public DateTime CreatedOn { get; set; }
-        public DateTime UpdatedAt { get; set; }
-    }
-}
- -
xAiModels/Models/XMcpServerDescriptor.cs
-
using System.Collections.Generic;
-
-namespace xAiModels.Models
-{
-    /// <summary>
-    /// Descriptor سرور MCP که مستقیماً از appSettings خوانده می‌شود
-    /// و سپس توسط Seeder به یک XAiMcpServer Entity تبدیل می‌گردد ...
-    /// </summary>
-    public class XMcpServerDescriptor
-    {
-        public string Name { get; set; }
-        public string Description { get; set; }
-        public bool Enabled { get; set; } = true;
-        public string Transport { get; set; } = "stdio";
-        public int TimeoutSeconds { get; set; } = 30;
-
-        // Stdio
-        public string Command { get; set; }
-        public List<string> Arguments { get; set; } = new();
-        public string WorkingDirectory { get; set; }
-        public Dictionary<string, string> EnvironmentVariables { get; set; }
-
-        // HTTP
-        public string Endpoint { get; set; }
-        public Dictionary<string, string> Headers { get; set; }
-    }
-}
-
-
- - - - -
-
-
۲
-
-

ثابت‌ها و Configuration

-
Constants / EntityConfiguration
-
-
-
-

ثابت‌های جدید را به XAiModelsConstants اضافه کنید (دقیقاً مطابق الگوی موجود):

- -
xAiModels/Constants/XAiModelsConstants.cs (MODIFY)
-
// ── اضافه کنید در struct XAiModelsConstants ──
-
-// Table Mapping
-public const string XAiMcpServerTable = "AiMcpServers";
-
-// GraphQL Collection Mappings
-public const string XAiMcpServerSingleName = "aiMcpServer";
-public const string XAiMcpServerCollectionName = "aiMcpServers";
-
-// Hubs
-public const string XAiMcpServerDtoHub = "aiMcpServerDto";
-public const string XAiMcpServerEntityHub = "aiMcpServerEntity";
-
-// EF Repositories Helper Extensions
-public const string GetXAiMcpServerEFRepositoryDescriptor = "GetXAiMcpServerEFRepositoryDescriptor";
- -
xAiModels/Configurations/Entities/XAiMcpServerEntityConfiguration.cs
-
using System;
-using xAiModels.Constants;
-using xDataService.Providers;
-using xAiModels.Models.Entities;
-using Microsoft.EntityFrameworkCore;
-using Microsoft.EntityFrameworkCore.Metadata.Builders;
-
-namespace xAiModels.Configurations.Entities
-{
-    public class XAiMcpServerEntityConfiguration : XBaseEntityTypeConfiguration<XAiMcpServer, Guid>
-    {
-        public override void Configure(EntityTypeBuilder<XAiMcpServer> builder)
-        {
-            builder.ToTable(XAiModelsConstants.XAiMcpServerTable);
-
-            // نام برای هر Owner یکتاست
-            builder.HasIndex(x => new { x.OwnerId, x.Name }).IsUnique();
-        }
-    }
-}
- -
xAiModels/Providers/XAiMcpServerEntityRegisterar.cs
-
using System;
-using xDataService.Providers;
-using xDataService.Interfaces;
-using xAiModels.Models.Entities;
-using Microsoft.EntityFrameworkCore;
-using xAiModels.Configurations.Entities;
-
-namespace xAiModels.Providers
-{
-    public class XAiMcpServerEntityRegisterar : XBaseEntityRegisterar, IXEntityRegisterar
-    {
-        public XAiMcpServerEntityRegisterar()
-        : base(nameof(XAiMcpServerEntityRegisterar))
-        {
-            AddEntity<XAiMcpServer, Guid>();
-        }
-
-        public override void ConfigureEntities(ModelBuilder modelBuilder)
-        {
-            modelBuilder
-                .ApplyConfigurationsFromAssembly(typeof(XAiMcpServerEntityConfiguration).Assembly);
-
-            base.ConfigureEntities(modelBuilder);
-        }
-    }
-}
-
-
- - - - -
-
-
۳
-
-

لایه Interfaces

-
Interfaces / Entities + Dtos + Enrichers
-
-
-
-

مطابق الگوی XAiProject، تمام اینترفیس‌های مربوطه را در سه پوشه Entities، Dtos و Enrichers ایجاد کنید:

- -

الف) Interfaces/Entities

- -
xAiModels/Interfaces/Entities/IXAiMcpServerKeyGenerator.cs
-
using System;
-using xDataService.Interfaces;
-using xAiModels.Models.Entities;
-
-namespace xAiModels.Interfaces.Entities
-{
-    public interface IXAiMcpServerKeyGenerator : IXKeyGenerator<XAiMcpServer, Guid> { }
-}
- -
xAiModels/Interfaces/Entities/IXAiMcpServerRepository.cs
-
using System;
-using xDataService.Interfaces;
-using xAiModels.Models.Entities;
-
-namespace xAiModels.Interfaces.Entities
-{
-    public interface IXAiMcpServerRepository : IXBaseRepository<XAiMcpServer, Guid> { }
-}
- -
xAiModels/Interfaces/Entities/IXAiMcpServerRepositoryEvents.cs
-
using xDataService.Interfaces;
-using xAiModels.Models.Entities;
-
-namespace xAiModels.Interfaces.Entities
-{
-    public interface IXAiMcpServerRepositoryEvents : IXBaseRepositoryEvents<XAiMcpServer> { }
-}
- -
xAiModels/Interfaces/Entities/IXAiMcpServerEntityHub.cs
-
using System;
-using xPushService.Interfaces;
-using xAiModels.Models.Entities;
-
-namespace xAiModels.Interfaces.Entities
-{
-    public interface IXAiMcpServerEntityHub : IXBaseEntityHub<XAiMcpServer, Guid> { }
-}
- -
xAiModels/Interfaces/Entities/IXAiMcpServerRepositoryProvider.cs
-
using System;
-using xPushService.Interfaces;
-using xAiModels.Models.Entities;
-using xAiModels.Providers.Entities;
-
-namespace xAiModels.Interfaces.Entities
-{
-    public interface IXAiMcpServerRepositoryProvider
-        : IXBaseEntityProvider<XAiMcpServer, Guid, XAiMcpServerEntityHub> { }
-}
- -

ب) Interfaces/Dtos

- -
xAiModels/Interfaces/Dtos/IXAiMcpServerDtoHub.cs
-
using System;
-using xAiModels.Models.Dtos;
-using xPushService.Interfaces;
-using xAiModels.Models.Entities;
-
-namespace xAiModels.Interfaces.Dtos
-{
-    public interface IXAiMcpServerDtoHub
-        : IXBaseDtoHub<XAiMcpServer, XAiMcpServerDto, Guid> { }
-}
- -
xAiModels/Interfaces/Dtos/IXAiMcpServerRepositoryService.cs
-
using System;
-using System.Threading;
-using xAiModels.Models.Dtos;
-using System.Threading.Tasks;
-using xDataService.Interfaces;
-using xAiModels.Models.Entities;
-
-namespace xAiModels.Interfaces.Dtos
-{
-    public interface IXAiMcpServerRepositoryService
-        : IXBaseRepositoryService<XAiMcpServer, XAiMcpServerDto, Guid>
-    {
-        /// <summary>
-        /// یافتن سرور بر اساس OwnerId و Name ...
-        /// </summary>
-        Task<XAiMcpServerDto> FindByNameAsync(
-            string ownerId,
-            string name,
-            CancellationToken cancellationToken = default
-        );
-    }
-}
- -
xAiModels/Interfaces/Dtos/IXAiMcpServerServiceProvider.cs
-
using System;
-using xAiModels.Models.Dtos;
-using xPushService.Interfaces;
-using xAiModels.Providers.Dtos;
-using xAiModels.Models.Entities;
-
-namespace xAiModels.Interfaces.Dtos
-{
-    public interface IXAiMcpServerServiceProvider
-        : IXBaseDtoProvider<XAiMcpServer, XAiMcpServerDto, Guid, XAiMcpServerDtoHub> { }
-}
- -

ج) Interfaces/Enrichers

- -
xAiModels/Interfaces/Enrichers/IXAiMcpServerEnricher.cs
-
using System.Threading;
-using xAiModels.Models.Dtos;
-using System.Threading.Tasks;
-using xAiModels.Models.Entities;
-using System.Collections.Generic;
-
-namespace xAiModels.Interfaces.Enrichers
-{
-    public interface IXAiMcpServerEnricher
-    {
-        Task<XAiMcpServerDto> Enrich(
-            XAiMcpServer source,
-            CancellationToken cancellationToken = default
-        );
-
-        Task<XAiMcpServerDto> Enrich(
-            XAiMcpServerDto source,
-            CancellationToken cancellationToken = default
-        );
-
-        Task<IEnumerable<XAiMcpServerDto>> EnrichRange(
-            IEnumerable<XAiMcpServer> sources,
-            CancellationToken cancellationToken = default
-        );
-
-        Task<IEnumerable<XAiMcpServerDto>> EnrichRange(
-            IEnumerable<XAiMcpServerDto> sources,
-            CancellationToken cancellationToken = default
-        );
-    }
-}
-
-
- - - - -
-
-
۴
-
-

لایه Repository

-
EF / Mongo / InMemory + KeyGenerator + Events + Hubs
-
-
-
-

سه نوع Repository و اجزای جانبی آن‌ها را دقیقاً مطابق با XAiProjectEFRepository و XAiProjectMongoRepository بسازید:

- -
xAiModels/Providers/Entities/XAiMcpServerEFRepository.cs
-
using System;
-using xDataService.Db;
-using xDataService.Providers;
-using xDataService.Interfaces;
-using xAiModels.Models.Entities;
-using xDataService.Configuration;
-using xAiModels.Interfaces.Entities;
-
-namespace xAiModels.Providers.Entities
-{
-    public class XAiMcpServerEFRepository<TContext>
-        : XBaseEFRepository<XAiMcpServer, Guid, TContext>, IXAiMcpServerRepository
-        where TContext : XDbContext
-    {
-        public XAiMcpServerEFRepository(
-            IXUnitOfWorks<TContext> unitOfWorks,
-            XDataServiceConfiguration configuration,
-            IXAiMcpServerKeyGenerator keyGenerator = null,
-            IXAiMcpServerRepositoryEvents baseRepositoryEvents = null
-        ) : base(unitOfWorks, configuration, keyGenerator, baseRepositoryEvents) { }
-    }
-}
- -
xAiModels/Providers/Entities/XAiMcpServerMongoRepository.cs
-
using System;
-using xDataService.Providers;
-using xAiModels.Models.Entities;
-using xDataService.Configuration;
-using xAiModels.Interfaces.Entities;
-
-namespace xAiModels.Providers.Entities
-{
-    public class XAiMcpServerMongoRepository
-        : XBaseMongoRepository<XAiMcpServer, Guid>, IXAiMcpServerRepository
-    {
-        public XAiMcpServerMongoRepository(
-            XDataBaseConfiguration dbConfiguration,
-            XDataServiceConfiguration configuration,
-            string collectionName = null,
-            IXAiMcpServerKeyGenerator keyGenerator = null,
-            IXAiMcpServerRepositoryEvents baseRepositoryEvents = null
-        ) : base(dbConfiguration, configuration, collectionName, keyGenerator, baseRepositoryEvents) { }
-    }
-}
- -
xAiModels/Providers/Entities/XAiMcpServerInMemoryRepository.cs
-
using System;
-using xDataService.Providers;
-using xAiModels.Models.Entities;
-using xDataService.Configuration;
-using xAiModels.Interfaces.Entities;
-
-namespace xAiModels.Providers.Entities
-{
-    public class XAiMcpServerInMemoryRepository
-        : XBaseInMemoryRepository<XAiMcpServer, Guid>, IXAiMcpServerRepository
-    {
-        public XAiMcpServerInMemoryRepository(
-            XDataServiceConfiguration configuration,
-            IXAiMcpServerKeyGenerator keyGenerator = null,
-            IXAiMcpServerRepositoryEvents baseRepositoryEvents = null
-        ) : base(configuration, keyGenerator, baseRepositoryEvents) { }
-    }
-}
- -
xAiModels/Providers/Entities/XAiMcpServerKeyGenerator.cs
-
using xDataService.Providers;
-using xAiModels.Models.Entities;
-using xAiModels.Interfaces.Entities;
-
-namespace xAiModels.Providers.Entities
-{
-    public class XAiMcpServerKeyGenerator
-        : XGuidKeyGenerator<XAiMcpServer>, IXAiMcpServerKeyGenerator { }
-}
- -
xAiModels/Providers/Entities/XAiMcpServerRepositoryEvents.cs
-
using xDataService.Providers;
-using xAiModels.Models.Entities;
-using xAiModels.Interfaces.Entities;
-
-namespace xAiModels.Providers.Entities
-{
-    public class XAiMcpServerRepositoryEvents
-        : XBaseRepositoryEvents<XAiMcpServer>, IXAiMcpServerRepositoryEvents { }
-}
- -
xAiModels/Providers/Entities/XAiMcpServerEntityHub.cs
-
using System;
-using xPushService.Base;
-using xAiModels.Models.Entities;
-using Microsoft.Extensions.Logging;
-using xAiModels.Interfaces.Entities;
-
-namespace xAiModels.Providers.Entities
-{
-    public class XAiMcpServerEntityHub
-        : XBaseEntityHub<XAiMcpServer, Guid>, IXAiMcpServerEntityHub
-    {
-        public XAiMcpServerEntityHub(ILogger<XAiMcpServerEntityHub> logger)
-            : base(logger) { }
-    }
-}
- -
xAiModels/Providers/Entities/XAiMcpServerRepositoryProvider.cs
-
using System;
-using xPushService.Base;
-using xAiModels.Models.Entities;
-using xDataService.Configuration;
-using xIdentityService.Interfaces;
-using Microsoft.AspNetCore.SignalR;
-using xAiModels.Interfaces.Entities;
-
-namespace xAiModels.Providers.Entities
-{
-    public class XAiMcpServerRepositoryProvider
-        : XBaseEntityProvider<XAiMcpServer, Guid, XAiMcpServerEntityHub>, IXAiMcpServerRepositoryProvider
-    {
-        public XAiMcpServerRepositoryProvider(
-            IHubContext<XAiMcpServerEntityHub> hub,
-            IXAiMcpServerRepository repository,
-            XDataServiceConfiguration dataConfiguration,
-            IXIdentityProvider identityProvider = null
-        ) : base(hub, repository, dataConfiguration, identityProvider) { }
-    }
-}
-
-
- - - - -
-
-
۵
-
-

لایه Service (RepositoryService + ServiceProvider + Enricher)

-
Providers/Dtos + Enrichers
-
-
-
-
xAiModels/Configurations/XAiModelMappersProfile.cs (MODIFY)
-
// ── درون سازنده XAiModelMappersProfile اضافه کنید ──
-
-// XAiMcpServer
-CreateMap<XAiMcpServer, XAiMcpServerDto>();
-CreateMap<XAiMcpServerDto, XAiMcpServer>();
- -
xAiModels/Providers/Enrichers/XAiMcpServerEnricher.cs
-
using System.Linq;
-using xModels.Dtos;
-using System.Threading;
-using xCommons.Extensions;
-using xAiModels.Models.Dtos;
-using System.Threading.Tasks;
-using xAiModels.Models.Entities;
-using System.Collections.Generic;
-using xIdentityService.Interfaces;
-using xIdentityService.Extensions;
-using xAiModels.Interfaces.Enrichers;
-
-namespace xAiModels.Providers.Enrichers
-{
-    public class XAiMcpServerEnricher : IXAiMcpServerEnricher
-    {
-        private readonly IXIdentityProvider identityProvider;
-
-        public XAiMcpServerEnricher(IXIdentityProvider identityProvider)
-        {
-            this.identityProvider = identityProvider;
-        }
-
-        public virtual async Task<XAiMcpServerDto> Enrich(
-            XAiMcpServer source,
-            CancellationToken cancellationToken = default
-        )
-        {
-            var result = source.MapConvert<XAiMcpServerDto, XAiMcpServer>();
-            result = await Enrich(source: result, cancellationToken: cancellationToken);
-            return result;
-        }
-
-        public virtual async Task<XAiMcpServerDto> Enrich(
-            XAiMcpServerDto source,
-            CancellationToken cancellationToken = default
-        )
-        {
-            XPersonDto owner = null;
-            if (!source.OwnerId.IsNullOrEmpty())
-            {
-                var device = identityProvider.GetDevice();
-                var userInfo = await identityProvider.GetUserInfo(
-                    device: device,
-                    userSelectByParam: source.OwnerId
-                );
-                owner = userInfo.ToXPersonDto();
-            }
-
-            var result = source.MapConvert<XAiMcpServerDto, XAiMcpServerDto>();
-            result.Owner = owner;
-            return result;
-        }
-
-        public virtual async Task<IEnumerable<XAiMcpServerDto>> EnrichRange(
-            IEnumerable<XAiMcpServer> sources,
-            CancellationToken cancellationToken = default
-        )
-        {
-            var tasks = sources.Select(x => Enrich(x, cancellationToken));
-            return await Task.WhenAll(tasks);
-        }
-
-        public virtual async Task<IEnumerable<XAiMcpServerDto>> EnrichRange(
-            IEnumerable<XAiMcpServerDto> sources,
-            CancellationToken cancellationToken = default
-        )
-        {
-            var tasks = sources.Select(x => Enrich(x, cancellationToken));
-            return await Task.WhenAll(tasks);
-        }
-    }
-}
- -
xAiModels/Providers/Dtos/XAiMcpServerRepositoryService.cs
-
using System;
-using System.Linq;
-using System.Threading;
-using xCommons.Extensions;
-using xAiModels.Models.Dtos;
-using System.Threading.Tasks;
-using xDataService.Providers;
-using xAiModels.Configurations;
-using xAiModels.Interfaces.Dtos;
-using xAiModels.Interfaces.Entities;
-using xAiModels.Interfaces.Enrichers;
-
-namespace xAiModels.Providers.Dtos
-{
-    public class XAiMcpServerRepositoryService
-        : XBaseRepositoryService<XAiMcpServer, XAiMcpServerDto, Guid>, IXAiMcpServerRepositoryService
-    {
-        private readonly IXAiMcpServerEnricher enricher;
-        private readonly IXAiMcpServerRepository repository;
-
-        public XAiMcpServerRepositoryService(
-            IXAiMcpServerRepository repository,
-            IXAiMcpServerEnricher enricher
-        ) : base(repository, mapperProfiles: [new XAiModelMappersProfile()])
-        {
-            this.enricher = enricher;
-            this.repository = repository;
-        }
-
-        /// <summary>
-        /// یافتن سرور بر اساس OwnerId و Name ...
-        /// </summary>
-        public virtual async Task<XAiMcpServerDto> FindByNameAsync(
-            string ownerId,
-            string name,
-            CancellationToken cancellationToken = default
-        )
-        {
-            // اعتبارسنجی ورودی‌ها
-            if (ownerId.IsNullOrEmpty() || name.IsNullOrEmpty())
-                return null;
-
-            // جستجو در Repository
-            var entity = await repository.FindOneAsync(
-                includeBuilder: null,
-                ignoreSoftDeleteds: true,
-                cancellationToken: cancellationToken,
-                predicate: x => x.OwnerId == ownerId && x.Name == name
-            );
-
-            // عدم یافتن → null
-            if (entity.IsNullOrDefault())
-                return null;
-
-            // Enrich و بازگشت
-            return await enricher.Enrich(source: entity, cancellationToken: cancellationToken);
-        }
-    }
-}
- -
xAiModels/Providers/Dtos/XAiMcpServerDtoHub.cs
-
using System;
-using xPushService.Base;
-using xAiModels.Models.Dtos;
-using xAiModels.Interfaces.Dtos;
-using xAiModels.Models.Entities;
-using Microsoft.Extensions.Logging;
-
-namespace xAiModels.Providers.Dtos
-{
-    public class XAiMcpServerDtoHub
-        : XBaseDtoHub<XAiMcpServer, XAiMcpServerDto, Guid>, IXAiMcpServerDtoHub
-    {
-        public XAiMcpServerDtoHub(ILogger<XAiMcpServerDtoHub> logger)
-            : base(logger) { }
-    }
-}
- -
xAiModels/Providers/Dtos/XAiMcpServerServiceProvider.cs
-
using System;
-using xPushService.Base;
-using xAiModels.Models.Dtos;
-using xAiModels.Interfaces.Dtos;
-using xAiModels.Models.Entities;
-using xDataService.Configuration;
-using xIdentityService.Interfaces;
-using Microsoft.AspNetCore.SignalR;
-
-namespace xAiModels.Providers.Dtos
-{
-    public class XAiMcpServerServiceProvider
-        : XBaseDtoProvider<XAiMcpServer, XAiMcpServerDto, Guid, XAiMcpServerDtoHub>, IXAiMcpServerServiceProvider
-    {
-        public XAiMcpServerServiceProvider(
-            IHubContext<XAiMcpServerDtoHub> hub,
-            XDataServiceConfiguration dataConfiguration,
-            IXAiMcpServerRepositoryService service,
-            IXIdentityProvider identityProvider = null
-        ) : base(hub, dataConfiguration, service, identityProvider) { }
-    }
-}
-
-
- - - - -
-
-
۶
-
-

Helper و ثبت در DI

-
XAiModelsHelper + XDIHelperExtension
-
-
-
-

مطابق الگوی موجود در XAiModelsHelper، سه متد برای ساخت Repository Descriptor اضافه کنید:

- -
xAiModels/Helpers/XAiModelsHelper.cs (MODIFY)
-
// ── درون کلاس XAiModelsHelper اضافه کنید ──
-
-#region XAiMcpServer ...
-// EF Repository Descriptor
-public static XEFRepositoryDescriptor<
-    XAiMcpServer, Guid,
-    IXAiMcpServerKeyGenerator, XAiMcpServerKeyGenerator,
-    IXAiMcpServerRepositoryEvents, XAiMcpServerRepositoryEvents,
-    XAiMcpServerGraphType, GuidGraphType,
-    XAiMcpServerGraphQuery,
-    IXAiMcpServerGraphQLTypeHelper, XAiMcpServerGraphQLTypeHelper,
-    XAiMcpServerGraphSchema,
-    IXAiMcpServerRepository,
-    XAiMcpServerEFRepository<TContext>, TContext
-> GetXAiMcpServerEFRepositoryDescriptor<TContext>()
-where TContext : XDbContext
-{
-    return new XEFRepositoryDescriptor<...>();  // پر کردن کامل نوع‌ها
-}
-
-// Mongo Repository Descriptor
-public static XMongoRepositoryDescriptor<
-    XAiMcpServer, Guid,
-    IXAiMcpServerKeyGenerator, XAiMcpServerKeyGenerator,
-    IXAiMcpServerRepositoryEvents, XAiMcpServerRepositoryEvents,
-    XAiMcpServerGraphType, GuidGraphType,
-    XAiMcpServerGraphQuery,
-    IXAiMcpServerGraphQLTypeHelper, XAiMcpServerGraphQLTypeHelper,
-    XAiMcpServerGraphSchema,
-    IXAiMcpServerRepository, XAiMcpServerMongoRepository
-> GetXAiMcpServerMongoRepositoryDescriptor()
-{
-    return new XMongoRepositoryDescriptor<...>();
-}
-
-// InMemory Repository Descriptor
-public static XInMemoryRepositoryDescriptor<
-    XAiMcpServer, Guid,
-    IXAiMcpServerKeyGenerator, XAiMcpServerKeyGenerator,
-    IXAiMcpServerRepositoryEvents, XAiMcpServerRepositoryEvents,
-    XAiMcpServerGraphType, GuidGraphType,
-    XAiMcpServerGraphQuery,
-    IXAiMcpServerGraphQLTypeHelper, XAiMcpServerGraphQLTypeHelper,
-    XAiMcpServerGraphSchema,
-    IXAiMcpServerRepository, XAiMcpServerInMemoryRepository
-> GetXAiMcpServerInMemoryRepositoryDescriptor()
-{
-    return new XInMemoryRepositoryDescriptor<...>();
-}
-#endregion
- -
- ⚠️ توجه: برای سادگی، GraphQL types (مانند XAiMcpServerGraphType، XAiMcpServerGraphQuery و...) در این مستند اورده نشده‌اند. اگر پروژه شما از GraphQL استفاده نمی‌کند، می‌توانید این پارامترها را با null جایگزین کنید یا با الگوگیری دقیق از XAiProjectGraphType و... آن‌ها را ایجاد نمایید. -
- -

سپس در XDIHelperExtension پروژه xAiModels، ثبت‌ها را اضافه کنید:

- -
xAiModels/DI/XDIHelperExtension.cs (MODIFY)
-
// ── ۱) متغیر استاتیک جدید اضافه کنید ──
-private static XRepositoryDescriptor aiMcpServerDescriptor = null;
-
-// ── ۲) درون switch روی repositoryType، در بخش EF ──
-aiMcpServerDescriptor = typeof(XAiModelsHelper)
-    .InvokeGenericMethod<XRepositoryDescriptor>(
-        args: null,
-        runtimeType: contextType,
-        methodName: XAiModelsConstants.GetXAiMcpServerEFRepositoryDescriptor
-    );
-
-// ── ۳) درون switch، در بخش Mongo ──
-aiMcpServerDescriptor = XAiModelsHelper.GetXAiMcpServerMongoRepositoryDescriptor();
-
-// ── ۴) درون switch، در بخش InMemory ──
-aiMcpServerDescriptor = XAiModelsHelper.GetXAiMcpServerInMemoryRepositoryDescriptor();
-
-// ── ۵) درون region Register Repository Descriptor ──
-if (!aiMcpServerDescriptor.IsNull())
-{
-    services.AddXRepository(lifeTime: lifeTime, descriptor: aiMcpServerDescriptor);
-}
-
-// ── ۶) درون region Register Services، یک region جدید اضافه کنید ──
-#region AiMcpServer ...
-services.Add(
-    new ServiceDescriptor(typeof(IXAiMcpServerServiceProvider),
-                          typeof(XAiMcpServerServiceProvider), lifeTime)
-);
-services.Add(
-    new ServiceDescriptor(typeof(IXAiMcpServerRepositoryService),
-                          typeof(XAiMcpServerRepositoryService), lifeTime)
-);
-services.Add(
-    new ServiceDescriptor(typeof(IXAiMcpServerRepositoryProvider),
-                          typeof(XAiMcpServerRepositoryProvider), lifeTime)
-);
-services.Add(
-    new ServiceDescriptor(typeof(IXAiMcpServerEnricher),
-                          typeof(XAiMcpServerEnricher), lifeTime)
-);
-#endregion
- -

همچنین در UseXAiDataService (همان فایل، برای Hubs):

- -
// ── اضافه کنید ──
-pushHelper.AddHub<XAiMcpServerDtoHub>(XAiModelsConstants.XAiMcpServerDtoHub);
-pushHelper.AddHub<XAiMcpServerEntityHub>(XAiModelsConstants.XAiMcpServerEntityHub);
-
-// در بخش Use Repository Descriptor
-if (!aiMcpServerDescriptor.IsNull())
-{
-    app.UseXRepository(descriptor: aiMcpServerDescriptor,
-                       isDevelopmentEnvironment: isDevelopmentEnvironment);
-}
-
-
- - - - -
-
-
۷
-
-

ثبت Registerar در DbContext

-
XAiApiDbContext.cs (MODIFY)
-
-
-
-

در فایل XAiApiDbContext.cs، نام Registerar جدید را به لیست dynamicEntityRegisterarsNames اضافه کنید:

- -
xAiApi/Database/XAiApiDbContext.cs (MODIFY)
-
dynamicEntityRegisterarsNames: [
-    nameof(XTagEntityRegisterar),
-    nameof(XFileEntityRegisterar),
-    nameof(XStringEntityRegisterar),
-    nameof(XAiMessageEntityRegisterar),
-    nameof(XAiProjectEntityRegisterar),
-    nameof(XAiConversationEntityRegisterar),
-    nameof(XAiMcpServerEntityRegisterar),    // ← جدید
-]
- -
- 💡 نکته: پس از این تغییر، یک Migration جدید برای جدول AiMcpServers بسازید: -

- dotnet ef migrations add AddAiMcpServersTable --project xAiApi --context XAiApiDbContext -

- سپس dotnet ef database update. -
-
-
- - - - -
-
-
۸
-
-

Seeder از appSettings

-
XMcpServersConfiguration + XMcpServerSeederService
-
-
-
-

این بخش هسته اصلی درخواست شماست: خواندن McpServers از appSettings، تبدیل به Entity، و ذخیره در DB. این عملیات به‌صورت IHostedService در استارتاپ اجرا می‌شود.

- -

الف) مدل Configuration

- -
xAiApi/Configurations/XMcpServersConfiguration.cs
-
using System.Collections.Generic;
-using xAiModels.Models;
-
-namespace xAiApi.Configurations
-{
-    /// <summary>
-    /// Configuration مربوط به McpServers که از appSettings خوانده می‌شود ...
-    /// </summary>
-    public class XMcpServersConfiguration
-    {
-        /// <summary>
-        /// آیا Seeder در استارتاپ اجرا شود؟
-        /// </summary>
-        public bool SyncOnStartup { get; set; } = true;
-
-        /// <summary>
-        /// آیا اگر سروری از قبل وجود دارد، فیلدهایش به‌روزرسانی شود؟
-        /// </summary>
-        public bool UpdateExisting { get; set; } = false;
-
-        /// <summary>
-        /// OwnerId پیش‌فرض برای سرورهای Seed شده ...
-        /// (اگر خالی باشد از "system" استفاده می‌شود)
-        /// </summary>
-        public string DefaultOwnerId { get; set; } = "system";
-
-        /// <summary>
-        /// لیست سرورهای MCP ...
-        /// </summary>
-        public List<XMcpServerDescriptor> Servers { get; set; } = new();
-    }
-}
- -

ب) سرویس Seeder

- -
xAiApi/Services/XMcpServerSeederService.cs
-
using System;
-using System.Linq;
-using System.Text.Json;
-using xAiModels.Models;
-using System.Threading;
-using System.Threading.Tasks;
-using xCommons.Extensions;
-using xAiModels.Models.Dtos;
-using System.Collections.Generic;
-using Microsoft.Extensions.Hosting;
-using xAiApi.Configurations;
-using Microsoft.Extensions.Logging;
-using Microsoft.Extensions.Options;
-using xAiModels.Interfaces.Dtos;
-
-namespace xAiApi.Services
-{
-    /// <summary>
-    /// سرویس پس‌زمینه‌ای که در استارتاپ، سرورهای MCP را از appSettings
-    /// می‌خواند و در دیتابیس ایجاد/به‌روزرسانی می‌کند ...
-    /// </summary>
-    public class XMcpServerSeederService : IHostedService
-    {
-        private readonly ILogger<XMcpServerSeederService> logger;
-        private readonly XMcpServersConfiguration config;
-        private readonly IXAiMcpServerRepositoryService repositoryService;
-
-        public XMcpServerSeederService(
-            ILogger<XMcpServerSeederService> logger,
-            IOptions<XMcpServersConfiguration> config,
-            IXAiMcpServerRepositoryService repositoryService
-        )
-        {
-            this.logger = logger;
-            this.config = config.Value;
-            this.repositoryService = repositoryService;
-        }
-
-        public async Task StartAsync(CancellationToken cancellationToken)
-        {
-            // اگر Sync غیرفعال است، هیچ کاری نکن
-            if (!config.SyncOnStartup)
-            {
-                logger.LogInformation(
-                    "MCP Seed: SyncOnStartup=false، عملیات Seed اجرا نشد.");
-                return;
-            }
-
-            // اگر لیست خالی است، خارج شو
-            if (!config.Servers.HasChild())
-            {
-                logger.LogInformation(
-                    "MCP Seed: هیچ سروری در appSettings تعریف نشده است.");
-                return;
-            }
-
-            logger.LogInformation(
-                "MCP Seed: شروع Seed برای {Count} سرور ...",
-                config.Servers.Count);
-
-            foreach (var descriptor in config.Servers)
-            {
-                // اعتبارسنجی حداقلی
-                if (descriptor.IsNullOrDefault() ||
-                    descriptor.Name.IsNullOrEmpty())
-                {
-                    logger.LogWarning("MCP Seed: یک Descriptor نامعتبر نادیده گرفته شد.");
-                    continue;
-                }
-
-                await SeedOneAsync(descriptor, cancellationToken);
-            }
-
-            logger.LogInformation("MCP Seed: عملیات به پایان رسید.");
-        }
-
-        public Task StopAsync(CancellationToken cancellationToken) => Task.CompletedTask;
-
-        // ────────────────────────────────────────────────────────
-        // Seed یک Descriptor
-        // ────────────────────────────────────────────────────────
-        private async Task SeedOneAsync(
-            XMcpServerDescriptor descriptor,
-            CancellationToken cancellationToken)
-        {
-            try
-            {
-                var ownerId = config.DefaultOwnerId.IsNullOrEmpty()
-                    ? "system"
-                    : config.DefaultOwnerId;
-
-                // بررسی وجود سرور با این نام و Owner
-                var existing = await repositoryService.FindByNameAsync(
-                    ownerId: ownerId,
-                    name: descriptor.Name,
-                    cancellationToken: cancellationToken
-                );
-
-                // ── حالت ایجاد ──
-                if (existing.IsNullOrDefault())
-                {
-                    var item = MapToDto(descriptor, ownerId, id: null);
-                    item.CreatedOn = DateTime.UtcNow;
-
-                    await repositoryService.AddAsync(
-                        item: item,
-                        saveChanges: true,
-                        cancellationToken: cancellationToken
-                    );
-
-                    logger.LogInformation(
-                        "MCP Seed: سرور '{Name}' ایجاد شد.", descriptor.Name);
-                    return;
-                }
-
-                // ── حالت به‌روزرسانی ──
-                if (!config.UpdateExisting)
-                {
-                    logger.LogDebug(
-                        "MCP Seed: سرور '{Name}' از قبل وجود دارد (UpdateExisting=false).",
-                        descriptor.Name);
-                    return;
-                }
-
-                var updateItem = MapToDto(descriptor, ownerId, id: existing.Id);
-                updateItem.CreatedOn = existing.CreatedOn;
-                updateItem.UpdatedAt = DateTime.UtcNow;
-
-                await repositoryService.UpdateAsync(
-                    item: updateItem,
-                    id: existing.Id,
-                    saveChanges: true,
-                    cancellationToken: cancellationToken
-                );
-
-                logger.LogInformation(
-                    "MCP Seed: سرور '{Name}' به‌روزرسانی شد.", descriptor.Name);
-            }
-            catch (Exception ex)
-            {
-                logger.LogError(ex,
-                    "MCP Seed: خطا در Seed سرور '{Name}'. این سرور نادیده گرفته می‌شود.",
-                    descriptor.Name);
-            }
-        }
-
-        // ────────────────────────────────────────────────────────
-        // تبدیل Descriptor به DTO
-        // ────────────────────────────────────────────────────────
-        private static XAiMcpServerDto MapToDto(
-            XMcpServerDescriptor d,
-            string ownerId,
-            Guid? id)
-        {
-            var item = new XAiMcpServerDto
-            {
-                OwnerId = ownerId,
-                Name = d.Name,
-                Description = d.Description,
-                Enabled = d.Enabled,
-                Transport = d.Transport,
-                Command = d.Command,
-                Endpoint = d.Endpoint,
-                TimeoutSeconds = d.TimeoutSeconds,
-                WorkingDirectory = d.WorkingDirectory,
-
-                // تبدیل لیست/دیکشنری به JSON برای ذخیره در DB
-                Arguments = d.Arguments.HasChild()
-                    ? JsonSerializer.Serialize(d.Arguments)
-                    : null,
-                EnvironmentVariables = d.EnvironmentVariables.HasChild()
-                    ? JsonSerializer.Serialize(d.EnvironmentVariables)
-                    : null,
-                Headers = d.Headers.HasChild()
-                    ? JsonSerializer.Serialize(d.Headers)
-                    : null,
-            };
-
-            if (id.HasValue) item.Id = id.Value;
-
-            return item;
-        }
-    }
-}
- -
- ✓ رفتار Seeder: -
    -
  • اگر سروری در DB نیست → ایجاد می‌شود
  • -
  • اگر هست و UpdateExisting = false → دست نمی‌خورد
  • -
  • اگر هست و UpdateExisting = true → فیلدها به‌روزرسانی می‌شوند
  • -
  • خطای یک سرور باعث توقف کل فرآیند نمی‌شود
  • -
-
-
-
- - - - -
-
-
۹
-
-

ثبت در Startup.cs

-
Startup.cs (MODIFY)
-
-
-
- -
// ── در ConfigureServices، بعد از AddXAiServices ──
-
-// ۱. ثبت XMcpServersConfiguration از appSettings
-services.Configure<XMcpServersConfiguration>(
-    Configuration.GetSection("McpServers"));
-
-// ۲. ثبت Seeder به‌صورت HostedService
-services.AddHostedService<XMcpServerSeederService>();
-
-// ۳. ثبت Connection Manager (از مرحله قبل)
-services.AddSingleton<XMcpServerConnectionManager>();
-
-// ۴. ثبت Health Monitor
-services.AddHostedService<XMcpHealthMonitorService>();
- -
- ⚠️ ترتیب اجرا: Seeder به‌عنوان IHostedService پس از ساخت کامل DI Container اجرا می‌شود، بنابراین به IXAiMcpServerRepositoryService دسترسی کامل دارد. این ترتیب تضمین می‌کند که تمام ثبت‌های ماژول xAiModels پیش از اجرای Seeder کامل شده باشند. -
-
-
- - - - -
-
-
۱۰
-
-

کنترلر CRUD برای مدیریت از طریق API

-
Controllers/McpServersController.cs
-
-
-
- -
xAiApi/Controllers/McpServersController.cs
-
using System;
-using System.Linq;
-using System.Threading;
-using System.Threading.Tasks;
-using xAiApi.Services;
-using xCommons.Providers;
-using xCommons.Extensions;
-using xExceptions.Constants;
-using xAiModels.Models.Dtos;
-using xCommons.Configurations;
-using Microsoft.AspNetCore.Mvc;
-using System.Collections.Generic;
-using xIdentityService.Interfaces;
-using xIdentityService.Controllers;
-using xAiModels.Interfaces.Dtos;
-using Microsoft.Extensions.Logging;
-using Microsoft.AspNetCore.Authorization;
-
-namespace xAiApi.Controllers
-{
-    [Authorize]
-    [Route("[controller]")]
-    public class McpServersController : XBaseIdentityApiV1Controller
-    {
-        private readonly IXAiMcpServerRepositoryService repositoryService;
-        private readonly XMcpServerConnectionManager connectionManager;
-
-        public McpServersController(
-            ILogger<McpServersController> logger,
-            XAppConfiguration appConfiguration,
-            IXIdentityProvider identityProvider,
-            XValidationProvider validationProvider,
-            XMcpServerConnectionManager connectionManager,
-            IXAiMcpServerRepositoryService repositoryService
-        ) : base(logger, appConfiguration, identityProvider, validationProvider)
-        {
-            this.connectionManager = connectionManager;
-            this.repositoryService = repositoryService;
-        }
-
-        #region Loaders ...
-        /// <summary>
-        /// لیست تمام سرورهای MCP متعلق به کاربر جاری ...
-        /// </summary>
-        [HttpGet("")]
-        public async Task<ActionResult<IEnumerable<XAiMcpServerDto>>> LoadAll(
-            CancellationToken cancellationToken = default)
-        {
-            try
-            {
-                var userInfo = await GetUserInfo();
-
-                var result = await repositoryService.FindManyAsync(
-                    includeBuilder: null,
-                    ignoreSoftDeleteds: true,
-                    cancellationToken: cancellationToken,
-                    predicate: x => x.OwnerId == userInfo.UserId,
-                    orderBuilder: x => x.OrderBy(y => y.Name)
-                );
-
-                return Ok(result);
-            }
-            catch (Exception ex)
-            {
-                return GetExceptionActionResult(ex);
-            }
-        }
-
-        /// <summary>
-        /// دریافت یک سرور بر اساس Id ...
-        /// </summary>
-        [HttpGet("{id:guid}")]
-        public async Task<ActionResult<XAiMcpServerDto>> GetById(
-            Guid id,
-            CancellationToken cancellationToken = default)
-        {
-            try
-            {
-                var userInfo = await GetUserInfo();
-
-                var item = await repositoryService.GetAsync(
-                    id: id,
-                    includeBuilder: null,
-                    ignoreSoftDeleteds: true,
-                    cancellationToken: cancellationToken
-                );
-
-                if (item.IsNullOrDefault() || item.OwnerId != userInfo.UserId)
-                    XException.NotFound.Throw();
-
-                return Ok(item);
-            }
-            catch (Exception ex)
-            {
-                return GetExceptionActionResult(ex);
-            }
-        }
-        #endregion
-
-        #region Creators ...
-        /// <summary>
-        /// ایجاد سرور MCP جدید ...
-        /// </summary>
-        [HttpPost("")]
-        public async Task<ActionResult<XAiMcpServerDto>> Create(
-            [FromBody] XAiMcpServerDto item,
-            CancellationToken cancellationToken = default)
-        {
-            try
-            {
-                if (item.IsNullOrDefault() || item.Name.IsNullOrEmpty())
-                    XException.InvalidArgs.Throw();
-
-                var userInfo = await GetUserInfo();
-
-                // بررسی یکتایی نام برای این Owner
-                var existing = await repositoryService.FindByNameAsync(
-                    ownerId: userInfo.UserId,
-                    name: item.Name,
-                    cancellationToken: cancellationToken
-                );
-
-                if (!existing.IsNullOrDefault())
-                    XException.InvalidArgs.Throw("این نام قبلاً استفاده شده است.");
-
-                // پر کردن فیلدهای ضروری
-                item.Id = Guid.Empty;  // اطمینان از اینکه Id جدید تولید می‌شود
-                item.OwnerId = userInfo.UserId;
-                item.CreatedOn = DateTime.UtcNow;
-                item.UpdatedAt = DateTime.UtcNow;
-
-                var result = await repositoryService.AddAsync(
-                    item: item,
-                    saveChanges: true,
-                    cancellationToken: cancellationToken
-                );
-
-                // بازسازی اتصال‌ها
-                await connectionManager.RefreshAsync();
-
-                return Ok(result);
-            }
-            catch (Exception ex)
-            {
-                return GetExceptionActionResult(ex);
-            }
-        }
-        #endregion
-
-        #region Updaters ...
-        /// <summary>
-        /// به‌روزرسانی سرور MCP ...
-        /// </summary>
-        [HttpPut("{id:guid}")]
-        public async Task<ActionResult<XAiMcpServerDto>> Update(
-            Guid id,
-            [FromBody] XAiMcpServerDto item,
-            CancellationToken cancellationToken = default)
-        {
-            try
-            {
-                if (item.IsNullOrDefault() || id == Guid.Empty)
-                    XException.InvalidArgs.Throw();
-
-                var userInfo = await GetUserInfo();
-
-                var existing = await repositoryService.GetAsync(
-                    id: id,
-                    includeBuilder: null,
-                    ignoreSoftDeleteds: true,
-                    cancellationToken: cancellationToken
-                );
-
-                if (existing.IsNullOrDefault() || existing.OwnerId != userInfo.UserId)
-                    XException.NotFound.Throw();
-
-                // پر کردن فیلدهای سیستم
-                item.Id = id;
-                item.OwnerId = existing.OwnerId;
-                item.CreatedOn = existing.CreatedOn;
-                item.UpdatedAt = DateTime.UtcNow;
-
-                var result = await repositoryService.UpdateAsync(
-                    item: item,
-                    id: id,
-                    saveChanges: true,
-                    cancellationToken: cancellationToken
-                );
-
-                // بازسازی اتصال‌ها
-                await connectionManager.RefreshAsync();
-
-                return Ok(result);
-            }
-            catch (Exception ex)
-            {
-                return GetExceptionActionResult(ex);
-            }
-        }
-        #endregion
-
-        #region Removers ...
-        /// <summary>
-        /// حذف نرم یک سرور MCP ...
-        /// </summary>
-        [HttpDelete("{id:guid}")]
-        public async Task<ActionResult<bool>> Remove(
-            Guid id,
-            CancellationToken cancellationToken = default)
-        {
-            try
-            {
-                var userInfo = await GetUserInfo();
-
-                var existing = await repositoryService.GetAsync(
-                    id: id,
-                    includeBuilder: null,
-                    ignoreSoftDeleteds: true,
-                    cancellationToken: cancellationToken
-                );
-
-                if (existing.IsNullOrDefault() || existing.OwnerId != userInfo.UserId)
-                    XException.NotFound.Throw();
-
-                await repositoryService.RemoveAsync(
-                    id: id,
-                    softDelete: true,
-                    saveChanges: true,
-                    cancellationToken: cancellationToken
-                );
-
-                // بازسازی اتصال‌ها
-                await connectionManager.RefreshAsync();
-
-                return Ok(true);
-            }
-            catch (Exception ex)
-            {
-                return GetExceptionActionResult(ex);
-            }
-        }
-        #endregion
-
-        #region Actions ...
-        /// <summary>
-        /// اعتبارسنجی و اتصال دستی به یک سرور ...
-        /// </summary>
-        [HttpPost("{id:guid}/Test")]
-        public async Task<ActionResult<string>> Test(
-            Guid id,
-            CancellationToken cancellationToken = default)
-        {
-            try
-            {
-                var userInfo = await GetUserInfo();
-
-                var item = await repositoryService.GetAsync(
-                    id: id,
-                    includeBuilder: null,
-                    ignoreSoftDeleteds: true,
-                    cancellationToken: cancellationToken
-                );
-
-                if (item.IsNullOrDefault() || item.OwnerId != userInfo.UserId)
-                    XException.NotFound.Throw();
-
-                var message = await connectionManager.TestServerAsync(
-                    item, cancellationToken);
-
-                return Ok(message);
-            }
-            catch (Exception ex)
-            {
-                return GetExceptionActionResult(ex);
-            }
-        }
-        #endregion
-    }
-}
- -
- 💡 مسیرهای API: - - - - - - - - - - -
متدمسیرتوضیح
GET/McpServersلیست تمام سرورهای کاربر
GET/McpServers/{id}دریافت یک سرور
POST/McpServersایجاد سرور جدید
PUT/McpServers/{id}به‌روزرسانی
DELETE/McpServers/{id}حذف نرم
POST/McpServers/{id}/Testاعتبارسنجی و تست اتصال
-
-
-
- - - - -
-
-
۱۱
-
-

به‌روزرسانی XMcpServerConnectionManager

-
حالا از DB می‌خواند، نه از IOptionsMonitor
-
-
-
-

در نسخه قبل، Connection Manager مستقیماً از IOptionsMonitor<XMcpServersConfiguration> می‌خواند. اکنون باید از دیتابیس بخواند:

- -
xAiApi/Services/XMcpServerConnectionManager.cs (MODIFY)
-
using System;
-using System.Linq;
-using System.Text.Json;
-using System.Threading;
-using System.Threading.Tasks;
-using xAiApi.Constants;
-using xAiModels.Models.Dtos;
-using System.Collections.Generic;
-using Microsoft.Extensions.Logging;
-using ModelContextProtocol.Client;
-using xAiModels.Interfaces.Dtos;
-
-namespace xAiApi.Services
-{
-    public class XMcpServerConnectionManager : IAsyncDisposable
-    {
-        private readonly ILogger<XMcpServerConnectionManager> logger;
-        private readonly IXAiMcpServerRepositoryService repositoryService;
-        private readonly Dictionary<Guid, McpClient> clients = new();
-        private readonly Dictionary<Guid, IList<McpClientTool>> tools = new();
-        private readonly SemaphoreSlim initLock = new(1, 1);
-        private bool isInitialized = false;
-
-        public XMcpServerConnectionManager(
-            ILogger<XMcpServerConnectionManager> logger,
-            IXAiMcpServerRepositoryService repositoryService)
-        {
-            this.logger = logger;
-            this.repositoryService = repositoryService;
-        }
-
-        /// <summary>
-        /// دریافت تمام ابزارهای موجود از سرورهای فعال ...
-        /// </summary>
-        public async Task<IList<McpClientTool>> GetAvailableToolsAsync(
-            CancellationToken cancellationToken = default)
-        {
-            if (isInitialized)
-                return tools.Values.SelectMany(t => t).ToList();
-
-            await initLock.WaitAsync(cancellationToken);
-            try
-            {
-                if (isInitialized)
-                    return tools.Values.SelectMany(t => t).ToList();
-
-                // ← خواندن از DB به‌جای IOptions
-                var servers = await repositoryService.FindManyAsync(
-                    includeBuilder: null,
-                    ignoreSoftDeleteds: true,
-                    cancellationToken: cancellationToken,
-                    predicate: x => x.Enabled
-                );
-
-                if (servers.HasChild())
-                {
-                    var tasks = servers.Select(s =>
-                        ConnectAndValidateAsync(s, cancellationToken));
-                    await Task.WhenAll(tasks);
-                }
-
-                isInitialized = true;
-                return tools.Values.SelectMany(t => t).ToList();
-            }
-            finally
-            {
-                initLock.Release();
-            }
-        }
-
-        /// <summary>
-        /// تست دستی یک سرور خاص ...
-        /// </summary>
-        public async Task<string> TestServerAsync(
-            XAiMcpServerDto server,
-            CancellationToken cancellationToken)
-        {
-            try
-            {
-                using var cts = CancellationTokenSource.CreateLinkedTokenSource(cancellationToken);
-                cts.CancelAfter(TimeSpan.FromSeconds(server.TimeoutSeconds));
-
-                var client = await CreateClientAsync(server, cts.Token);
-                await client.PingAsync(cts.Token);
-                var serverTools = await client.ListToolsAsync(cts.Token);
-
-                var names = string.Join(", ", serverTools.Select(t => t.Name));
-                return $"✓ سرور '{server.Name}' پاسخگو است. {serverTools.Count} ابزار: {names}";
-            }
-            catch (Exception ex)
-            {
-                return $"✗ خطا: {ex.Message}";
-            }
-        }
-
-        // ────────────────────────────────────────────────────────
-        private async Task ConnectAndValidateAsync(
-            XAiMcpServerDto descriptor,
-            CancellationToken cancellationToken)
-        {
-            try
-            {
-                using var cts = CancellationTokenSource.CreateLinkedTokenSource(cancellationToken);
-                cts.CancelAfter(TimeSpan.FromSeconds(descriptor.TimeoutSeconds));
-
-                var client = await CreateClientAsync(descriptor, cts.Token);
-                await client.PingAsync(cts.Token);
-                var serverTools = await client.ListToolsAsync(cts.Token);
-
-                clients[descriptor.Id] = client;
-                tools[descriptor.Id] = serverTools;
-
-                logger.LogInformation(
-                    "MCP '{Name}': {Count} ابزار کشف شد.",
-                    descriptor.Name, serverTools.Count);
-            }
-            catch (Exception ex)
-            {
-                logger.LogWarning(ex,
-                    "MCP '{Name}': اتصال برقرار نشد، نادیده گرفته شد.",
-                    descriptor.Name);
-            }
-        }
-
-        // ────────────────────────────────────────────────────────
-        private static async Task<McpClient> CreateClientAsync(
-            XAiMcpServerDto s,
-            CancellationToken cancellationToken)
-        {
-            IClientTransport transport = s.Transport?.ToLowerInvariant() switch
-            {
-                "http" => new HttpClientTransport(new HttpClientTransportOptions
-                {
-                    Endpoint = new Uri(s.Endpoint!),
-                    AdditionalHeaders = ParseJsonDict(s.Headers),
-                    TransportMode = HttpTransportMode.AutoDetect
-                }),
-                _ => new StdioClientTransport(new StdioClientTransportOptions
-                {
-                    Command = s.Command ?? "dotnet",
-                    Arguments = ParseJsonList(s.Arguments) ?? new List<string>(),
-                    WorkingDirectory = s.WorkingDirectory,
-                    EnvironmentVariables = ParseJsonDict(s.EnvironmentVariables)?
-                        .ToDictionary(kv => kv.Key, kv => (string?)kv.Value),
-                    Name = s.Name,
-                    ShutdownTimeout = TimeSpan.FromSeconds(5)
-                })
-            };
-
-            return await McpClient.CreateAsync(transport,
-                cancellationToken: cancellationToken);
-        }
-
-        // ────────────────────────────────────────────────────────
-        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);
-
-        // ────────────────────────────────────────────────────────
-        public async Task RefreshAsync()
-        {
-            logger.LogInformation("MCP: بازسازی اتصال‌ها ...");
-
-            foreach (var client in clients.Values)
-            {
-                try { await client.DisposeAsync(); } catch { }
-            }
-            clients.Clear();
-            tools.Clear();
-
-            isInitialized = false;
-            await GetAvailableToolsAsync(CancellationToken.None);
-        }
-
-        public async ValueTask DisposeAsync()
-        {
-            foreach (var client in clients.Values)
-            {
-                try { await client.DisposeAsync(); } catch { }
-            }
-            initLock.Dispose();
-        }
-    }
-}
- -
- ✓ نتیجه: حالا مدیریت کامل سرورهای MCP از طریق API انجام می‌شود. با هر تغییر (ایجاد، به‌روزرسانی، حذف)، متد RefreshAsync() فراخوانی می‌شود و ابزارهای کش‌شده به‌روز می‌شوند. appSettings فقط منبع Seed اولیه است. -
-
-
- - - - -
-
-
۱۲
-
-

نمونه کامل appsettings.json

-
appsettings.json (MODIFY)
-
-
-
- -
{
-  "AiApiConfiguration": {
-    "Models": [ /* ... مدل‌های موجود ... */ ],
-    "Prompts": [ /* ... پرامپت‌های موجود ... */ ]
-  },
-
-  "McpServers": {
-    "SyncOnStartup": true,
-    "UpdateExisting": false,
-    "DefaultOwnerId": "system",
-    "Servers": [
-      {
-        "Name": "xai-knowledge",
-        "Description": "سرور MCP جستجو در پایگاه دانش",
-        "Enabled": true,
-        "Transport": "stdio",
-        "Command": "dotnet",
-        "Arguments": [ "xAiMcpServer.dll" ],
-        "TimeoutSeconds": 20
-      },
-      {
-        "Name": "remote-tools",
-        "Description": "ابزارهای تیمی از راه دور",
-        "Enabled": true,
-        "Transport": "http",
-        "Endpoint": "https://tools.example.com/mcp",
-        "Headers": {
-          "X-API-Key": "your-key"
-        },
-        "TimeoutSeconds": 30
-      },
-      {
-        "Name": "file-processor",
-        "Description": "پردازش فایل با معیارهای سفارشی",
-        "Enabled": false,
-        "Transport": "stdio",
-        "Command": "node",
-        "Arguments": [ "file-processor.js", "--port", "3000" ],
-        "EnvironmentVariables": {
-          "LOG_LEVEL": "info"
-        },
-        "TimeoutSeconds": 15
-      }
-    ]
-  },
-
-  "ConnectionStrings": { /* ... */ },
-  "Logging": { /* ... */ }
-}
-
-
- - - - -
-
-
۱۳
-
-

تست و اعتبارسنجی

-
Testing & Validation
-
-
-
-

جریان تست پیشنهادی:

- -
    -
  1. Migration: پس از اعمال Migration، جدول AiMcpServers را در دیتابیس بررسی کنید.
  2. -
  3. اجرای اپلیکیشن: لاگ‌های Seeder را در Output مشاهده کنید — باید پیام‌هایی مانند "MCP Seed: سرور 'xai-knowledge' ایجاد شد." نمایش داده شود.
  4. -
  5. بررسی DB: با یک Query ساده (یا از طریق SQL Server Management Studio) رکوردهای ایجاد شده را ببینید.
  6. -
  7. تست API: با یک توکن معتبر، GET /McpServers را فراخوانی کنید و لیست سرورها را ببینید.
  8. -
  9. تست ایجاد: یک سرور جدید با POST /McpServers بسازید.
  10. -
  11. تست Connection: با POST /McpServers/{id}/Test اعتبارسنجی کنید.
  12. -
  13. تست Function Calling: از /DefaultAi/AskText استفاده کنید و ببینید که LLM ابزارهای MCP را فراخوانی می‌کند یا خیر.
  14. -
- -
- ⚠️ نکات مهم: -
    -
  • اگر Seeder با خطا مواجه شد، بقیه سرورها نباید تحت تأثیر قرار گیرند — این در کد پیاده‌سازی شده است.
  • -
  • هنگام اجرای dotnet ef migrations add، اگر خطای "GraphType not found" دریافت کردید، مقادیر null را برای GraphQL types جایگزین کنید یا آن‌ها را بسازید.
  • -
  • در محیط توسعه، پیشنهاد می‌شود UpdateExisting = true باشد تا تغییرات appSettings سریع اعمال شوند.
  • -
  • در محیط عملیاتی، UpdateExisting = false باشد تا APIها بازنویسی نشوند.
  • -
-
-
-
- - - - -
-
-
۱۴
-
-

جمع‌بندی و چک‌لیست نهایی

-
Summary & Checklist
-
-
-
-

چک‌لیست فایل‌های جدید/تغییر یافته:

- -
    -
  • Entity، DTO و Descriptor در xAiModels/Models ایجاد شد
  • -
  • EntityConfiguration و EntityRegisterar اضافه شد
  • -
  • Constants جدید در XAiModelsConstants افزوده شد
  • -
  • تمام Interfaces (Entities/Dtos/Enrichers) ایجاد شد
  • -
  • Repositoryها (EF/Mongo/InMemory) + KeyGenerator + Events + Hub + Provider ساخته شد
  • -
  • RepositoryService، ServiceProvider، Enricher پیاده‌سازی شد
  • -
  • Helper (سه متد Descriptor) به XAiModelsHelper اضافه شد
  • -
  • ثبت در XDIHelperExtension انجام شد
  • -
  • Mapper Profile به‌روزرسانی شد
  • -
  • Registerar در XAiApiDbContext ثبت شد
  • -
  • Migration اجرا شد
  • -
  • XMcpServersConfiguration و XMcpServerSeederService ایجاد شد
  • -
  • XMcpServerConnectionManager برای خواندن از DB تغییر کرد
  • -
  • McpServersController با CRUD کامل اضافه شد
  • -
  • Startup.cs به‌روزرسانی شد (Configure + HostedServices)
  • -
  • appsettings.json با بخش McpServers تکمیل شد
  • -
- -
-

🎯 نتیجه نهایی

-

با اجرای این مراحل، معماری شما به سطح بالاتری از پویایی و قابلیت مدیریت می‌رسد:

-

- appSettings → Seeder → DB → API CRUD → Connection Manager → ChatOptions.Tools → LLM -

-

- سرورهای MCP کاملاً قابل مدیریت از طریق API هستند، از طریق appSettings به‌طور خودکار Seed می‌شوند، به‌صورت دوره‌ای Health Check می‌شوند، و ابزارهایشان به‌صورت داینامیک در دسترس مدل‌های زبانی قرار می‌گیرند — بدون نیاز به تغییر کد یا ری‌استارت. -

-
-
-
- -
- -
- - -
تاریخ تهیه: آبان ۱۴۰۵  |  نسخه: ۱.۰  |  طبقه‌بندی: فنی-داخلی
-
- -
- - - - -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\xAiApi\wwwroot\Storage\Uploads\Document\xSaherElm_0da0136c-9f49-439d-bc78-84aa19e17262.html - - - - - - -نقشه BPMN2 تعاملی | مولفه‌های معماری سامانه هوش مصنوعی سازمانی - - - - -
- -
-
-
- -
-
-
شماره مستند: BPMN-1405-001
-
نسخه: ۱.۰
-
تاریخ تهیه: مهر ۱۴۰۵
-
طبقه‌بندی: محرمانه
-
-
- -
- BPMN 2.0 INTERACTIVE MAP -

نقشه فرایندی تعاملی مولفه‌ها

-

سامانه هوش مصنوعی سازمانی — بر اساس معماری کلان ARCH-1405-001

-
-
- -
- -
- خلاصه مدیریتی،
- این مستند، تمام مولفه‌های معماری کلان سامانه هوش مصنوعی سازمانی (مستند ARCH-1405-001) را بر اساس استاندارد BPMN 2.0 رسم می‌کند. مولفه‌ها در قالب Lane (لایه‌های معماری) سازمان‌دهی شده‌اند و روابط میان آنها با Sequence Flow نمایش داده می‌شود. با کلیک روی هر مولفه، مودالی شامل وظایف، ورودی‌ها و خروجی‌ها و ارتباطات آن نمایش داده می‌شود. -
- -
-
-
۱
-
-

راهنمای نقشه BPMN2

-
How to Read the Map
-
-
-
-

نقشه زیر بر اساس استاندارد BPMN 2.0 ترسیم شده است. هر Lane نماینده یک لایه معماری است و هر Task (مستطیل) نماینده یک مولفه. فلش‌ها جریان درخواست/کنترل را نشان می‌دهند. روی هر مولفه کلیک کنید تا جزئیات آن را در مودال مشاهده کنید.

- -
-
-
۸
-
Lane (لایه + محور عرضی)
-
-
-
۲۵+
-
مولفه قابل کلیک
-
-
-
BPMN 2.0
-
استاندارد رسم
-
-
- -
- 💡 نحوه استفاده: نشانگر ماوس را روی هر مستطیل ببرید تا هایلایت شود؛ سپس کلیک کنید تا مودال اطلاعات (وظایف، ورودی‌ها، خروجی‌ها و ارتباطات) باز شود. برای بستن مودال، کلید Esc را بزنید یا روی پس‌زمینه کلیک کنید. -
-
-
- -
-
-
۲
-
-

نقشه BPMN2 تعاملی

-
Interactive BPMN2 Process Map
-
-
-
- -
-
- لایه تعامل/گزارش - لایه کنترل/هوش - لایه ارکستراسیون - لایه داده - محور حاکمیت - محور مشاهده‌پذیری -
- 👆 روی هر مولفه کلیک کنید -
- -
- - - - - - - - - - - - - - - - - L1 — تعامل و تجربه - Interaction Layer - - - - - - - - L2 — کنترل دسترسی - Access & Session - - - - - - - - L3 — ارکستراسیون - Orchestration / Agent Core - - - - - - - - L4 — هوش و مدل‌ها - Intelligence Layer - - - - - - - - L5 — داده و منابع - Data & Resources - - - - - - - - L6 — خروجی و گزارش - Output & Reporting - - - - - - - - X — حاکمیت داده - Data Governance (Cross-cutting) - - - - - - - - Y — مشاهده‌پذیری - Observability (Cross-cutting) - - - - - - - - کاربر / Actor - External Actor - - - - - - - - رابط وب - Web UI - - - - - - نسخه دسکتاپ - Desktop App - - - - - - درگاه API - API Gateway - - - - - - - احراز هویت - Authentication - - - - - - مدیریت نشست - Session Manager - - - - - - موتور مجوزها - Permission Engine - - - - - - مدیریت نقش‌ها - Role Manager - - - - - - - موتور ایجنت - Agent Engine - - - - - - برنامه‌ریز - Planner - - - - - - انتخاب‌گر ابزار - Tool Selector - - - - - - مدیریت جریان - Flow Manager - - - - - - تأیید انسانی - Human-in-the-loop - - - - - - - درگاه مدل‌ها - Model Gateway - - - - - - مدیریت مدل - Model Manager - - - - - - بازیابی و تقویت - RAG - - - - - - حافظه و زمینه - Memory & Context - - - - - - - منابع دانش - Knowledge Sources - - - - - - مدیریت فایل - File & Folder - - - - - - سرویس‌های خارجی - External Services - - - - - - ابزارهای عملیاتی - Operational Tools - - - - - - - تولید گزارش - Report Generator - - - - - - مبدل قالب - Format Converter - - - - - - داشبورد مصرف - Usage Dashboard - - - - - - - سیاست‌گذار داده - Data Policy - - - - - - ممیزی و لاگ - Audit & Log - - - - - - سنسور محرمانگی - Confidentiality Sensor - - - - - - - متریک و ردیابی - Metrics & Tracing - - - - - - - کاربر سازمانی - Actor / User - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - درخواست - درخواست - درخواست - زمینه - مجوزها - استدلال - ابزار - نتیجه - فایل - فیلتر - متریک - - - - راهنمای نمادها (BPMN 2.0): - - Task / مولفه - - Sequence Flow - - Data / Control Flow - - Actor - - - -
- -
- 💡 نکته: این نقشه بر اساس استاندارد BPMN 2.0 ترسیم شده است. Laneها نماینده لایه‌های معماری (L1 تا L6) و محورهای عرضی (X و Y) هستند. فلش‌های ممتد نماینده Sequence Flow (جریان اصلی درخواست) و فلش‌های نقطه‌چین نماینده Data/Control Flow (جریان داده و کنترل عرضی) هستند. -
-
-
- -
-
-
۳
-
-

جدول مولفه‌ها و ارتباطات

-
Component & Connection Summary
-
-
-
-

جدول زیر خلاصه‌ای از تمام مولفه‌های نقشه و ارتباطات ورودی/خروجی آنهاست. برای جزئیات بیشتر، روی هر مولفه در نقشه کلیک کنید.

- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
Laneمولفهورودی اصلیخروجی اصلیمقصد
L1رابط وب / دسکتاپ / APIدرخواست کاربردرخواست ساختاریافتهمدیریت نشست
L2احراز هویتاعتبارنامههویت تأییدشدهمدیریت نشست
L2مدیریت نشستهویت + درخواستنشست فعالموتور ایجنت
L2موتور مجوزهانقش‌هافهرست مجازموتور ایجنت
L2مدیریت نقش‌هاتعریف نقشمجوزهای به‌روزموتور مجوزها
L3موتور ایجنتهدف + زمینهبرنامه / نتیجهبرنامه‌ریز / گزارش
L3برنامه‌ریزهدفمراحل اجراییانتخاب‌گر ابزار
L3انتخاب‌گر ابزارمرحلهابزار انتخاب‌شدهابزارهای عملیاتی
L3مدیریت جریاننتیجه اجراتصمیم ادامه/اصلاحموتور ایجنت
L3تأیید انسانیدرخواست تأییدتأیید/ردموتور ایجنت
L4درگاه مدل‌هادرخواست استدلالپاسخ مدلموتور ایجنت
L4مدیریت مدلفهرست مدلمدل مجازدرگاه مدل‌ها
L4بازیابی و تقویتپرسششواهددرگاه مدل‌ها
L4حافظه و زمینهتاریخچهزمینه فعالدرگاه مدل‌ها
L5منابع دانشدرخواست بازیابیاطلاعات مرتبطبازیابی و تقویت
L5مدیریت فایلمسیر فایلمحتوای فایلتولید گزارش
L5سرویس‌های خارجیدرخواست APIپاسخ سرویسدرگاه مدل‌ها
L5ابزارهای عملیاتیفراخوانینتیجه اجرامدیریت جریان
L6تولید گزارشنتیجه ایجنتگزارشمبدل قالب
L6مبدل قالبگزارشWord/Excelرابط کاربری
L6داشبورد مصرفمتریکگزارش مصرفرابط کاربری
Xسیاست‌گذار دادهسیاست سازمانیمحدودیت انتقالسرویس خارجی / درگاه مدل
Xممیزی و لاگرخدادهالاگ ممیزیداشبورد
Xسنسور محرمانگیپاسخ پیش از ارائهپاسخ فیلترشدهرابط کاربری
Yمتریک و ردیابیرخداد اجرامتریکداشبورد مصرف
-
-
- -
-
-
۴
-
-

جمع‌بندی

-
Summary
-
-
-
-

این مستند، تمام مولفه‌های معماری کلان سامانه هوش مصنوعی سازمانی را بر اساس استاندارد BPMN 2.0 رسم کرده است. ویژگی‌های کلیدی این نقشه:

- -
    -
  • ۸ Lane: شش لایه معماری + دو محور عرضی (حاکمیت داده و مشاهده‌پذیری) + Actor
  • -
  • ۲۵+ مولفه قابل کلیک: هر مولفه دارای مودال اطلاعاتی شامل وظایف، ورودی، خروجی و ارتباطات
  • -
  • دو نوع جریان: Sequence Flow (ممتد) برای جریان اصلی و Data/Control Flow (نقطه‌چین) برای جریان عرضی
  • -
  • رنگ‌بندی معنادار: هر لایه با رنگ مشخص، محورهای عرضی با خط‌چین و رنگ متمایز
  • -
  • نگاشت به نیازمندی‌ها: هر مولفه به محور نیازمندی مرتبط (REQ-1405-001) ارجاع داده شده است
  • -
- -
- نکته کلیدی: این نقشه BPMN2، پل ارتباطی بین معماری کلان (ARCH-1405-001) و طراحی تفصیلی است. هر مولفه در این نقشه، در مرحله طراحی تفصیلی به یک یا چند سرویس/ماژول قابل پیاده‌سازی تبدیل خواهد شد. -
-
-
- -
-

🎯 ارزش این مستند

-

نقشه BPMN2 تعاملی، امکان درک سریع و دقیق معماری را برای ذی‌نفعان فنی و غیرفنی فراهم می‌کند.

-

هر مولفه با کلیک، اطلاعات کامل وظایف و ارتباطات ورودی/خروجی را نمایش می‌دهد و مبنای طراحی تفصیلی و پیاده‌سازی قرار می‌گیرد.

-
- 💎 ارزش پیشنهادی:
- استاندارد BPMN 2.0 + تعامل‌پذیری کامل + نگاشت به نیازمندی‌ها + مبنای طراحی تفصیلی -
-
- -
- این مستند محرمانه بوده و صرفاً جهت ارائه به کارفرمای محترم تهیه شده است. هرگونه کپی‌برداری یا افشا بدون اجازه کتبی ممنوع است. -
- -
- -
- - -
تاریخ تهیه: مهر ۱۴۰۵  |  نسخه: ۱.۰  |  طبقه‌بندی: محرمانه
-
- -
- - - - - - - - - -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\xAiApi\wwwroot\Storage\Uploads\Document\xSaherElm_0e4bdfcb-39a4-4b1f-94fa-d8159119150e.html - - - - - - -طراحی قابلیت مدیریت ApiKey و برنامه‌های کاربردی | مستند فنی - - - -
-
-
-
- -
-
-
شماره مستند: ARCH-APIKEY-1405-002
-
نسخه: ۱.۰
-
تاریخ تهیه: ۱۲ مهر ۱۴۰۵
-
تهیه‌کننده: هادی خزاعی اصل
-
طبقه‌بندی: محرمانه
-
-
-
-API KEY MANAGEMENT SYSTEM -

طراحی قابلیت مدیریت ApiKey و برنامه‌های کاربردی

-

بررسی نیازمندی‌ها، معماری و پیاده‌سازی گام به گام

-
-
- -
- -
-توسعه‌دهنده گرامی،
-این مستند به‌عنوان یک طرح جامع فنی، قابلیت ایجاد برنامه‌های کاربردی دارای ApiKey را با پیروی از الگوهای OAuth2 در پلتفرم xDashboard بررسی می‌کند. در این سند، علاوه بر نیازمندی‌های اعلام‌شده، نیازمندی‌های تکمیلی و پیشنهادات بهبودی نیز ارائه شده است تا یک راهکار کامل، امن و مقیاس‌پذیر طراحی گردد. -
- - - - - -
-
-
۱
-
-

خلاصه اجرایی و آمار کلیدی

-
Executive Summary & Key Statistics
-
-
-
-

سیستم مدیریت ApiKey، یک لایه امنیتی جدید به پلتفرم xDashboard اضافه می‌کند که امکان ایجاد برنامه‌های کاربردی (Applications) با کلیدهای دسترسی موقت را فراهم می‌سازد. این سیستم بر پایه الگوهای OAuth2 Client Credentials طراحی شده و با زیرساخت IdentityServer4 موجود در xIds یکپارچه می‌گردد.

- -
-
-
۳
-
لایه اصلی پیاده‌سازی
-
-
-
۵
-
Entity جدید
-
-
-
۱۲+
-
نیازمندی تکمیلی
-
-
-
۴
-
مرحله پیاده‌سازی
-
-
- -
-نکته کلیدی: این راهکار با حفظ سازگاری کامل با الگوهای موجود پروژه (مانند XValidationProvider، XException، XPolicies و IXIdentityManager)، قابلیت ادغام بدون اصطکاک با اکوسیستم فعلی را دارد. -
-
-
- - -
-
-
۲
-
-

بررسی نیازمندی‌های اعلام‌شده

-
Analysis of Stated Requirements
-
-
-
-

بر اساس درخواست اعلام‌شده، سه نیازمندی اصلی شناسایی شده‌اند:

- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
#نیازمندیمحل پیاده‌سازیالگوی مرجع
۱ایجاد برنامه کاربردی و تولید ApiKey با مدت انقضای قابل تنظیمxIdsOAuth2 Client Credentials
۲اعتبارسنجی ApiKey در سرویس‌های مرتبطxIdentityServiceToken Introspection
۳تعریف دسترسی بر اساس ApiKey در احراز هویتxIds + xApiPolicy-based Authorization
- -
-💡 تحلیل اولیه: این نیازمندی‌ها در واقع پیاده‌سازی یک OAuth2 Client کامل هستند که در آن هر "برنامه کاربردی" معادل یک Client در IdentityServer4 بوده و ApiKey معادل ClientSecret است. با این حال، برای مدیریت بهتر چرخه حیات، نیاز به یک لایه انتزاعی بالاتر داریم. -
-
-
- - -
-
-
۳
-
-

نیازمندی‌های تکمیلی و پیشنهادات بهبود

-
Additional Requirements & Improvement Suggestions
-
-
-
-

در بررسی دقیق‌تر، نیازمندی‌های زیر شناسایی شدند که در درخواست اولیه ذکر نشده‌اند اما برای یک پیاده‌سازی کامل و امن ضروری هستند:

- -

🔐 الف) نیازمندی‌های امنیتی

-
-
-
🔑
-

۱. چرخش کلید (Key Rotation)

-

امکان تولید کلید جدید بدون اختلال در سرویس‌های در حال اجرا، با پشتیبانی از همزیستی موقت کلید قدیم و جدید.

-
-
-
🚫
-

۲. ابطال فوری (Revocation)

-

امکان Revoke کردن ApiKey قبل از انقضای طبیعی، برای موارد اضطراری مانند نشت کلید.

-
-
-
🌐
-

۳. IP Whitelist

-

محدودسازی استفاده از ApiKey به IPهای مشخص برای کاهش ریسک سوءاستفاده در صورت نشت.

-
-
-
🔒
-

۴. Rate Limiting

-

محدودیت تعداد درخواست در واحد زمان برای هر ApiKey جهت جلوگیری از سوءاستفاده و حملات DoS.

-
-
- -

📊 ب) نیازمندی‌های مدیریتی

-
-
-
📝
-

۵. Metadata و توضیحات

-

ذخیره نام برنامه، توضیحات، نام مالک و اطلاعات تماس برای هر ApiKey.

-
-
-
👤
-

۶. Owner Assignment

-

تخصیص هر ApiKey به یک کاربر یا سازمان مشخص برای مدیریت متمرکز و حسابرسی.

-
-
-
📈
-

۷. Audit Log

-

ثبت کامل لاگ استفاده از هر ApiKey شامل زمان، IP، Endpoint و نتیجه درخواست.

-
-
-
🏷️
-

۸. Scope Management

-

تعریف دقیق Scopeهای مجاز برای هر ApiKey (مانند read, write, admin) مشابه OAuth2.

-
-
- -

⚙️ ج) نیازمندی‌های عملیاتی

-
-
-
🔔
-

۹. Notification System

-

اطلاع‌رسانی به مالک قبل از انقضای ApiKey (مثلاً ۷ روز قبل) از طریق Email/SMS.

-
-
-
🔄
-

۱۰. Auto-Extension

-

امکان تمدید خودکار ApiKey در صورت فعال بودن برنامه (اختیاری).

-
-
-
📦
-

۱۱. Bulk Operations

-

امکان ایجاد، ابطال یا تمدید دسته‌ای ApiKeyها برای مدیریت در مقیاس بزرگ.

-
-
-
🗂️
-

۱۲. Tagging & Categorization

-

دسته‌بندی ApiKeyها بر اساس نوع برنامه (Mobile, Web, IoT, Third-party) برای گزارش‌گیری.

-
-
- -
-⚠️ پیشنهاد مهم: پیاده‌سازی حداقل موارد ۱ تا ۴ (چرخش کلید، ابطال فوری، IP Whitelist، Rate Limiting) برای یک سیستم تولیدی (Production) الزامی است. سایر موارد بر اساس اولویت کسب‌وکار در فازهای بعدی قابل اضافه شدن هستند. -
-
-
- - -
-
-
۴
-
-

طراحی معماری و مدل داده

-
Architecture Design & Data Model
-
-
-
- -

🏗️ معماری کلی سیستم

-
-
-
لایه API
-
ApplicationController — مدیریت برنامه‌ها و ApiKeyها (CRUD)
-
-
-
لایه سرویس
-
XApplicationManager — منطق تجاری، تولید کلید، مدیریت چرخه حیات
-
-
-
لایه زیرساخت
-
XApiKeyValidator + XApiKeyAuthProvider — اعتبارسنجی و احراز هویت
-
-
-
لایه داده
-
XApplication + XApiKey + XApiKeyUsageLog — Entityهای جدید
-
-
- -

📋 مدل‌های داده پیشنهادی

- -
-// Entity: XApplication (برنامه کاربردی)
-public class XApplication : XBaseGuidIDEntity
-{
-    [Required][StringLength(255)]
-    public string Name { get; set; }
-    
-    [StringLength(1000)]
-    public string Description { get; set; }
-    
-    [Required][StringLength(255)]
-    public string OwnerId { get; set; } // XUser.Id
-    
-    public XApplicationType Type { get; set; }
-    public bool IsActive { get; set; } = true;
-    public DateTime CreatedOn { get; set; }
-    public DateTime UpdatedAt { get; set; }
-    
-    // Navigation
-    public virtual ICollection<XApiKey> ApiKeys { get; set; }
-} -
- -
-// Entity: XApiKey (کلید دسترسی)
-public class XApiKey : XBaseGuidIDEntity
-{
-    [Required]
-    public Guid ApplicationId { get; set; }
-    
-    [Required][StringLength(512)]
-    public string KeyHash { get; set; } // SHA256 of ApiKey
-    
-    [StringLength(100)]
-    public string KeyPrefix { get; set; } // "xapp_abc123..."
-    
-    [Required]
-    public DateTime ExpiresAt { get; set; }
-    
-    public DateTime CreatedOn { get; set; }
-    public DateTime? LastUsedAt { get; set; }
-    public DateTime? RevokedAt { get; set; }
-    public string RevokedBy { get; set; }
-    
-    public bool IsRevoked => RevokedAt.HasValue;
-    public bool IsExpired => DateTime.UtcNow >= ExpiresAt;
-    public bool IsActive => !IsRevoked && !IsExpired;
-    
-    // Scope & Restrictions
-    [StringLength(1000)]
-    public string AllowedScopes { get; set; } // JSON array
-    
-    [StringLength(2000)]
-    public string AllowedIPs { get; set; } // Comma-separated
-    
-    public int RateLimitPerMinute { get; set; } = 60;
-    
-    // Navigation
-    public virtual XApplication Application { get; set; }
-} -
- -
-// Entity: XApiKeyUsageLog (لاگ استفاده)
-public class XApiKeyUsageLog : XBaseLongIDEntity
-{
-    public Guid ApiKeyId { get; set; }
-    public string Endpoint { get; set; }
-    public string HttpMethod { get; set; }
-    public string ClientIP { get; set; }
-    public int StatusCode { get; set; }
-    public DateTime RequestedOn { get; set; }
-    public long ResponseTimeMs { get; set; }
-} -
- -

🔢 Enumهای مورد نیاز

-
-public enum XApplicationType
-{
-    Web, Mobile, Desktop, IoT, ThirdParty, Service
-}
-
-public enum XApiKeyScope
-{
-    [StringValue("read")] Read,
-    [StringValue("write")] Write,
-    [StringValue("admin")] Admin,
-    [StringValue("manage")] Manage
-} -
-
-
- - -
-
-
۵
-
-

مرحله ۱: پیاده‌سازی در xIds

-
Phase 1: Implementation in xIds Module
-
-
-
- -

📌 گام ۱.۱: افزودن تنظیمات قابل پیکربندی

-

در کلاس XIdentityConfiguration (موجود در xIdentityModels)، بخش جدید برای تنظیمات ApiKey اضافه می‌شود:

- -
-// File: xIdentityModels/Configurations/XIdentityConfiguration.cs
-public class XIdentityConfiguration
-{
-    // ... existing properties ...
-    
-    public XApiKeyConfiguration ApiKey { get; set; } = new();
-}
-
-public class XApiKeyConfiguration
-{
-    // Default expiration in minutes (e.g., 43200 = 30 days)
-    public int DefaultExpirationMinutes { get; set; } = 43200;
-    
-    // Maximum allowed expiration (e.g., 525600 = 1 year)
-    public int MaxExpirationMinutes { get; set; } = 525600;
-    
-    // Maximum ApiKeys per Application
-    public int MaxKeysPerApplication { get; set; } = 10;
-    
-    // Notification before expiration (minutes)
-    public int NotifyBeforeMinutes { get; set; } = 10080; // 7 days
-    
-    // Enable audit logging
-    public bool EnableAuditLog { get; set; } = true;
-    
-    // Default rate limit (requests per minute)
-    public int DefaultRateLimit { get; set; } = 60;
-} -
- -

📌 گام ۱.۲: افزودن DbContext و Migration

-

در XIdentityDbContext، DbSetهای جدید اضافه می‌شوند:

- -
-// File: xIds/DbContext/XIdentityDbContext.cs
-public class XIdentityDbContext : IdentityDbContext
-{
-    // ... existing DbSets ...
-    
-    public DbSet<XApplication> Applications { get; set; }
-    public DbSet<XApiKey> ApiKeys { get; set; }
-    public DbSet<XApiKeyUsageLog> ApiKeyUsageLogs { get; set; }
-    
-    protected override void OnModelCreating(ModelBuilder modelBuilder)
-    {
-        base.OnModelCreating(modelBuilder);
-        
-        // Configure XApplication
-        modelBuilder.Entity<XApplication>(e => {
-            e.HasIndex(a => a.Name).IsUnique();
-            e.HasMany(a => a.ApiKeys)
-             .WithOne(k => k.Application)
-             .HasForeignKey(k => k.ApplicationId);
-        });
-        
-        // Configure XApiKey
-        modelBuilder.Entity<XApiKey>(e => {
-            e.HasIndex(k => k.KeyHash).IsUnique();
-            e.HasIndex(k => k.ExpiresAt);
-        });
-    }
-} -
- -

📌 گام ۱.۳: پیاده‌سازی XApplicationManager

-

یک کلاس جدید برای مدیریت برنامه‌ها و ApiKeyها مشابه الگوی XIdentityManager موجود:

- -
-// File: xIds/Interfaces/IXApplicationManager.cs
-public interface IXApplicationManager
-{
-    // Application CRUD
-    Task<XApplicationDto> CreateApplication(XApplicationDto item, string ownerId);
-    Task<XApplicationDto> UpdateApplication(Guid id, XApplicationDto item);
-    Task<bool> DeleteApplication(Guid id);
-    Task<XApplicationDto> GetApplication(Guid id);
-    Task<IEnumerable<XApplicationDto>> GetOwnerApplications(string ownerId);
-    
-    // ApiKey Management
-    Task<XApiKeyCreationResult> CreateApiKey(
-        Guid applicationId,
-        TimeSpan? expiration = null,
-        IEnumerable<string> scopes = null,
-        IEnumerable<string> allowedIPs = null,
-        int? rateLimit = null);
-    
-    Task<bool> RevokeApiKey(Guid apiKeyId, string revokedBy);
-    Task<XApiKeyDto> RotateApiKey(Guid apiKeyId, TimeSpan? newExpiration = null);
-    Task<IEnumerable<XApiKeyDto>> GetApplicationApiKeys(Guid applicationId);
-    
-    // Validation
-    Task<XApiKeyValidationResult> ValidateApiKey(string apiKey, string clientIP);
-} -
- -

📌 گام ۱.۴: تولید امن ApiKey

-

الگوی تولید کلید باید از نظر رمزنگاری امن باشد:

- -
-// File: xIds/Helpers/XApiKeyGenerator.cs
-public static class XApiKeyGenerator
-{
-    public static (string plainKey, string hash, string prefix) Generate()
-    {
-        // Generate 32 bytes of cryptographically secure random data
-        var randomBytes = new byte[32];
-        using (var rng = RandomNumberGenerator.Create())
-        {
-            rng.GetBytes(randomBytes);
-        }
-        
-        // Format: xapp_{base64url}
-        var plainKey = $"xapp_{Convert.ToBase64String(randomBytes)
-            .Replace("+", "-").Replace("/", "_").TrimEnd('=')}";
-        
-        // Hash with SHA256 for storage (never store plain key)
-        using (var sha256 = SHA256.Create())
-        {
-            var hashBytes = sha256.ComputeHash(Encoding.UTF8.GetBytes(plainKey));
-            var hash = BitConverter.ToString(hashBytes).Replace("-", "").ToLower();
-            
-            // Prefix for quick identification (first 12 chars)
-            var prefix = plainKey.Substring(0, 16) + "...";
-            
-            return (plainKey, hash, prefix);
-        }
-    }
-    
-    public static bool Verify(string plainKey, string storedHash)
-    {
-        using (var sha256 = SHA256.Create())
-        {
-            var hashBytes = sha256.ComputeHash(Encoding.UTF8.GetBytes(plainKey));
-            var computedHash = BitConverter.ToString(hashBytes)
-                .Replace("-", "").ToLower();
-            return computedHash == storedHash;
-        }
-    }
-} -
- -
-✅ ویژگی‌های امنیتی این طراحی: -
    -
  • کلید ApiKey هرگز به‌صورت Plain Text ذخیره نمی‌شود (فقط Hash)
  • -
  • استفاده از RandomNumberGenerator برای تولید امن
  • -
  • پیشوند xapp_ برای شناسایی سریع نوع کلید
  • -
  • Prefix کوتاه برای نمایش در UI بدون افشای کلید کامل
  • -
-
-
-
- - -
-
-
۶
-
-

مرحله ۲: سرویس اعتبارسنجی ApiKey

-
Phase 2: ApiKey Validation Service
-
-
-
- -

📌 گام ۲.۱: طراحی XApiKeyValidator

-

این سرویس مسئولیت اعتبارسنجی کامل ApiKey را بر عهده دارد:

- -
-// File: xIds/Validators/XApiKeyValidator.cs
-public class XApiKeyValidator : IXApiKeyValidator
-{
-    private readonly XIdentityDbContext _dbContext;
-    private readonly IXIdentityConfiguration _config;
-    private readonly IMemoryCache _cache; // For rate limiting
-    
-    public async Task<XApiKeyValidationResult> ValidateAsync(
-        string apiKey, string clientIP, string requiredScope = null)
-    {
-        var result = new XApiKeyValidationResult();
-        
-        // Step 1: Compute hash of provided key
-        var hash = XApiKeyGenerator.ComputeHash(apiKey);
-        
-        // Step 2: Lookup in database
-        var keyEntity = await _dbContext.ApiKeys
-            .Include(k => k.Application)
-            .FirstOrDefaultAsync(k => k.KeyHash == hash);
-        
-        if (keyEntity == null)
-        {
-            result.IsValid = false;
-            result.Error = XException.InvalidApiKey;
-            return result;
-        }
-        
-        // Step 3: Check expiration
-        if (keyEntity.IsExpired)
-        {
-            result.IsValid = false;
-            result.Error = XException.ApiKeyExpired;
-            return result;
-        }
-        
-        // Step 4: Check revocation
-        if (keyEntity.IsRevoked)
-        {
-            result.IsValid = false;
-            result.Error = XException.ApiKeyRevoked;
-            return result;
-        }
-        
-        // Step 5: Check application active
-        if (!keyEntity.Application.IsActive)
-        {
-            result.IsValid = false;
-            result.Error = XException.ApplicationDisabled;
-            return result;
-        }
-        
-        // Step 6: Check IP whitelist
-        if (!string.IsNullOrEmpty(keyEntity.AllowedIPs))
-        {
-            var allowedIPs = keyEntity.AllowedIPs.Split(',');
-            if (!allowedIPs.Contains(clientIP))
-            {
-                result.IsValid = false;
-                result.Error = XException.IPNotAllowed;
-                return result;
-            }
-        }
-        
-        // Step 7: Check rate limit
-        if (!CheckRateLimit(keyEntity.Id, keyEntity.RateLimitPerMinute))
-        {
-            result.IsValid = false;
-            result.Error = XException.RateLimitExceeded;
-            return result;
-        }
-        
-        // Step 8: Check scope (if required)
-        if (!string.IsNullOrEmpty(requiredScope))
-        {
-            var scopes = JsonConvert.DeserializeObject<List<string>>(keyEntity.AllowedScopes);
-            if (!scopes.Contains(requiredScope))
-            {
-                result.IsValid = false;
-                result.Error = XException.InsufficientScope;
-                return result;
-            }
-        }
-        
-        // Step 9: Update LastUsedAt
-        keyEntity.LastUsedAt = DateTime.UtcNow;
-        await _dbContext.SaveChangesAsync();
-        
-        // Step 10: Build success result
-        result.IsValid = true;
-        result.ApplicationId = keyEntity.ApplicationId;
-        result.OwnerId = keyEntity.Application.OwnerId;
-        result.Scopes = JsonConvert.DeserializeObject<List<string>>(keyEntity.AllowedScopes);
-        
-        return result;
-    }
-} -
- -

📌 گام ۲.۲: پیاده‌سازی Rate Limiter

-
-private bool CheckRateLimit(Guid apiKeyId, int limitPerMinute)
-{
-    var cacheKey = $"ratelimit:{apiKeyId}";
-    var currentCount = _cache.GetOrCreate(cacheKey, entry => {
-        entry.SlidingExpiration = TimeSpan.FromMinutes(1);
-        return 0;
-    });
-    
-    if (currentCount >= limitPerMinute)
-        return false;
-    
-    _cache.Set(cacheKey, currentCount + 1, TimeSpan.FromMinutes(1));
-    return true;
-} -
-
-
- - -
-
-
۷
-
-

مرحله ۳: سرویس احراز هویت مبتنی بر ApiKey

-
Phase 3: ApiKey Authentication Service
-
-
-
- -

📌 گام ۳.۱: ایجاد Authentication Handler

-

برای یکپارچگی با ASP.NET Core Authentication، یک Handler جدید ایجاد می‌کنیم:

- -
-// File: xIdentityService/Authentication/XApiKeyAuthenticationHandler.cs
-public class XApiKeyAuthenticationHandler : AuthenticationHandler<XApiKeyAuthenticationOptions>
-{
-    public const string AuthenticationScheme = "XApiKey";
-    public const string HeaderName = "X-Api-Key";
-    
-    private readonly IXApiKeyValidator _validator;
-    
-    protected override async Task<AuthenticateResult> HandleAuthenticateAsync()
-    {
-        // Extract ApiKey from header
-        if (!Request.Headers.ContainsKey(HeaderName))
-            return AuthenticateResult.NoResult();
-        
-        var apiKey = Request.Headers[HeaderName].ToString();
-        var clientIP = Request.HttpContext.Connection.RemoteIpAddress?.ToString();
-        
-        // Validate ApiKey
-        var validationResult = await _validator.ValidateAsync(apiKey, clientIP);
-        
-        if (!validationResult.IsValid)
-            return AuthenticateResult.Fail(validationResult.Error.Message);
-        
-        // Build ClaimsPrincipal
-        var claims = new[]
-        {
-            new Claim(ClaimTypes.Name, validationResult.OwnerId),
-            new Claim("application_id", validationResult.ApplicationId.ToString()),
-            new Claim("auth_type", "apikey"),
-            new Claim(JwtClaimTypes.Scope, "apikey"),
-        };
-        
-        // Add scope claims
-        var scopeClaims = validationResult.Scopes
-            .Select(s => new Claim(JwtClaimTypes.Scope, s));
-        
-        var identity = new ClaimsIdentity(claims.Union(scopeClaims), AuthenticationScheme);
-        var principal = new ClaimsPrincipal(identity);
-        var ticket = new AuthenticationTicket(principal, AuthenticationScheme);
-        
-        return AuthenticateResult.Success(ticket);
-    }
-} -
- -

📌 گام ۳.۲: ثبت در Startup

-
-// File: xApi/Startup.cs - ConfigureServices
-services.AddAuthentication(options => {
-    options.DefaultScheme = JwtBearerDefaults.AuthenticationScheme;
-})
-.AddJwtBearer(/* existing config */)
-.AddScheme<XApiKeyAuthenticationOptions, XApiKeyAuthenticationHandler>(
-    XApiKeyAuthenticationHandler.AuthenticationScheme,
-    options => { });
-
-// Authorization policies for ApiKey
-services.AddAuthorization(options => {
-    options.AddPolicy("ApiKeyAccess", policy => {
-        policy.AddAuthenticationSchemes(XApiKeyAuthenticationHandler.AuthenticationScheme);
-        policy.RequireAuthenticatedUser();
-    });
-    
-    // Scope-based policies
-    options.AddPolicy("ApiKeyRead", policy => {
-        policy.AddAuthenticationSchemes(XApiKeyAuthenticationHandler.AuthenticationScheme);
-        policy.RequireClaim(JwtClaimTypes.Scope, "read", "write", "admin");
-    });
-}); -
- -

📌 گام ۳.۳: استفاده در Controllerها

-
-// Example: Supporting both JWT and ApiKey authentication
-[Authorize(Policy = "ApiKeyRead")]
-public class DataController : ControllerBase
-{
-    [HttpGet("items")]
-    public async Task<ActionResult> GetItems()
-    {
-        // Works with both JWT Bearer and X-Api-Key header
-        var userId = User.Identity.Name;
-        // ...
-    }
-} -
-
-
- - -
-
-
۸
-
-

مرحله ۴: API Endpoints

-
Phase 4: API Endpoints Design
-
-
-
- -

📌 طراحی Controller

-
-// File: xIds/Controllers/ApplicationController.cs
-[ApiController]
-[Route("api/v1/applications")]
-[Authorize(Policy = XPolicies.EnabledUser)]
-public class ApplicationController : XIBaseController
-{
-    // Application CRUD
-    [HttpPost]
-    public async Task<ActionResult<XApplicationDto>> Create(XApplicationDto model);
-    
-    [HttpGet]
-    public async Task<ActionResult<IEnumerable<XApplicationDto>>> GetMyApplications();
-    
-    [HttpPut("{id}")]
-    public async Task<ActionResult> Update(Guid id, XApplicationDto model);
-    
-    [HttpDelete("{id}")]
-    public async Task<ActionResult> Delete(Guid id);
-    
-    // ApiKey Management
-    [HttpPost("{appId}/apikeys")]
-    public async Task<ActionResult<XApiKeyCreationResponse>> CreateApiKey(
-        Guid appId, XCreateApiKeyRequest request);
-    
-    [HttpGet("{appId}/apikeys")]
-    public async Task<ActionResult<IEnumerable<XApiKeyDto>>> GetApiKeys(Guid appId);
-    
-    [HttpPost("apikeys/{id}/revoke")]
-    public async Task<ActionResult> RevokeApiKey(Guid id);
-    
-    [HttpPost("apikeys/{id}/rotate")]
-    public async Task<ActionResult<XApiKeyCreationResponse>> RotateApiKey(Guid id);
-} -
- -

📋 DTOهای مورد نیاز

- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
DTOکاربردفیلدهای کلیدی
XApplicationDtoنمایش برنامهId, Name, Description, Type, IsActive, CreatedOn
XCreateApplicationRequestدرخواست ساخت برنامهName, Description, Type
XApiKeyDtoنمایش ApiKey (بدون کلید کامل)Id, KeyPrefix, ExpiresAt, LastUsedAt, Scopes, IsActive
XCreateApiKeyRequestدرخواست ساخت ApiKeyExpirationMinutes, Scopes, AllowedIPs, RateLimit
XApiKeyCreationResponseپاسخ ساخت (فقط یکبار کلید کامل)ApiKey (plain), ExpiresAt, KeyPrefix
- -
-🔴 نکته امنیتی بسیار مهم: کلید ApiKey به‌صورت Plain Text فقط یکبار در پاسخ XApiKeyCreationResponse به کاربر نمایش داده می‌شود. پس از آن، فقط KeyPrefix قابل مشاهده است و کاربر در صورت فراموشی کلید، باید آن را Rotate کند. -
-
-
- - -
-
-
۹
-
-

جریان عملیات و سناریوها

-
Operational Flows & Scenarios
-
-
-
- -

🔄 سناریوی ۱: ایجاد برنامه و دریافت ApiKey

-
-
-
۱
-
-کاربر درخواست ایجاد برنامه را ارسال می‌کند -POST /api/v1/applications با payload شامل نام، توضیحات و نوع برنامه -
-
-
-
۲
-
-سیستم برنامه را ایجاد می‌کند -ذخیره XApplication با OwnerId = کاربر فعلی -
-
-
-
۳
-
-کاربر درخواست ApiKey می‌کند -POST /api/v1/applications/{appId}/apikeys با تنظیمات انقضا و scope -
-
-
-
۴
-
-سیستم ApiKey تولید و برمی‌گرداند -کلید Plain Text فقط یکبار نمایش داده می‌شود، Hash در DB ذخیره می‌شود -
-
-
- -

🔄 سناریوی ۲: استفاده از ApiKey در درخواست API

-
-
-
۱
-
-کلاینت درخواست API را ارسال می‌کند -Header: X-Api-Key: xapp_abc123... -
-
-
-
۲
-
-Authentication Handler کلید را استخراج می‌کند -XApiKeyAuthenticationHandler فعال می‌شود -
-
-
-
۳
-
-اعتبارسنجی کامل انجام می‌شود -بررسی انقضا، ابطال، IP whitelist، rate limit، scope -
-
-
-
۴
-
-ClaimsPrincipal ساخته می‌شود -با OwnerId، ApplicationId و Scopes -
-
-
-
۵
-
-درخواست به Controller هدایت می‌شود -Authorization policy بررسی و پاسخ ارسال می‌گردد -
-
-
- -

🔄 سناریوی ۳: چرخش کلید (Key Rotation)

-
-
-
۱
-
-کاربر درخواست چرخش کلید را می‌دهد -POST /api/v1/applications/apikeys/{id}/rotate -
-
-
-
۲
-
-کلید جدید تولید می‌شود -کلید قدیمی برای مدت grace period (مثلاً ۱ ساعت) فعال می‌ماند -
-
-
-
۳
-
-کلید جدید به کاربر داده می‌شود -کاربر کلید جدید را در برنامه خود جایگزین می‌کند -
-
-
-
۴
-
-پس از grace period، کلید قدیمی منقضی می‌شود -Background job کلیدهای قدیمی را غیرفعال می‌کند -
-
-
-
-
- - -
-
-
۱۰
-
-

الگوهای امنیتی و ملاحظات

-
Security Patterns & Considerations
-
-
-
- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
الگوی امنیتیپیاده‌سازیاهمیت
Hashing کلیدSHA256 - کلید Plain Text هرگز ذخیره نمی‌شودحیاتی
HTTPS OnlyApiKey فقط از طریق HTTPS قابل ارسال استحیاتی
Rate Limitingبر اساس ApiKey و IP با MemoryCacheبالا
IP Whitelistمحدودسازی به IPهای مجازبالا
Scope Managementهر ApiKey scope مشخصی داردبالا
Audit Loggingثبت تمام استفاده‌ها در XApiKeyUsageLogمتوسط
Expirationمدت زمان محدود با قابلیت تمدیدبالا
Revocationامکان ابطال فوری در صورت نشتحیاتی
Key Rotationچرخش بدون downtime با grace periodمتوسط
One-time Displayکلید فقط یکبار به کاربر نمایش داده می‌شودبالا
- -
-🎯 یکپارچگی با OAuth2: این طراحی با الگوی OAuth2 Client Credentials Grant همخوانی کامل دارد. در واقع هر Application معادل یک OAuth2 Client و هر ApiKey معادل یک Client Secret است. در آینده می‌توان به‌راحتی این سیستم را به IdentityServer4 متصل کرد و از token endpoint آن برای تبدیل ApiKey به JWT استفاده نمود. -
- -

🔐 ملاحظات امنیتی تکمیلی

-
    -
  • ذخیره‌سازی: کلید ApiKey هرگز در Log یا Response بعد از ساخت ذخیره نمی‌شود
  • -
  • انتقال: فقط از طریق Header (X-Api-Key)، نه URL Query
  • -
  • طول کلید: حداقل ۲۵۶ بیت (۳۲ بایت) entropy
  • -
  • Brute Force Protection: پس از ۵ تلاش ناموفق، IP برای ۱۵ دقیقه block می‌شود
  • -
  • CORS: برای Endpoints حساس، CORS باید به‌دقت پیکربندی شود
  • -
-
-
- - -
-
-
۱۱
-
-

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

-
Summary & Next Steps
-
-
-
- -

✅ خلاصه طراحی

-

این مستند یک راهکار کامل برای مدیریت ApiKey در پلتفرم xDashboard ارائه می‌دهد که شامل موارد زیر است:

-
    -
  • مدل داده کامل با ۳ Entity جدید (XApplication, XApiKey, XApiKeyUsageLog)
  • -
  • پیاده‌سازی امن تولید و ذخیره‌سازی کلید با SHA256
  • -
  • Authentication Handler یکپارچه با ASP.NET Core
  • -
  • سیستم Rate Limiting و IP Whitelist
  • -
  • امکان چرخش کلید بدون downtime
  • -
  • سیستم Audit Log کامل
  • -
  • یکپارچگی با OAuth2 برای توسعه آینده
  • -
- -

📋 گام‌های اجرایی پیشنهادی

- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
فازفعالیتزمان تخمینی
۱طراحی و تصویب مدل داده + Migration۱ روز
۲پیاده‌سازی XApplicationManager + XApiKeyGenerator۲ روز
۳پیاده‌سازی XApiKeyValidator + Rate Limiter۱ روز
۴پیاده‌سازی Authentication Handler۱ روز
۵طراحی و پیاده‌سازی API Endpoints۲ روز
۶تست امنیتی و Unit Test۲ روز
۷مستندسازی API و راهنمای کلاینت۱ روز
مجموع زمان تخمینی۱۰ روز کاری
- -
-

🎯 توصیه نهایی

-

این طراحی با رعایت کامل اصول امنیتی و انطباق با الگوهای موجود پروژه (IdentityServer4, XPolicies, XValidationProvider) آماده پیاده‌سازی است. پیشنهاد می‌شود فاز اول با حداقل نیازمندی‌های امنیتی (Hashing, HTTPS, Expiration, Revocation) شروع شود و قابلیت‌های پیشرفته (IP Whitelist, Rate Limiting, Audit Log) در فازهای بعدی اضافه گردند.

-
-💎 ارزش پیشنهادی:
-امنیت سطح Enterprise + یکپارچگی کامل با OAuth2 + مقیاس‌پذیری بالا + قابلیت ردیابی و حسابرسی کامل -
-
- -
-📞 گام بعدی: در صورت تأیید این طراحی، می‌توانیم پیاده‌سازی را با فاز ۱ (مدل داده و Migration) شروع کنیم. کدها دقیقاً مطابق الگوهای موجود پروژه (Partial Classes برای Manager، Validation با GroupValidationBuilder، و Exception Handling با XException) نوشته خواهند شد. -
-
-
- -
-این مستند محرمانه بوده و صرفاً جهت طراحی و پیاده‌سازی داخلی تهیه شده است. هرگونه کپی‌برداری یا افشا بدون اجازه کتبی ممنوع است. -
- -
- -
- - -
تاریخ تهیه: ۱۲ مهر ۱۴۰۵  |  نسخه: ۱.۰  |  طبقه‌بندی: محرمانه
-
- -
- - - -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\xAiApi\wwwroot\Storage\Uploads\Document\xSaherElm_28cb240e-d19e-453e-872d-b7ba14ecd418.html - - - - - - -معرفی ساختار محصول هوش مصنوعی سازمانی | شرکت پارسا پلیمر شریف - - - - -
- -
-
-
- -
-
-
شماره مستند: PROD-1405-001
-
نسخه: ۱.۰
-
تاریخ تهیه: مهر ۱۴۰۵
-
طبقه‌بندی: محرمانه
-
-
- -
- PRODUCT ARCHITECTURE OVERVIEW -

معرفی ساختار محصول هوش مصنوعی سازمانی

-

محصول در دست توسعه — رایان پرداز کاوش | معرفی به شرکت پارسا پلیمر شریف

-
-
- -
- -
- کارفرمای محترم، شرکت پارسا پلیمر شریف،
- این مستند به معرفی ساختار محصولی می‌پردازد که در شرکت رایان پرداز کاوش در دست توسعه است. تمرکز این مستند، معرفی قابلیت‌های محصول بر اساس معماری آن است. هدف، ارائه تصویری شفاف از ساختار محصول و قابلیت‌هایی است که می‌تواند به نیازهای سازمان‌هایی مانند شرکت پارسا پلیمر پاسخ دهد. بدیهی است که شناخت دقیق نیازمندی‌های اختصاصی سازمان شما، مستلزم گفتگو و دریافت بازخورد از تیم فنی شماست و این مستند صرفاً نقطه شروع این گفتگو محسوب می‌شود. -
- -
-
-
۱
-
-

خلاصه اجرایی

-
Executive Summary
-
-
-
-

شرکت رایان پرداز کاوش در حال توسعه یک سامانه هوش مصنوعی سازمانی ایجنت‌محور است که معماری آن بر پایه شش لایه اصلی و دو محور عرضی طراحی شده است. این محصول با تمرکز بر چهار محور کلیدی در حال توسعه است: ایجنت قابل‌آزمون، توسعه‌پذیری از طریق MCP، حاکمیت داده با مدل‌های لوکال، و کنترل دسترسی لایه‌ای تا سطح ابزار ایجنت.

- -

این مستند قصد دارد ساختار محصول و قابلیت‌های پیش‌بینی‌شده در معماری آن را به‌صورت شفاف معرفی کند. سازمان‌هایی مانند شرکت پارسا پلیمر شریف که با داده‌های حساس، اسناد سازمانی و فرایندهای پیچیده سروکار دارند، می‌توانند از این ساختار برای پاسخ به نیازهای خود بهره ببرند. شناخت دقیق نیازمندی‌های سازمان شما و تطبیق محصول با آن، گام بعدی این همکاری خواهد بود.

- -
-
-
معماری
شش‌لایه
-
پایه طراحی محصول
-
-
-
MCP
محور
-
توسعه‌پذیری نامحدود
-
-
-
مدل
لوکال
-
حاکمیت داده و محرمانگی
-
-
- -
- نکته کلیدی: این مستند، معرفی ساختار محصول در دست توسعه است. قابلیت‌های مطرح‌شده بر اساس معماری محصول تعریف شده‌اند و می‌توانند مبنای گفتگوی فنی با تیم ارزیابی شرکت پارسا پلیمر شریف قرار گیرند. -
-
-
- -
-
-
۲
-
-

معماری محصول در دست توسعه

-
Product Architecture Under Development
-
-
-
-

محصول در دست توسعه رایان پرداز کاوش، بر پایه یک معماری لایه‌ای طراحی شده است که جداسازی دغدغه‌ها و اعمال سیستماتیک حاکمیت و مشاهده‌پذیری را در تمام لایه‌ها تضمین می‌کند. این معماری، مبنای توسعه قابلیت‌های محصول قرار گرفته است.

- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
لایه معماریقابلیت‌های پیش‌بینی‌شده در محصولوضعیت توسعه
لایه تعاملرابط وب سازمانی، نسخه دسکتاپ، درگاه APIدر دست توسعه
لایه کنترل دسترسیاحراز هویت، مدیریت نشست، موتور مجوزها، مدیریت نقش‌هادر دست توسعه
لایه ارکستراسیون (هسته ایجنت)موتور ایجنت، برنامه‌ریز، انتخاب‌گر ابزار، مدیریت جریان، نقاط تأیید انسانیدر دست توسعه
لایه هوش و مدل‌هادرگاه مدل‌ها، مدیریت مدل، بازیابی و تقویت (RAG)، حافظه و زمینهدر دست توسعه
لایه داده و منابعمنابع دانش، مدیریت فایل، سرویس‌های خارجی، ابزارهای عملیاتیدر دست توسعه
لایه خروجی و گزارشتولید گزارش، مبدل قالب (Word/Excel)، داشبورد مصرفدر دست توسعه
محور عرضی حاکمیت دادهسیاست‌گذار داده، ممیزی و لاگ، سنسور محرمانگیدر دست توسعه
محور عرضی مشاهده‌پذیریمتریک و ردیابی مصرف، زمان پاسخ، نرخ خطادر دست توسعه
- -
- 💡 نکته: معماری فوق، مبنای توسعه محصول قرار گرفته است. قابلیت‌های هر لایه در حال پیاده‌سازی و تکمیل هستند و در جلسه فنی، جزئیات بیشتر و زمان‌بندی توسعه هر بخش قابل ارائه خواهد بود. این ساختار به‌گونه‌ای طراحی شده که امکان تطبیق با نیازمندی‌های سازمان‌های مختلف، از جمله شرکت پارسا پلیمر شریف، را فراهم کند. -
-
-
- -
-
-
۳
-
-

ساختار محصول: سامانه ایجنت‌محور سازمانی

-
Product Structure: Enterprise Agentic System
-
-
-
-

هسته محصول در دست توسعه، یک موتور ایجنت است که بر اساس معماری تعریف‌شده، هدف کاربر را به مراحل اجرایی تبدیل می‌کند، برای هر مرحله ابزار یا منبع مناسب را از میان فهرست مجاز انتخاب می‌کند، عملیات را اجرا می‌کند، نتیجه را ارزیابی کرده و در صورت نیاز مسیر را اصلاح می‌کند. این ساختار، محصول را از یک سیستم پرسش‌وپاسخ ساده متمایز می‌سازد و امکان پاسخ به نیازهای پیچیده سازمانی را فراهم می‌آورد.

- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
لایه معماریقابلیت پیش‌بینی‌شده در ساختار محصول
لایه تعاملرابط وب سازمانی، نسخه دسکتاپ، درگاه API
لایه کنترل دسترسیاحراز هویت، مدیریت نشست، موتور مجوزها، مدیریت نقش‌ها
لایه ارکستراسیون (هسته ایجنت)موتور ایجنت، برنامه‌ریز، انتخاب‌گر ابزار، مدیریت جریان، نقاط تأیید انسانی
لایه هوش و مدل‌هادرگاه مدل‌ها، مدیریت مدل، بازیابی و تقویت (RAG)، حافظه و زمینه
لایه داده و منابعمنابع دانش، مدیریت فایل، سرویس‌های خارجی، ابزارهای عملیاتی
لایه خروجی و گزارشتولید گزارش، مبدل قالب (Word/Excel)، داشبورد مصرف
محور عرضی حاکمیت دادهسیاست‌گذار داده، ممیزی و لاگ، سنسور محرمانگی
محور عرضی مشاهده‌پذیریمتریک و ردیابی مصرف، زمان پاسخ، نرخ خطا
- -
- 💡 نکته: قابلیت‌های فوق بر اساس معماری محصول تعریف شده‌اند و مبنای توسعه آن قرار گرفته‌اند. این ساختار می‌تواند در جلسه فنی با تیم ارزیابی شرکت پارسا پلیمر شریف بررسی و با نیازمندی‌های سازمان شما تطبیق داده شود. -
-
-
- -
-
-
۴
-
-

توسعه‌پذیری از طریق MCP

-
Extensibility via MCP
-
-
-
-

MCP (Model Context Protocol) در ساختار محصول ما به‌عنوان لایه استاندارد اتصال ایجنت به ابزارها و منابع در نظر گرفته شده است. بر اساس این معماری، هر قابلیت جدید می‌تواند در قالب یک MCP Server تعریف شود و به سامانه اضافه گردد.

- -
- تأکید معماری: از منظر ساختار محصول، محدودیت معماری برای افزودن قابلیت از طریق MCP وجود ندارد. هر MCP Server جدید در Tool Registry ثبت می‌شود و در صورت وجود مجوز، در اختیار ایجنت قرار می‌گیرد. این رویکرد، محصول را قادر می‌سازد تا با نیازهای متنوع سازمانی، از جمله نیازهای محتمل شرکت پارسا پلیمر شریف، هم‌راستا شود. -
- -

نمونه قابلیت‌های قابل افزودن با MCP:

- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
حوزه سازمانینمونه MCP Serverکاربرد بالقوه
منابع انسانیHR MCPمرخصی، آموزش، اطلاعات پرسنلی
مالی و بودجهFinance MCPبودجه، هزینه، فاکتور، مراکز هزینه
تولید و انبارProduction MCPموجودی، سفارش، فرمولاسیون
مدیریت اسنادDMS MCPجستجو و بازیابی اسناد سازمانی
پایگاه دادهDB MCPپرسش کنترل‌شده از داده‌ها
فایل و پوشهFile MCPدسترسی کنترل‌شده به فایل‌های محلی/شبکه
همکاری سازمانیCollaboration MCPایمیل، تقویم، اعلان
سامانه‌های سازمانیERP/CRM MCPیکپارچه‌سازی فرایندهای سازمانی
- -
- ✓ نتیجه: ساختار محصول از طریق MCP، امکان توسعه قابلیت‌ها را فراهم می‌کند. هر ابزار جدید، سرویس جدید یا منبع داده جدید، با تعریف یک MCP Server و ثبت در Tool Registry، به قابلیت‌های ایجنت اضافه می‌شود. این رویکرد می‌تواند پاسخگوی نیازهای متنوع سازمانی باشد. -
-
-
- -
-
-
۵
-
-

حاکمیت داده و رویکرد مدل‌های لوکال

-
Data Governance & Local Model Approach
-
-
-
-

در ساختار محصول، حاکمیت داده به‌عنوان یک محور عرضی در تمام لایه‌ها در نظر گرفته شده است. برای سازمان‌هایی که با داده‌های حساس مانند فرمولاسیون، اطلاعات مشتریان، فرایندهای تولید و اسناد سازمانی سروکار دارند، استفاده از مدل‌های آنلاین می‌تواند با حاکمیت داده و محرمانگی در تناقض باشد؛ زیرا داده از مرز سازمان خارج می‌شود و کنترل کامل بر ذخیره‌سازی، پردازش و استفاده ثانویه از آن وجود ندارد.

- -
- ⚠️ ریسک مدل‌های آنلاین برای داده‌های حساس: -
    -
  • خروج داده‌های حساس از مرز سازمان
  • -
  • عدم کنترل بر ذخیره‌سازی داده در سرورهای خارجی
  • -
  • احتمال استفاده از داده برای آموزش مدل‌های بعدی
  • -
  • وابستگی به اینترنت بین‌الملل و ریسک قطع سرویس
  • -
  • عدم انطباق با سیاست‌های محرمانگی سازمانی
  • -
-
- -

رویکرد پیش‌بینی‌شده در ساختار محصول:

- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
تصمیمرویکرد در ساختار محصول
مدل پیش‌فرضمدل لوکال از طریق Model Gateway و Ollama/On-Prem
داده حساسعدم خروج از مرز سازمان
مدل آنلاینفقط برای داده غیرحساس، با تأیید سیاست و به‌صورت استثنا
آموزش مدلعدم استفاده از داده سازمان برای آموزش مدل‌های خارجی
استقرارOn-Premise با امکان عملکرد در قطع اینترنت بین‌الملل
ممیزیثبت کامل مسیر داده و تصمیمات ایجنت
- -
- ✓ نتیجه: در ساختار محصول، حاکمیت داده به‌عنوان یک سیاست اجرایی در نظر گرفته شده است. مدل لوکال، پیش‌فرض است و داده حساس سازمان، از مرز آن خارج نمی‌شود. این رویکرد می‌تواند برای سازمان‌هایی با الزامات محرمانگی بالا، از جمله شرکت پارسا پلیمر شریف، مناسب باشد. -
-
-
- -
-
-
۶
-
-

کنترل دسترسی ایجنت و محدودسازی ابزارهای تصمیم‌گیرنده

-
Agent Access Control & Tool Restriction
-
-
-
-

در ساختار محصول، کنترل دسترسی تنها به رابط کاربری محدود نمی‌شود. موتور مجوزها پیش از فراخوانی ایجنت، فهرست مجاز کاربر را تعیین می‌کند و این فهرست به ایجنت تصمیم‌گیرنده ابلاغ می‌شود:

- -
- - -
- -

این یعنی ایجنت تصمیم‌گیرنده نمی‌تواند ابزاری خارج از مجوز کاربر را فراخوانی کند، حتی اگر آن ابزار در Tool Registry ثبت شده باشد. این محدودسازی در سطح معماری اعمال می‌شود و توسط موتور مجوزها به ایجنت ابلاغ می‌گردد.

- -
- نکته حساس: ساختار محصول از ترکیب RBAC (نقش‌محور) و ABAC (ویژگی‌محور) پشتیبانی می‌کند تا کنترل دسترسی را تا سطح رکورد، سند، واحد سازمانی و حتی فیلد اطلاعاتی ممکن سازد. این رویکرد می‌تواند برای سازمان‌هایی با ساختار دسترسی پیچیده، از جمله شرکت پارسا پلیمر شریف، مناسب باشد. -
-
-
- -
-
-
۷
-
-

دفاع لایه‌ای برای حفظ محرمانگی

-
Layered Defense for Confidentiality
-
-
-
-

در ساختار محصول، برای جلوگیری از افشای اطلاعات، دفاع لایه‌ای در نظر گرفته شده است. این دفاع شامل شش نقطه مستقل است که هر یک از منظری متفاوت، محرمانگی را تضمین می‌کند:

- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
لایهکنترلهدف
لایه ۱احراز هویت و نشستتأیید هویت و سطح دسترسی فعال
لایه ۲موتور مجوزهامحدودسازی مدل، ابزار و منبع پیش از اجرا
لایه ۳فهرست مجاز ابزار ایجنتجلوگیری از انتخاب ابزار غیرمجاز
لایه ۴فیلتر بازیابی RAGبازیابی فقط از منابع مجاز کاربر
لایه ۵سنسور محرمانگی خروجیجلوگیری از افشای اطلاعات در پاسخ نهایی
لایه ۶ممیزی و لاگثبت و ردیابی تمام تصمیمات و دسترسی‌ها
- -
- ⚠️ نکته حیاتی: لایه‌های ۲ (موتور مجوزها) و ۵ (سنسور محرمانگی) مستقل از هم هستند. حتی اگر ایجنت یا مدل بخواهد اطلاعات خارج از دسترس را افشا کند، در دو نقطه مستقل مسدود می‌شود. این رویکرد دفاع لایه‌ای، در ساختار محصول پیش‌بینی شده است تا محرمانگی اطلاعات در سطوح دسترسی مختلف تضمین شود. -
- -
- ✓ رویکرد ساختاری: دفاع لایه‌ای در محصول به‌گونه‌ای طراحی شده که پرسش‌های یکسان با حساب‌های دارای مجوزهای متفاوت، پاسخ‌های متفاوت و متناسب با سطح دسترسی هر کاربر دریافت کنند. همچنین تلاش برای دور زدن مجوزها از طریق پرسش مستقیم، غیرمستقیم یا خلاصه‌سازی، در دو نقطه مستقل مسدود می‌شود. -
-
-
- -
-
-
۸
-
-

مثال جریان کار: یک درخواست، دو ایجنت

-
Workflow Example: One Request, Two Agents
-
-
-
-

برای روشن‌تر شدن ساختار کنترل دسترسی در محصول، یک سناریوی نمونه را بررسی می‌کنیم. کارمندی درخواست می‌دهد:

- -
-

«می‌خواهم در دوره تخصصی پلیمر در آبان شرکت کنم؛ هزینه آن از بودجه واحد پرداخت شود و مرخصی آموزشی هم ثبت شود.»

-
— درخواست نمونه واحد کارمند
-
- -

این یک درخواست واحد است، اما برای پاسخ به آن به دو حوزه نیاز است: منابع انسانی و مالی. ساختار محصول، این درخواست را به‌صورت زیر پردازش می‌کند:

- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
مرحلهمسئولاقدامکنترل دسترسی
۱ایجنت مسیریابتشخیص نیاز به HR و Financeفقط ابزارهای مجاز کاربر
۲ایجنت منابع انسانیبررسی مرخصی و شرایط آموزشفقط رکورد HR خود کارمند و سیاست آموزش
۳ایجنت مالیبررسی بودجه و هزینه دورهفقط بودجه مرکز هزینه واحد کاربر
۴ترکیب نتایجتولید پاسخ نهاییسنسور محرمانگی خروجی
۵تأیید انسانیاگر هزینه از سقف بیشتر باشدتوقف و دریافت تأیید
- -

نحوه اعمال کنترل دسترسی در این سناریو:

- -
    -
  • - ایجنت منابع انسانی - به ابزارهای مرخصی و آموزش دسترسی دارد، اما به حقوق، ارزیابی عملکرد یا پرونده سایر کارکنان دسترسی ندارد. -
  • -
  • - ایجنت مالی - به بودجه مرکز هزینه واحد کاربر دسترسی دارد، اما به فیش حقوقی یا اطلاعات مالی سایر واحدها دسترسی ندارد. -
  • -
  • - در صورت عدم مجوز مالی - اگر کاربر مجوز مالی نداشته باشد، ایجنت مالی پاسخ «عدم دسترسی» یا خروجی تجمیعی غیرمحرمانه ارائه می‌دهد. -
  • -
  • - اتصال از طریق MCP - هر دو ایجنت از طریق MCP به ابزارهای مجاز متصل می‌شوند و فهرست ابزار مجاز توسط موتور مجوزها تعیین می‌شود. -
  • -
  • - ممیزی کامل - تمام مراحل در سیستم ممیزی ثبت می‌شود و قابل ردیابی است. -
  • -
- -
- 💡 نتیجه مثال: ساختار محصول به‌گونه‌ای طراحی شده که یک درخواست واحد را میان چند ایجنت توزیع کند، بدون اینکه مرزهای محرمانگی نقض شود. هر ایجنت فقط به ابزارها و منابعی دسترسی دارد که کاربر مجاز است، و این محدودسازی در سطح معماری محصول اعمال می‌شود. -
-
-
- -
-
-
۹
-
-

قابلیت‌های محصول در پاسخ به نیازهای رایج سازمانی

-
Product Capabilities vs. Common Organizational Needs
-
-
-
-

ساختار محصول در دست توسعه، قابلیت‌هایی را پیش‌بینی کرده است که می‌تواند به نیازهای رایج سازمان‌های صنعتی و دانش‌بنیان پاسخ دهد. جدول زیر، این قابلیت‌ها را در کنار نیازهای رایج سازمانی نشان می‌دهد. بدیهی است که تطبیق دقیق با نیازمندی‌های شرکت پارسا پلیمر شریف، مستلزم گفتگوی فنی با تیم ارزیابی شماست.

- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
نیاز رایج سازمانیقابلیت پیش‌بینی‌شده در ساختار محصول
دستیار هوشمند و ایجنت تصمیم‌گیرندهموتور ایجنت با برنامه‌ریزی، انتخاب ابزار، اجرا، اصلاح و Human-in-the-loop
مدیریت دسترسی کاربران و واحدهای سازمانیRBAC/ABAC، کنترل تا سطح رکورد، فهرست مجاز ابزار، دفاع لایه‌ای
شفافیت مصرف و هزینهداشبورد مصرف، گزارش هزینه به تفکیک کاربر/مدل/ایجنت، درگاه API
تعامل کاربری و تولید گزارشرابط وب/دسکتاپ، تحلیل فایل، خروجی Word/Excel، ارجاع به منبع
حاکمیت داده و محرمانگی اطلاعاتمدل لوکال، On-Premise، عدم خروج داده حساس، MCP کنترل‌شده
پیاده‌سازی، آموزش و پشتیبانینقشه راه فازبندی‌شده، مستندسازی، آموزش و پشتیبانی
عملکرد پایدار و تاب‌آوریعملکرد در قطع اینترنت با مدل لوکال، SLA قابل تعریف، آمادگی پایلوت
- -
- ✓ نتیجه: ساختار محصول به‌گونه‌ای طراحی شده که بتواند به نیازهای رایج سازمان‌های صنعتی و دانش‌بنیان پاسخ دهد. برای بررسی تطابق دقیق با نیازمندی‌های شرکت پارسا پلیمر شریف، آماده دریافت و بررسی نیازمندی‌های تیم فنی شما هستیم. -
-
-
- -
-
-
۱۰
-
-

وضعیت توسعه محصول و گام بعدی

-
Development Status & Next Step
-
-
-
-

وضعیت فعلی: محصول در شرکت رایان پرداز کاوش بر پایه معماری شش‌لایه + دو محور عرضی، در دست توسعه است. فازهای توسعه محصول به‌صورت زیر سازمان‌دهی شده‌اند:

- -
-
-
-
فاز A: هسته ایجنت و رابط پایه
-

درگاه مدل، موتور ایجنت، رابط کاربری، احراز هویت — در دست توسعه

-
-
-
-
-
-
فاز B: ابزارها، RAG و منابع دانش
-

Tool Registry، MCP Client، RAG با ارجاع، مدیریت فایل — در دست توسعه

-
-
-
-
-
-
فاز C: حاکمیت داده و کنترل دسترسی
-

موتور مجوزها، سنسور محرمانگی، ممیزی، سیاست‌گذار داده — در دست توسعه

-
-
-
-
-
-
فاز D: گزارش، تأیید انسانی و مشاهده‌پذیری
-

تولید گزارش، مبدل قالب، Human-in-the-loop، داشبورد مصرف — در دست توسعه

-
-
-
-
-
-
فاز E: Cross-Platform و آماده‌سازی محصول
-

نسخه دسکتاپ، موبایل، مدیریت مدل، استقرار On-Premise — در برنامه توسعه

-
-
-
-
- -

گام بعدی پیشنهادی:

- -
    -
  • - برگزاری جلسه معرفی و گفتگوی فنی - معرفی ساختار محصول و دریافت بازخورد از تیم فنی شرکت پارسا پلیمر شریف -
  • -
  • - دریافت نیازمندی‌های اختصاصی سازمان - شناخت دقیق نیازهای شرکت پارسا پلیمر شریف برای تطبیق محصول -
  • -
  • - ارائه سناریوی نمونه Agent - نمایش ساختار ایجنت بر اساس معماری محصول -
  • -
  • - بررسی امکان اجرای پایلوت محدود - شامل زمان، هزینه، پیش‌نیازها و معیارهای موفقیت -
  • -
  • - ارائه پیشنهاد تجاری شفاف - بر اساس دامنه همکاری و نیازمندی‌های سازمانی -
  • -
- -
- 📞 گام بعدی: در صورت تمایل به ادامه گفتگو، آماده برگزاری جلسه فنی برای معرفی ساختار محصول، دریافت نیازمندی‌های اختصاصی شرکت پارسا پلیمر شریف و بررسی امکان تطبیق محصول با آن نیازها هستم. این جلسه، نقطه شروع همکاری و شناخت متقابل خواهد بود. -
-
-
- -
-
-
۱۱
-
-

جمع‌بندی و پیشنهاد نهایی

-
Final Summary & Recommendation
-
-
-
-

این مستند، ساختار محصول هوش مصنوعی سازمانی در دست توسعه رایان پرداز کاوش را معرفی کرد. ویژگی‌های متمایز این ساختار:

- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
ویژگیرویکرد ساختار محصول
معماری پایهشش لایه + دو محور عرضی
توسعه‌پذیری MCPبدون محدودیت معماری
حاکمیت دادهمدل لوکال (حاکمیت کامل)
کنترل دسترسی ایجنتتا سطح ابزار و رکورد
دفاع محرمانگیشش لایه مستقل
وضعیت توسعهدر دست توسعه
- -
-

🎯 پیشنهاد نهایی

-

ساختار محصول در دست توسعه رایان پرداز کاوش، بر پایه معماری شش‌لایه + دو محور عرضی طراحی شده و قابلیت‌هایی را پیش‌بینی کرده است که می‌تواند به نیازهای رایج سازمان‌های صنعتی و دانش‌بنیان پاسخ دهد.

-

توسعه‌پذیری از طریق MCP، حاکمیت داده با مدل‌های لوکال، کنترل دسترسی تا سطح ابزار ایجنت، و دفاع لایه‌ای برای محرمانگی، چهار ستون اصلی این ساختار هستند.

-
- 💎 ارزش پیشنهادی ساختار محصول:
- معماری ایجنت‌محور + توسعه‌پذیری MCP + حاکمیت داده با مدل لوکال + کنترل دسترسی تا سطح ابزار + دفاع لایه‌ای -
-
- -
- 📞 گام بعدی: در صورت تمایل به ادامه گفتگو، آماده برگزاری جلسه فنی برای معرفی ساختار محصول، دریافت نیازمندی‌های اختصاصی شرکت پارسا پلیمر شریف و بررسی امکان تطبیق محصول با آن نیازها هستم. این جلسه، نقطه شروع همکاری و شناخت متقابل خواهد بود. -
-
-
- -
- این مستند محرمانه بوده و صرفاً جهت ارائه به کارفرمای محترم تهیه شده است. هرگونه کپی‌برداری یا افشا بدون اجازه کتبی ممنوع است. -
- -
- -
- - -
تاریخ تهیه: مهر ۱۴۰۵  |  نسخه: ۱.۰  |  طبقه‌بندی: محرمانه
-
- -
- - - - -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\xAiApi\wwwroot\Storage\Uploads\Document\xSaherElm_2a48ed4e-5c7a-406a-97d7-044165d6365c.html - - - - - - -بررسی فنی و راهنمای جامع ابزار AirLLM - - - -
-
-
-
- -
-
-
شماره مستند: TECH-1405-002
-
نسخه: ۱.۰
-
تاریخ تهیه: ۲۸ مهر ۱۴۰۵
-
طبقه‌بندی: داخلی / فنی
-
-
-
-TECHNICAL REVIEW & GUIDE -

بررسی فنی و راهنمای جامع ابزار AirLLM

-

تحلیل معماری، قابلیت‌ها و راهنمای پیاده‌سازی مدل‌های زبانی بزرگ روی سخت‌افزار محدود

-
-
- -
-
-همکاران و ذینفعان محترم،
-این مستند به‌عنوان تحلیلی جامع و مبتنی بر بررسی‌های فنی عمیق، ابزار AirLLM را از منظر معماری، کارایی و نحوه پیاده‌سازی مورد ارزیابی قرار می‌دهد. هدف از تهیه این سند، ارائه شفافیت کامل فنی و تسهیل تصمیم‌گیری برای به‌کارگیری این راهکار در زیرساخت‌های هوش مصنوعی با منابع محدود است. -
- -
-
-
۱
-
-

خلاصه اجرایی

-
Executive Summary
-
-
-
-

ابزار AirLLM یک کتابخانه پیشرفته در حوزه هوش مصنوعی است که با هدف کاهش چشمگیر مصرف حافظه گرافیکی (VRAM) در هنگام استنتاج (Inference) و آموزش (Training) مدل‌های زبانی بزرگ (LLM) طراحی شده است. این ابزار امکان اجرای مدل‌های عظیم (مانند مدل‌های ۷۰ میلیارد پارامتری و بالاتر) را روی کارت‌های گرافیک با ظرفیت حداقل ۴ گیگابایت فراهم می‌کند، بدون آنکه نیاز به کوانتیزاسیون (Quantization)، تقطیر (Distillation) یا هرس کردن (Pruning) مدل باشد.

-
-نتیجه کلیدی: با به‌کارگیری AirLLM، محدودیت‌های سخت‌افزاری به حداقل رسیده و امکان استقرار مدل‌های پیشرفته (حتی مدل‌های ۶۷۱ میلیارد پارامتری مانند DeepSeek-V3) روی سخت‌افزارهای سطح متوسط با مصرف حدود ۱۲ گیگابایت VRAM میسر می‌گردد. -
-
-
- -
-
-
۲
-
-

معماری و مکانیزم عملکرد

-
Architecture & Mechanism
-
-
-
-

مکانیزم اصلی AirLLM بر پایه تکنیک «بارگذاری لایه‌ای» (Layer-wise Loading) استوار است. به جای بارگذاری کل مدل در حافظه گرافیکی، این ابزار فرآیند را به گام‌های زیر تقسیم می‌کند:

-
-گام ۱: تجزیه و ذخیره‌سازی اولیه
-در اولین اجرا، مدل اصلی از مخزن Hugging Face دریافت شده و به صورت لایه‌به‌لایه در حافظه دیسک (Storage) ذخیره می‌شود. -

-گام ۲: بارگذاری پویا در GPU
-در حین فرآیند استنتاج، تنها یک لایه از مدل در هر لحظه روی GPU بارگذاری می‌شود. -

-گام ۳: محاسبه و انتقال حالت (State)
-پس از انجام محاسبات روی لایه فعلی، نتایج میانی (Activations) به لایه بعدی منتقل شده و لایه قبلی بلافاصله از VRAM تخلیه می‌شود. -
-
-💡 نتیجه معماری: این رویکرد باعث می‌شود حافظه VRAM مورد نیاز، به جای وابستگی به اندازه کل مدل، تنها به اندازه بزرگ‌ترین لایه مدل وابسته باشد که انقلابی در مدیریت منابع محسوب می‌شود. -
-
-
- -
-
-
۳
-
-

مدل‌های پشتیبانی‌شده و مصرف حافظه

-
Supported Models & VRAM Consumption
-
-
-
-

این کتابخانه با تقریباً تمام خانواده‌های مدل‌های متن‌باز محبوب سازگاری کامل دارد. جدول زیر نمایی از توانایی AirLLM در مدیریت منابع برای مدل‌های مختلف را نشان می‌دهد:

- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
نام مدلاندازه تقریبیحداقل VRAM مورد نیاز
Qwen3 / Mistral / Phi≈8B~۱ تا ۲ گیگابایت
Qwen3-30B / Mixtral (MoE)30–47B~۱ تا ۳ گیگابایت
Qwen3.8-27B (dense VL)27B~۳.۳۳ گیگابایت
Qwen3.8-Flash-Next (MoE + PLE)~180B~۵.۹۵ گیگابایت
Llama 3.x 70B (full precision)70B~۴ گیگابایت
DeepSeek-V3671B~۱۲ گیگابایت
-
-
- -
-
-
۴
-
-

راهنمای گام‌به‌گام پیاده‌سازی

-
Step-by-Step Implementation Guide
-
-
-
-

برای استقرار و اجرای این ابزار، مراحل زیر به دقت طراحی و پیاده‌سازی شده‌اند:

-
-پیش‌نیاز حیاتی: اطمینان از وجود فضای دیسک کافی در پوشه کش Hugging Face برای ذخیره‌سازی لایه‌های تجزیه‌شده مدل در اولین اجرا. -
-

گام ۱: نصب کتابخانه

-
pip install airllm
- -

گام ۲: مقداردهی اولیه مدل

-
from airllm import AutoModel
-
-# شناسه مخزن Hugging Face مدل مورد نظر را وارد کنید
-model = AutoModel.from_pretrained("Qwen/Qwen3-32B")
-
-# نکته: برای فعال‌سازی فشرده‌سازی و افزایش سرعت تا ۳ برابر (اختیاری):
-# model = AutoModel.from_pretrained("model-name", compression='4bit')
-
- -

گام ۳: آماده‌سازی ورودی و اجرای استنتاج

-
MAX_LENGTH = 128
-input_text = ['What is the capital of United States?']
-
-input_tokens = model.tokenizer(
-    input_text,
-    return_tensors="pt",
-    return_attention_mask=False,
-    truncation=True,
-    max_length=MAX_LENGTH,
-    padding=False
-)
-
-generation_output = model.generate(
-    input_tokens['input_ids'].cuda(),
-    max_new_tokens=20,
-    use_cache=True,
-    return_dict_in_generate=True
-)
-
-output = model.tokenizer.decode(generation_output.sequences[0])
-print(output)
-
-
-
- -
-
-
۵
-
-

جمع‌بندی و توصیه‌های فنی

-
Conclusion & Technical Recommendations
-
-
-
-

با توجه به تحلیل‌های انجام‌شده، به‌کارگیری AirLLM مزایای بی‌نظیری را برای پروژه‌هایی با محدودیت سخت‌افزاری فراهم می‌آورد:

- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
مزیتروش سنتی (بارگذاری کامل)روش AirLLM (لایه‌ای)
مصرف VRAMبسیار بالا (غیرقابل اجرا روی GPUهای ضعیف)بهینه و متناسب با اندازه لایه
نیاز به کوانتیزاسیونالزامی برای کاهش مصرفغیرالزامی (حفظ دقت کامل)
سرعت استنتاج (با فشرده‌سازی)پایهتا ۳ برابر سریع‌تر (با 4bit/8bit)
ارزش خالص فنی—بسیار بالاتر
- -
-

🎯 توصیه نهایی معماری

-

با توجه به بررسی‌های جامع فنی، استفاده از AirLLM بهترین انتخاب برای استقرار مدل‌های زبانی بزرگ در محیط‌هایی با محدودیت VRAM است.

-

این راهکار نه تنها هزینه‌های زیرساختی را به شکل قابل‌توجهی کاهش می‌دهد، بلکه بدون قربانی کردن دقت مدل (در حالت بدون فشرده‌سازی)، عملکردی پایدار و قابل اتکا ارائه می‌کند.

-
-💎 ارزش پیشنهادی:
-حذف محدودیت سخت‌افزاری + حفظ دقت مدل + امکان فشرده‌سازی اختیاری برای افزایش سرعت + سازگاری گسترده با اکوسیستم Hugging Face -
-
-
-
- -
-این مستند محرمانه بوده و صرفاً جهت استفاده داخلی در شرکت فن آوران ساحر علم تهیه شده است. هرگونه کپی‌برداری یا افشا بدون اجازه کتبی ممنوع است. -
-
- -
- - -
شرکت: فن آوران ساحر علم  |  تاریخ تهیه: ۲۸ مهر ۱۴۰۵  |  نسخه: ۱.۰  |  طبقه‌بندی: داخلی / فنی
-
-
- - - -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\xAiApi\wwwroot\Storage\Uploads\Document\xSaherElm_2e627fe4-93a8-4d6f-8f18-38eb87b1587b.html - - - - - - -پروپوزال راهکار هوش مصنوعی سازمانی | شرکت پارسا پلیمر شریف - - - - -
- -
-
-
- -
-
-
شماره مستند: PROP-1405-002
-
نسخه: ۱.۰
-
تاریخ تهیه: مهر ۱۴۰۵
-
طبقه‌بندی: محرمانه
-
-
- -
- PROPOSAL & SOLUTION -

پروپوزال راهکار هوش مصنوعی سازمانی

-

سامانه ایجنت‌محور با توسعه‌پذیری MCP و حاکمیت داده درون‌سازمانی

-
-
- -
- -
- کارفرمای محترم، شرکت پارسا پلیمر شریف،
- این مستند در پاسخ به درخواست رسمی شما (REQ-1405-001) تهیه شده است و راهکار پیشنهادی ما را به‌عنوان محصولی که معماری کلان آن در سازمان ما طراحی و پیاده‌سازی شده است معرفی می‌نماید. تمرکز این پروپوزال بر چهار محور اساسی است: ایجنت قابل‌آزمون، توسعه‌پذیری نامحدود از طریق MCP، حاکمیت داده با مدل‌های لوکال، و کنترل دسترسی لایه‌ای تا سطح ابزار ایجنت. هدف، ارائه شفافیت کامل و اثبات عملی قابلیت‌ها در جلسه دمو و پایلوت محدود است. -
- -
-
-
۱
-
-

خلاصه اجرایی

-
Executive Summary
-
-
-
-

درخواست شرکت پارسا پلیمر شریف، یک RFP فنی، دقیق و آزمون‌محور است. تیم ارزیابی شما با مفاهیمی مانند Agent در برابر Assistant، Human-in-the-loop، RAG، مدیریت دسترسی تا سطح سند/رکورد و حاکمیت داده کاملاً آشناست. بنابراین، پیشنهاد ما بر «ادعا» استوار نیست؛ بر قابلیت اثبات عملی استوار است.

- -

محصول پیشنهادی، یک سامانه هوش مصنوعی سازمانی ایجنت‌محور است که معماری آن در سازمان ما طراحی و پیاده‌سازی شده و آماده ارائه در جلسه دمو و اجرای پایلوت محدود است. این محصول با تمرکز بر چهار محور کلیدی طراحی شده است:

- -
-
-
ایجنت
قابل‌آزمون
-
برنامه‌ریزی، انتخاب ابزار، اجرا و اصلاح
-
-
-
MCP
نامحدود
-
توسعه‌پذیری بدون محدودیت معماری
-
-
-
مدل
لوکال
-
حاکمیت داده و محرمانگی کامل
-
-
- -
- نتیجه کلیدی: آنچه به سازمان شما ارائه می‌شود، نه یک طرح مفهومی، بلکه یک محصول عملیاتی است که معماری شش‌لایه + دو محور عرضی آن پیاده‌سازی شده و آماده اثبات در آزمون‌های عملی (سناریوی Agent، آزمون نفوذ دسترسی، عملکرد در قطع اینترنت) می‌باشد. -
-
-
- -
-
-
۲
-
-

جایگاه پیشنهاد: محصول پیاده‌سازی‌شده، نه طرح مفهومی

-
Implemented Product vs. Conceptual Design
-
-
-
-

نکته متمایز این پیشنهاد آن است که معماری مطرح‌شده در مستندات فنی شما (ARCH-1405-001)، در سازمان ما به‌عنوان یک محصول طراحی و پیاده‌سازی شده است. این یعنی:

- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
شاخصطرح مفهومی (رایج در بازار)محصول پیاده‌سازی‌شده (پیشنهاد ما)
وضعیت معماریروی کاغذ و در مرحله طراحیطراحی و پیاده‌سازی شده
قابلیت اثبات عملیمحدود به ادعا و اسلایدقابل نمایش در جلسه دمو
ریسک پیاده‌سازیبالا (عدم اطمینان از تحقق)حداقل (محصول موجود است)
زمان تحویلطولانی (چرخه کامل توسعه)کوتاه (سفارشی‌سازی و استقرار)
نتیجه نهاییریسک بالا و زمان طولانیاطمینان بالا و تحویل سریع
- -
- ✓ مزیت کلیدی: شما با یک محصول زنده و آزمون‌پذیر مواجه هستید، نه با وعده‌های آینده. تمام قابلیت‌های مطرح‌شده در این پروپوزال، امروز در سازمان ما قابل نمایش و آزمون هستند. -
-
-
- -
-
-
۳
-
-

محصول پیشنهادی: سامانه ایجنت‌محور سازمانی

-
Proposed Product: Enterprise Agentic System
-
-
-
-

محصول ما یک چت‌بات ساده نیست. هسته محصول، یک موتور ایجنت است که هدف کاربر را به مراحل اجرایی تبدیل می‌کند، برای هر مرحله ابزار یا منبع مناسب را از میان فهرست مجاز انتخاب می‌کند، عملیات را اجرا می‌کند، نتیجه را ارزیابی کرده و در صورت نیاز مسیر را اصلاح می‌کند.

- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
لایه معماریقابلیت در محصول پیشنهادی
لایه تعاملرابط وب سازمانی، نسخه دسکتاپ، درگاه API
لایه کنترل دسترسیاحراز هویت، مدیریت نشست، موتور مجوزها، مدیریت نقش‌ها
لایه ارکستراسیون (هسته ایجنت)موتور ایجنت، برنامه‌ریز، انتخاب‌گر ابزار، مدیریت جریان، نقاط تأیید انسانی
لایه هوش و مدل‌هادرگاه مدل‌ها، مدیریت مدل، بازیابی و تقویت (RAG)، حافظه و زمینه
لایه داده و منابعمنابع دانش، مدیریت فایل، سرویس‌های خارجی، ابزارهای عملیاتی
لایه خروجی و گزارشتولید گزارش، مبدل قالب (Word/Excel)، داشبورد مصرف
محور عرضی حاکمیت دادهسیاست‌گذار داده، ممیزی و لاگ، سنسور محرمانگی
محور عرضی مشاهده‌پذیریمتریک و ردیابی مصرف، زمان پاسخ، نرخ خطا
- -
- 💡 نکته: تمام لایه‌های فوق در محصول ما پیاده‌سازی شده‌اند و در جلسه دمو به‌صورت عملی قابل نمایش هستند. این ادعا با اجرای سناریوی چندمرحله‌ای Agent و آزمون‌های دسترسی، اثبات خواهد شد. -
-
-
- -
-
-
۴
-
-

توسعه‌پذیری نامحدود از طریق MCP

-
Unlimited Extensibility via MCP
-
-
-
-

MCP (Model Context Protocol) در محصول ما به‌عنوان لایه استاندارد اتصال ایجنت به ابزارها و منابع استفاده می‌شود. هر قابلیت جدید می‌تواند در قالب یک MCP Server تعریف شود و بدون تغییر در هسته محصول به سامانه اضافه گردد.

- -
- تأکید معماری: از منظر معماری محصول، هیچ محدودیتی برای افزودن قابلیت از طریق MCP وجود ندارد. محدودیت تنها از جنس سیاست سازمانی و مجوزهای دسترسی است، نه از جنس معماری. هر MCP Server جدید در Tool Registry ثبت می‌شود و در صورت وجود مجوز، در اختیار ایجنت قرار می‌گیرد. -
- -

نمونه قابلیت‌های قابل افزودن با MCP:

- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
حوزه سازمانینمونه MCP Serverکاربرد پیشنهادی
منابع انسانیHR MCPمرخصی، آموزش، اطلاعات پرسنلی
مالی و بودجهFinance MCPبودجه، هزینه، فاکتور، مراکز هزینه
تولید و انبارProduction MCPموجودی، سفارش، فرمولاسیون
مدیریت اسنادDMS MCPجستجو و بازیابی اسناد سازمانی
پایگاه دادهDB MCPپرسش کنترل‌شده از داده‌ها
فایل و پوشهFile MCPدسترسی کنترل‌شده به فایل‌های محلی/شبکه
همکاری سازمانیCollaboration MCPایمیل، تقویم، اعلان
سامانه‌های سازمانیERP/CRM MCPیکپارچه‌سازی فرایندهای سازمانی
- -
- ✓ نتیجه: توسعه‌پذیری محصول از طریق MCP، عملاً نامحدود است. هر ابزار جدید، سرویس جدید یا منبع داده جدید، با تعریف یک MCP Server و ثبت در Tool Registry، به قابلیت‌های ایجنت اضافه می‌شود — بدون نیاز به تغییر در هسته محصول. -
-
-
- -
-
-
۵
-
-

حاکمیت داده و ضرورت مدل‌های لوکال

-
Data Governance & Local Model Necessity
-
-
-
-

در سناریوی شرکت پارسا پلیمر شریف — با اطلاعات حساس فرمولاسیون، مشتریان، فرایندها و اسناد سازمانی — استفاده از مدل‌های آنلاین، ذاتاً با حاکمیت داده و محرمانگی در تناقض است. زیرا داده از مرز سازمان خارج می‌شود و کنترل کامل بر ذخیره‌سازی، پردازش و استفاده ثانویه از آن وجود ندارد.

- -
- ⚠️ ریسک مدل‌های آنلاین: -
    -
  • خروج داده‌های حساس از مرز سازمان
  • -
  • عدم کنترل بر ذخیره‌سازی داده در سرورهای خارجی
  • -
  • احتمال استفاده از داده برای آموزش مدل‌های بعدی
  • -
  • وابستگی به اینترنت بین‌الملل و ریسک قطع سرویس
  • -
  • عدم انطباق با سیاست‌های محرمانگی سازمانی
  • -
-
- -

معماری پیشنهادی حاکمیت داده:

- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
تصمیمپیاده‌سازی در محصول
مدل پیش‌فرضمدل لوکال از طریق Model Gateway و Ollama/On-Prem
داده حساسهرگز از مرز سازمان خارج نمی‌شود
مدل آنلاینفقط برای داده غیرحساس، با تأیید سیاست و به‌صورت استثنا
آموزش مدلداده سازمان برای آموزش مدل‌های خارجی استفاده نمی‌شود
استقرارOn-Premise با امکان عملکرد در قطع اینترنت بین‌الملل
ممیزیثبت کامل مسیر داده و تصمیمات ایجنت
- -
- ✓ نتیجه: در سناریوی پیشنهادی، حاکمیت داده نه یک ادعا، بلکه یک سیاست اجرایی در معماری محصول است. مدل لوکال، پیش‌فرض است و داده حساس سازمان هرگز از مرز آن خارج نمی‌شود. -
-
-
- -
-
-
۶
-
-

کنترل دسترسی ایجنت و محدودسازی ابزارهای تصمیم‌گیرنده

-
Agent Access Control & Tool Restriction
-
-
-
-

محصول ما کنترل دسترسی را تنها به رابط کاربری محدود نمی‌کند. موتور مجوزها پیش از فراخوانی ایجنت، فهرست مجاز کاربر را تعیین می‌کند و این فهرست به ایجنت تصمیم‌گیرنده ابلاغ می‌شود:

- -
- - -
- -

این یعنی ایجنت تصمیم‌گیرنده نمی‌تواند ابزاری خارج از مجوز کاربر را فراخوانی کند، حتی اگر آن ابزار در Tool Registry ثبت شده باشد. این محدودسازی در سطح معماری اعمال می‌شود و توسط موتور مجوزها به ایجنت ابلاغ می‌گردد.

- -
- نکته حساس: پشتیبانی از ترکیب RBAC (نقش‌محور) و ABAC (ویژگی‌محور) در محصول ما، کنترل دسترسی را تا سطح رکورد، سند، واحد سازمانی و حتی فیلد اطلاعاتی ممکن می‌سازد. این دقیقاً پاسخ به نیازمندی محور ۲ RFP شماست. -
-
-
- -
-
-
۷
-
-

دفاع لایه‌ای برای حفظ محرمانگی

-
Layered Defense for Confidentiality
-
-
-
-

محصول ما برای جلوگیری از افشای اطلاعات، دفاع لایه‌ای را پیاده‌سازی کرده است. این دفاع شامل شش نقطه مستقل است که هر یک از منظری متفاوت، محرمانگی را تضمین می‌کند:

- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
لایهکنترلهدف
لایه ۱احراز هویت و نشستتأیید هویت و سطح دسترسی فعال
لایه ۲موتور مجوزهامحدودسازی مدل، ابزار و منبع پیش از اجرا
لایه ۳فهرست مجاز ابزار ایجنتجلوگیری از انتخاب ابزار غیرمجاز
لایه ۴فیلتر بازیابی RAGبازیابی فقط از منابع مجاز کاربر
لایه ۵سنسور محرمانگی خروجیجلوگیری از افشای اطلاعات در پاسخ نهایی
لایه ۶ممیزی و لاگثبت و ردیابی تمام تصمیمات و دسترسی‌ها
- -
- ⚠️ نکته حیاتی: لایه‌های ۲ (موتور مجوزها) و ۵ (سنسور محرمانگی) مستقل از هم هستند. حتی اگر ایجنت یا مدل بخواهد اطلاعات خارج از دسترس را افشا کند، در دو نقطه مستقل مسدود می‌شود. این دقیقاً پاسخ به آزمون نفوذ دسترسی کارفرماست. -
- -
- ✓ قابلیت اثبات: در جلسه دمو، پرسش‌های یکسان با حساب‌های دارای مجوزهای متفاوت مطرح خواهد شد تا نشان داده شود پاسخ‌ها بر مبنای اطلاعات مجاز هر کاربر تولید می‌شوند. همچنین تلاش برای دور زدن مجوزها از طریق پرسش مستقیم، غیرمستقیم یا خلاصه‌سازی، مسدود خواهد شد. -
-
-
- -
-
-
۸
-
-

مثال جریان کار: یک درخواست، دو ایجنت

-
Workflow Example: One Request, Two Agents
-
-
-
-

برای روشن‌تر شدن کنترل دسترسی در محصول، یک سناریوی واقعی را بررسی می‌کنیم. کارمندی درخواست می‌دهد:

- -
-

«می‌خواهم در دوره تخصصی پلیمر در آبان شرکت کنم؛ هزینه آن از بودجه واحد پرداخت شود و مرخصی آموزشی هم ثبت شود.»

-
— درخواست واحد کارمند
-
- -

این یک درخواست واحد است، اما برای پاسخ به آن به دو حوزه نیاز است: منابع انسانی و مالی. محصول ما این درخواست را به‌صورت زیر پردازش می‌کند:

- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
مرحلهمسئولاقدامکنترل دسترسی
۱ایجنت مسیریابتشخیص نیاز به HR و Financeفقط ابزارهای مجاز کاربر
۲ایجنت منابع انسانیبررسی مرخصی و شرایط آموزشفقط رکورد HR خود کارمند و سیاست آموزش
۳ایجنت مالیبررسی بودجه و هزینه دورهفقط بودجه مرکز هزینه واحد کاربر
۴ترکیب نتایجتولید پاسخ نهاییسنسور محرمانگی خروجی
۵تأیید انسانیاگر هزینه از سقف بیشتر باشدتوقف و دریافت تأیید
- -

نحوه اعمال کنترل دسترسی در این سناریو:

- -
    -
  • - ایجنت منابع انسانی - به ابزارهای مرخصی و آموزش دسترسی دارد، اما به حقوق، ارزیابی عملکرد یا پرونده سایر کارکنان دسترسی ندارد. -
  • -
  • - ایجنت مالی - به بودجه مرکز هزینه واحد کاربر دسترسی دارد، اما به فیش حقوقی یا اطلاعات مالی سایر واحدها دسترسی ندارد. -
  • -
  • - در صورت عدم مجوز مالی - اگر کاربر مجوز مالی نداشته باشد، ایجنت مالی پاسخ «عدم دسترسی» یا خروجی تجمیعی غیرمحرمانه ارائه می‌دهد. -
  • -
  • - اتصال از طریق MCP - هر دو ایجنت از طریق MCP به ابزارهای مجاز متصل می‌شوند و فهرست ابزار مجاز توسط موتور مجوزها تعیین می‌شود. -
  • -
  • - ممیزی کامل - تمام مراحل در سیستم ممیزی ثبت می‌شود و قابل ردیابی است. -
  • -
- -
- 💡 نتیجه مثال: محصول ما می‌تواند یک درخواست واحد را میان چند ایجنت توزیع کند، بدون اینکه مرزهای محرمانگی نقض شود. هر ایجنت فقط به ابزارها و منابعی دسترسی دارد که کاربر مجاز است، و این محدودسازی در سطح معماری محصول اعمال می‌شود. -
-
-
- -
-
-
۹
-
-

انطباق با محورهای RFP شرکت پارسا پلیمر شریف

-
Compliance with RFP Requirements
-
-
-
-

جدول زیر نشان می‌دهد محصول پیشنهادی، چگونه به هر یک از هفت محور RFP شما پاسخ می‌دهد:

- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
محور RFPپاسخ محصول
محور ۱: ماهیت ایجنتموتور ایجنت با برنامه‌ریزی، انتخاب ابزار، اجرا، اصلاح و Human-in-the-loop
محور ۲: دسترسیRBAC/ABAC، کنترل تا سطح رکورد، فهرست مجاز ابزار، دفاع لایه‌ای
محور ۳: پلن و مصرفداشبورد مصرف، گزارش هزینه به تفکیک کاربر/مدل/ایجنت، API
محور ۴: رابط و گزارشرابط وب/دسکتاپ، تحلیل فایل، خروجی Word/Excel، ارجاع به منبع
محور ۵: حاکمیت دادهمدل لوکال، On-Premise، عدم خروج داده حساس، MCP کنترل‌شده
محور ۶: پیاده‌سازی و آموزشنقشه راه فازبندی‌شده، مستندسازی، آموزش و پشتیبانی
محور ۷: عملکرد و تاب‌آوریعملکرد در قطع اینترنت با مدل لوکال، SLA قابل تعریف، آمادگی پایلوت
- -
- ✓ نتیجه: محصول پیشنهادی، به‌صورت سیستماتیک به تمام هفت محور RFP شما پاسخ می‌دهد. این پاسخ‌ها نه ادعای مکتوب، بلکه قابلیت‌های پیاده‌سازی‌شده و قابل‌آزمون هستند. -
-
-
- -
-
-
۱۰
-
-

وضعیت بلوغ محصول و گام بعدی

-
Product Maturity & Next Step
-
-
-
-

وضعیت فعلی: معماری مطرح‌شده در سازمان ما طراحی و پیاده‌سازی شده و به‌عنوان محصول قابل ارائه درآمده است. فازهای کلیدی محصول شامل موارد زیر است:

- -
-
-
-
فاز A: هسته ایجنت و رابط پایه
-

درگاه مدل، موتور ایجنت، رابط Blazor، احراز هویت — پیاده‌سازی شده

-
-
-
-
-
-
فاز B: ابزارها، RAG و منابع دانش
-

Tool Registry، MCP Client، RAG با ارجاع، مدیریت فایل — پیاده‌سازی شده

-
-
-
-
-
-
فاز C: حاکمیت داده و کنترل دسترسی
-

موتور مجوزها، سنسور محرمانگی، ممیزی، سیاست‌گذار داده — پیاده‌سازی شده

-
-
-
-
-
-
فاز D: گزارش، تأیید انسانی و مشاهده‌پذیری
-

تولید گزارش، مبدل قالب، Human-in-the-loop، داشبورد مصرف — پیاده‌سازی شده

-
-
-
-
-
-
فاز E: Cross-Platform و آماده‌سازی محصول
-

نسخه دسکتاپ، موبایل، مدیریت مدل، استقرار On-Premise — پیاده‌سازی شده

-
-
-
-
- -

گام بعدی پیشنهادی:

- -
    -
  • - برگزاری جلسه معرفی و دموی فنی - نمایش عملی محصول و پاسخ به سؤالات فنی تیم ارزیابی -
  • -
  • - اجرای سناریوی چندمرحله‌ای Agent - در محیط آزمایشی، شامل ابزار، خطا و مداخله انسانی -
  • -
  • - اجرای آزمون نفوذ دسترسی - با حساب‌های متفاوت و تلاش برای دور زدن مجوزها -
  • -
  • - ارائه برنامه پایلوت محدود - شامل زمان، هزینه، پیش‌نیازها و معیارهای موفقیت -
  • -
  • - ارائه پیشنهاد تجاری شفاف - بر اساس دامنه پایلوت و نیازمندی‌های سازمانی -
  • -
- -
- 📞 گام بعدی: در صورت تمایل به شروع همکاری، آماده برگزاری جلسه فنی برای تشریح جزئیات محصول، اجرای دموی عملی و ارائه برنامه پایلوت محدود هستم. پیش‌نویس قرارداد نیز بر اساس توافقات حاصله آماده امضا می‌باشد. -
-
-
- -
-
-
۱۱
-
-

جمع‌بندی و پیشنهاد نهایی

-
Final Summary & Recommendation
-
-
-
-

محصول پیشنهادی ما برای شرکت پارسا پلیمر شریف، یک سامانه هوش مصنوعی سازمانی آماده ارائه است که معماری آن در سازمان ما طراحی و پیاده‌سازی شده است. ویژگی‌های متمایز این پیشنهاد:

- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
ویژگیطرح مفهومی (رایج)محصول پیشنهادی ما
وضعیت پیاده‌سازیروی کاغذپیاده‌سازی شده
توسعه‌پذیری MCPمحدود یا نامشخصنامحدود از منظر معماری
حاکمیت دادهمدل آنلاین (ریسک محرمانگی)مدل لوکال (حاکمیت کامل)
کنترل دسترسی ایجنتمحدود به رابط کاربریتا سطح ابزار و رکورد
دفاع محرمانگییک لایهشش لایه مستقل
قابلیت اثباتادعای مکتوبدموی عملی و آزمون‌پذیر
ارزش خالص ایجاد شده—بسیار بالاتر
- -
-

🎯 پیشنهاد نهایی

-

با توجه به تحلیل‌های انجام‌شده، محصول پیشنهادی ما نه یک طرح مفهومی، بلکه یک سامانه پیاده‌سازی‌شده و آزمون‌پذیر است که به تمام محورهای RFP شما پاسخ می‌دهد.

-

توسعه‌پذیری نامحدود از طریق MCP، حاکمیت داده با مدل‌های لوکال، کنترل دسترسی تا سطح ابزار ایجنت، و دفاع لایه‌ای برای محرمانگی، چهار ستون اصلی این پیشنهاد هستند.

-
- 💎 ارزش پیشنهادی:
- ایجنت قابل‌آزمون + توسعه‌پذیری MCP + حاکمیت داده با مدل لوکال + کنترل دسترسی تا سطح ابزار + دفاع لایه‌ای + آمادگی پایلوت -
-
- -
- 📞 گام بعدی: در صورت تأیید این پروپوزال، آماده ارائه نسخه تفصیلی پیشنهاد فنی و تجاری، سناریوی نمونه Agent برای جلسه دمو، و برنامه زمان‌بندی پایلوت هستم. جلسه فنی پیشنهادی در اسرع وقت قابل برگزاری است. -
-
-
- -
- این مستند محرمانه بوده و صرفاً جهت ارائه به کارفرمای محترم تهیه شده است. هرگونه کپی‌برداری یا افشا بدون اجازه کتبی ممنوع است. -
- -
- -
- - -
تاریخ تهیه: مهر ۱۴۰۵  |  نسخه: ۱.۰  |  طبقه‌بندی: محرمانه
-
- -
- - - - -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\xAiApi\wwwroot\Storage\Uploads\Document\xSaherElm_3096683f-c9d2-4ee3-aa17-f6d2100104f0.html - - - - - - -نگاشت نقشه راه دانش فنی به roadmap.sh | سامانه هوش مصنوعی سازمانی - - - - -
- -
-
-
- -
-
-
شماره مستند: MAP-1405-001
-
نسخه: ۱.۰
-
تاریخ تهیه: آذر ۱۴۰۵
-
طبقه‌بندی: محرمانه
-
-
- -
- ROADMAP.SH MAPPING -

نگاشت نقشه راه دانش فنی به roadmap.sh

-

سامانه هوش مصنوعی سازمانی — از معماری تا محصول

-
-
- -
- -
- خلاصه مدیریتی،
- این مستند، نگاشت نقشه راه دانش فنی سامانه هوش مصنوعی سازمانی (مستند ROAD-1405-001) به نقشه‌های راه موجود در سایت roadmap.sh را ارائه می‌دهد. هدف، استفاده از منابع آموزشی جامعه‌محور و شناخته‌شده این سایت به‌عنوان ستون فقرات آموزشی برای هر فاز نقشه راه است. در این نگاشت، مشخص می‌شود هر فاز از نقشه راه دانش فنی، با کدام نقشه(های) راه roadmap.sh پوشش داده می‌شود، چه شکاف‌هایی وجود دارد و چگونه باید تکمیل شود. رویکرد نگاشت، فارغ از سکو و مبتنی بر مفاهیم و الگوها است. -
- -
-
-
۱
-
-

معرفی roadmap.sh و رویکرد نگاشت

-
About roadmap.sh & Mapping Approach
-
-
-
-

roadmap.sh یکی از محبوب‌ترین منابع جامعه‌محور برای نقشه‌های راه مهارت‌های فنی است که توسط صدها هزار توسعه‌دهنده در ماه استفاده می‌شود. این سایت مجموعه‌ای از نقشه‌های راه برای نقش‌های مختلف (Backend، Frontend، DevOps، AI Engineer، Cyber Security، Software Architect و...) ارائه می‌دهد که هر یک شامل موضوعات، منابع و مسیر یادگیری است.

- -
-
-
◇
-
فارغ از سکو
-

در استفاده از نقشه‌های راه، تمرکز بر مفاهیم و الگوهاست، نه ابزارهای خاص.

-
-
-
◈
-
ستون فقرات آموزشی
-

roadmap.sh چارچوب کلی می‌دهد؛ تکمیل با منابع تخصصی در بخش‌های دارای شکاف.

-
-
-
▤
-
نگاشت فاز به نقشه
-

هر فاز از ROAD-1405-001 به یک یا چند نقشه راه roadmap.sh نگاشت می‌شود.

-
-
-
✓
-
حفظ خروجی قابل‌آزمون
-

خروجی‌های قابل‌آزمون (Deliverable) هر فاز، مبنای ارزیابی پیشرفت باقی می‌مانند.

-
-
- -
- اصل حاکم: roadmap.sh به‌عنوان نقشه راه آموزشی استفاده می‌شود، نه به‌عنوان نقشه راه محصول. یعنی موضوعات آن برای کسب دانش فنی تیم به کار می‌رود، اما خروجی‌های قابل‌آزمون و الزامات کارفرما (REQ-1405-001) همچنان معیار اصلی پیشرفت هستند. -
-
-
- -
-
-
۲
-
-

نمای کلی نگاشت

-
Mapping Overview
-
-
-
-

جدول زیر، نگاشت کلی هفت فاز نقشه راه دانش فنی به نقشه‌های راه roadmap.sh را نشان می‌دهد:

- -
-
-
۷
-
فاز نقشه راه
-
-
-
۶
-
نقشه راه roadmap.sh
-
-
-
۱
-
شکاف اصلی (ایجنت)
-
-
- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
فاز ROAD-1405-001نقشه(های) راه roadmap.shدرجه پوششنیاز به تکمیل
فاز ۱: مبانی سیستم‌ها و دادهBackend Developer (بخش‌های ابتدایی)بالاجزئی (مدیریت کلید، رمزنگاری پیشرفته)
فاز ۲: مبانی مهندسی نرم‌افزارSoftware Design and Architectureبالاجزئی (Hexagonal، آزمون‌پذیری)
فاز ۳: مبانی هوش مصنوعی و مدل‌هاAI Engineerبالامتوسط (ارزیابی مدل، حاکمیت AI)
فاز ۴: معماری سیستم‌های توزیع‌شدهSystem Designبالامتوسط (BPMN 2.0، Event Sourcing)
فاز ۵: معماری ایجنت و ارکستراسیونAI Engineer (پیشرفته) + Software Architectپایینقابل توجه (منابع تخصصی ایجنت)
فاز ۶: امنیت، حاکمیت داده و انطباقCyber Securityبالامتوسط (OWASP LLM، ISO 42001)
فاز ۷: معماری کلان، محصول و عملیاتDevOps + Software Architectمتوسطمتوسط (مدیریت محصول، ADR)
- -
- 💡 نکته: بیشترین شکاف در فاز ۵ (معماری ایجنت) است. roadmap.sh در نقشه AI Engineer به AI Agents اشاره دارد، اما معماری عمیق ایجنت (برنامه‌ریزی، انتخاب ابزار، حلقه بازخورد، چند-ایجنت) را پوشش نمی‌دهد. این فاز نیازمند منابع تخصصی تکمیلی است. -
-
-
- -
-
-
۳
-
-

نگاشت تفصیلی فاز به نقشه راه

-
Detailed Phase-to-Roadmap Mapping
-
-
-
-

در ادامه، هر فاز به‌صورت تفصیلی نگاشت شده است؛ شامل موضوعات پوشش‌داده‌شده، شکاف‌ها و منابع تکمیلی پیشنهادی:

- - -
-
-
۱
-
-

مبانی سیستم‌ها و داده

-
Phase 1 — Foundations of Systems & Data
-
-
←
-
Backend Developer
-
-
-

نقشه راه Backend Developer در roadmap.sh، مبانی اینترنت، پروتکل HTTP، پایگاه‌های داده، مدل داده و مبانی امنیت را پوشش می‌دهد که با فاز ۱ نقشه راه دانش فنی هم‌پوشانی بالایی دارد.

- -
-
-
موضوعات پوشش‌داده‌شده
-
    -
  • مبانی اینترنت و DNS
  • -
  • HTTP/HTTPS و REST
  • -
  • پایگاه‌های داده رابطه‌ای و NoSQL
  • -
  • مدل‌سازی داده
  • -
  • مبانی احراز هویت
  • -
-
-
-
موضوعات نیازمند تکمیل
-
    -
  • مدیریت کلید پیشرفته (NIST SP 800-57)
  • -
  • رمزنگاری نامتقارن و امضای دیجیتال
  • -
  • Data Lake و Data Warehouse
  • -
  • مدل تهدید پایه
  • -
-
-
- -

منابع تکمیلی پیشنهادی:

-
- RFC 8446 (TLS 1.3) - NIST SP 800-57 - ISO/IEC 27001 (مبانی) -
- -

خروجی قابل‌آزمون (از ROAD-1405-001):

-
    -
  • نقشه مفهومی داده سازمان + سند مدل تهدید پایه
  • -
-
-
- - -
-
-
۲
-
-

مبانی مهندسی نرم‌افزار

-
Phase 2 — Software Engineering Foundations
-
-
←
-
Software Design and Architecture
-
-
-

نقشه راه Software Design and Architecture، الگوهای طراحی، اصول SOLID، معماری تمیز و جداسازی دغدغه‌ها را پوشش می‌دهد که با فاز ۲ هم‌پوشانی بالایی دارد.

- -
-
-
موضوعات پوشش‌داده‌شده
-
    -
  • اصول SOLID
  • -
  • الگوهای طراحی (GoF)
  • -
  • معماری لایه‌ای و MVC
  • -
  • Separation of Concerns
  • -
  • مبانی آزمون‌پذیری
  • -
-
-
-
موضوعات نیازمند تکمیل
-
    -
  • معماری Hexagonal (Ports & Adapters)
  • -
  • Test Double (Mock، Stub، Fake)
  • -
  • Contract Testing
  • -
  • ADR (Architecture Decision Records)
  • -
-
-
- -

منابع تکمیلی پیشنهادی:

-
- Clean Architecture (Robert C. Martin) - Hexagonal Architecture (Alistair Cockburn) - ISO/IEC 25010 -
- -

خروجی قابل‌آزمون (از ROAD-1405-001):

-
    -
  • سند اصول و الگوهای منتخب + نمونه اولیه ساختار Hexagonal
  • -
-
-
- - -
-
-
۳
-
-

مبانی هوش مصنوعی و مدل‌ها

-
Phase 3 — AI & Model Foundations
-
-
←
-
AI Engineer
-
-
-

نقشه راه AI Engineer در roadmap.sh، مبانی LLM، Prompt Engineering، RAG، پایگاه‌های داده برداری و ارزیابی مدل‌ها را پوشش می‌دهد. این نقشه راه، هسته لایه هوش (L4) معماری را پوشش می‌دهد.

- -
-
-
موضوعات پوشش‌داده‌شده
-
    -
  • مبانی مدل‌های زبانی
  • -
  • Prompt Engineering
  • -
  • RAG و Vector Database
  • -
  • Function Calling
  • -
  • ارزیابی کیفیت پاسخ
  • -
-
-
-
موضوعات نیازمند تکمیل
-
    -
  • NIST AI RMF و ISO 42001
  • -
  • Hallucination Detection پیشرفته
  • -
  • Bias و Fairness
  • -
  • سیاست دسترسی به مدل‌های جدید
  • -
-
-
- -

منابع تکمیلی پیشنهادی:

-
- NIST AI RMF - ISO/IEC 42001 - Attention Is All You Need -
- -

خروجی قابل‌آزمون (از ROAD-1405-001):

-
    -
  • سند ارزیابی مدل‌ها + نمونه اولیه RAG
  • -
-
-
- - -
-
-
۴
-
-

معماری سیستم‌های توزیع‌شده

-
Phase 4 — Distributed Systems Architecture
-
-
←
-
System Design
-
-
-

نقشه راه System Design، مباحث مقیاس‌پذیری، دسترس‌پذیری، الگوهای توزیع‌شده (CQRS، Event-Driven) و trade-offها را پوشش می‌دهد که با فاز ۴ هم‌پوشانی بالایی دارد.

- -
-
-
موضوعات پوشش‌داده‌شده
-
    -
  • مقیاس‌پذیری و Load Balancing
  • -
  • Caching Strategies
  • -
  • Event-Driven Architecture
  • -
  • CQRS و Event Sourcing (مفهومی)
  • -
  • Circuit Breaker و Retry
  • -
-
-
-
موضوعات نیازمند تکمیل
-
    -
  • BPMN 2.0 (برای مدل‌سازی فرایند)
  • -
  • OpenTelemetry (مشاهده‌پذیری)
  • -
  • Saga Pattern پیشرفته
  • -
  • Idempotency و Distributed Locking
  • -
-
-
- -

منابع تکمیلی پیشنهادی:

-
- Enterprise Integration Patterns - Release It! (Michael Nygard) - OpenTelemetry Spec - BPMN 2.0 -
- -

خروجی قابل‌آزمون (از ROAD-1405-001):

-
    -
  • سند الگوهای معماری منتخب + نقشه BPMN2 تکمیلی
  • -
-
-
- - -
-
-
۵
-
-

معماری ایجنت و ارکستراسیون

-
Phase 5 — Agent Architecture & Orchestration
-
-
←
-
AI Engineer + Software Architect
-
-
-

این فاز، بیشترین شکاف را در roadmap.sh دارد. نقشه AI Engineer به AI Agents اشاره دارد، اما معماری عمیق ایجنت (برنامه‌ریزی، انتخاب ابزار، حلقه بازخورد، چند-ایجنت) را پوشش نمی‌دهد. نقشه Software Architect نیز دید کلان می‌دهد اما تخصصی ایجنت نیست.

- -
- ⚠️ شکاف اصلی: roadmap.sh معماری ایجنت (Agent Architecture) را به‌طور عمیق پوشش نمی‌دهد. این فاز نیازمند منابع تخصصی تکمیلی است: مقالات علمی (ReAct، Reflexion، Plan-and-Execute)، مستندات پروتکل‌ها (MCP)، و منابع تخصصی طراحی ایجنت. -
- -
-
-
موضوعات پوشش‌داده‌شده (جزئی)
-
    -
  • مفاهیم پایه AI Agent
  • -
  • Function Calling
  • -
  • Tool Use (مقدماتی)
  • -
  • حافظه و زمینه
  • -
-
-
-
موضوعات نیازمند منابع تخصصی
-
    -
  • الگوهای برنامه‌ریزی (ReAct، Reflexion)
  • -
  • Tool Selection Strategies
  • -
  • Human-in-the-loop Patterns
  • -
  • Multi-Agent Orchestration
  • -
  • ارزیابی ایجنت (Task Success Rate)
  • -
  • Guardrails و Kill Switch
  • -
-
-
- -

منابع تکمیلی پیشنهادی:

-
- ReAct (Yao et al.) - Reflexion (Shinn et al.) - Model Context Protocol (MCP) - NIST AI RMF (کنترل) -
- -

خروجی قابل‌آزمون (از ROAD-1405-001):

-
    -
  • سناریوی نمونه Agent (قابل ارائه در جلسه دمو) + چارچوب ارزیابی ایجنت
  • -
-
-
- - -
-
-
۶
-
-

امنیت، حاکمیت داده و انطباق

-
Phase 6 — Security, Data Governance & Compliance
-
-
←
-
Cyber Security
-
-
-

نقشه راه Cyber Security در roadmap.sh، مباحث IAM (Identity & Access Management)، رمزنگاری، امنیت وب و OWASP را پوشش می‌دهد که با فاز ۶ هم‌پوشانی بالایی دارد و مستقیماً به محور عرضی حاکمیت (X) مرتبط است.

- -
-
-
موضوعات پوشش‌داده‌شده
-
    -
  • OAuth 2.0 و OpenID Connect
  • -
  • RBAC و ABAC
  • -
  • OWASP Top 10 و API Security
  • -
  • رمزنگاری و TLS
  • -
  • Audit Logging
  • -
-
-
-
موضوعات نیازمند تکمیل
-
    -
  • OWASP LLM Top 10
  • -
  • Prompt Injection و Jailbreak
  • -
  • ISO/IEC 42001 (مدیریت AI)
  • -
  • NIST AI RMF (کنترل)
  • -
  • ReBAC و Fine-grained Access
  • -
-
-
- -

منابع تکمیلی پیشنهادی:

-
- OAuth 2.0 (RFC 6749) - OpenID Connect Core - OWASP LLM Top 10 - ISO/IEC 27001 - ISO/IEC 42001 -
- -

خروجی قابل‌آزمون (از ROAD-1405-001):

-
    -
  • سند مدل دسترسی و حاکمیت داده + سناریوی آزمون نفوذ دسترسی
  • -
-
-
- - -
-
-
۷
-
-

معماری کلان، محصول و عملیات

-
Phase 7 — Enterprise Architecture, Product & Operations
-
-
←
-
DevOps + Software Architect
-
-
-

ترکیب دو نقشه راه DevOps (برای SRE، مشاهده‌پذیری و عملیات) و Software Architect (برای نگاشت معماری به محصول و مدیریت چرخه عمر) پوشش مناسبی برای فاز ۷ فراهم می‌کند.

- -
-
-
موضوعات پوشش‌داده‌شده
-
    -
  • SLI/SLO/SLA
  • -
  • مشاهده‌پذیری (Logging، Metrics، Tracing)
  • -
  • Incident Management
  • -
  • معماری سازمانی (TOGAF مفهومی)
  • -
  • Release Strategies
  • -
-
-
-
موضوعات نیازمند تکمیل
-
    -
  • مدیریت محصول (Product Vision، Roadmap)
  • -
  • Token Accounting و Cost Attribution
  • -
  • ADR (Architecture Decision Records)
  • -
  • Capability Mapping
  • -
  • Team Topologies (مفهومی)
  • -
-
-
- -

منابع تکمیلی پیشنهادی:

-
- TOGAF ADM - Google SRE Book - OpenAPI Specification - ADR - ISO/IEC 20000 -
- -

خروجی قابل‌آزمون (از ROAD-1405-001):

-
    -
  • سند معماری محصول + سند SLA و SLO
  • -
-
-
- -
-
- -
-
-
۴
-
-

شکاف‌های کلیدی و راهکار تکمیل

-
Key Gaps & Completion Strategy
-
-
-
-

roadmap.sh به‌عنوان ستون فقرات آموزشی، پوشش خوبی برای فازهای ۱ تا ۴، ۶ و ۷ دارد. اما شکاف‌های زیر باید با منابع تخصصی تکمیل شوند:

- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
شکاففاز مرتبطراهکار تکمیل
معماری ایجنت (Agent Architecture)فاز ۵مقالات ReAct، Reflexion، Plan-and-Execute + مستندات MCP + منابع تخصصی طراحی ایجنت
ارزیابی ایجنتفاز ۵چارچوب‌های ارزیابی (Task Success Rate، Step Efficiency) + آزمون سناریومحور
امنیت LLMفاز ۶OWASP LLM Top 10 + Prompt Injection + Jailbreak Detection
حاکمیت AIفاز ۳، ۶NIST AI RMF + ISO/IEC 42001 + OECD AI Principles
BPMN 2.0فاز ۴مستندات OMG BPMN 2.0 + الگوهای مدل‌سازی فرایند
مدیریت محصولفاز ۷منابع تخصصی Product Management + Prioritization Frameworks
- -
- ⚠️ نکته مهم: شکاف معماری ایجنت (فاز ۵) بحرانی‌ترین شکاف است، زیرا این فاز مستقیماً به محور ۱ نیازمندی‌های کارفرما (ایجنت قابل‌آزمون) و نقطه عطف M4 (آمادگی برای جلسه دمو) مرتبط است. بنابراین، منابع تخصصی این فاز باید به‌صورت جدی و جداگانه دنبال شوند. -
-
-
- -
-
-
۵
-
-

نقشه راه تلفیقی پیشنهادی

-
Recommended Integrated Roadmap
-
-
-
-

بر اساس نگاشت فوق، نقشه راه تلفیقی زیر پیشنهاد می‌شود که roadmap.sh را با منابع تخصصی تکمیل می‌کند:

- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
فازمنبع اصلی (roadmap.sh)منبع تکمیلیخروجی قابل‌آزمون
۱Backend DeveloperNIST SP 800-57، RFC 8446نقشه داده + مدل تهدید
۲Software Design & ArchitectureClean Architecture، Hexagonalسند الگوها + نمونه Hexagonal
۳AI EngineerNIST AI RMF، ISO 42001ارزیابی مدل + نمونه RAG
۴System DesignBPMN 2.0، OpenTelemetry، Release It!الگوهای معماری + BPMN2
۵AI Engineer + Software ArchitectReAct، Reflexion، MCP، منابع تخصصی ایجنتسناریوی Agent + چارچوب ارزیابی
۶Cyber SecurityOWASP LLM Top 10، ISO 27001/42001مدل دسترسی + آزمون نفوذ
۷DevOps + Software ArchitectGoogle SRE، TOGAF، OpenAPIمعماری محصول + SLA/SLO
- -
- ✓ نکته کلیدی: نقطه عطف M4 (آمادگی برای جلسه دمو) با تکمیل فازهای ۱ تا ۶ و به‌ویژه فاز ۵ با منابع تخصصی محقق می‌شود. roadmap.sh برای فازهای ۱ تا ۴ و ۶ ستون فقرات است، اما فاز ۵ نیازمند منابع تخصصی جداگانه است. -
-
-
- -
-
-
۶
-
-

لینک‌های مرجع roadmap.sh

-
roadmap.sh Reference Links
-
-
-
-

لینک‌های مستقیم به نقشه‌های راه پیشنهادی در roadmap.sh:

- -
-
  • - Backend Developer - -
  • -
  • - Software Design and Architecture - -
  • -
  • - AI Engineer - -
  • -
  • - System Design - -
  • -
  • - Software Architect - -
  • -
  • - Cyber Security - -
  • -
  • - DevOps - -
  • -
    - -
    - 💡 نکته: roadmap.sh به‌طور مداوم به‌روزرسانی می‌شود. توصیه می‌شود لینک‌ها و محتوای نقشه‌های راه به‌صورت دوره‌ای بازبینی شوند تا از آخرین تغییرات مطلع شوید. -
    -
    -
    - -
    -
    -
    ۷
    -
    -

    جمع‌بندی

    -
    Summary
    -
    -
    -
    -

    این مستند، نگاشت نقشه راه دانش فنی (ROAD-1405-001) به نقشه‌های راه roadmap.sh را ارائه داد. ویژگی‌های کلیدی:

    - -
      -
    • - پوشش بالای فازهای ۱ تا ۴، ۶ و ۷ - با نقشه‌های راه Backend، Software Design، AI Engineer، System Design، Cyber Security، DevOps و Software Architect -
    • -
    • - شکاف بحرانی در فاز ۵ (ایجنت) - نیازمند منابع تخصصی تکمیلی (ReAct، Reflexion، MCP) -
    • -
    • - حفظ خروجی‌های قابل‌آزمون - هر فاز همچنان با Deliverable مشخص از ROAD-1405-001 ارزیابی می‌شود -
    • -
    • - رویکرد فارغ از سکو - استفاده از roadmap.sh برای مفاهیم و الگوها، نه ابزارهای خاص -
    • -
    • - نقشه راه تلفیقی - ترکیب roadmap.sh با منابع تخصصی برای پوشش کامل هفت فاز -
    • -
    - -
    - توصیه نهایی: roadmap.sh به‌عنوان ستون فقرات آموزشی برای فازهای ۱ تا ۴، ۶ و ۷ استفاده شود. برای فاز ۵ (هسته تمایز محصول)، منابع تخصصی ایجنت (مقالات علمی و مستندات پروتکل‌ها) به‌صورت جداگانه دنبال شوند. نقطه عطف M4 (آمادگی برای جلسه دمو) با تکمیل فازهای ۱ تا ۶ و منابع تخصصی فاز ۵ محقق می‌شود. -
    -
    -
    - -
    -

    🎯 ارزش این مستند

    -

    این مستند، پل ارتباطی بین نقشه راه دانش فنی داخلی و منابع آموزشی جامعه‌محور roadmap.sh را فراهم می‌کند.

    -

    با این نگاشت، تیم فنی می‌تواند از منابع شناخته‌شده و به‌روز roadmap.sh برای فازهای مختلف استفاده کند و شکاف‌ها را با منابع تخصصی تکمیل نماید.

    -
    - 💎 ارزش پیشنهادی:
    - ستون فقرات آموزشی roadmap.sh + منابع تخصصی تکمیلی + حفظ خروجی قابل‌آزمون + رویکرد فارغ از سکو + نقشه راه تلفیقی -
    -
    - -
    - این مستند محرمانه بوده و صرفاً جهت ارائه به کارفرمای محترم تهیه شده است. هرگونه کپی‌برداری یا افشا بدون اجازه کتبی ممنوع است. -
    - -
    - -
    - - -
    تاریخ تهیه: آذر ۱۴۰۵  |  نسخه: ۱.۰  |  طبقه‌بندی: محرمانه
    -
    - -
    - - - - -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\xAiApi\wwwroot\Storage\Uploads\Document\xSaherElm_4c60f04d-bd98-4ec0-af18-7beb569dfb05.html - - - - - - - رفع مشکل تست XApiKey در Swagger | مستند فنی - - - -
    -
    -
    -
    -
    شماره مستند: XIDS-SWAGGER-APIKEY-002
    -
    نسخه: ۲.۰
    -
    تاریخ تهیه: ۲۰ مهر ۱۴۰۵
    -
    طبقه‌بندی: داخلی — فنی
    -
    -
    -
    -

    رفع مشکل تست XApiKey در Swagger UI

    -

    تحلیل ریشه‌ای و راه‌حل گام‌به‌گام برای فعال‌سازی کامل

    -
    -
    - -
    - - -
    -
    -
    ۱
    -
    -

    خلاصه مشکل شناسایی‌شده

    -
    Problem Summary
    -
    -
    -
    -

    - پس از بررسی دقیق کدهای پروژه xIds، مشخص شد که اگرچه زیرساخت - XApiKeyAuthenticationHandler و Policyهای مربوطه به‌درستی پیاده‌سازی شده‌اند، - اما چهار مشکل معماری مانع از کارکرد صحیح احراز هویت با API Key در Swagger می‌شوند. -

    - -
    - 🔴 مشکلات شناسایی‌شده: -
      -
    1. ترتیب ثبت Schemeها: XApiKey اول ثبت شده و به‌عنوان DefaultScheme انتخاب می‌شود — در نتیجه درخواست‌های Bearer Token هم به آن حواله می‌شوند و شکست می‌خورند.
    2. -
    3. عدم تنظیم DefaultScheme: در AddAuthentication() هیچ DefaultScheme مشخصی تعیین نشده است.
    4. -
    5. محدودیت LocalApi Policy: Policy IdentityServerConstants.LocalApi.PolicyName فقط Scheme IdentityServerAccessToken را قبول می‌کند.
    6. -
    7. عدم وجود PolicyScheme هوشمند: هیچ مکانیزمی برای انتخاب پویای Scheme بر اساس Header درخواست وجود ندارد.
    8. -
    -
    -
    -
    - - -
    -
    -
    ۲
    -
    -

    تحلیل جریان فعلی احراز هویت

    -
    Current Authentication Flow Analysis
    -
    -
    -
    -

    - در کد فعلی XDIHelperExtension.AddXIdentityServerAuthentication، ترتیب ثبت به این صورت است: -

    - -
    // xIds/DI/XDIHelperExtension.cs — کد فعلی -var authBuilder = services.AddAuthentication(); // ← DefaultScheme تنظیم نشده! - -// ۱. ثبت XApiKey (اول) -if (addApiKeyAuthentication) -{ - authBuilder.AddScheme<..., XApiKeyAuthenticationHandler>( - "XApiKey", options => { }); -} - -// ۲. ثبت JwtBearer -authBuilder.AddJwtBearer(options => { - options.ForwardDefaultSelector = context => { ... }; -}) -// ۳. ثبت LocalApi -.AddLocalApi();
    - -
    - 💡 نکته کلیدی: - وقتی AddAuthentication() بدون پارامتر فراخوانی می‌شود و سپس اولین Scheme (XApiKey) ثبت می‌گردد، - ASP.NET Core به‌صورت خودکار XApiKey را به‌عنوان DefaultScheme در نظر می‌گیرد. - این یعنی تمام درخواست‌ها (حتی آن‌هایی که Bearer Token دارند) ابتدا به XApiKeyAuthenticationHandler می‌روند - و چون Header X-Api-Key وجود ندارد، NoResult برمی‌گردانند. -
    - -
    -
    جریان فعلی (معیوب):
    - درخواست با Bearer Token - → - DefaultScheme = XApiKey - → - NoResult (بدون Header) - → - 401 Unauthorized ❌ -
    - -
    -
    جریان مطلوب (پس از اصلاح):
    - درخواست - → - PolicyScheme (هوشمند) - → - XApiKey یا LocalApi - → - 200 OK ✓ -
    -
    -
    - - -
    -
    -
    ۳
    -
    -

    گام ۱ — اصلاح AddXIdentityServerAuthentication با PolicyScheme

    -
    Step 1: Fix Authentication Registration with PolicyScheme
    -
    -
    -
    -
    -
    حیاتی — فایل: xIds/DI/XDIHelperExtension.cs
    -

    توضیح:

    -

    - باید از AddPolicyScheme استفاده کنیم تا یک Scheme هوشمند بسازیم که بر اساس - وجود Header X-Api-Key در درخواست، Scheme مناسب را انتخاب کند. - همچنین DefaultScheme و DefaultChallengeScheme باید به‌درستی تنظیم شوند. -

    -
    - -

    کد اصلاح‌شده کامل:

    -
    // xIds/DI/XDIHelperExtension.cs -// متد: AddXIdentityServerAuthentication - -public static void AddXIdentityServerAuthentication( - this IServiceCollection services, - IConfiguration configuration, - bool addApiKeyAuthentication = false -) -{ - // افزودنی‌های مورد نیاز - services.AddXIdentityResourceConfiguration(configuration); - - // ═══════════════════════════════════════════════════════ - // ثبت XApiKey Scheme (قبل از هر چیز دیگر) - // ═══════════════════════════════════════════════════════ - if (addApiKeyAuthentication) - { - services.AddAuthentication() - .AddScheme<AuthenticationSchemeOptions, XApiKeyAuthenticationHandler>( - XAuthenticationScheme.XApiKey.GetStringValue(), - options => { }); - } - - // ═══════════════════════════════════════════════════════ - // تعریف PolicyScheme هوشمند برای مسیریابی درخواست‌ها - // ═══════════════════════════════════════════════════════ - var smartSchemeName = "SmartAuthScheme"; - - services.AddAuthentication(options => - { - // DefaultScheme = PolicyScheme هوشمند - options.DefaultScheme = smartSchemeName; - options.DefaultAuthenticateScheme = smartSchemeName; - options.DefaultChallengeScheme = smartSchemeName; - }) - .AddPolicyScheme(smartSchemeName, "Smart Authentication Scheme", options => - { - options.ForwardDefaultSelector = context => - { - // بررسی وجود Header X-Api-Key - var apiKeyHeader = XHeader.ApiKey.GetStringValue(); - if (context.Request.Headers.ContainsKey(apiKeyHeader)) - { - return XAuthenticationScheme.XApiKey.GetStringValue(); - } - - // در غیر این صورت، از LocalApi (IdentityServer) استفاده کن - return XAuthentication.IDENTITY_SERVER_LOCAL_API; - }; - }) - .AddJwtBearer(XAuthenticationScheme.XToken.GetStringValue(), options => - { - options.Authority = configuration - .GetSection("IdentityResourceConfiguration:Authority").Value; - options.TokenValidationParameters.ValidateAudience = false; - options.TokenValidationParameters.ValidTypes = new[] { "at+jwt" }; - }) - .AddOAuth2Introspection(XAuthenticationScheme.XIntrospection.GetStringValue(), options => - { - var identityConfig = configuration.GetXIdentityResourceConfiguration(); - options.Authority = identityConfig.Authority; - options.ClientId = identityConfig.ApiName; - options.ClientSecret = identityConfig.ClientSecret; - }) - .AddLocalApi(); -}
    - -
    - ✅ چرا این راه‌حل کار می‌کند؟ -
      -
    • PolicyScheme به‌عنوان DefaultScheme عمل می‌کند و بر اساس Header تصمیم می‌گیرد.
    • -
    • اگر X-Api-Key وجود داشته باشد → به XApiKeyAuthenticationHandler حواله می‌دهد.
    • -
    • در غیر این صورت → به LocalApi (IdentityServer) حواله می‌دهد.
    • -
    • هیچ‌گاه Scheme اشتباه انتخاب نمی‌شود.
    • -
    -
    -
    -
    - - -
    -
    -
    ۴
    -
    -

    گام ۲ — اصلاح LocalApi Policy برای پذیرش XApiKey

    -
    Step 2: Fix LocalApi Policy to Accept XApiKey
    -
    -
    -
    -
    -
    مهم — فایل: xIds/DI/XDIHelperExtension.cs
    -

    توضیح:

    -

    - در متد AddXAuthorization، Policy LocalApi.PolicyName - فقط Scheme IdentityServerAccessToken را قبول می‌کند. - باید این Policy را اصلاح کنیم تا XApiKey را هم بپذیرد. -

    -
    - -
    // xIds/DI/XDIHelperExtension.cs -// متد: AddXAuthorization - -public static void AddXAuthorization( - this IServiceCollection services, - IDictionary<string, AuthorizationPolicy> policies = null -) -{ - services.AddAuthorization(options => - { - // ... کدهای قبلی برای policies و xPolicies ... - - // ═══════════════════════════════════════════════════════ - // اصلاح LocalApi Policy برای پذیرش هر دو Scheme - // ═══════════════════════════════════════════════════════ - options.AddPolicy(IdentityServerConstants.LocalApi.PolicyName, policy => - { - policy.AddAuthenticationSchemes(new[] - { - IdentityServerConstants.LocalApi.AuthenticationScheme, - XAuthenticationScheme.XApiKey.GetStringValue() // ← اضافه شد - }); - policy.RequireAuthenticatedUser(); - }); - }); - - services.AddSingleton<IAuthorizationHandler, RequiredRolesHandler>(); -}
    - -
    - 💡 نکته: - با این اصلاح، Endpointهایی که [Authorize(LocalApi.PolicyName)] دارند، - هم با Bearer Token و هم با X-Api-Key قابل دسترسی خواهند بود. -
    -
    -
    - - -
    -
    -
    ۵
    -
    -

    گام ۳ — بررسی و اصلاح Swagger Security Definition

    -
    Step 3: Verify Swagger Security Configuration
    -
    -
    -
    -
    -
    بررسی — فایل: xCommons/Extensions/DIExtensions.cs
    -

    توضیح:

    -

    - در کد فعلی AddXSwaggerGenOptions، Security Definition برای XApiKey - به‌درستی تعریف شده است. اما باید مطمئن شویم که addXApiKeyAuthorization - در فراخوانی AddXSwagger مقدار true دارد. -

    -
    - -

    بررسی Startup.cs:

    -
    // xIds/Startup.cs — ConfigureServices - -// ثبت Swagger — مطمئن شوید پارامترها درست هستند -var xmlFile = $"{Assembly.GetExecutingAssembly().GetName().Name}.xml"; -var xmlPath = Path.Combine(AppContext.BaseDirectory, xmlFile); - -services.AddXSwagger( - Configuration, - xmlFilePath: xmlPath, - addRequiredXPoweredFilter: true, - addXTokenAuthorization: true, - addXApiKeyAuthorization: true, // ← باید true باشد - addDefaultValueFilter: true -);
    - -

    خروجی مورد انتظار در Swagger UI:

    -
    - 🔑 در Swagger UI باید دو دکمه "Authorize" ببینید: -
      -
    • accessToken: برای Bearer Token (مقدار: Bearer {token})
    • -
    • X-Api-Key: برای API Key (مقدار: xapp_xxxxxxxxxxxx)
    • -
    -
    -
    -
    - - -
    -
    -
    ۶
    -
    -

    گام ۴ — اصلاح XApiKeyAuthenticationHandler

    -
    Step 4: Verify XApiKeyAuthenticationHandler
    -
    -
    -
    -
    -
    بررسی — فایل: xIds/Providers/XApiKeyAuthenticationHandler.cs
    -

    توضیح:

    -

    - Handler فعلی به‌درستی پیاده‌سازی شده است. فقط یک نکته مهم: - مطمئن شوید که ValidateApiKey در XApplicationProvider - مقدار requiredScope را به‌درستی بررسی می‌کند. -

    -
    - -

    کد فعلی Handler (صحیح است):

    -
    // xIds/Providers/XApiKeyAuthenticationHandler.cs -protected override async Task<AuthenticateResult> HandleAuthenticateAsync() -{ - // ۱. استخراج API Key از Header - var apiKeyHeader = HeaderName; // "X-Api-Key" - if (!Request.Headers.ContainsKey(apiKeyHeader)) - return AuthenticateResult.NoResult(); - - var apiKey = Request.Headers[apiKeyHeader].ToString(); - if (apiKey.IsNullOrEmpty()) - return AuthenticateResult.NoResult(); - - // ۲. استخراج Client IP - var clientIP = Request.HttpContext.Connection.RemoteIpAddress?.ToString(); - - // ۳. اعتبارسنجی API Key - var validationResult = await applicationProvider.ValidateApiKey( - apiKey: apiKey, - clientIP: clientIP - ); - - if (validationResult.Errors.HasChild()) - { - var message = validationResult.Errors.ToListString('\n'); - return AuthenticateResult.Fail(message); - } - - // ۴. ساخت Claims - var claims = new List<Claim> { - new(ClaimTypes.Name, validationResult.OwnerId), - new(JwtClaimTypes.Subject, validationResult.OwnerId), - new(XCustomClaims.ApplicationId, validationResult.ApplicationId.ToString()), - new(XCustomClaims.AuthType, "apikey"), - }; - - // ۵. اضافه کردن Scopeها - if (validationResult.Scopes != null) - { - foreach (var scope in validationResult.Scopes) - { - claims.Add(new Claim(JwtClaimTypes.Scope, scope)); - } - } - - // ۶. ساخت Principal و Ticket - var identity = new ClaimsIdentity(claims, Scheme.Name); - var principal = new ClaimsPrincipal(identity); - var ticket = new AuthenticationTicket(principal, Scheme.Name); - - return AuthenticateResult.Success(ticket); -}
    - -
    - ✅ وضعیت Handler: - کد فعلی Handler صحیح است و نیازی به تغییر ندارد. - فقط مطمئن شوید که validationResult.Scopes مقادیر صحیح - (read, write, admin, manage) - را برمی‌گرداند. -
    -
    -
    - - -
    -
    -
    ۷
    -
    -

    گام ۵ — راهنمای تست در Swagger UI

    -
    Step 5: Testing Guide in Swagger UI
    -
    -
    -
    -

    مراحل تست گام‌به‌گام:

    - -
    -
    تست ۱
    -

    ساخت Application و API Key

    -

    ابتدا یک Application بسازید و سپس یک API Key برای آن ایجاد کنید:

    -
    # ۱. ساخت Application (با Bearer Token احراز هویت کنید) -POST /Applications -Content-Type: application/json -Authorization: Bearer {access_token} -X-PoweredBy: {xPoweredValue} - -{ - "name": "TestApp", - "description": "Test Application", - "type": 0 -} - -# ۲. ساخت API Key (با Bearer Token) -POST /Applications/{applicationId}/ApiKeys/Create -Content-Type: application/json -Authorization: Bearer {access_token} -X-PoweredBy: {xPoweredValue} - -{ - "scopes": ["read", "write", "manage"], - "rateLimit": 60, - "expirationMinutes": 43200, - "allowedIPs": ["127.0.0.1", "::1"] -} - -# پاسخ شامل plainKey است — آن را ذخیره کنید! -# مثال: xapp_abc123def456...
    -
    - -
    -
    تست ۲
    -

    استفاده از API Key در Swagger UI

    -

    در Swagger UI:

    -
      -
    1. روی دکمه "Authorize" (بالا سمت راست) کلیک کنید.
    2. -
    3. در بخش "X-Api-Key"، کلید API دریافتی را وارد کنید.
    4. -
    5. روی "Authorize" و سپس "Close" کلیک کنید.
    6. -
    7. Endpoint GET /Account/Test/HiApiKeyAccess را پیدا کنید.
    8. -
    9. روی "Try it out" و سپس "Execute" کلیک کنید.
    10. -
    -
    - -
    -
    تست ۳
    -

    نتایج مورد انتظار

    - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
    سناریوپاسخ مورد انتظاروضعیت
    API Key معتبر + Scope کافی200 OK — "Hi ApiKey Access, is Passed ..."✓ صحیح
    API Key نامعتبر401 Unauthorized — "ApiKey not found"✓ صحیح
    API Key منقضی‌شده401 — "ApiKey is Expired"✓ صحیح
    Scope ناکافی403 Forbidden✓ صحیح
    IP غیرمجاز401 — "Client IP not Allowed"✓ صحیح
    Rate Limit رد شده401 — "ApiKey Rate Limit Reached"✓ صحیح
    -
    - -
    -
    تست ۴
    -

    تست با cURL (برای اطمینان بیشتر)

    -
    # تست مستقیم با cURL -curl -X GET "https://localhost:5001/Account/Test/HiApiKeyAccess" \ - -H "X-Api-Key: xapp_your_api_key_here" \ - -H "X-PoweredBy: your_powered_value" \ - -k - -# پاسخ مورد انتظار: -# "Hi ApiKey Access, is Passed ..."
    -
    -
    -
    - - -
    -
    -
    ۸
    -
    -

    چک‌لیست نهایی اصلاحات

    -
    Final Checklist
    -
    -
    -
    - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
    ردیففایلتغییراولویت
    ۱xIds/DI/XDIHelperExtension.csبازنویسی AddXIdentityServerAuthentication با PolicyScheme🔴 حیاتی
    ۲xIds/DI/XDIHelperExtension.csاصلاح AddXAuthorization — افزودن XApiKey به LocalApi Policy🔴 حیاتی
    ۳xIds/Startup.csبررسی addXApiKeyAuthorization: true در AddXSwagger🟡 بررسی
    ۴xIds/Providers/XApiKeyAuthenticationHandler.csتأیید صحت کد (نیاز به تغییر ندارد)🟢 تأیید
    ۵xIdentityHelper/XAuthorizationHelper.csتأیید Policyهای ApiKey (نیاز به تغییر ندارد)🟢 تأیید
    -
    -
    - - -
    -
    -
    ۹
    -
    -

    جمع‌بندی و نکات پایانی

    -
    Conclusion
    -
    -
    -
    -

    - ریشه اصلی مشکل تست XApiKey در Swagger، نحوه ثبت Authentication Schemes - و عدم استفاده از PolicyScheme هوشمند بود. با اعمال اصلاحات گام ۱ و ۲، - سیستم احراز هویت به‌صورت خودکار بر اساس Header درخواست، Scheme مناسب را انتخاب می‌کند - و Swagger UI می‌تواند به‌درستی با API Key احراز هویت نماید. -

    - -
    - 🎯 نتیجه نهایی: -
      -
    • درخواست‌های دارای Header X-Api-Key → به XApiKeyAuthenticationHandler هدایت می‌شوند.
    • -
    • درخواست‌های دارای Header Authorization: Bearer → به LocalApi (IdentityServer) هدایت می‌شوند.
    • -
    • Swagger UI هر دو روش احراز هویت را پشتیبانی می‌کند.
    • -
    • Policyهای ApiKeyAccess, ApiKeyReadAccess و غیره به‌درستی کار می‌کنند.
    • -
    -
    - -
    - ⚠️ نکته مهم: - پس از اعمال تغییرات، حتماً پروژه را Clean و Rebuild کنید - و سپس Swagger UI را با Ctrl+F5 رفرش نمایید تا تغییرات Security Definition - به‌درستی اعمال شوند. -
    -
    -
    - -
    - -
    - - -
    تاریخ انتشار: ۲۰ مهر ۱۴۰۵ | نسخه: ۲.۰ | طبقه‌بندی: داخلی — فنی
    -
    -
    - - - -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\xAiApi\wwwroot\Storage\Uploads\Document\xSaherElm_560a6d9a-eefe-4125-9b3d-6ce0264876cb.html - - - - - - -معرفی ساختار محصول هوش مصنوعی سازمانی | رایان پرداز کاوش - - - - -
    - -
    -
    -
    - -
    -
    -
    شماره مستند: PROD-1405-001
    -
    نسخه: ۱.۰
    -
    تاریخ تهیه: مهر ۱۴۰۵
    -
    طبقه‌بندی: محرمانه
    -
    -
    - -
    - PRODUCT ARCHITECTURE OVERVIEW -

    معرفی ساختار محصول هوش مصنوعی سازمانی

    -

    محصول در دست توسعه — رایان پرداز کاوش

    -
    -
    - -
    - -
    - کارفرمای محترم،
    - این مستند به معرفی ساختار محصولی می‌پردازد که در شرکت رایان پرداز کاوش در دست توسعه است. تمرکز این مستند، معرفی قابلیت‌های محصول بر اساس معماری آن است. هدف، ارائه تصویری شفاف از ساختار محصول و قابلیت‌هایی است که می‌تواند به نیازهای سازمان‌های صنعتی و دانش‌بنیان پاسخ دهد. بدیهی است که شناخت دقیق نیازمندی‌های اختصاصی هر سازمان، مستلزم گفتگو و دریافت بازخورد از تیم فنی آن سازمان است و این مستند صرفاً نقطه شروع این گفتگو محسوب می‌شود. -
    - -
    -
    -
    ۱
    -
    -

    خلاصه اجرایی

    -
    Executive Summary
    -
    -
    -
    -

    شرکت رایان پرداز کاوش در حال توسعه یک سامانه هوش مصنوعی سازمانی ایجنت‌محور است که معماری آن بر پایه شش لایه اصلی و دو محور عرضی طراحی شده است. این محصول با تمرکز بر چهار محور کلیدی در حال توسعه است: ایجنت قابل‌آزمون، توسعه‌پذیری از طریق MCP، حاکمیت داده با مدل‌های لوکال، و کنترل دسترسی لایه‌ای تا سطح ابزار ایجنت.

    - -

    این مستند قصد دارد ساختار محصول و قابلیت‌های پیش‌بینی‌شده در معماری آن را به‌صورت شفاف معرفی کند. سازمان‌هایی که با داده‌های حساس، اسناد سازمانی و فرایندهای پیچیده سروکار دارند، می‌توانند از این ساختار برای پاسخ به نیازهای خود بهره ببرند. شناخت دقیق نیازمندی‌های هر سازمان و تطبیق محصول با آن، گام بعدی این همکاری خواهد بود.

    - -
    -
    -
    معماری
    شش‌لایه
    -
    پایه طراحی محصول
    -
    -
    -
    MCP
    محور
    -
    توسعه‌پذیری نامحدود
    -
    -
    -
    مدل
    لوکال
    -
    حاکمیت داده و محرمانگی
    -
    -
    - -
    - نکته کلیدی: این مستند، معرفی ساختار محصول در دست توسعه است. قابلیت‌های مطرح‌شده بر اساس معماری محصول تعریف شده‌اند و می‌توانند مبنای گفتگوی فنی با تیم ارزیابی کارفرما قرار گیرند. -
    -
    -
    - -
    -
    -
    ۲
    -
    -

    معماری محصول در دست توسعه

    -
    Product Architecture Under Development
    -
    -
    -
    -

    محصول در دست توسعه رایان پرداز کاوش، بر پایه یک معماری لایه‌ای طراحی شده است که جداسازی دغدغه‌ها و اعمال سیستماتیک حاکمیت و مشاهده‌پذیری را در تمام لایه‌ها تضمین می‌کند. این معماری، مبنای توسعه قابلیت‌های محصول قرار گرفته است.

    - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
    لایه معماریقابلیت‌های پیش‌بینی‌شده در محصولوضعیت توسعه
    لایه تعاملرابط وب سازمانی، نسخه دسکتاپ، درگاه APIدر دست توسعه
    لایه کنترل دسترسیاحراز هویت، مدیریت نشست، موتور مجوزها، مدیریت نقش‌هادر دست توسعه
    لایه ارکستراسیون (هسته ایجنت)موتور ایجنت، برنامه‌ریز، انتخاب‌گر ابزار، مدیریت جریان، نقاط تأیید انسانیدر دست توسعه
    لایه هوش و مدل‌هادرگاه مدل‌ها، مدیریت مدل، بازیابی و تقویت (RAG)، حافظه و زمینهدر دست توسعه
    لایه داده و منابعمنابع دانش، مدیریت فایل، سرویس‌های خارجی، ابزارهای عملیاتیدر دست توسعه
    لایه خروجی و گزارشتولید گزارش، مبدل قالب (Word/Excel)، داشبورد مصرفدر دست توسعه
    محور عرضی حاکمیت دادهسیاست‌گذار داده، ممیزی و لاگ، سنسور محرمانگیدر دست توسعه
    محور عرضی مشاهده‌پذیریمتریک و ردیابی مصرف، زمان پاسخ، نرخ خطادر دست توسعه
    - -
    - 💡 نکته: معماری فوق، مبنای توسعه محصول قرار گرفته است. قابلیت‌های هر لایه در حال پیاده‌سازی و تکمیل هستند و در جلسه فنی، جزئیات بیشتر و زمان‌بندی توسعه هر بخش قابل ارائه خواهد بود. این ساختار به‌گونه‌ای طراحی شده که امکان تطبیق با نیازمندی‌های سازمان‌های مختلف را فراهم کند. -
    -
    -
    - -
    -
    -
    ۳
    -
    -

    ساختار محصول: سامانه ایجنت‌محور سازمانی

    -
    Product Structure: Enterprise Agentic System
    -
    -
    -
    -

    هسته محصول در دست توسعه، یک موتور ایجنت است که بر اساس معماری تعریف‌شده، هدف کاربر را به مراحل اجرایی تبدیل می‌کند، برای هر مرحله ابزار یا منبع مناسب را از میان فهرست مجاز انتخاب می‌کند، عملیات را اجرا می‌کند، نتیجه را ارزیابی کرده و در صورت نیاز مسیر را اصلاح می‌کند. این ساختار، محصول را از یک سیستم پرسش‌وپاسخ ساده متمایز می‌سازد و امکان پاسخ به نیازهای پیچیده سازمانی را فراهم می‌آورد.

    - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
    لایه معماریقابلیت پیش‌بینی‌شده در ساختار محصول
    لایه تعاملرابط وب سازمانی، نسخه دسکتاپ، درگاه API
    لایه کنترل دسترسیاحراز هویت، مدیریت نشست، موتور مجوزها، مدیریت نقش‌ها
    لایه ارکستراسیون (هسته ایجنت)موتور ایجنت، برنامه‌ریز، انتخاب‌گر ابزار، مدیریت جریان، نقاط تأیید انسانی
    لایه هوش و مدل‌هادرگاه مدل‌ها، مدیریت مدل، بازیابی و تقویت (RAG)، حافظه و زمینه
    لایه داده و منابعمنابع دانش، مدیریت فایل، سرویس‌های خارجی، ابزارهای عملیاتی
    لایه خروجی و گزارشتولید گزارش، مبدل قالب (Word/Excel)، داشبورد مصرف
    محور عرضی حاکمیت دادهسیاست‌گذار داده، ممیزی و لاگ، سنسور محرمانگی
    محور عرضی مشاهده‌پذیریمتریک و ردیابی مصرف، زمان پاسخ، نرخ خطا
    - -
    - 💡 نکته: قابلیت‌های فوق بر اساس معماری محصول تعریف شده‌اند و مبنای توسعه آن قرار گرفته‌اند. این ساختار می‌تواند در جلسه فنی با تیم ارزیابی کارفرما بررسی و با نیازمندی‌های سازمان تطبیق داده شود. -
    -
    -
    - -
    -
    -
    ۴
    -
    -

    توسعه‌پذیری از طریق MCP

    -
    Extensibility via MCP
    -
    -
    -
    -

    MCP (Model Context Protocol) در ساختار محصول ما به‌عنوان لایه استاندارد اتصال ایجنت به ابزارها و منابع در نظر گرفته شده است. بر اساس این معماری، هر قابلیت جدید می‌تواند در قالب یک MCP Server تعریف شود و به سامانه اضافه گردد.

    - -
    - تأکید معماری: از منظر ساختار محصول، محدودیت معماری برای افزودن قابلیت از طریق MCP وجود ندارد. هر MCP Server جدید در Tool Registry ثبت می‌شود و در صورت وجود مجوز، در اختیار ایجنت قرار می‌گیرد. این رویکرد، محصول را قادر می‌سازد تا با نیازهای متنوع سازمانی هم‌راستا شود. -
    - -

    نمونه قابلیت‌های قابل افزودن با MCP:

    - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
    حوزه سازمانینمونه MCP Serverکاربرد بالقوه
    منابع انسانیHR MCPمرخصی، آموزش، اطلاعات پرسنلی
    مالی و بودجهFinance MCPبودجه، هزینه، فاکتور، مراکز هزینه
    تولید و انبارProduction MCPموجودی، سفارش، فرمولاسیون
    مدیریت اسنادDMS MCPجستجو و بازیابی اسناد سازمانی
    پایگاه دادهDB MCPپرسش کنترل‌شده از داده‌ها
    فایل و پوشهFile MCPدسترسی کنترل‌شده به فایل‌های محلی/شبکه
    همکاری سازمانیCollaboration MCPایمیل، تقویم، اعلان
    سامانه‌های سازمانیERP/CRM MCPیکپارچه‌سازی فرایندهای سازمانی
    - -
    - ✓ نتیجه: ساختار محصول از طریق MCP، امکان توسعه قابلیت‌ها را فراهم می‌کند. هر ابزار جدید، سرویس جدید یا منبع داده جدید، با تعریف یک MCP Server و ثبت در Tool Registry، به قابلیت‌های ایجنت اضافه می‌شود. این رویکرد می‌تواند پاسخگوی نیازهای متنوع سازمانی باشد. -
    -
    -
    - -
    -
    -
    ۵
    -
    -

    حاکمیت داده و رویکرد مدل‌های لوکال

    -
    Data Governance & Local Model Approach
    -
    -
    -
    -

    در ساختار محصول، حاکمیت داده به‌عنوان یک محور عرضی در تمام لایه‌ها در نظر گرفته شده است. برای سازمان‌هایی که با داده‌های حساس مانند فرمولاسیون، اطلاعات مشتریان، فرایندهای تولید و اسناد سازمانی سروکار دارند، استفاده از مدل‌های آنلاین می‌تواند با حاکمیت داده و محرمانگی در تناقض باشد؛ زیرا داده از مرز سازمان خارج می‌شود و کنترل کامل بر ذخیره‌سازی، پردازش و استفاده ثانویه از آن وجود ندارد.

    - -
    - ⚠️ ریسک مدل‌های آنلاین برای داده‌های حساس: -
      -
    • خروج داده‌های حساس از مرز سازمان
    • -
    • عدم کنترل بر ذخیره‌سازی داده در سرورهای خارجی
    • -
    • احتمال استفاده از داده برای آموزش مدل‌های بعدی
    • -
    • وابستگی به اینترنت بین‌الملل و ریسک قطع سرویس
    • -
    • عدم انطباق با سیاست‌های محرمانگی سازمانی
    • -
    -
    - -

    رویکرد پیش‌بینی‌شده در ساختار محصول:

    - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
    تصمیمرویکرد در ساختار محصول
    مدل پیش‌فرضمدل لوکال از طریق Model Gateway و Ollama/On-Prem
    داده حساسعدم خروج از مرز سازمان
    مدل آنلاینفقط برای داده غیرحساس، با تأیید سیاست و به‌صورت استثنا
    آموزش مدلعدم استفاده از داده سازمان برای آموزش مدل‌های خارجی
    استقرارOn-Premise با امکان عملکرد در قطع اینترنت بین‌الملل
    ممیزیثبت کامل مسیر داده و تصمیمات ایجنت
    - -
    - ✓ نتیجه: در ساختار محصول، حاکمیت داده به‌عنوان یک سیاست اجرایی در نظر گرفته شده است. مدل لوکال، پیش‌فرض است و داده حساس سازمان، از مرز آن خارج نمی‌شود. این رویکرد می‌تواند برای سازمان‌هایی با الزامات محرمانگی بالا مناسب باشد. -
    -
    -
    - -
    -
    -
    ۶
    -
    -

    کنترل دسترسی ایجنت و محدودسازی ابزارهای تصمیم‌گیرنده

    -
    Agent Access Control & Tool Restriction
    -
    -
    -
    -

    در ساختار محصول، کنترل دسترسی تنها به رابط کاربری محدود نمی‌شود. موتور مجوزها پیش از فراخوانی ایجنت، فهرست مجاز کاربر را تعیین می‌کند و این فهرست به ایجنت تصمیم‌گیرنده ابلاغ می‌شود:

    - -
    - - -
    - -

    این یعنی ایجنت تصمیم‌گیرنده نمی‌تواند ابزاری خارج از مجوز کاربر را فراخوانی کند، حتی اگر آن ابزار در Tool Registry ثبت شده باشد. این محدودسازی در سطح معماری اعمال می‌شود و توسط موتور مجوزها به ایجنت ابلاغ می‌گردد.

    - -
    - نکته حساس: ساختار محصول از ترکیب RBAC (نقش‌محور) و ABAC (ویژگی‌محور) پشتیبانی می‌کند تا کنترل دسترسی را تا سطح رکورد، سند، واحد سازمانی و حتی فیلد اطلاعاتی ممکن سازد. این رویکرد می‌تواند برای سازمان‌هایی با ساختار دسترسی پیچیده مناسب باشد. -
    -
    -
    - -
    -
    -
    ۷
    -
    -

    دفاع لایه‌ای برای حفظ محرمانگی

    -
    Layered Defense for Confidentiality
    -
    -
    -
    -

    در ساختار محصول، برای جلوگیری از افشای اطلاعات، دفاع لایه‌ای در نظر گرفته شده است. این دفاع شامل شش نقطه مستقل است که هر یک از منظری متفاوت، محرمانگی را تضمین می‌کند:

    - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
    لایهکنترلهدف
    لایه ۱احراز هویت و نشستتأیید هویت و سطح دسترسی فعال
    لایه ۲موتور مجوزهامحدودسازی مدل، ابزار و منبع پیش از اجرا
    لایه ۳فهرست مجاز ابزار ایجنتجلوگیری از انتخاب ابزار غیرمجاز
    لایه ۴فیلتر بازیابی RAGبازیابی فقط از منابع مجاز کاربر
    لایه ۵سنسور محرمانگی خروجیجلوگیری از افشای اطلاعات در پاسخ نهایی
    لایه ۶ممیزی و لاگثبت و ردیابی تمام تصمیمات و دسترسی‌ها
    - -
    - ⚠️ نکته حیاتی: لایه‌های ۲ (موتور مجوزها) و ۵ (سنسور محرمانگی) مستقل از هم هستند. حتی اگر ایجنت یا مدل بخواهد اطلاعات خارج از دسترس را افشا کند، در دو نقطه مستقل مسدود می‌شود. این رویکرد دفاع لایه‌ای، در ساختار محصول پیش‌بینی شده است تا محرمانگی اطلاعات در سطوح دسترسی مختلف تضمین شود. -
    - -
    - ✓ رویکرد ساختاری: دفاع لایه‌ای در محصول به‌گونه‌ای طراحی شده که پرسش‌های یکسان با حساب‌های دارای مجوزهای متفاوت، پاسخ‌های متفاوت و متناسب با سطح دسترسی هر کاربر دریافت کنند. همچنین تلاش برای دور زدن مجوزها از طریق پرسش مستقیم، غیرمستقیم یا خلاصه‌سازی، در دو نقطه مستقل مسدود می‌شود. -
    -
    -
    - -
    -
    -
    ۸
    -
    -

    مثال جریان کار: یک درخواست، دو ایجنت

    -
    Workflow Example: One Request, Two Agents
    -
    -
    -
    -

    برای روشن‌تر شدن ساختار کنترل دسترسی در محصول، یک سناریوی نمونه را بررسی می‌کنیم. کارمندی درخواست می‌دهد:

    - -
    -

    «می‌خواهم در دوره تخصصی پلیمر در آبان شرکت کنم؛ هزینه آن از بودجه واحد پرداخت شود و مرخصی آموزشی هم ثبت شود.»

    -
    — درخواست نمونه واحد کارمند
    -
    - -

    این یک درخواست واحد است، اما برای پاسخ به آن به دو حوزه نیاز است: منابع انسانی و مالی. ساختار محصول، این درخواست را به‌صورت زیر پردازش می‌کند:

    - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
    مرحلهمسئولاقدامکنترل دسترسی
    ۱ایجنت مسیریابتشخیص نیاز به HR و Financeفقط ابزارهای مجاز کاربر
    ۲ایجنت منابع انسانیبررسی مرخصی و شرایط آموزشفقط رکورد HR خود کارمند و سیاست آموزش
    ۳ایجنت مالیبررسی بودجه و هزینه دورهفقط بودجه مرکز هزینه واحد کاربر
    ۴ترکیب نتایجتولید پاسخ نهاییسنسور محرمانگی خروجی
    ۵تأیید انسانیاگر هزینه از سقف بیشتر باشدتوقف و دریافت تأیید
    - -

    نحوه اعمال کنترل دسترسی در این سناریو:

    - -
      -
    • - ایجنت منابع انسانی - به ابزارهای مرخصی و آموزش دسترسی دارد، اما به حقوق، ارزیابی عملکرد یا پرونده سایر کارکنان دسترسی ندارد. -
    • -
    • - ایجنت مالی - به بودجه مرکز هزینه واحد کاربر دسترسی دارد، اما به فیش حقوقی یا اطلاعات مالی سایر واحدها دسترسی ندارد. -
    • -
    • - در صورت عدم مجوز مالی - اگر کاربر مجوز مالی نداشته باشد، ایجنت مالی پاسخ «عدم دسترسی» یا خروجی تجمیعی غیرمحرمانه ارائه می‌دهد. -
    • -
    • - اتصال از طریق MCP - هر دو ایجنت از طریق MCP به ابزارهای مجاز متصل می‌شوند و فهرست ابزار مجاز توسط موتور مجوزها تعیین می‌شود. -
    • -
    • - ممیزی کامل - تمام مراحل در سیستم ممیزی ثبت می‌شود و قابل ردیابی است. -
    • -
    - -
    - 💡 نتیجه مثال: ساختار محصول به‌گونه‌ای طراحی شده که یک درخواست واحد را میان چند ایجنت توزیع کند، بدون اینکه مرزهای محرمانگی نقض شود. هر ایجنت فقط به ابزارها و منابعی دسترسی دارد که کاربر مجاز است، و این محدودسازی در سطح معماری محصول اعمال می‌شود. -
    -
    -
    - -
    -
    -
    ۹
    -
    -

    قابلیت‌های محصول در پاسخ به نیازهای رایج سازمانی

    -
    Product Capabilities vs. Common Organizational Needs
    -
    -
    -
    -

    ساختار محصول در دست توسعه، قابلیت‌هایی را پیش‌بینی کرده است که می‌تواند به نیازهای رایج سازمان‌های صنعتی و دانش‌بنیان پاسخ دهد. جدول زیر، این قابلیت‌ها را در کنار نیازهای رایج سازمانی نشان می‌دهد. بدیهی است که تطبیق دقیق با نیازمندی‌های اختصاصی هر سازمان، مستلزم گفتگوی فنی با تیم ارزیابی آن سازمان است.

    - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
    نیاز رایج سازمانیقابلیت پیش‌بینی‌شده در ساختار محصول
    دستیار هوشمند و ایجنت تصمیم‌گیرندهموتور ایجنت با برنامه‌ریزی، انتخاب ابزار، اجرا، اصلاح و Human-in-the-loop
    مدیریت دسترسی کاربران و واحدهای سازمانیRBAC/ABAC، کنترل تا سطح رکورد، فهرست مجاز ابزار، دفاع لایه‌ای
    شفافیت مصرف و هزینهداشبورد مصرف، گزارش هزینه به تفکیک کاربر/مدل/ایجنت، درگاه API
    تعامل کاربری و تولید گزارشرابط وب/دسکتاپ، تحلیل فایل، خروجی Word/Excel، ارجاع به منبع
    حاکمیت داده و محرمانگی اطلاعاتمدل لوکال، On-Premise، عدم خروج داده حساس، MCP کنترل‌شده
    پیاده‌سازی، آموزش و پشتیبانینقشه راه فازبندی‌شده، مستندسازی، آموزش و پشتیبانی
    عملکرد پایدار و تاب‌آوریعملکرد در قطع اینترنت با مدل لوکال، SLA قابل تعریف، آمادگی پایلوت
    - -
    - ✓ نتیجه: ساختار محصول به‌گونه‌ای طراحی شده که بتواند به نیازهای رایج سازمان‌های صنعتی و دانش‌بنیان پاسخ دهد. برای بررسی تطابق دقیق با نیازمندی‌های اختصاصی کارفرما، آماده دریافت و بررسی نیازمندی‌های تیم فنی هستیم. -
    -
    -
    - -
    -
    -
    ۱۰
    -
    -

    وضعیت توسعه محصول و گام بعدی

    -
    Development Status & Next Step
    -
    -
    -
    -

    وضعیت فعلی: محصول در شرکت رایان پرداز کاوش بر پایه معماری شش‌لایه + دو محور عرضی، در دست توسعه است. فازهای توسعه محصول به‌صورت زیر سازمان‌دهی شده‌اند:

    - -
    -
    -
    -
    فاز A: هسته ایجنت و رابط پایه
    -

    درگاه مدل، موتور ایجنت، رابط کاربری، احراز هویت — در دست توسعه

    -
    -
    -
    -
    -
    -
    فاز B: ابزارها، RAG و منابع دانش
    -

    Tool Registry، MCP Client، RAG با ارجاع، مدیریت فایل — در دست توسعه

    -
    -
    -
    -
    -
    -
    فاز C: حاکمیت داده و کنترل دسترسی
    -

    موتور مجوزها، سنسور محرمانگی، ممیزی، سیاست‌گذار داده — در دست توسعه

    -
    -
    -
    -
    -
    -
    فاز D: گزارش، تأیید انسانی و مشاهده‌پذیری
    -

    تولید گزارش، مبدل قالب، Human-in-the-loop، داشبورد مصرف — در دست توسعه

    -
    -
    -
    -
    -
    -
    فاز E: Cross-Platform و آماده‌سازی محصول
    -

    نسخه دسکتاپ، موبایل، مدیریت مدل، استقرار On-Premise — در برنامه توسعه

    -
    -
    -
    -
    - -

    گام بعدی پیشنهادی:

    - -
      -
    • - برگزاری جلسه معرفی و گفتگوی فنی - معرفی ساختار محصول و دریافت بازخورد از تیم فنی کارفرما -
    • -
    • - دریافت نیازمندی‌های اختصاصی سازمان - شناخت دقیق نیازهای کارفرما برای تطبیق محصول -
    • -
    • - ارائه سناریوی نمونه Agent - نمایش ساختار ایجنت بر اساس معماری محصول -
    • -
    • - بررسی امکان اجرای پایلوت محدود - شامل زمان، هزینه، پیش‌نیازها و معیارهای موفقیت -
    • -
    • - ارائه پیشنهاد تجاری شفاف - بر اساس دامنه همکاری و نیازمندی‌های سازمانی -
    • -
    - -
    - 📞 گام بعدی: در صورت تمایل به ادامه گفتگو، آماده برگزاری جلسه فنی برای معرفی ساختار محصول، دریافت نیازمندی‌های اختصاصی کارفرما و بررسی امکان تطبیق محصول با آن نیازها هستم. این جلسه، نقطه شروع همکاری و شناخت متقابل خواهد بود. -
    -
    -
    - -
    -
    -
    ۱۱
    -
    -

    جمع‌بندی و پیشنهاد نهایی

    -
    Final Summary & Recommendation
    -
    -
    -
    -

    این مستند، ساختار محصول هوش مصنوعی سازمانی در دست توسعه رایان پرداز کاوش را معرفی کرد. ویژگی‌های متمایز این ساختار:

    - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
    ویژگیرویکرد ساختار محصول
    معماری پایهشش لایه + دو محور عرضی
    توسعه‌پذیری MCPبدون محدودیت معماری
    حاکمیت دادهمدل لوکال (حاکمیت کامل)
    کنترل دسترسی ایجنتتا سطح ابزار و رکورد
    دفاع محرمانگیشش لایه مستقل
    وضعیت توسعهدر دست توسعه
    - -
    -

    🎯 پیشنهاد نهایی

    -

    ساختار محصول در دست توسعه رایان پرداز کاوش، بر پایه معماری شش‌لایه + دو محور عرضی طراحی شده و قابلیت‌هایی را پیش‌بینی کرده است که می‌تواند به نیازهای رایج سازمان‌های صنعتی و دانش‌بنیان پاسخ دهد.

    -

    توسعه‌پذیری از طریق MCP، حاکمیت داده با مدل‌های لوکال، کنترل دسترسی تا سطح ابزار ایجنت، و دفاع لایه‌ای برای محرمانگی، چهار ستون اصلی این ساختار هستند.

    -
    - 💎 ارزش پیشنهادی ساختار محصول:
    - معماری ایجنت‌محور + توسعه‌پذیری MCP + حاکمیت داده با مدل لوکال + کنترل دسترسی تا سطح ابزار + دفاع لایه‌ای -
    -
    - -
    - 📞 گام بعدی: در صورت تمایل به ادامه گفتگو، آماده برگزاری جلسه فنی برای معرفی ساختار محصول، دریافت نیازمندی‌های اختصاصی کارفرما و بررسی امکان تطبیق محصول با آن نیازها هستم. این جلسه، نقطه شروع همکاری و شناخت متقابل خواهد بود. -
    -
    -
    - -
    - این مستند محرمانه بوده و صرفاً جهت ارائه به کارفرمای محترم تهیه شده است. هرگونه کپی‌برداری یا افشا بدون اجازه کتبی ممنوع است. -
    - -
    - -
    - - -
    تاریخ تهیه: مهر ۱۴۰۵  |  نسخه: ۱.۰  |  طبقه‌بندی: محرمانه
    -
    - -
    - - - - -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\xAiApi\wwwroot\Storage\Uploads\Document\xSaherElm_6aa5608b-7bb0-4fab-8eaa-c6345e801b03.html - - - - - - -راهنمای گام‌به‌گام ساخت MCP Server در C# .NET Standard 2.0 - - - - -
    - -
    -
    -
    -
    -
    شماره مستند: GUIDE-MCP-1405-001
    -
    نسخه: ۱.۰
    -
    تاریخ تهیه: آبان ۱۴۰۵
    -
    طبقه‌بندی: آموزشی-فنی
    -
    -
    -
    - STEP-BY-STEP TUTORIAL -

    راهنمای گام‌به‌گام ساخت MCP Server در C#

    -

    پیاده‌سازی کامل با .NET Standard 2.0 و کتابخانه رسمی ModelContextProtocol

    -
    -
    - -
    - -
    - هدف مستند:
    - این مستند، یک راهنمای عملی و گام‌به‌گام برای ساخت یک MCP Server (Model Context Protocol Server) با استفاده از زبان C# و کتابخانه رسمی ModelContextProtocol است. تمام مراحل با کدهای کامل و قابل اجرا ارائه شده و پروژه نهایی روی .NET Standard 2.0 کامپایل می‌شود تا با طیف گسترده‌ای از فریم‌ورک‌ها (از جمله .NET Framework قدیمی‌تر) سازگار باشد. در پایان، سرور ما با کلاینت‌هایی مانند Claude Desktop یا GitHub Copilot قابل استفاده خواهد بود. -
    - - - - -
    -
    -
    ۰
    -
    -

    MCP چیست و چرا اهمیت دارد؟

    -
    What is MCP? / Why it matters
    -
    -
    -
    -

    Model Context Protocol (MCP) یک پروتکل باز و استاندارد است که توسط شرکت Anthropic معرفی شده و هدف آن، ایجاد یک زبان مشترک بین مدل‌های زبانی (LLM) و منابع خارجی (مانند دیتابیس، API، فایل‌سیستم، ابزارهای داخلی سازمان) است. به کمک MCP، مدل‌های زبانی می‌توانند به‌طور استاندارد و امن، به داده‌ها و قابلیت‌های خارجی دسترسی داشته باشند بدون آنکه نیاز به کدنویسی اختصاصی برای هر مدل باشد.

    - -
    -
    -
    استاندارد
    باز
    -
    پشتیبانی توسط Anthropic، Microsoft، و جامعه
    -
    -
    -
    سه
    قابلیت
    -
    Tools، Resources، Prompts
    -
    -
    -
    قابل
    حمل
    -
    یک سرور، چند کلاینت
    -
    -
    - -

    سه قابلیت اصلی MCP:

    - - - - - - - - - - - - - - - - - - - - - - - - - -
    قابلیتتوضیحمثال
    Toolsتوابع قابل فراخوانی توسط مدل (مانند Function Calling)جستجو در دیتابیس، ارسال ایمیل، محاسبه
    Resourcesداده‌های فقط‌خواندنی که مدل می‌تواند بخواندفایل، رکورد دیتابیس، تنظیمات
    Promptsقالب‌های آماده برای پرامپت‌هاالگوهای پاسخ، شخصیت‌ها، سناریوها
    - -
    - 💡 نکته: در این مستند، تمرکز ما بر روی Tools خواهد بود، چراکه پرکاربردترین قابلیت MCP است و اجازه می‌دهد منطق تجاری موجود در پروژه‌های C# خود را به‌راحتی در اختیار مدل‌های زبانی قرار دهید. -
    -
    -
    - - - - -
    -
    -
    ۱
    -
    -

    پیش‌نیازها و آماده‌سازی محیط

    -
    Prerequisites
    -
    -
    -
    -

    پیش از شروع، مطمئن شوید که موارد زیر روی سیستم شما نصب و آماده هستند:

    - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
    پیش‌نیازحداقل نسخهتوضیح
    .NET SDK8.0 یا بالاتربرای اجرا و Build پروژه (خود کتابخانه روی netstandard2.0 کار می‌کند)
    IDE یا Editor—Visual Studio 2022، VS Code، یا Rider
    NuGet—به‌طور خودکار همراه .NET SDK نصب می‌شود
    کلاینت MCP (اختیاری)—Claude Desktop، GitHub Copilot، یا هر MCP Client دیگر برای تست
    - -

    بررسی نصب .NET SDK:

    -

    در ترمینال یا Command Prompt دستور زیر را اجرا کنید:

    - -
    dotnet --version
    - -

    اگر نسخه ۸.۰ یا بالاتر نمایش داده شد، همه چیز آماده است. در غیر این صورت، از سایت رسمی dotnet.microsoft.com/download آخرین نسخه را دانلود و نصب کنید.

    - -
    - ⚠️ توجه به .NET Standard 2.0: اگرچه خود پروژه شما بر روی netstandard2.0 کامپایل می‌شود، اما برای اجرای آن و ساخت DLL نیاز به یک SDK مدرن دارید. این SDK هنگام اجرا، پروژه شما را به یک باینری سازگار تبدیل می‌کند. کتابخانه ModelContextProtocol به‌طور رسمی از netstandard2.0 پشتیبانی می‌کند. -
    -
    -
    - - - - -
    -
    -
    ۲
    -
    -

    ایجاد پروژه جدید

    -
    Create a New Project
    -
    -
    -
    -

    در ترمینال، به مسیری که می‌خواهید پروژه در آن ساخته شود بروید و دستور زیر را اجرا کنید:

    - -
    dotnet new console -n SampleMcpServer
    -cd SampleMcpServer
    - -

    این دستور یک پروژه کنسول ساده با نام SampleMcpServer ایجاد می‌کند و شما را به پوشه آن منتقل می‌کند.

    - -
    -SampleMcpServer/ -├── Program.cs -├── SampleMcpServer.csproj -└── obj/ -
    - -
    - 💡 چرا Console؟ سرورهای MCP اغلب به‌صورت پروسه‌های Console اجرا می‌شوند و از طریق stdin/stdout با کلاینت (مثلاً Claude Desktop) ارتباط برقرار می‌کنند. این نوع Transport که stdio نامیده می‌شود، ساده‌ترین و پرکاربردترین روش برای اتصال کلاینت و سرور در محیط دسکتاپ است. -
    -
    -
    - - - - -
    -
    -
    ۳
    -
    -

    افزودن پکیج‌های NuGet

    -
    Add NuGet Packages
    -
    -
    -
    -

    دو پکیج اصلی نیاز دارید:

    - -
    dotnet add package ModelContextProtocol
    -dotnet add package Microsoft.Extensions.Hosting
    - -

    توضیح پکیج‌ها:

    - - - - - - - - - - - - - - - - - -
    پکیجنقش
    ModelContextProtocolهسته اصلی SDK — شامل سرور، کلاینت، Transportها (stdio/http)، و Attributeهای `[McpServerTool]`
    Microsoft.Extensions.Hostingزیرساخت Host و Dependency Injection — برای راه‌اندازی سرویس‌ها با الگوی مدرن .NET
    - -
    - 💡 تأیید نسخه: کتابخانه ModelContextProtocol به‌طور فعال توسط Microsoft و Anthropic توسعه داده می‌شود و نسخه آن مرتباً به‌روزرسانی می‌شود. برای دریافت آخرین نسخه از nuget.org استفاده کنید. -
    -
    -
    - - - - -
    -
    -
    ۴
    -
    -

    پیکربندی فایل پروژه (.csproj)

    -
    Configure Project File
    -
    -
    -
    -

    فایل SampleMcpServer.csproj را باز کنید و مطمئن شوید که TargetFramework روی netstandard2.0 تنظیم شده و پکیج‌ها به‌درستی اضافه شده‌اند:

    - -
    SampleMcpServer.csproj
    -
    <Project Sdk="Microsoft.NET.Sdk">
    -
    -  <PropertyGroup>
    -    <OutputType>Exe</OutputType>
    -    <TargetFramework>netstandard2.0</TargetFramework>
    -    <Nullable>enable</Nullable>
    -    <LangVersion>latest</LangVersion>
    -  </PropertyGroup>
    -
    -  <ItemGroup>
    -    <PackageReference Include="ModelContextProtocol" Version="*" />
    -    <PackageReference Include="Microsoft.Extensions.Hosting" Version="*" />
    -  </ItemGroup>
    -
    -</Project>
    - -

    توضیح فیلدها:

    - - - - - - - - - - - - - - - - - - - - - - - - - -
    فیلدتوضیح
    OutputTypeExe — پروژه یک برنامه اجرایی (console app) خواهد بود
    TargetFrameworknetstandard2.0 — سازگاری با .NET Framework 4.6.1+ و .NET Core 2.0+
    Nullableenable — فعال‌سازی بررسی nullability (امنیت بیشتر)
    LangVersionlatest — استفاده از آخرین امکانات زبان C#
    - -
    - ⚠️ نکته مهم: اگر از Version="*" استفاده می‌کنید، NuGet آخرین نسخه پایدار را نصب می‌کند. در محیط عملیاتی توصیه می‌شود نسخه دقیق (مانند "0.4.0-preview") را مشخص کنید تا از تغییرات ناخواسته جلوگیری شود. -
    -
    -
    - - - - -
    -
    -
    ۵
    -
    -

    تعریف اولین Tool (ابزار MCP)

    -
    Define Your First MCP Tool
    -
    -
    -
    -

    در ریشه پروژه، فایل جدیدی به نام EchoTool.cs بسازید. در این فایل، یک کلاس ساده با متد Echo تعریف می‌کنیم که هر پیامی را به مدل بازمی‌گرداند:

    - -
    EchoTool.cs
    -
    using System.ComponentModel;
    -using ModelContextProtocol.Server;
    -
    -[McpServerToolType]
    -public static class EchoTool
    -{
    -    [McpServerTool, Description("Echoes the message back to the client.")]
    -    public static string Echo(string message) => $"hello {message}";
    -}
    - -

    توضیح Attributeها و اجزا:

    - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
    جزءنقش
    [McpServerToolType]به SDK اعلام می‌کند که این کلاس شامل Tool است و باید اسکن شود
    [McpServerTool]متد را به‌عنوان یک Tool قابل فراخوانی توسط LLM ثبت می‌کند
    [Description(...)]توضیح انسانی که به مدل زبانی داده می‌شود تا بداند این Tool چه کاری انجام می‌دهد
    string messageپارامتر ورودی — SDK به‌طور خودکار JSON Schema را از این signature تولید می‌کند
    string (return type)نوع بازگشتی — می‌تواند string، Task<string> یا هر شیء سریالایزپذیر باشد
    - -
    - ✓ چرا این سادگی مهم است؟ شما نیازی به نوشتن JSON Schema دستی، یا پیاده‌سازی هندلرهای پیچیده ندارید. SDK از روی signature متد و Attributeها، به‌طور خودکار همه چیز را می‌سازد. این رویکرد «Attribute-Driven» کار را بسیار ساده می‌کند. -
    -
    -
    - - - - -
    -
    -
    ۶
    -
    -

    پیکربندی و اجرای سرور در Program.cs

    -
    Configure and Run the Server
    -
    -
    -
    -

    محتوای فایل Program.cs را با کد زیر جایگزین کنید. این کد، Host را می‌سازد، لاگ‌ها را به stderr هدایت می‌کند، و سرور را با Transport از نوع stdio راه‌اندازی می‌نماید:

    - -
    Program.cs
    -
    using Microsoft.Extensions.DependencyInjection;
    -using Microsoft.Extensions.Hosting;
    -using Microsoft.Extensions.Logging;
    -using ModelContextProtocol.Server;
    -
    -var builder = Host.CreateApplicationBuilder(args);
    -
    -builder.Logging.AddConsole(consoleLogOptions =>
    -{
    -    // Configure all logs to go to stderr so they don't corrupt the MCP protocol stream.
    -    consoleLogOptions.LogToStandardErrorThreshold = LogLevel.Trace;
    -});
    -
    -builder.Services
    -    .AddMcpServer()
    -    .WithStdioServerTransport()
    -    .WithToolsFromAssembly();
    -
    -await builder.Build().RunAsync();
    - -

    تشریح خط‌به‌خط:

    - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
    خطتوضیح
    Host.CreateApplicationBuilder(args)ساخت Builder مدرن .NET با پشتیبانی از Configuration و DI
    AddConsole(...LogToStandardErrorThreshold...)بحرانی: هدایت لاگ‌ها به stderr. اگر لاگ‌ها به stdout بروند، با پروتکل MCP تداخل می‌کنند و ارتباط قطع می‌شود
    AddMcpServer()ثبت سرویس‌های MCP در DI Container
    WithStdioServerTransport()استفاده از stdin/stdout برای ارتباط — برای کلاینت‌های دسکتاپ ایده‌آل است
    WithToolsFromAssembly()اسکن خودکار اسمبلی و ثبت هر کلاسی که با [McpServerToolType] علامت‌گذاری شده
    await builder.Build().RunAsync()ساخت Host و شروع به گوش دادن برای درخواست‌ها
    - -
    - ⚠️ هشدار بسیار مهم: در استفاده از stdio، هرگز از Console.WriteLine برای لاگ استفاده نکنید. این کار پیام‌های پروتکل را خراب می‌کند. تمام لاگ‌ها باید از طریق ILogger و با تنظیم LogToStandardErrorThreshold به stderr هدایت شوند. اگر این نکته رعایت نشود، سرور به‌ظاهر اجرا می‌شود اما کلاینت نمی‌تواند با آن ارتباط برقرار کند. -
    -
    -
    - - - - -
    -
    -
    ۷
    -
    -

    ساخت و اجرا

    -
    Build & Run
    -
    -
    -
    -

    در پوشه پروژه، دستور زیر را اجرا کنید:

    - -
    dotnet build
    -dotnet run
    - -

    سرور شما اجرا خواهد شد و منتظر دریافت پیام‌ها از طریق stdin خواهد بود. در این حالت، سرور در حالت منفعل (Passive) است و تنها زمانی که کلاینت MCP به آن متصل شود، شروع به کار خواهد کرد.

    - -

    چه اتفاقی در پس‌زمینه می‌افتد؟

    -
      -
    1. SDK اسمبلی را اسکن کرده و کلاس EchoTool را کشف می‌کند.
    2. -
    3. از روی متد Echo، یک Tool با پارامتر ورودی message: string و نوع بازگشتی string استخراج می‌کند.
    4. -
    5. یک JSON Schema خودکار برای این Tool تولید می‌کند.
    6. -
    7. سرور شروع به گوش دادن به stdin می‌کند.
    8. -
    9. وقتی کلاینت متصل می‌شود، ابتدا یک پیام initialize می‌فرستد و سرور با معرفی خودش و ابزارهای موجود پاسخ می‌دهد.
    10. -
    11. سپس کلاینت می‌تواند پیام‌های tools/list یا tools/call بفرستد.
    12. -
    - -
    - 💡 چه چیزی روی stdout می‌رود؟ فقط پیام‌های JSON-RPC پروتکل MCP. هیچ خروجی اضافی مجاز نیست. اگر می‌خواهید تست کنید، فقط از طریق یک کلاینت MCP اقدام کنید. -
    -
    -
    - - - - -
    -
    -
    ۸
    -
    -

    تست با کلاینت MCP

    -
    Testing with an MCP Client
    -
    -
    -
    -

    برای تست، می‌توانید از Claude Desktop، VS Code Copilot یا هر MCP Client دیگری استفاده کنید. در ادامه، نمونه پیکربندی برای دو کلاینت پرکاربرد ارائه شده است.

    - -

    الف) Claude Desktop

    -

    فایل پیکربندی claude_desktop_config.json را باز کنید (در ویندوز در مسیر %APPDATA%\Claude\ و در macOS در ~/Library/Application Support/Claude/) و بخش mcpServers را اضافه کنید:

    - -
    {
    -  "mcpServers": {
    -    "sample-echo": {
    -      "command": "dotnet",
    -      "args": [
    -        "run",
    -        "--project",
    -        "C:\\Path\\To\\SampleMcpServer\\SampleMcpServer.csproj"
    -      ]
    -    }
    -  }
    -}
    - -

    ب) VS Code (Copilot + MCP)

    -

    در فایل .vscode/mcp.json:

    - -
    {
    -  "servers": {
    -    "sample-echo": {
    -      "command": "dotnet",
    -      "args": [
    -        "run",
    -        "--project",
    -        "${workspaceFolder}/SampleMcpServer/SampleMcpServer.csproj"
    -      ]
    -    }
    -  }
    -}
    - -

    ج) تست دستی با JSON-RPC

    -

    اگر می‌خواهید بدون کلاینت تست کنید، می‌توانید مستقیماً پیام JSON-RPC بفرستید. در ترمینال سرور را اجرا کنید و سپس پیام‌های زیر را روی stdin آن بنویسید:

    - -
    // درخواست initialize
    -{"jsonrpc":"2.0","id":1,"method":"initialize","params":{"protocolVersion":"2024-11-05","capabilities":{},"clientInfo":{"name":"test","version":"1.0"}}}
    -
    -// دریافت لیست ابزارها
    -{"jsonrpc":"2.0","id":2,"method":"tools/list","params":{}}
    -
    -// فراخوانی ابزار Echo
    -{"jsonrpc":"2.0","id":3,"method":"tools/call","params":{"name":"Echo","arguments":{"message":"World"}}}
    - -
    - ✓ پاسخ مورد انتظار: پس از فراخوانی Echo، باید چیزی شبیه به این دریافت کنید: -

    - {"jsonrpc":"2.0","id":3,"result":{"content":[{"type":"text","text":"hello World"}]}} -
    -
    -
    - - - - -
    -
    -
    ۹
    -
    -

    افزودن Toolهای پیشرفته‌تر

    -
    Advanced Tools
    -
    -
    -
    -

    Toolهای MCP می‌توانند پیچیده‌تر از یک Echo ساده باشند. در ادامه، چند الگوی پیشرفته آورده شده است:

    - -

    الف) Tool با چند پارامتر و نوع‌های مختلف

    -
    [McpServerTool, Description("Adds two numbers and returns the result.")]
    -public static int Add(
    -    [Description("First number")] int a,
    -    [Description("Second number")] int b
    -) => a + b;
    - -

    ب) Tool با پارامتر اختیاری

    -
    [McpServerTool, Description("Searches for a term, with optional limit.")]
    -public static string Search(
    -    [Description("The search query")] string query,
    -    [Description("Maximum results (default: 10)")] int limit = 10
    -) => $"Searching for '{query}' with limit {limit}";
    - -

    ج) Tool Async با CancellationToken

    -
    [McpServerTool, Description("Fetches data from a remote API.")]
    -public static async Task<string> FetchData(
    -    [Description("The resource identifier")] string id,
    -    CancellationToken cancellationToken = default
    -)
    -{
    -    using var http = new HttpClient();
    -    return await http.GetStringAsync($"https://api.example.com/{id}", cancellationToken);
    -}
    - -

    د) Tool با Dependency Injection

    -

    برای استفاده از سرویس‌های موجود، می‌توانید Tool را به‌صورت non-static تعریف کنید و سرویس‌ها را از طریق سازنده تزریق کنید:

    - -
    [McpServerToolType]
    -public class DatabaseTool
    -{
    -    private readonly IMyRepository _repository;
    -
    -    // DI automatically resolves the dependency
    -    public DatabaseTool(IMyRepository repository)
    -    {
    -        _repository = repository;
    -    }
    -
    -    [McpServerTool, Description("Retrieves a record by ID.")]
    -    public async Task<string> GetRecord(string id, CancellationToken ct = default)
    -    {
    -        var record = await _repository.GetByIdAsync(id, ct);
    -        return record?.ToJson() ?? "Not found";
    -    }
    -}
    - -
    - 💡 نکته: برای ثبت سرویس‌های DI، پیش از builder.Build() آن‌ها را اضافه کنید: -

    - builder.Services.AddScoped<IMyRepository, MyRepository>(); -
    -
    -
    - - - - -
    -
    -
    ۱۰
    -
    -

    روش جایگزین: استفاده از MCPSharp

    -
    Alternative: MCPSharp Community Library
    -
    -
    -
    -

    اگر به یک API ساده‌تر و مختصرتر علاقه‌مند هستید، می‌توانید از کتابخانه جامعه MCPSharp استفاده کنید. این کتابخانه نیز از netstandard2.0 پشتیبانی می‌کند و با تعداد خطوط کمتر، همان قابلیت‌ها را ارائه می‌دهد.

    - -

    نصب:

    -
    dotnet add package MCPSharp
    - -

    مثال کامل:

    -
    using MCPSharp;
    -
    -public class Calculator
    -{
    -    [McpTool("add", "Adds two numbers")]
    -    public static int Add(
    -        [McpParameter(true)] int a,
    -        [McpParameter(true)] int b
    -    ) => a + b;
    -
    -    [McpTool("multiply", "Multiplies two numbers")]
    -    public static int Multiply(
    -        [McpParameter(true)] int a,
    -        [McpParameter(true)] int b
    -    ) => a * b;
    -}
    -
    -await MCPServer.StartAsync("CalculatorServer", "1.0.0");
    - -

    مقایسه دو رویکرد:

    - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
    ویژگیModelContextProtocol (رسمی)MCPSharp (جامعه)
    نگهداریMicrosoft + Anthropicجامعه (Community)
    پشتیبانی از .NET Standard 2.0✓✓
    میزان کد Boilerplateمتوسطحداقل
    پشتیبانی از DI✓ کاملمحدود
    Transport HTTP✓در حال توسعه
    توصیه برای پروژه‌های عملیاتیModelContextProtocol (رسمی)
    - -
    - ⚠️ توصیه: برای پروژه‌های عملیاتی و سازمانی، استفاده از کتابخانه رسمی ModelContextProtocol توصیه می‌شود زیرا پشتیبانی بلندمدت، به‌روزرسانی‌های امنیتی، و سازگاری با آخرین تغییرات پروتکل MCP را تضمین می‌کند. MCPSharp برای پروژه‌های کوچک، یادگیری، یا Prototype مناسب است. -
    -
    -
    - - - - -
    -
    -
    ۱۱
    -
    -

    گزینه پیشرفته: HTTP Transport

    -
    Optional: HTTP Transport
    -
    -
    -
    -

    اگر می‌خواهید سرور MCP شما از راه دور (Remote) قابل دسترسی باشد (مثلاً در یک کانتینر Docker یا روی یک سرور Cloud)، می‌توانید به‌جای stdio از HTTP Transport استفاده کنید.

    - -
    - 💡 چه زمانی HTTP؟ -
      -
    • چندین کلاینت به‌طور همزمان می‌خواهند وصل شوند
    • -
    • سرور در محیطی جدا از کلاینت اجرا می‌شود (Docker، Kubernetes، Cloud)
    • -
    • نیاز به احراز هویت مرکزی و Rate Limiting دارید
    • -
    -
    - -

    تغییرات لازم در Program.cs:

    -
    using Microsoft.AspNetCore.Builder;
    -using Microsoft.Extensions.DependencyInjection;
    -using Microsoft.Extensions.Hosting;
    -using ModelContextProtocol.Server;
    -
    -var builder = WebApplication.CreateBuilder(args);
    -
    -builder.Services
    -    .AddMcpServer()
    -    .WithHttpTransport()       // ← به‌جای WithStdioServerTransport
    -    .WithToolsFromAssembly();
    -
    -var app = builder.Build();
    -
    -app.MapMcp();                   // ← مسیر /mcp را فعال می‌کند
    -
    -app.Run();
    - -

    همچنین باید پکیج Microsoft.AspNetCore را اضافه کنید و نوع پروژه را از Microsoft.NET.Sdk به Microsoft.NET.Sdk.Web تغییر دهید.

    - -
    - ⚠️ توجه: HTTP Transport در .NET Standard 2.0 به‌طور کامل پشتیبانی نمی‌شود. برای استفاده از این قابلیت، بهتر است پروژه را به net8.0 یا بالاتر ارتقا دهید. اگر مجبور به استفاده از .NET Standard 2.0 هستید، از stdio استفاده کنید و یک پروسه فرزند بسازید. -
    -
    -
    - - - - -
    -
    -
    ۱۲
    -
    -

    بهترین روش‌ها و نکات عملیاتی

    -
    Best Practices
    -
    -
    -
    -
      -
    • هر Tool را با [Description] واضح و دقیق توصیف کنید — مدل از این توضیح برای تصمیم‌گیری استفاده می‌کند
    • -
    • پارامترها را با نوع‌های مشخص (نه object) تعریف کنید تا JSON Schema دقیق‌تری تولید شود
    • -
    • برای عملیات طولانی، از Task و CancellationToken استفاده کنید
    • -
    • خطاها را با Exceptionهای واضح پرتاب کنید — SDK آن‌ها را به JSON-RPC Error تبدیل می‌کند
    • -
    • ورودی‌ها را اعتبارسنجی کنید (Validation) — مدل ممکن است ورودی نامعتبر بفرستد
    • -
    • لاگ‌ها را هرگز روی stdout ننویسید — از ILogger و stderr استفاده کنید
    • -
    • از [McpServerToolType] روی کلاس‌های Helper استفاده کنید تا ابزارها در فایل‌های مختلف تقسیم شوند
    • -
    • در محیط عملیاتی، Transport را بر اساس سناریو انتخاب کنید (stdio برای دسکتاپ، HTTP برای Cloud)
    • -
    • ورژن پروتکل MCP را در نظر بگیرید — کلاینت و سرور باید سازگار باشند
    • -
    • برای تست خودکار، از JSON-RPC خام در سناریوهای Integration Test استفاده کنید
    • -
    - -

    الگوی پیشنهادی ساختار پروژه:

    -
    -SampleMcpServer/ -├── Tools/ -│ ├── EchoTool.cs -│ ├── CalculatorTool.cs -│ └── DatabaseTool.cs -├── Services/ -│ ├── IMyRepository.cs -│ └── MyRepository.cs -├── Models/ -│ └── RecordDto.cs -├── Program.cs -├── appsettings.json -└── SampleMcpServer.csproj -
    -
    -
    - - - - -
    -
    -
    ۱۳
    -
    -

    جمع‌بندی

    -
    Summary
    -
    -
    -
    -

    در این مستند، به‌صورت گام‌به‌گام، ساخت یک MCP Server با C# و .NET Standard 2.0 را بررسی کردیم. مراحلی که پشت سر گذاشتیم:

    - -
      -
    • با مفهوم MCP و سه قابلیت اصلی آن (Tools، Resources، Prompts) آشنا شدیم
    • -
    • پیش‌نیازها و محیط توسعه را آماده کردیم
    • -
    • یک پروژه Console جدید با dotnet new console ساختیم
    • -
    • پکیج‌های ModelContextProtocol و Microsoft.Extensions.Hosting را نصب کردیم
    • -
    • فایل .csproj را برای netstandard2.0 پیکربندی کردیم
    • -
    • اولین Tool خود را با [McpServerTool] تعریف کردیم
    • -
    • سرور را در Program.cs با stdio Transport راه‌اندازی کردیم
    • -
    • نحوه تست با Claude Desktop و VS Code را فرا گرفتیم
    • -
    • الگوهای پیشرفته‌تر (Async، DI، پارامترهای اختیاری) را بررسی کردیم
    • -
    • با کتابخانه جایگزین MCPSharp آشنا شدیم
    • -
    • روش استفاده از HTTP Transport برای سناریوهای Cloud را دیدیم
    • -
    • بهترین روش‌های عملیاتی را مرور کردیم
    • -
    - -
    -

    🎯 نتیجه نهایی

    -

    شما اکنون یک MCP Server کامل و عملیاتی در اختیار دارید که:

    -

    - با استاندارد باز MCP سازگار است، از .NET Standard 2.0 پشتیبانی می‌کند، به‌راحتی با Claude Desktop و GitHub Copilot یکپارچه می‌شود، و منطق تجاری موجود شما را در دسترس مدل‌های زبانی قرار می‌دهد. -

    -
    - 💎 ارزش پیشنهادی:
    - یکپارچگی استاندارد با LLM + بدون تغییر ساختار موجود پروژه + قابلیت حمل بالا + سادگی توسعه -
    -
    - -
    - 📞 گام بعدی پیشنهادی: پس از ساخت این سرور ساده، می‌توانید: -
      -
    • سرویس‌های موجود خود را به‌عنوان Toolهای MCP ثبت کنید (مانند RAG، مدیریت مکالمه، پردازش فایل)
    • -
    • سرور را در CI/CD قرار دهید و به‌صورت خودکار منتشر کنید
    • -
    • با یک MCP Client متصل شوید و تست End-to-End انجام دهید
    • -
    • در صورت نیاز، به سمت HTTP Transport و استقرار در کانتینر حرکت کنید
    • -
    -
    -
    -
    - -
    - این مستند آموزشی بوده و برای تیم‌های فنی و توسعه‌دهندگان تهیه شده است. استفاده از آن در پروژه‌های داخلی و تجاری مجاز است. -
    - -
    - -
    - - -
    تاریخ تهیه: آبان ۱۴۰۵  |  نسخه: ۱.۰  |  طبقه‌بندی: آموزشی-فنی
    -
    - -
    - - - - -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\xAiApi\wwwroot\Storage\Uploads\Document\xSaherElm_6b96ea86-c4b1-49a2-b46a-df5be36b52e5.html - - - - - - -معماری کلان محصول | سامانه هوش مصنوعی سازمانی - - - - -
    - -
    -
    -
    - -
    -
    -
    شماره مستند: ARCH-1405-001
    -
    نسخه: ۱.۰
    -
    تاریخ تهیه: مهر ۱۴۰۵
    -
    طبقه‌بندی: محرمانه
    -
    -
    - -
    - HIGH-LEVEL ARCHITECTURE -

    معماری کلان محصول

    -

    سامانه هوش مصنوعی سازمانی — پاسخ به نیازمندی‌های پارسا پلیمر شریف

    -
    -
    - -
    - -
    - خلاصه مدیریتی،
    - این مستند به توصیف معماری کلان سامانه هوش مصنوعی سازمانی می‌پردازد که بر اساس تحلیل نیازمندی‌های شرکت پارسا پلیمر شریف (مستند REQ-1405-001) تدوین شده است. رویکرد این معماری، تفکر سیستماتیک و فارغ از سکو و جزئیات پیاده‌سازی است. هدف، شناسایی اجزاء و مولفه‌های اصلی سامانه، روابط میان آنها، و جریان‌های اطلاعاتی و کنترلی است تا مبنای طراحی تفصیلی و پیاده‌سازی قرار گیرد. -
    - -
    -
    -
    ۱
    -
    -

    اصول حاکم بر معماری

    -
    Architectural Principles
    -
    -
    -
    -

    معماری این سامانه بر پایه اصول زیر شکل گرفته است که برگرفته از نیازمندی‌های صریح کارفرما و رویکرد تفکر سیستماتیک است:

    - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
    اصلتوضیحمبنای نیازمندی
    جداسازی دغدغه‌هاتفکیک لایه‌های تعامل، کنترل، هوش، داده و حاکمیت به‌گونه‌ای که تغییر در یک لایه، حداقل اثر را بر لایه‌های دیگر داشته باشدمحور ۱، ۲، ۵
    حاکمیت‌محوریکنترل دسترسی، ممیزی و سیاست‌های داده به‌صورت عرضی (Cross-cutting) در تمام لایه‌ها اعمال می‌شود، نه به‌صورت جزیره‌ایمحور ۲، ۵
    ایجنت‌محوری قابل‌آزمونموتور ایجنت به‌عنوان یک مولفه مستقل با قابلیت برنامه‌ریزی، انتخاب ابزار، اجرا و اصلاح، قابل مشاهده و آزمون باشدمحور ۱
    شفافیت مصرفاندازه‌گیری و گزارش‌گیری مصرف در سطح کاربر، مدل، ایجنت و ابزار به‌صورت یکپارچهمحور ۳
    تاب‌آوری و استقرارپذیریامکان استقرار درون‌سازمانی (On-Premise) و عملکرد در شرایط قطع اینترنت بین‌المللمحور ۵، ۷
    توسعه‌پذیری و سفارشی‌سازیامکان افزودن مدل‌ها، ابزارها، ایجنت‌ها و منابع داده جدید بدون تغییر در هستهمحور ۱، ۶
    - -
    - اصل حاکم: معماری باید به‌گونه‌ای باشد که هر ادعای قابلیت، قابل اثبات و آزمون باشد. این یعنی هر مولفه باید دارای مرز مشخص، رابط تعریف‌شده و رفتار قابل مشاهده باشد. -
    -
    -
    - -
    -
    -
    ۲
    -
    -

    نمای کلی سیستم

    -
    System Overview
    -
    -
    -
    -

    سامانه به‌صورت کلان از شش لایه اصلی و دو محور عرضی تشکیل شده است. این ساختار لایه‌ای، جداسازی دغدغه‌ها را تضمین می‌کند و محورهای عرضی، حاکمیت و امنیت را در تمام لایه‌ها اعمال می‌نمایند.

    - -
    -
    -
    لایه ۱: تعامل و تجربه کاربری (Interaction Layer)
    -
    - رابط وب سازمانی - نسخه دسکتاپ - رابط API - کانال‌های ارتباطی -
    -
    - -
    ▼
    - -
    -
    لایه ۲: کنترل دسترسی و نشست (Access & Session Layer)
    -
    - احراز هویت - مدیریت نشست - اعمال مجوزها - مدیریت نقش‌ها -
    -
    - -
    ▼
    - -
    -
    لایه ۳: هماهنگی و ارکستراسیون (Orchestration Layer)
    -
    - موتور ایجنت - برنامه‌ریز - انتخاب‌گر ابزار - مدیریت جریان - نقاط تأیید انسانی -
    -
    - -
    ▼
    - -
    -
    لایه ۴: هوش و مدل‌ها (Intelligence Layer)
    -
    - درگاه مدل‌ها - مدیریت مدل - بازیابی و تقویت (RAG) - حافظه و زمینه -
    -
    - -
    ▼
    - -
    -
    لایه ۵: داده و منابع (Data & Resources Layer)
    -
    - منابع دانش سازمانی - فایل‌ها و پوشه‌ها - پایگاه‌های داده - سرویس‌های خارجی - ابزارهای عملیاتی -
    -
    - -
    ▼
    - -
    -
    لایه ۶: خروجی و گزارش (Output & Reporting Layer)
    -
    - تولید گزارش - خروجی Word/Excel - ارجاع به منابع - داشبورد مصرف -
    -
    -
    - -
    -
    -
    محور عرضی ۱: حاکمیت داده و امنیت
    -
    سیاست‌های داده، ممیزی، محرمانگی، جلوگیری از افشا — اعمال در تمام لایه‌ها
    -
    -
    -
    محور عرضی ۲: مشاهده‌پذیری و اندازه‌گیری
    -
    لاگ، متریک، ردیابی مصرف، گزارش هزینه — اعمال در تمام لایه‌ها
    -
    -
    - -
    - 💡 نکته معماری: محورهای عرضی به‌صورت Cross-cutting Concerns طراحی شده‌اند؛ یعنی هر درخواست کاربر، در هر لایه‌ای که پردازش شود، از فیلتر حاکمیت و مشاهده‌پذیری عبور می‌کند. این تضمین می‌کند که نیازمندی‌های محور ۲ (دسترسی) و محور ۳ (مصرف) به‌صورت سیستماتیک و نه جزیره‌ای برآورده شوند. -
    -
    -
    - -
    -
    -
    ۳
    -
    -

    اجزاء و مولفه‌های اصلی

    -
    Core Components
    -
    -
    -
    -

    هر لایه از مولفه‌هایی تشکیل شده است که مسئولیت مشخص و رابط تعریف‌شده دارند. در ادامه، مولفه‌های کلیدی هر لایه تشریح می‌شود:

    - -

    لایه ۱: تعامل و تجربه کاربری

    - - - - - - - - - - - - - - - - - - - - - - - - - -
    مولفهمسئولیتنیازمندی مرتبط
    رابط وب سازمانیتعامل کاربران با سامانه از طریق مرورگر، شامل چت، آپلود فایل، مشاهده گزارشمحور ۴
    نسخه دسکتاپدسترسی به قابلیت‌های سامانه از طریق اپلیکیشن دسکتاپ با قابلیت دسترسی به فایل‌های محلیمحور ۴
    درگاه APIامکان یکپارچه‌سازی سیستم‌های سازمانی و استفاده از اعتبار اختصاصیمحور ۳
    - -

    لایه ۲: کنترل دسترسی و نشست

    - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
    مولفهمسئولیتنیازمندی مرتبط
    احراز هویتتأیید هویت کاربران و یکپارچه‌سازی با سامانه‌های هویت سازمانیمحور ۲
    مدیریت نقش‌هاتعریف و مدیریت نقش‌ها، کاربران و سطوح دسترسی واحدهای مختلفمحور ۲
    موتور مجوزهااعمال مجوزها در سطح مدل، منبع، ابزار و رکورد؛ فهرست مجاز مدل‌ها و ابزارهامحور ۲
    مدیریت نشستحفظ زمینه کاربر، سطح دسترسی فعال و سیاست‌های نشستمحور ۲
    - -

    لایه ۳: هماهنگی و ارکستراسیون (هسته ایجنت)

    - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
    مولفهمسئولیتنیازمندی مرتبط
    موتور ایجنتهسته اصلی تصمیم‌گیری؛ دریافت هدف، تولید برنامه، اجرا و اصلاح بر اساس نتیجهمحور ۱
    برنامه‌ریز (Planner)تبدیل هدف به مراحل اجرایی قابل پیگیریمحور ۱
    انتخاب‌گر ابزار (Tool Selector)انتخاب ابزار یا منبع مناسب از میان فهرست مجاز کاربرمحور ۱، ۲
    مدیریت جریان (Flow Manager)هدایت جریان اجرا، مدیریت حالت‌ها، واکنش به خطا و تغییر شرایطمحور ۱
    نقاط تأیید انسانیتعریف و اجرای نقاط Human-in-the-loop برای تأیید عملیات حساسمحور ۱
    - -

    لایه ۴: هوش و مدل‌ها

    - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
    مولفهمسئولیتنیازمندی مرتبط
    درگاه مدل‌ها (Model Gateway)لایه انتزاع دسترسی به مدل‌های مختلف (داخلی/خارجی) با سیاست‌های یکسانمحور ۱، ۵
    مدیریت مدلفهرست مدل‌های مجاز، نسخه‌بندی، به‌روزرسانی و سیاست دسترسی به مدل‌های جدیدمحور ۱
    بازیابی و تقویت (RAG)بازیابی اطلاعات از منابع مجاز کاربر و تقویت پاسخ مدل با شواهدمحور ۲، ۴
    حافظه و زمینهمدیریت زمینه مکالمه، حافظه کوتاه‌مدت و بلندمدت با رعایت سطح دسترسیمحور ۲
    - -

    لایه ۵: داده و منابع

    - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
    مولفهمسئولیتنیازمندی مرتبط
    منابع دانش سازمانیمخازن دانش، اسناد، پایگاه‌های دانش و محتوای ساختاریافته/غیرساختاریافتهمحور ۴، ۵
    مدیریت فایل و پوشهدسترسی کنترل‌شده به فایل‌های محلی/شبکه و تحلیل چند فایلمحور ۴
    سرویس‌های خارجیاتصال به سرویس‌های ثالث از طریق API با سیاست‌های حاکمیت دادهمحور ۵
    ابزارهای عملیاتیمجموعه ابزارهای قابل فراخوانی توسط ایجنت (جستجو، محاسبه، ارسال، تبدیل و...)محور ۱
    - -

    لایه ۶: خروجی و گزارش

    - - - - - - - - - - - - - - - - - - - - - - - - - -
    مولفهمسئولیتنیازمندی مرتبط
    تولید گزارشتولید خروجی متنی، جدولی و نموداری با قابلیت ویرایش و ارجاع به منابعمحور ۴
    مبدل قالبتبدیل خروجی به Word، Excel و سایر قالب‌های موردنیازمحور ۴
    داشبورد مصرفنمایش مصرف و هزینه به تفکیک کاربر، مدل، ایجنت و ابزارمحور ۳
    - -

    محورهای عرضی

    - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
    مولفهمسئولیتنیازمندی مرتبط
    سیاست‌گذار دادهتعریف و اعمال سیاست‌های ذخیره‌سازی، انتقال و آموزش مدلمحور ۵
    ممیزی و لاگثبت تمام تعاملات، تصمیمات ایجنت و دسترسی‌ها برای ممیزیمحور ۲، ۵
    سنسور محرمانگیشناسایی و جلوگیری از افشای اطلاعات خارج از سطح دسترسی در پاسخ‌هامحور ۲
    متریک و ردیابیاندازه‌گیری مصرف توکن، زمان پاسخ، نرخ خطا و شاخص‌های عملکردمحور ۳، ۷
    -
    -
    - -
    -
    -
    ۴
    -
    -

    روابط میان مولفه‌ها

    -
    Component Relationships
    -
    -
    -
    -

    روابط میان مولفه‌ها بر اساس جریان درخواست و جریان کنترل تعریف می‌شود. هر درخواست کاربر از لایه تعامل وارد شده و پس از عبور از لایه‌های کنترل، ارکستراسیون و هوش، به منابع داده دسترسی پیدا کرده و خروجی از لایه گزارش بازمی‌گردد.

    - -

    جریان اصلی درخواست (Request Flow)

    -
    -
    -
    ۱
    -
    ورود درخواست
    -

    کاربر از طریق رابط وب/دسکتاپ/API درخواست را ارسال می‌کند.

    -
    -
    -
    ۲
    -
    احراز و مجوز
    -

    لایه کنترل، هویت کاربر را تأیید و سطح دسترسی فعال را تعیین می‌کند.

    -
    -
    -
    ۳
    -
    تصمیم ارکستراسیون
    -

    موتور ایجنت نوع درخواست (پاسخ ساده / برنامه‌ریزی چندمرحله‌ای) را تشخیص می‌دهد.

    -
    -
    -
    ۴
    -
    بازیابی و استدلال
    -

    لایه هوش با رعایت مجوزها، اطلاعات را بازیابی و مدل مناسب را فراخوانی می‌کند.

    -
    -
    -
    ۵
    -
    اجرای ابزار
    -

    در صورت نیاز، ایجنت ابزار مجاز را انتخاب و عملیات را اجرا می‌کند.

    -
    -
    -
    ۶
    -
    تولید خروجی
    -

    لایه گزارش، پاسخ یا گزارش نهایی را با ارجاع به منابع تولید می‌کند.

    -
    -
    - -

    جدول روابط کلیدی میان مولفه‌ها

    - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
    از مولفهبه مولفهنوع رابطهتوضیح
    رابط کاربریمدیریت نشستدرخواست/پاسخهر تعامل کاربر از این مسیر وارد و نشست فعال می‌شود
    مدیریت نشستموتور مجوزهاپرس‌وجوسطح دسترسی و فهرست مجاز کاربر استعلام می‌شود
    موتور مجوزهاموتور ایجنتاعمال محدودیتفهرست ابزارها، مدل‌ها و منابع مجاز به ایجنت ابلاغ می‌شود
    موتور ایجنتبرنامه‌ریزفراخوانیهدف کاربر برای تولید برنامه اجرایی ارسال می‌شود
    برنامه‌ریزانتخاب‌گر ابزاردرخواست انتخاببرای هر مرحله، ابزار مناسب از فهرست مجاز انتخاب می‌شود
    انتخاب‌گر ابزارابزارهای عملیاتیفراخوانیابزار انتخاب‌شده اجرا و نتیجه بازمی‌گردد
    موتور ایجنتنقاط تأیید انسانیتوقف/تأییددر عملیات حساس، اجرا متوقف و منتظر تأیید انسان می‌شود
    موتور ایجنتدرگاه مدل‌هافراخوانی مدلبرای استدلال، تولید متن یا تصمیم‌گیری، مدل مناسب فراخوانی می‌شود
    درگاه مدل‌هامدیریت مدلاستعلاممدل مجاز و نسخه فعال برای کاربر بررسی می‌شود
    بازیابی و تقویتمنابع دانش سازمانیبازیابیاطلاعات مرتبط با رعایت سطح دسترسی بازیابی می‌شود
    سنسور محرمانگیتولید گزارشفیلترپاسخ نهایی پیش از ارائه، از نظر افشای اطلاعات بررسی می‌شود
    متریک و ردیابیداشبورد مصرفتغذیه دادهداده‌های مصرف و هزینه برای گزارش‌گیری ارسال می‌شود
    - -
    - ✓ نکته کلیدی درباره روابط: مسیر موتور مجوزها ← موتور ایجنت و سنسور محرمانگی ← تولید گزارش دو مسیر حیاتی برای پاسخ به آزمون نفوذ دسترسی کارفرما هستند. این دو مسیر تضمین می‌کنند که حتی اگر ایجنت یا مدل بخواهد اطلاعات خارج از دسترس را افشا کند، در دو نقطه مستقل مسدود شود (دفاع لایه‌ای). -
    -
    -
    - -
    -
    -
    ۵
    -
    -

    جریان‌های کلیدی سیستم

    -
    Key System Flows
    -
    -
    -
    -

    سه جریان اصلی در سامانه وجود دارد که هر یک از منظر تفکر سیستماتیک، رفتار متفاوتی از خود نشان می‌دهند:

    - -

    جریان ۱: پاسخ ساده (Simple Response)

    -

    درخواست کاربر مستقیماً به لایه هوش رفته، مدل پاسخ تولید می‌کند و پس از فیلتر محرمانگی، به کاربر بازمی‌گردد. این جریان برای پرسش‌های ساده و بدون نیاز به ابزار یا چند مرحله است.

    - -

    جریان ۲: پاسخ مبتنی بر بازیابی (RAG Flow)

    -

    درخواست کاربر ابتدا به بازیابی اطلاعات از منابع مجاز می‌رود، شواهد بازیابی‌شده به مدل تزریق می‌شود و پاسخ با ارجاع به منابع تولید می‌گردد. این جریان برای پرسش‌های دانش‌محور و تحلیل اسناد است.

    - -

    جریان ۳: اجرای چندمرحله‌ای ایجنت (Agentic Flow)

    -

    این جریان، هسته تمایز سامانه است و مستقیماً پاسخ به محور ۱ نیازمندی‌هاست:

    - -
    -
    -
    -
    ۱. دریافت هدف
    -
    هدف کاربر در موتور ایجنت ثبت می‌شود
    -
    -
    ←
    -
    -
    ۲. تولید برنامه
    -
    برنامه‌ریز مراحل اجرایی را تولید می‌کند
    -
    -
    -
    -
    -
    ۳. انتخاب ابزار
    -
    برای هر مرحله ابزار مجاز انتخاب می‌شود
    -
    -
    ←
    -
    -
    ۴. اجرا
    -
    ابزار اجرا و نتیجه دریافت می‌شود
    -
    -
    -
    -
    -
    ۵. ارزیابی نتیجه
    -
    نتیجه با هدف مقایسه می‌شود
    -
    -
    ←
    -
    -
    ۶. اصلاح یا خاتمه
    -
    در صورت نیاز، برنامه اصلاح و ادامه می‌یابد
    -
    -
    -
    -
    -
    نقاط تأیید انسانی
    -
    در عملیات حساس، اجرا متوقف و منتظر تأیید می‌شود
    -
    -
    -
    مدیریت خطا
    -
    در صورت خطا، برنامه بازنگری یا به کاربر اعلام می‌شود
    -
    -
    -
    - -
    - 💡 تمایز ایجنت از Assistant: در جریان ۳، سامانه هدف را به مراحل اجرایی تبدیل می‌کند، ابزار انتخاب می‌کند، عملیات را اجرا می‌کند و بر اساس نتیجه، مراحل بعدی را تعیین یا اصلاح می‌کند. این رفتار حلقه‌ای (Closed-loop) است، در حالی که Assistant صرفاً به یک درخواست پاسخ می‌دهد. این تمایز، دقیقاً همان چیزی است که کارفرما در محور ۱ به‌عنوان قابلیت قابل‌آزمون درخواست کرده است. -
    -
    -
    - -
    -
    -
    ۶
    -
    -

    نگاشت نیازمندی‌ها به مولفه‌های معماری

    -
    Requirements-to-Architecture Mapping
    -
    -
    -
    -

    جدول زیر نشان می‌دهد هر محور از نیازمندی‌های کارفرما، توسط کدام لایه‌ها و مولفه‌های معماری پوشش داده می‌شود:

    - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
    محور نیازمندیلایه‌های درگیرمولفه‌های کلیدینحوه پوشش
    محور ۱: ماهیت و ایجنتلایه ۳، ۴موتور ایجنت، برنامه‌ریز، انتخاب‌گر ابزار، مدیریت جریان، نقاط تأیید انسانیجریان ۳ به‌صورت حلقه‌ای و قابل‌آزمون
    محور ۲: دسترسیلایه ۲ + محور عرضیمدیریت نقش‌ها، موتور مجوزها، سنسور محرمانگی، ممیزیدفاع لایه‌ای در دو نقطه مستقل
    محور ۳: پلن و مصرفمحور عرضی + لایه ۶متریک و ردیابی، داشبورد مصرف، درگاه APIاندازه‌گیری در سطح کاربر/مدل/ایجنت
    محور ۴: رابط و گزارشلایه ۱، ۵، ۶رابط وب، نسخه دسکتاپ، مدیریت فایل، تولید گزارش، مبدل قالبپوشش کامل تعامل و خروجی
    محور ۵: حاکمیت دادهمحور عرضی + لایه ۵سیاست‌گذار داده، ممیزی، درگاه مدل‌ها، مدیریت منابعاعمال عرضی در تمام لایه‌ها
    محور ۶: پیاده‌سازی و آموزشهمه لایه‌هاتوسعه‌پذیری مولفه‌ها، رابط‌های تعریف‌شدهامکان سفارشی‌سازی لایه‌ای
    محور ۷: عملکرد و تاب‌آوریمحور عرضی + لایه ۴، ۵متریک و ردیابی، درگاه مدل‌ها، مدیریت منابعامکان استقرار درون‌سازمانی
    -
    -
    - -
    -
    -
    ۷
    -
    -

    ویژگی‌های کیفی معماری

    -
    Architectural Quality Attributes
    -
    -
    -
    -

    معماری کلان باید ویژگی‌های کیفی زیر را تضمین کند که مستقیماً از نیازمندی‌های کارفرما استخراج شده‌اند:

    - -
    - - -
    - -
    -
    -

    تاب‌آوری

    -
      -
    • استقرار درون‌سازمانی
    • -
    • قطع اینترنت عملکرد محلی
    • -
    • مدل‌ها چندگانه
    • -
    -
    -
    -

    توسعه‌پذیری

    -
      -
    • مدل جدید بدون تغییر هسته
    • -
    • ابزار جدید ثبت در فهرست
    • -
    • ایجنت اختصاصی قابل تعریف
    • -
    -
    -
    - -
    - نکته کلیدی: ویژگی «قابلیت آزمون» در این معماری یک ویژگی درجه‌یک است، نه ثانویه. هر مولفه‌ای که رفتار آن قابل مشاهده و اندازه‌گیری نباشد، نمی‌تواند در جلسه دمو و آزمون‌های عملی کارفرما پاسخگو باشد. بنابراین، مرزهای مولفه‌ها و رابط‌های آنها به‌گونه‌ای طراحی شده که هر ادعا، قابل اثبات باشد. -
    -
    -
    - -
    -
    -
    ۸
    -
    -

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

    -
    Architecture Summary
    -
    -
    -
    -

    معماری کلان ارائه‌شده، پاسخی سیستماتیک و فارغ از سکو به نیازمندی‌های شرکت پارسا پلیمر شریف است. ویژگی‌های متمایز این معماری:

    - -
      -
    • - ساختار شش‌لایه + دو محور عرضی - جداسازی دغدغه‌ها و اعمال سیستماتیک حاکمیت و مشاهده‌پذیری در تمام لایه‌ها -
    • -
    • - موتور ایجنت به‌عنوان هسته مستقل - با قابلیت برنامه‌ریزی، انتخاب ابزار، اجرا، ارزیابی و اصلاح — قابل مشاهده و آزمون -
    • -
    • - دفاع لایه‌ای برای دسترسی - دو نقطه مستقل کنترل (موتور مجوزها و سنسور محرمانگی) برای پاسخ به آزمون نفوذ کارفرما -
    • -
    • - شفافیت مصرف به‌صورت عرضی - اندازه‌گیری و گزارش در سطح کاربر، مدل، ایجنت و ابزار -
    • -
    • - استقرارپذیری درون‌سازمانی - با انتزاع درگاه مدل‌ها و مدیریت منابع، امکان عملکرد در شرایط قطع اینترنت -
    • -
    • - توسعه‌پذیری بدون تغییر هسته - افزودن مدل‌ها، ابزارها و ایجنت‌های جدید از طریق رابط‌های تعریف‌شده -
    • -
    - -
    - 📞 گام بعدی: این معماری کلان، مبنای طراحی تفصیلی (Detailed Design) و پیاده‌سازی خواهد بود. در گام بعدی، می‌توان طراحی تفصیلی هر لایه، رابط‌های مولفه‌ها، و سناریوی نمونه Agent برای جلسه دمو را تدوین کرد. -
    -
    -
    - -
    -

    🎯 ارزش معماری

    -

    این معماری، پاسخی سیستماتیک، لایه‌ای و فارغ از سکو به نیازمندی‌های فنی و آزمون‌محور کارفرماست.

    -

    هر ادعای قابلیت، دارای مولفه مسئول، رابط تعریف‌شده و رفتار قابل مشاهده است تا در جلسه دمو و آزمون‌های عملی قابل اثبات باشد.

    -
    - 💎 ارزش پیشنهادی معماری:
    - جداسازی دغدغه‌ها + حاکمیت عرضی + ایجنت قابل‌آزمون + دفاع لایه‌ای + شفافیت مصرف + استقرارپذیری -
    -
    - -
    - این مستند محرمانه بوده و صرفاً جهت ارائه به کارفرمای محترم تهیه شده است. هرگونه کپی‌برداری یا افشا بدون اجازه کتبی ممنوع است. -
    - -
    - -
    - - -
    تاریخ تهیه: مهر ۱۴۰۵  |  نسخه: ۱.۰  |  طبقه‌بندی: محرمانه
    -
    - -
    - - - - -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\xAiApi\wwwroot\Storage\Uploads\Document\xSaherElm_7cd76322-fd9c-4970-8e97-18a3308f7b90.html - - - - - - -پیاده‌سازی عملیاتی معماری | سامانه هوش مصنوعی سازمانی با .NET و Microsoft Agent Framework - - - - -
    - -
    -
    -
    - -
    -
    -
    شماره مستند: IMPL-1405-001
    -
    نسخه: ۱.۰
    -
    تاریخ تهیه: مهر ۱۴۰۵
    -
    طبقه‌بندی: محرمانه
    -
    -
    - -
    - IMPLEMENTATION ROADMAP -

    پیاده‌سازی عملیاتی معماری

    -

    سامانه هوش مصنوعی سازمانی با .NET و Microsoft Agent Framework

    -
    -
    - -
    - -
    - کارفرمای محترم،
    - این مستند، نقشه راه عملیاتی پیاده‌سازی معماری کلان سامانه هوش مصنوعی سازمانی (مستند ARCH-1405-001) را با استفاده از استک .NET، Microsoft.Extensions.AI و Microsoft Agent Framework ارائه می‌دهد. رویکرد پیاده‌سازی Cross-Platform است و از کامپایل کدبیس واحد برای سکوهای مختلف (دسکتاپ و موبایل) پشتیبانی می‌کند. هدف، تبدیل معماری به یک محصول قابل ارائه، قابل آزمون و ارزش‌آفرین است. -
    - -
    -
    -
    ۱
    -
    -

    مقدمه: شرح مسئله و ضرورت محصول در عصر AI-Driven

    -
    Problem Statement & AI-Driven Necessity
    -
    -
    -
    -

    سازمان‌های امروزی با انبوهی از داده‌ها، اسناد و فرایندهای پیچیده مواجه‌اند که مدیریت و بهره‌برداری مؤثر از آن‌ها بدون ابزارهای هوشمند، عملاً غیرممکن شده است. در این میان، هوش مصنوعی دیگر یک مزیت رقابتی نیست؛ یک ضرورت بقا است. سازمان‌هایی که نتوانند دانش پراکنده خود را به قالب‌های قابل پرسش، قابل تحلیل و قابل اقدام تبدیل کنند، در برابر رقبای داده‌محور به سرعت عقب می‌مانند.

    - -

    مسئله اصلی، فقدان دسترسی یکپارچه به دانش سازمانی، ناتوانی در تحلیل سریع حجم بالای اسناد، و عدم وجود سازوکاری برای خودکارسازی تصمیم‌گیری‌های چندمرحله‌ای است. راهکارهای سنتی (جستجوی کلیدواژه، پایگاه‌های دانش ایستا، یا چت‌بات‌های ساده) نمی‌توانند پاسخگوی نیاز به استدلال، برنامه‌ریزی و اجرای عملیات باشند.

    - -
    -
    -
    AI
    Driven
    -
    ضرورت بقا در عصر داده
    -
    -
    -
    ایجنت
    محور
    -
    فراتر از چت‌بات ساده
    -
    -
    -
    Cross
    Platform
    -
    کدبیس واحد، چند سکو
    -
    -
    - -
    - نتیجه کلیدی: آنچه سازمان‌ها به آن نیاز دارند، یک سامانه ایجنت‌محور است که بتواند اهداف را به مراحل اجرایی تبدیل کند، ابزار مناسب را انتخاب نماید، عملیات را انجام دهد و بر اساس نتیجه، مسیر خود را اصلاح کند. این مستند، نقشه راه پیاده‌سازی چنین سامانه‌ای را ارائه می‌دهد. -
    -
    -
    - -
    -
    -
    ۲
    -
    -

    استک فنی و رویکرد پیاده‌سازی

    -
    Technical Stack & Implementation Approach
    -
    -
    -
    -

    استک فنی انتخاب‌شده بر پایه سه اصل استوار است: انتزاع مدل (برای تعویض‌پذیری)، ارکستراسیون ایجنت (برای قابلیت آزمون) و Cross-Platform (برای پوشش سکوهای مختلف با کدبیس واحد).

    - -

    ۲.۱ اجزای استک

    - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
    لایهفناورینقش در معماری
    زبان و پلتفرم.NET 8/10Runtime یکپارچه برای Backend و سرویس‌ها
    انتزاع مدلMicrosoft.Extensions.AIرابط یکپارچه برای اتصال به هر ارائه‌دهنده مدل (IChatClient، IEmbeddingGenerator)
    ارکستراسیون ایجنتMicrosoft Agent Frameworkهسته ایجنت (AIAgent)، گراف چند-ایجنت (WorkflowBuilder)، ثبت ابزار (AIFunctionFactory)، MCP Client
    دسکتاپ Cross-PlatformElectronNET.Coreاجرای Blazor/ASP.NET Core در پوسته Electron برای Windows/macOS/Linux
    موبایل Cross-PlatformIonic + Capacitorرابط WebView با دسترسی به APIهای بومی برای Android/iOS
    - -

    ۲.۲ نقش Microsoft.Extensions.AI

    - -

    این کتابخانه، یک لایه انتزاع برای مدل‌های زبانی فراهم می‌کند. مزایای کلیدی آن در معماری ما:

    - -
      -
    • - IChatClient — رابط یکپارچه مدل‌ها - امکان اتصال به هر ارائه‌دهنده مدل (Azure OpenAI، OpenAI، Ollama و...) بدون تغییر در منطق ایجنت. این انتزاع مستقیماً به نیازمندی «فهرست مجاز مدل‌ها» (محور ۲ نیازمندی‌ها) پاسخ می‌دهد: با تعریف چند IChatClient و اعمال محدودیت در لایه بالاتر، می‌توان مدل مجاز هر کاربر را کنترل کرد. -
    • -
    • - Middleware — تزریق دغدغه‌های عرضی - قابلیت تزریق Telemetry (OpenTelemetry)، Caching و Logging به خط لوله فراخوانی مدل. این ویژگی، پیاده‌سازی محور عرضی مشاهده‌پذیری (Y) را بدون تغییر در منطق اصلی ممکن می‌کند. -
    • -
    • - IEmbeddingGenerator — انتزاع Embedding - رابط یکپارچه برای تولید Embedding در جریان RAG، با قابلیت تعویض ارائه‌دهنده بدون تغییر در منطق بازیابی. -
    • -
    - -

    ۲.۳ نقش Microsoft Agent Framework

    - -

    این فریم‌ورک، نسل بعدی Semantic Kernel و AutoGen است و قابلیت‌های زیر را برای پیاده‌سازی لایه ارکستراسیون (L3) فراهم می‌کند:

    - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
    قابلیتکاربرد در معماری
    AIAgentهسته ایجنت؛ تولید برنامه، انتخاب ابزار، اجرا و اصلاح بر اساس نتیجه
    Agent Sessionمدیریت زمینه مکالمه (حافظه کوتاه‌مدت) — مولفه «حافظه و زمینه» در L4
    AIFunctionFactoryثبت ابزارها به‌عنوان توابع قابل فراخوانی توسط LLM — مولفه «انتخاب‌گر ابزار» در L3
    WorkflowBuilderگراف چند-ایجنت (Orchestrator-Worker) با Edges و شرایط — مولفه «مدیریت جریان» در L3
    MCP Clientکشف پویای ابزارها در زمان اجرا — توسعه‌پذیری لایه ابزار
    Middlewareنقاط تأیید انسانی (Human-in-the-loop) — مولفه «تأیید انسانی» در L3
    - -

    ۲.۴ رویکرد Cross-Platform

    - -

    رویکرد Cross-Platform با هدف کامپایل کدبیس واحد برای سکوهای مختلف طراحی شده است:

    - -
    -
    -
    دسکتاپ (Windows/macOS/Linux)
    -
      -
    • استفاده از ElectronNET.Core
    • -
    • اجرای پروژه ASP.NET Core/Blazor در پوسته Electron
    • -
    • کدبیس واحد .NET، خروجی اجرایی برای هر سه سکو
    • -
    • دسترسی کنترل‌شده به فایل‌های محلی
    • -
    -
    -
    -
    موبایل (Android/iOS)
    -
      -
    • استفاده از Ionic + Capacitor
    • -
    • رابط WebView با دسترسی به APIهای بومی
    • -
    • ارتباط با Backend .NET از طریق API
    • -
    • مناسب برای فرم‌ها، چت و داشبوردهای سبک
    • -
    -
    -
    - -
    - 💡 نکته معماری: رابط کاربری اصلی (چت، آپلود فایل، گزارش) در Blazor پیاده‌سازی می‌شود که هم در Electron (دسکتاپ) و هم در مرورگر (وب) قابل اجراست. نسخه موبایل Ionic صرفاً برای سناریوهای سبک (اعلان‌ها، تأییدات) استفاده می‌شود تا از پیچیدگی غیرضروری جلوگیری شود. -
    -
    -
    - -
    -
    -
    ۳
    -
    -

    نقشه راه پیاده‌سازی گام‌به‌گام به تفکیک مولفه‌ها

    -
    Step-by-Step Implementation Roadmap by Component
    -
    -
    -
    -

    پیاده‌سازی در پنج فاز اجرایی سازمان‌دهی شده است. هر فاز، مجموعه‌ای از مولفه‌های معماری را پوشش می‌دهد و با خروجی قابل‌آزمون پایان می‌یابد. ترتیب فازها بر اساس وابستگی فنی و اولویت ارزش‌آفرینی تعیین شده است.

    - - -
    -
    -
    A
    -
    -

    فاز A — هسته ایجنت و رابط پایه

    -
    Core Agent & Base UI
    -
    -
    -
    -

    این فاز، پایه‌ای‌ترین قابلیت محصول را می‌سازد: یک ایجنت که می‌تواند به مدل متصل شود، درخواست کاربر را دریافت کند و پاسخ دهد. بدون این فاز، هیچ قابلیت دیگری قابل ارائه نیست.

    - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
    مولفه معماریرویکرد پیاده‌سازیوابستگی
    درگاه مدل‌ها (L4)پیاده‌سازی Factory برای IChatClient؛ تعریف چند ارائه‌دهنده (Azure OpenAI، Ollama) و انتخاب بر اساس Configuration—
    موتور ایجنت (L3)ساخت AIAgent با استفاده از chatClient.AsAIAgent()؛ تعریف Instructions برای رفتار پایهدرگاه مدل‌ها
    رابط وب (L1)پیاده‌سازی Blazor Server برای چت پایه؛ اتصال به موتور ایجنت از طریق SignalRموتور ایجنت
    احراز هویت (L2)ASP.NET Core Identity + OIDC برای یکپارچه‌سازی با سامانه هویت سازمانی—
    درگاه API (L1)ASP.NET Core Minimal API برای دسترسی برنامه‌نویسی و یکپارچه‌سازیاحراز هویت
    - -

    خروجی قابل‌آزمون فاز A:

    -
      -
    • چت پایه با ایجنت: کاربر می‌تواند وارد شود، پرسش بپرسد و پاسخ از مدل دریافت کند
    • -
    • تعویض‌پذیری مدل: تغییر مدل از طریق Configuration بدون تغییر کد
    • -
    -
    -
    - - -
    -
    -
    B
    -
    -

    فاز B — ابزارها، RAG و منابع دانش

    -
    Tools, RAG & Knowledge Sources
    -
    -
    -
    -

    این فاز، ایجنت را از یک چت‌بات ساده به یک ایجنت واقعی تبدیل می‌کند: توانایی فراخوانی ابزار و جستجو در منابع دانش سازمانی.

    - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
    مولفه معماریرویکرد پیاده‌سازیوابستگی
    انتخاب‌گر ابزار (L3)ثبت ابزارها با AIFunctionFactory.Create()؛ تعریف Tool Registry برای مدیریت فهرست ابزارهای مجازموتور ایجنت
    ابزارهای عملیاتی (L5)پیاده‌سازی متدهای C# به‌عنوان Function Tools (جستجو، محاسبه، تبدیل و...)انتخاب‌گر ابزار
    RAG (L4)استفاده از IEmbeddingGenerator برای تولید Embedding؛ ذخیره در Vector Store؛ بازیابی با رعایت سطح دسترسیدرگاه مدل‌ها
    منابع دانش (L5)Indexer برای SharePoint/File System؛ Chunking و ذخیره در Vector StoreRAG
    مدیریت فایل (L5)File API با بررسی مجوز پیش از دسترسی؛ تحلیل چند فایلموتور مجوزها
    حافظه و زمینه (L4)استفاده از AgentSession برای حفظ زمینه مکالمه؛ مدیریت Context Windowموتور ایجنت
    - -

    خروجی قابل‌آزمون فاز B:

    -
      -
    • ایجنت ابزارمحور: ایجنت می‌تواند ابزار فراخوانی کند و نتیجه را در پاسخ به کار گیرد
    • -
    • RAG با ارجاع: پاسخ‌ها با ارجاع به منبع بازیابی‌شده ارائه می‌شوند
    • -
    • دسترسی کنترل‌شده به فایل: کاربر فقط به فایل‌های مجاز دسترسی دارد
    • -
    -
    -
    - - -
    -
    -
    C
    -
    -

    فاز C — حاکمیت داده و کنترل دسترسی

    -
    Data Governance & Access Control
    -
    -
    -
    -

    این فاز، پاسخ مستقیم به آزمون نفوذ دسترسی کارفرما (محور ۲ نیازمندی‌ها) است. بدون این فاز، محصول نمی‌تواند در محیط سازمانی حساس مورد استفاده قرار گیرد.

    - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
    مولفه معماریرویکرد پیاده‌سازیوابستگی
    موتور مجوزها (L2)Policy-based Authorization در ASP.NET Core؛ پیاده‌سازی ABAC برای کنترل تا سطح سند/رکورداحراز هویت
    مدیریت نقش‌ها (L2)تعریف نقش‌ها و مجوزها؛ تخصیص کاربران واحدهای مختلفاحراز هویت
    مدیریت نشست (L2)AgentSession + Distributed Cache برای حفظ سطح دسترسی فعال در طول تعاملموتور مجوزها
    سیاست‌گذار داده (X)تعریف و اعمال سیاست‌های ذخیره‌سازی، انتقال و آموزش مدل؛ Data Classification—
    سنسور محرمانگی (X)Output Filter پیش از ارائه پاسخ؛ شناسایی و جلوگیری از افشای اطلاعات خارج از سطح دسترسیموتور مجوزها
    ممیزی و لاگ (X)ثبت تمام تعاملات، تصمیمات ایجنت و دسترسی‌ها؛ Tamper-evident Logs—
    - -
    - ⚠️ نکته حیاتی: این فاز باید دفاع لایه‌ای را پیاده‌سازی کند: موتور مجوزها (پیش از فراخوانی مدل) و سنسور محرمانگی (پس از تولید پاسخ). این دو نقطه مستقل، تضمین می‌کنند که حتی اگر ایجنت یا مدل بخواهد اطلاعات خارج از دسترس را افشا کند، در دو نقطه مسدود شود. -
    - -

    خروجی قابل‌آزمون فاز C:

    -
      -
    • مدل دسترسی کامل: نقش‌ها، مجوزها و کنترل تا سطح رکورد
    • -
    • سناریوی آزمون نفوذ: پرسش یکسان با حساب‌های متفاوت + تلاش برای دور زدن مجوزها — قابل اجرا در جلسه دمو
    • -
    -
    -
    - - -
    -
    -
    D
    -
    -

    فاز D — گزارش، تأیید انسانی و مشاهده‌پذیری

    -
    Reporting, Human-in-the-loop & Observability
    -
    -
    -
    -

    این فاز، محصول را از یک ابزار تحلیلی به یک محصول سازمانی کامل تبدیل می‌کند.

    - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
    مولفه معماریرویکرد پیاده‌سازیوابستگی
    مدیریت جریان (L3)WorkflowBuilder برای گراف چندمرحله‌ای؛ تعریف Edges و شرایط ادامه/اصلاحموتور ایجنت
    تأیید انسانی (L3)Middleware در Agent Framework برای توقف در نقاط حساس؛ Approval API برای دریافت تأییدمدیریت جریان
    تولید گزارش (L6)Razor + QuestPDF/ClosedXML برای تولید خروجی متنی، جدولی و نموداری با ارجاع به منابعموتور ایجنت
    مبدل قالب (L6)تبدیل خروجی به Word، Excel و PDFتولید گزارش
    داشبورد مصرف (L6)Metrics + Blazor Dashboard برای نمایش مصرف و هزینه به تفکیک کاربر، مدل و ایجنتمتریک و ردیابی
    متریک و ردیابی (Y)OpenTelemetry + Serilog برای اندازه‌گیری مصرف توکن، زمان پاسخ و نرخ خطا—
    - -

    خروجی قابل‌آزمون فاز D:

    -
      -
    • گزارش کامل با ارجاع: خروجی Word/Excel با منابع
    • -
    • جریان چندمرحله‌ای با تأیید انسانی: قابل نمایش در جلسه دمو
    • -
    • داشبورد مصرف: شفافیت هزینه به تفکیک کاربر/مدل
    • -
    -
    -
    - - -
    -
    -
    E
    -
    -

    فاز E — Cross-Platform و آماده‌سازی محصول

    -
    Cross-Platform & Product Readiness
    -
    -
    -
    -

    این فاز نهایی، محصول را برای ارائه در سکوهای مختلف و آماده‌سازی برای استقرار سازمانی آماده می‌کند.

    - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
    مولفهرویکرد پیاده‌سازیوابستگی
    نسخه دسکتاپ (L1)ElectronNET.Core برای بسته‌بندی Blazor در پوسته Electron برای Windows/macOS/Linuxرابط وب
    نسخه موبایل (L1)Ionic + Capacitor برای سناریوهای سبک (اعلان، تأیید)درگاه API
    مدیریت مدل (L4)Model Registry برای نسخه‌بندی و سیاست دسترسی به مدل‌های جدیددرگاه مدل‌ها
    استقرار On-Premiseپشتیبانی از مدل‌های محلی (Ollama) برای عملکرد در قطع اینترنت بین‌المللدرگاه مدل‌ها
    - -

    خروجی قابل‌آزمون فاز E:

    -
      -
    • محصول Cross-Platform: نسخه وب + دسکتاپ + موبایل از کدبیس واحد
    • -
    • تاب‌آوری: عملکرد در شرایط قطع اینترنت بین‌الملل
    • -
    -
    -
    - -
    - ✓ نکته کلیدی: فازهای A تا C، پاسخ به محورهای ۱، ۲ و ۵ نیازمندی‌ها هستند و آمادگی برای جلسه دمو و آزمون عملی کارفرما را فراهم می‌کنند. فازهای D و E، محصول را برای استقرار بلندمدت و پاسخ به محورهای ۴، ۶ و ۷ آماده می‌سازند. -
    -
    -
    - -
    -
    -
    ۴
    -
    -

    تیم، تخصص‌ها و مهارت‌های موردنیاز

    -
    Team, Expertise & Required Skills
    -
    -
    -
    -

    پیاده‌سازی این معماری نیازمند تیمی چندنقشی با هم‌پوشانی مهارت‌هاست. جدول زیر نقش‌ها، تخصص‌ها و سطح مهارت موردنیاز را نشان می‌دهد:

    - -

    ۴.۱ جدول نقش‌ها و مهارت‌ها

    - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
    نقشتخصص اصلیمهارت‌های کلیدیسطحتعداد
    معمار ارشدطراحی سیستم‌های توزیع‌شده.NET، Agent Framework، الگوهای طراحی، BPMNخبره۱
    توسعه‌دهنده Backend (ایجنت)Microsoft Agent FrameworkAIAgent، AIFunctionFactory، WorkflowBuilder، MCPپیشرفته۲
    توسعه‌دهنده Backend (داده/RAG)RAG و Vector StoreIEmbeddingGenerator، Chunking، Retrievalپیشرفته۱
    توسعه‌دهنده Frontend (Blazor)Blazor + ElectronNETBlazor Server/WASM، CSS، ElectronNETپیشرفته۲
    توسعه‌دهنده موبایل (Ionic)Ionic + CapacitorTypeScript، Angular/React، Capacitor APIمیانی۱
    مهندس امنیتIAM و حاکمیت دادهOAuth 2.0، OIDC، Policy-based Auth، OWASP LLM Top 10پیشرفته۱
    مهندس DevOpsCI/CD و مشاهده‌پذیری.NET Build، OpenTelemetry، Dockerپیشرفته۱
    مهندس تستتست ایجنت و RAGxUnit، Test Containers، Scenario Testingمیانی۱
    - -
    -
    -
    ۱۰
    -
    نفر برای پیاده‌سازی کامل
    -
    -
    -
    ۴
    -
    نفر برای شروع سریع (فاز A)
    -
    -
    -
    ۲
    -
    نقش حیاتی (معمار + ایجنت)
    -
    -
    - -

    ۴.۲ نکات کلیدی تیم

    - -
      -
    • - نقش «توسعه‌دهنده Backend (ایجنت)» حیاتی‌ترین نقش است - این نقش باید به‌طور کامل بر Microsoft Agent Framework مسلط باشد. تسلط بر Semantic Kernel به‌عنوان پیش‌نیاز توصیه می‌شود، زیرا Agent Framework نسل بعدی آن است. -
    • -
    • - معمار ارشد باید هم‌زمان بر .NET و مفاهیم AI مسلط باشد - صرف تسلط بر معماری نرم‌افزار کافی نیست؛ درک عمیق از RAG، Agentic Patterns و محدودیت‌های مدل‌های زبانی ضروری است. -
    • -
    • - مهندس امنیت باید با OWASP LLM Top 10 آشنا باشد - به‌ویژه LLM01 (Prompt Injection) و LLM02 (Sensitive Information Disclosure) که مستقیماً به آزمون نفوذ دسترسی کارفرما مرتبط است. -
    • -
    • - تیم حداقلی برای شروع (فاز A) - معمار ارشد + ۲ توسعه‌دهنده Backend (ایجنت) + ۱ توسعه‌دهنده Blazor = ۴ نفر. این تیم می‌تواند اثبات مفهوم (PoC) را در ۴ تا ۶ هفته ارائه دهد. -
    • -
    -
    -
    - -
    -
    -
    ۵
    -
    -

    ارزش‌آفرینی محصول و معیارهای استاندارد اندازه‌گیری

    -
    Value Creation & Standard Measurement Metrics
    -
    -
    -
    -

    ارزش این محصول را می‌توان بر اساس معیارهای استاندارد اندازه‌گیری کرد. رویکرد ما، استفاده از چارچوب ROI و شاخص‌های کلیدی عملکرد (KPI) است تا ارزش‌آفرینی قابل اثبات و قابل پیگیری باشد.

    - -

    ۵.۱ معیارهای استاندارد اندازه‌گیری ارزش

    - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
    معیارشاخص (KPI)روش اندازه‌گیری
    کارایی عملیاتیکاهش زمان جستجو و تحلیل اسناد (Time-to-Answer)مقایسه زمان قبل/بعد از استقرار
    دقت تصمیمنرخ پاسخ صحیح با ارجاع به منبع (Precision/Recall)ارزیابی نمونه‌ای دوره‌ای
    صرفه‌جویی هزینهکاهش ساعت نیروی انسانی صرف‌شدهمحاسبه ROI (ساعت صرفه‌جویی × نرخ ساعتی)
    رضایت کاربرNPS یا CSAT کاربران سازمانینظرسنجی دوره‌ای
    تاب‌آوریUptime و MTTR (میانگین زمان بازیابی)پایش SLO
    انطباق و امنیتنرخ موفقیت در آزمون نفوذ دسترسیآزمون دوره‌ای (محور ۲ نیازمندی‌ها)
    - -
    - فرمول ROI: بر اساس چارچوب استاندارد ROI، بازگشت سرمایه به‌صورت زیر محاسبه می‌شود:

    - ROI% = [(مجموع منافع) − (هزینه دستیابی + هزینه نگهداری)] ÷ (هزینه دستیابی + هزینه نگهداری) × ۱۰۰ -
    - -

    ۵.۲ ارزش‌های کلیدی برای سازمان

    - -
    - - -
    - -
    -
    -

    کاهش ریسک افشا

    -
      -
    • دفاع لایه‌ای دو نقطه مستقل
    • -
    • ممیزی کامل
    • -
    • انطباق OWASP LLM
    • -
    -
    -
    -

    تاب‌آوری در شرایط تحریم

    -
      -
    • استقرار On-Premise
    • -
    • مدل محلی Ollama
    • -
    • قطع اینترنت بدون اختلال
    • -
    -
    -
    - -

    ۵.۳ تخمین کمی ارزش (نمونه)

    - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
    سناریوفرضصرفه‌جویی سالانه تخمینی
    جستجوی اسناد۵۰ کاربر × ۲ ساعت/هفته صرفه‌جویی۵,۲۰۰ ساعت/سال
    تحلیل قراردادها۲۰ سند/ماه × ۳ ساعت صرفه‌جویی۷۲۰ ساعت/سال
    تولید گزارش۱۰۰ گزارش/سال × ۴ ساعت صرفه‌جویی۴۰۰ ساعت/سال
    جمع صرفه‌جویی—۶,۳۲۰ ساعت/سال
    - -
    - 💡 نکته: با نرخ ساعتی فرضی، بازگشت سرمایه (ROI) معمولاً در ۶ تا ۱۲ ماه قابل تحقق است. این تخمین بر اساس سناریوهای محافظه‌کارانه محاسبه شده و با گسترش استفاده، ارزش واقعی افزایش می‌یابد. -
    -
    -
    - -
    -
    -
    ۶
    -
    -

    جمع‌بندی و گام بعدی

    -
    Summary & Next Step
    -
    -
    -
    -

    این مستند، نقشه راه عملیاتی پیاده‌سازی معماری سامانه هوش مصنوعی سازمانی را با استک .NET + Microsoft.Extensions.AI + Microsoft Agent Framework ارائه داد. جمع‌بندی ویژگی‌های کلیدی:

    - -
      -
    • - استک فنی یکپارچه - Microsoft.Extensions.AI برای انتزاع مدل‌ها، Microsoft Agent Framework برای ارکستراسیون ایجنت، و رویکرد Cross-Platform با ElectronNET (دسکتاپ) و Ionic (موبایل) -
    • -
    • - پنج فاز اجرایی گام‌به‌گام - فاز A (هسته ایجنت) → فاز B (ابزار و RAG) → فاز C (حاکمیت و دسترسی) → فاز D (گزارش و مشاهده‌پذیری) → فاز E (Cross-Platform) -
    • -
    • - تیم ۱۰ نفره - با حداقل ۴ نفر برای شروع سریع (فاز A) در بازه ۴ تا ۶ هفته -
    • -
    • - ارزش‌آفرینی قابل اندازه‌گیری - بر اساس معیارهای استاندارد (کارایی، دقت، هزینه، رضایت، تاب‌آوری، انطباق) و فرمول ROI -
    • -
    • - انطباق با نیازمندی‌ها - فازهای A تا C آمادگی برای جلسه دمو و آزمون عملی کارفرما را فراهم می‌کنند -
    • -
    - -
    -

    🎯 گام بعدی پیشنهادی

    -

    پیاده‌سازی فاز A (هسته: درگاه مدل + موتور ایجنت + رابط Blazor + احراز هویت) به‌عنوان اثبات مفهوم (PoC) در بازه ۴ تا ۶ هفته.

    -

    سپس ارائه در جلسه دمو به کارفرما با تمرکز بر فازهای A تا C برای پاسخ به محورهای ۱، ۲ و ۵ نیازمندی‌ها.

    -
    - 💎 ارزش پیشنهادی:
    - استک یکپارچه .NET + Agent Framework + Cross-Platform + تیم ۱۰ نفره + ارزش‌آفرینی قابل اندازه‌گیری -
    -
    - -
    - 📞 گام بعدی: در صورت تمایل به شروع همکاری، آماده برگزاری جلسه فنی برای تشریح جزئیات فاز A و زمان‌بندی PoC هستم. پیش‌نویس قرارداد نیز بر اساس توافقات حاصله آماده امضا می‌باشد. -
    -
    -
    - -
    - این مستند محرمانه بوده و صرفاً جهت ارائه به کارفرمای محترم تهیه شده است. هرگونه کپی‌برداری یا افشا بدون اجازه کتبی ممنوع است. -
    - -
    - -
    - - -
    تاریخ تهیه: مهر ۱۴۰۵  |  نسخه: ۱.۰  |  طبقه‌بندی: محرمانه
    -
    - -
    - - - - -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\xAiApi\wwwroot\Storage\Uploads\Document\xSaherElm_8404e5e6-f5fb-4c8f-876e-a293cda84af9.html - - - - - - -نقشه راه دانش فنی | از معماری تا محصول - - - - -
    - -
    -
    -
    - -
    -
    -
    شماره مستند: ROAD-1405-001
    -
    نسخه: ۱.۰
    -
    تاریخ تهیه: آبان ۱۴۰۵
    -
    طبقه‌بندی: محرمانه
    -
    -
    - -
    - TECHNICAL KNOWLEDGE ROADMAP -

    نقشه راه دانش فنی

    -

    از معماری تا محصول — سامانه هوش مصنوعی سازمانی

    -
    -
    - -
    - -
    - خلاصه مدیریتی،
    - این مستند، نقشه راه کسب دانش فنی لازم برای پیاده‌سازی معماری کلان سامانه هوش مصنوعی سازمانی (مستند ARCH-1405-001) و تبدیل آن به محصول قابل ارائه را ترسیم می‌کند. رویکرد این نقشه راه فارغ از سکو است؛ یعنی هیچ زبان برنامه‌نویسی، استک عملیاتی یا ابزار خاصی پیشنهاد نمی‌شود. تمرکز بر استانداردها و الگوهای طراحی و پیاده‌سازی است و مسیر از پایه‌ای‌ترین مباحث تا مباحث کلان معماری را پوشش می‌دهد. هدف، ایجاد توانمندی پایدار در تیم فنی برای پیاده‌سازی، نگهداری و تکامل محصول است. -
    - -
    -
    -
    ۱
    -
    -

    اصول حاکم بر نقشه راه

    -
    Guiding Principles
    -
    -
    -
    -

    این نقشه راه بر پایه اصول زیر طراحی شده است که مستقیماً از الزامات شما و ماهیت معماری محصول استخراج شده‌اند:

    - -
    -
    -
    ◇
    -
    فارغ از سکو
    -

    هیچ زبان، فریم‌ورک یا استک خاصی توصیه نمی‌شود؛ تمرکز بر مفاهیم و الگوهای قابل انتقال.

    -
    -
    -
    ◎
    -
    استانداردمحوری
    -

    تکیه بر استانداردهای شناخته‌شده (BPMN 2.0، OAuth 2.0، OpenID Connect، OWASP، ISO 42001، NIST AI RMF و...).

    -
    -
    -
    ▤
    -
    الگومحوری
    -

    یادگیری الگوهای طراحی و معماری (لایه‌ای، رویدادمحور، Hexagonal، CQRS، Circuit Breaker و...).

    -
    -
    -
    ↑
    -
    از پایه تا کلان
    -

    شروع از مبانی (داده، شبکه، امنیت) و حرکت تدریجی به سمت معماری کلان و حاکمیت.

    -
    -
    -
    ⟳
    -
    یادگیری تدریجی
    -

    مسیر پیوسته با نقاط عطف مشخص؛ هر فاز، پیش‌نیاز فاز بعدی است.

    -
    -
    -
    ✓
    -
    قابلیت اثبات
    -

    هر فاز با خروجی قابل‌آزمون (Deliverable) پایان می‌یابد تا دانش به مهارت تبدیل شود.

    -
    -
    - -
    - اصل حاکم: هدف این نقشه راه، تربیت معمار و مهندس توانمند است، نه صرفاً آموزش ابزار. بنابراین، در هر فاز، «چرایی» و «الگو» بر «چگونگی ابزار» مقدم است. این رویکرد تضمین می‌کند که دانش کسب‌شده با تغییر سکوها و ابزارها از بین نرود. -
    -
    -
    - -
    -
    -
    ۲
    -
    -

    نمای کلی نقشه راه

    -
    Roadmap Overview
    -
    -
    -
    -

    نقشه راه در هفت فاز سازمان‌دهی شده است. هر فاز دارای موضوعات کلیدی، استانداردهای مرتبط و خروجی قابل‌آزمون است. فازها به‌صورت پیوسته طراحی شده‌اند؛ اما تیم‌های با تجربه‌تر می‌توانند برخی موضوعات فازهای ابتدایی را به‌صورت موازی مرور کنند.

    - -
    -
    -
    ۷
    -
    فاز اصلی
    -
    -
    -
    ۴۰+
    -
    موضوع کلیدی
    -
    -
    -
    ۲۵+
    -
    استاندارد و الگو
    -
    -
    - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
    فازعنوانتمرکز اصلیسطح
    ۱مبانی سیستم‌ها و دادهشبکه، داده، مدل داده، رمزنگاری پایهپایه
    ۲مبانی مهندسی نرم‌افزارالگوهای طراحی، معماری تمیز، آزمون‌پذیریپایه
    ۳مبانی هوش مصنوعی و مدل‌هامدل‌های زبانی، Embedding، RAG، ارزیابیمیانی
    ۴معماری سیستم‌های توزیع‌شدهلایه‌بندی، رویدادمحوری، تاب‌آوری، مقیاس‌پذیریمیانی
    ۵معماری ایجنت و ارکستراسیونبرنامه‌ریزی، انتخاب ابزار، حلقه بازخورد، Human-in-the-loopپیشرفته
    ۶امنیت، حاکمیت داده و انطباقOAuth، RBAC/ABAC، محرمانگی، ممیزی، ISO 42001پیشرفته
    ۷معماری کلان، محصول و عملیاتمعماری سازمانی، SRE، مشاهده‌پذیری، مدیریت محصولخبره
    - -
    - 💡 نکته: ترتیب فازها بر اساس وابستگی دانشی است، نه ترتیب زمانی دقیق. تیم‌های با تجربه می‌توانند فازهای ۱ و ۲ را به‌صورت فشرده مرور کنند و تمرکز اصلی را بر فازهای ۳ تا ۷ بگذارند. -
    -
    -
    - -
    -
    -
    ۳
    -
    -

    فاز ۱: مبانی سیستم‌ها و داده

    -
    Phase 1 — Foundations of Systems & Data
    -
    -
    -
    -
    -
    -
    ۱
    -
    -

    مبانی سیستم‌ها و داده

    -
    پایه‌ای‌ترین لایه دانش — پیش‌نیاز همه فازها
    -
    -
    -
    -

    این فاز، پایه‌ای‌ترین دانش لازم برای درک هر سیستم نرم‌افزاری و داده‌محور را فراهم می‌کند. بدون تسلط بر این مبانی، درک لایه‌های بالاتر معماری (به‌ویژه حاکمیت داده و امنیت) ناقص خواهد بود.

    - -
    -
    -
    مبانی شبکه و ارتباطات
    -
      -
    • مدل OSI و TCP/IP
    • -
    • HTTP/HTTPS، REST، gRPC (مفهومی)
    • -
    • وب‌سوکت و ارتباطات بلادرنگ
    • -
    • مفاهیم پروکسی، فایروال و DMZ
    • -
    -
    -
    -
    مبانی داده
    -
      -
    • مدل داده رابطه‌ای و NoSQL (مفهومی)
    • -
    • نرمال‌سازی و مدل‌سازی داده
    • -
    • تراکنش و ACID
    • -
    • مفاهیم Data Lake و Data Warehouse
    • -
    -
    -
    -
    مبانی رمزنگاری
    -
      -
    • رمزنگاری متقارن و نامتقارن
    • -
    • هش و امضای دیجیتال
    • -
    • TLS و مدیریت گواهی
    • -
    • مدیریت کلید (Key Management)
    • -
    -
    -
    -
    مبانی سیستم‌عامل و منابع
    -
      -
    • مدیریت پردازش و حافظه
    • -
    • سیستم فایل و مجوزها
    • -
    • مفاهیم Container و مجازی‌سازی
    • -
    • مدیریت منابع (CPU، RAM، I/O)
    • -
    -
    -
    - -

    استانداردها و مراجع کلیدی:

    -
    - RFC 7230 (HTTP) - RFC 8446 (TLS 1.3) - ISO/IEC 27001 (مبانی امنیت) - NIST SP 800-57 (مدیریت کلید) -
    - -

    خروجی قابل‌آزمون (Deliverable):

    -
      -
    • نقشه مفهومی داده سازمان: شناسایی منابع داده، جریان‌ها و مالکیت داده
    • -
    • سند مدل تهدید پایه: شناسایی دارایی‌ها، تهدیدها و کنترل‌های پایه امنیتی
    • -
    -
    -
    -
    -
    - -
    -
    -
    ۴
    -
    -

    فاز ۲: مبانی مهندسی نرم‌افزار

    -
    Phase 2 — Software Engineering Foundations
    -
    -
    -
    -
    -
    -
    ۲
    -
    -

    مبانی مهندسی نرم‌افزار

    -
    الگوهای طراحی، معماری تمیز و آزمون‌پذیری
    -
    -
    -
    -

    این فاز، دانش پایه‌ای مهندسی نرم‌افزار را فراهم می‌کند که برای پیاده‌سازی هر لایه از معماری (از رابط کاربری تا موتور ایجنت) ضروری است. تمرکز بر الگوها است، نه ابزارها.

    - -
    -
    -
    اصول طراحی (SOLID و فراتر)
    -
      -
    • اصول SOLID
    • -
    • DRY، KISS، YAGNI
    • -
    • Separation of Concerns
    • -
    • Dependency Inversion
    • -
    -
    -
    -
    الگوهای طراحی کلاسیک
    -
      -
    • الگوهای سازنده (Factory، Builder)
    • -
    • الگوهای ساختاری (Adapter، Facade)
    • -
    • الگوهای رفتاری (Strategy، Observer)
    • -
    • الگوهای معماری (MVC، MVVM، Clean)
    • -
    -
    -
    -
    معماری تمیز و Hexagonal
    -
      -
    • لایه‌بندی و جهت وابستگی
    • -
    • Ports & Adapters
    • -
    • جداسازی دامنه از زیرساخت
    • -
    • قابلیت تعویض مؤلفه‌ها
    • -
    -
    -
    -
    آزمون‌پذیری
    -
      -
    • هرم آزمون (Unit/Integration/E2E)
    • -
    • Test Double (Mock، Stub، Fake)
    • -
    • Test-Driven Design (مفهومی)
    • -
    • Contract Testing
    • -
    -
    -
    - -

    استانداردها و مراجع کلیدی:

    -
    - Clean Architecture (Robert C. Martin) - Hexagonal Architecture (Alistair Cockburn) - GoF Design Patterns - ISO/IEC 25010 (کیفیت نرم‌افزار) -
    - -

    خروجی قابل‌آزمون (Deliverable):

    -
      -
    • سند اصول و الگوهای منتخب: تعیین الگوهای پایه برای هر لایه معماری
    • -
    • نمونه اولیه ساختار Hexagonal: پیاده‌سازی یک مؤلفه نمونه با Ports & Adapters
    • -
    -
    -
    -
    -
    - -
    -
    -
    ۵
    -
    -

    فاز ۳: مبانی هوش مصنوعی و مدل‌ها

    -
    Phase 3 — AI & Model Foundations
    -
    -
    -
    -
    -
    -
    ۳
    -
    -

    مبانی هوش مصنوعی و مدل‌ها

    -
    مدل‌های زبانی، Embedding، RAG و ارزیابی
    -
    -
    -
    -

    این فاز، دانش تخصصی هوش مصنوعی و مدل‌های زبانی را فراهم می‌کند که مستقیماً به لایه هوش (L4) معماری مرتبط است. تمرکز بر درک مفهومی و الگوهای استفاده است، نه پیاده‌سازی مدل از صفر.

    - -
    -
    -
    مبانی مدل‌های زبانی
    -
      -
    • معماری Transformer (مفهومی)
    • -
    • توکن‌سازی و Embedding
    • -
    • Temperature، Top-p، Context Window
    • -
    • تفاوت مدل‌های Base و Instruct
    • -
    -
    -
    -
    الگوهای استفاده از مدل
    -
      -
    • Prompt Engineering اصولی
    • -
    • Few-shot و Chain-of-Thought
    • -
    • Structured Output (JSON Mode)
    • -
    • Function Calling / Tool Use
    • -
    -
    -
    -
    بازیابی و تقویت (RAG)
    -
      -
    • مفاهیم Vector Database
    • -
    • Chunking و Indexing
    • -
    • Retrieval Strategies
    • -
    • Citation و Source Attribution
    • -
    -
    -
    -
    ارزیابی و کیفیت
    -
      -
    • معیارهای ارزیابی پاسخ
    • -
    • Hallucination Detection
    • -
    • Benchmarking مدل‌ها
    • -
    • A/B Testing برای Prompt
    • -
    -
    -
    -
    مدیریت مدل
    -
      -
    • نسخه‌بندی مدل‌ها
    • -
    • مدل‌های داخلی در برابر خارجی
    • -
    • هزینه و مصرف توکن
    • -
    • سیاست دسترسی به مدل‌های جدید
    • -
    -
    -
    -
    اخلاق و مخاطرات AI
    -
      -
    • Bias و Fairness
    • -
    • Privacy در مدل‌ها
    • -
    • Explainability
    • -
    • مسئولیت‌پذیری
    • -
    -
    -
    - -

    استانداردها و مراجع کلیدی:

    -
    - NIST AI RMF - ISO/IEC 42001 (مدیریت AI) - OECD AI Principles - Attention Is All You Need (مرجع Transformer) -
    - -

    خروجی قابل‌آزمون (Deliverable):

    -
      -
    • سند ارزیابی مدل‌ها: مقایسه مدل‌های نامزد بر اساس معیارهای کیفیت، هزینه و حاکمیت
    • -
    • نمونه اولیه RAG: پیاده‌سازی یک جریان بازیابی و تقویت با ارجاع به منبع
    • -
    -
    -
    -
    -
    - -
    -
    -
    ۶
    -
    -

    فاز ۴: معماری سیستم‌های توزیع‌شده

    -
    Phase 4 — Distributed Systems Architecture
    -
    -
    -
    -
    -
    -
    ۴
    -
    -

    معماری سیستم‌های توزیع‌شده

    -
    لایه‌بندی، رویدادمحوری، تاب‌آوری و مقیاس‌پذیری
    -
    -
    -
    -

    این فاز، دانش معماری سیستم‌های توزیع‌شده را فراهم می‌کند که برای پیاده‌سازی لایه‌های L1 تا L6 و محورهای عرضی ضروری است. تمرکز بر الگوهای معماری است، نه محصولات خاص.

    - -
    -
    -
    الگوهای معماری لایه‌ای
    -
      -
    • Layered Architecture
    • -
    • Hexagonal / Ports & Adapters
    • -
    • Microservices و Modular Monolith
    • -
    • API Gateway Pattern
    • -
    -
    -
    -
    رویدادمحوری و پیام‌رسانی
    -
      -
    • Event-Driven Architecture
    • -
    • Publish-Subscribe Pattern
    • -
    • Event Sourcing و CQRS (مفهومی)
    • -
    • Saga Pattern برای تراکنش‌های توزیع‌شده
    • -
    -
    -
    -
    تاب‌آوری (Resilience)
    -
      -
    • Circuit Breaker
    • -
    • Retry و Backoff
    • -
    • Bulkhead و Rate Limiting
    • -
    • Graceful Degradation
    • -
    -
    -
    -
    مقیاس‌پذیری و عملکرد
    -
      -
    • Load Balancing (مفهومی)
    • -
    • Caching Strategies
    • -
    • Async Processing
    • -
    • Backpressure
    • -
    -
    -
    -
    هماهنگی توزیع‌شده
    -
      -
    • Service Discovery
    • -
    • Configuration Management
    • -
    • Distributed Locking
    • -
    • Idempotency
    • -
    -
    -
    -
    مشاهده‌پذیری (Observability)
    -
      -
    • Logging، Metrics، Tracing
    • -
    • OpenTelemetry (مفهومی)
    • -
    • Health Check و Readiness
    • -
    • Alerting Strategies
    • -
    -
    -
    - -

    استانداردها و مراجع کلیدی:

    -
    - Enterprise Integration Patterns (Hohpe & Woolf) - Release It! (Michael Nygard) - OpenTelemetry Specification - BPMN 2.0 (برای مدل‌سازی فرایند) -
    - -

    خروجی قابل‌آزمون (Deliverable):

    -
      -
    • سند الگوهای معماری منتخب: تعیین الگوهای لایه‌بندی، رویدادمحوری و تاب‌آوری برای هر لایه
    • -
    • نقشه BPMN2 تکمیلی: به‌روزرسانی نقشه فرایندی با الگوهای تاب‌آوری و خطا
    • -
    -
    -
    -
    -
    - -
    -
    -
    ۷
    -
    -

    فاز ۵: معماری ایجنت و ارکستراسیون

    -
    Phase 5 — Agent Architecture & Orchestration
    -
    -
    -
    -
    -
    -
    ۵
    -
    -

    معماری ایجنت و ارکستراسیون

    -
    هسته تمایز محصول — برنامه‌ریزی، انتخاب ابزار و حلقه بازخورد
    -
    -
    -
    -

    این فاز، تخصصی‌ترین بخش نقشه راه است و مستقیماً به لایه ارکستراسیون (L3) و پاسخ به محور ۱ نیازمندی‌های کارفرما مرتبط می‌شود. تمرکز بر الگوهای طراحی ایجنت و قابلیت آزمون است.

    - -
    -
    -
    مفاهیم پایه ایجنت
    -
      -
    • تفاوت Agent، Assistant و Workflow
    • -
    • حلقه تصمیم‌گیری (Observe-Think-Act)
    • -
    • Autonomy Levels
    • -
    • Goal vs Task vs Step
    • -
    -
    -
    -
    الگوهای برنامه‌ریزی
    -
      -
    • ReAct (Reasoning + Acting)
    • -
    • Plan-and-Execute
    • -
    • Tree of Thoughts
    • -
    • Reflexion و Self-Correction
    • -
    -
    -
    -
    مدیریت ابزار (Tool Use)
    -
      -
    • Tool Registry و Discovery
    • -
    • Tool Selection Strategies
    • -
    • Tool Result Validation
    • -
    • Error Handling در ابزار
    • -
    -
    -
    -
    حافظه و زمینه
    -
      -
    • Short-term vs Long-term Memory
    • -
    • Context Window Management
    • -
    • Summarization Strategies
    • -
    • Memory Isolation بر اساس دسترسی
    • -
    -
    -
    -
    Human-in-the-loop
    -
      -
    • نقاط تأیید انسانی
    • -
    • Approval Workflows
    • -
    • Escalation Patterns
    • -
    • Audit Trail تصمیمات
    • -
    -
    -
    -
    چند-ایجنت (Multi-Agent)
    -
      -
    • Orchestrator-Worker Pattern
    • -
    • Agent Communication Protocols
    • -
    • Shared Memory و Coordination
    • -
    • Conflict Resolution
    • -
    -
    -
    -
    ارزیابی ایجنت
    -
      -
    • Task Success Rate
    • -
    • Step Efficiency
    • -
    • Error Recovery Rate
    • -
    • Scenario-based Testing
    • -
    -
    -
    -
    ایمنی و کنترل
    -
      -
    • Guardrails و Constraints
    • -
    • Action Whitelisting
    • -
    • Sandboxing (مفهومی)
    • -
    • Kill Switch و Rollback
    • -
    -
    -
    - -

    استانداردها و مراجع کلیدی:

    -
    - ReAct (Yao et al.) - Reflexion (Shinn et al.) - Model Context Protocol (MCP) — مفهومی - NIST AI RMF (بخش کنترل) -
    - -

    خروجی قابل‌آزمون (Deliverable):

    -
      -
    • سناریوی نمونه Agent: پیاده‌سازی یک سناریوی چندمرحله‌ای با ابزار، خطا و مداخله انسانی — قابل ارائه در جلسه دمو
    • -
    • چارچوب ارزیابی ایجنت: معیارها و روش‌های آزمون رفتار ایجنت
    • -
    -
    -
    -
    -
    - -
    -
    -
    ۸
    -
    -

    فاز ۶: امنیت، حاکمیت داده و انطباق

    -
    Phase 6 — Security, Data Governance & Compliance
    -
    -
    -
    -
    -
    -
    ۶
    -
    -

    امنیت، حاکمیت داده و انطباق

    -
    محور عرضی حاکمیت — پاسخ به آزمون نفوذ کارفرما
    -
    -
    -
    -

    این فاز، دانش لازم برای پیاده‌سازی محور عرضی حاکمیت داده (X) و پاسخ به محورهای ۲ و ۵ نیازمندی‌های کارفرما را فراهم می‌کند. تمرکز بر الگوهای امنیتی و استانداردهای انطباق است.

    - -
    -
    -
    احراز هویت و مجوزدهی
    -
      -
    • OAuth 2.0 و OpenID Connect
    • -
    • JWT و Session Management
    • -
    • RBAC (نقش‌محور)
    • -
    • ABAC (ویژگی‌محور)
    • -
    -
    -
    -
    کنترل دسترسی پیشرفته
    -
      -
    • ReBAC (رابطه‌محور)
    • -
    • Fine-grained Access Control
    • -
    • Row-level و Document-level Security
    • -
    • Policy-as-Code
    • -
    -
    -
    -
    محرمانگی داده
    -
      -
    • Data Classification
    • -
    • Data Loss Prevention (DLP)
    • -
    • Data Masking و Redaction
    • -
    • Output Filtering (سنسور محرمانگی)
    • -
    -
    -
    -
    ممیزی و ردگیری
    -
      -
    • Audit Logging
    • -
    • Tamper-evident Logs
    • -
    • Traceability تصمیمات
    • -
    • Retention Policies
    • -
    -
    -
    -
    امنیت مدل و AI
    -
      -
    • Prompt Injection
    • -
    • Jailbreak Detection
    • -
    • Data Poisoning (مفهومی)
    • -
    • Model Inversion و Extraction
    • -
    -
    -
    -
    انطباق و حاکمیت
    -
      -
    • ISO/IEC 27001
    • -
    • ISO/IEC 42001 (مدیریت AI)
    • -
    • NIST AI RMF
    • -
    • GDPR (مفهومی) و قوانین داخلی
    • -
    -
    -
    -
    امنیت زیرساخت
    -
      -
    • OWASP Top 10
    • -
    • OWASP API Security Top 10
    • -
    • OWASP LLM Top 10
    • -
    • Secure by Design
    • -
    -
    -
    -
    حاکمیت داده سازمانی
    -
      -
    • Data Ownership و Stewardship
    • -
    • Data Lineage
    • -
    • Data Quality Management
    • -
    • Policy Enforcement Points
    • -
    -
    -
    - -

    استانداردها و مراجع کلیدی:

    -
    - OAuth 2.0 (RFC 6749) - OpenID Connect Core - OWASP Top 10 / API / LLM - ISO/IEC 27001 - ISO/IEC 42001 - NIST AI RMF -
    - -

    خروجی قابل‌آزمون (Deliverable):

    -
      -
    • سند مدل دسترسی و حاکمیت داده: تعریف نقش‌ها، سطوح دسترسی و سیاست‌های داده
    • -
    • سناریوی آزمون نفوذ دسترسی: طراحی آزمون‌های پرسش مستقیم/غیرمستقیم برای اثبات عدم افشا — قابل اجرا در جلسه دمو
    • -
    -
    -
    -
    -
    - -
    -
    -
    ۹
    -
    -

    فاز ۷: معماری کلان، محصول و عملیات

    -
    Phase 7 — Enterprise Architecture, Product & Operations
    -
    -
    -
    -
    -
    -
    ۷
    -
    -

    معماری کلان، محصول و عملیات

    -
    از معماری به محصول قابل ارائه و پایدار
    -
    -
    -
    -

    این فاز، دانش لازم برای تبدیل معماری به محصول قابل ارائه و عملیات پایدار را فراهم می‌کند. تمرکز بر معماری سازمانی، مدیریت محصول و عملیات است.

    - -
    -
    -
    معماری سازمانی
    -
      -
    • TOGAF (مفهومی)
    • -
    • Zachman Framework (مفهومی)
    • -
    • Architecture Decision Records (ADR)
    • -
    • Capability Mapping
    • -
    -
    -
    -
    مدیریت محصول
    -
      -
    • Product Vision و Roadmap
    • -
    • Prioritization Frameworks
    • -
    • Product-Market Fit
    • -
    • Feature Flagging
    • -
    -
    -
    -
    عملیات و SRE
    -
      -
    • SLI/SLO/SLA
    • -
    • Error Budget
    • -
    • Incident Management
    • -
    • Postmortem Culture
    • -
    -
    -
    -
    مشاهده‌پذیری پیشرفته
    -
      -
    • Distributed Tracing
    • -
    • Log Aggregation
    • -
    • Metrics و Dashboards
    • -
    • Anomaly Detection
    • -
    -
    -
    -
    مصرف و هزینه
    -
      -
    • Token Accounting
    • -
    • Cost Attribution
    • -
    • Quota Management
    • -
    • Usage Reporting
    • -
    -
    -
    -
    مدیریت تغییر و انتشار
    -
      -
    • Release Strategies
    • -
    • Blue-Green و Canary (مفهومی)
    • -
    • Rollback Strategies
    • -
    • Versioning Policies
    • -
    -
    -
    -
    مستندسازی و آموزش
    -
      -
    • Architecture Documentation
    • -
    • API Documentation (OpenAPI)
    • -
    • Runbook و Playbook
    • -
    • Training Programs
    • -
    -
    -
    -
    توسعه تیم و فرهنگ
    -
      -
    • Team Topologies (مفهومی)
    • -
    • Knowledge Sharing
    • -
    • Code Review Culture
    • -
    • Continuous Learning
    • -
    -
    -
    - -

    استانداردها و مراجع کلیدی:

    -
    - TOGAF ADM - Google SRE Book - OpenAPI Specification - Architecture Decision Records (ADR) - ISO/IEC 20000 (مدیریت خدمت) -
    - -

    خروجی قابل‌آزمون (Deliverable):

    -
      -
    • سند معماری محصول: نگاشت معماری کلان به قابلیت‌های محصول و نقشه راه انتشار
    • -
    • سند SLA و SLO: تعریف تعهد سطح خدمت و شاخص‌های کلیدی عملکرد — پاسخ به محور ۷ نیازمندی‌ها
    • -
    -
    -
    -
    -
    - -
    -
    -
    ۱۰
    -
    -

    ماتریس مهارت تیم

    -
    Team Skill Matrix
    -
    -
    -
    -

    جدول زیر، ماتریس مهارت پیشنهادی برای تیم فنی را نشان می‌دهد. سطح موردنیاز برای هر نقش، بر اساس فازهای نقشه راه تعیین شده است:

    - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
    نقش / حوزه مهارتفاز ۱-۲فاز ۳-۴فاز ۵-۶فاز ۷
    مهندس نرم‌افزارپیشرفتهمیانیپایهپایه
    مهندس دادهپیشرفتهمیانیمیانیپایه
    مهندس هوش مصنوعیپایهپیشرفتهپیشرفتهمیانی
    معمار سیستممیانیپیشرفتهپیشرفتهخبره
    مهندس امنیتمیانیپایهخبرهپیشرفته
    مهندس عملیات / SREمیانیمیانیمیانیپیشرفته
    مدیر محصولپایهپایهمیانیخبره
    - -
    - 💡 نکته: این ماتریس نشان می‌دهد که هیچ نقشی به‌تنهایی تمام فازها را پوشش نمی‌دهد. تیم چندنقشی با هم‌پوشانی مهارت‌ها، کلید موفقیت است. در تیم‌های کوچک، افراد باید در چند نقش (مثلاً مهندس نرم‌افزار + مهندس AI) مهارت داشته باشند. -
    -
    -
    - -
    -
    -
    ۱۱
    -
    -

    نقاط عطف و گام‌های اجرایی

    -
    Milestones & Execution Steps
    -
    -
    -
    -

    نقشه راه در قالب پنج نقطه عطف قابل پیگیری است. هر نقطه عطف، تجمیع خروجی چند فاز و نشان‌دهنده آمادگی برای گام بعدی است:

    - -
    -
    M1
    -
    -
    آمادگی پایه
    -

    تکمیل فازهای ۱ و ۲ — تیم بر مبانی داده، شبکه، امنیت پایه و الگوهای مهندسی نرم‌افزار مسلط است. خروجی: نقشه داده سازمان + سند اصول و الگوهای منتخب.

    -
    -
    - -
    -
    M2
    -
    -
    آمادگی هوش مصنوعی
    -

    تکمیل فاز ۳ — تیم قادر به ارزیابی مدل‌ها، طراحی RAG و ارزیابی کیفیت پاسخ است. خروجی: سند ارزیابی مدل‌ها + نمونه اولیه RAG.

    -
    -
    - -
    -
    M3
    -
    -
    آمادگی معماری توزیع‌شده
    -

    تکمیل فاز ۴ — تیم قادر به طراحی لایه‌بندی، رویدادمحوری و تاب‌آوری است. خروجی: سند الگوهای معماری منتخب + نقشه BPMN2 تکمیلی.

    -
    -
    - -
    -
    M4
    -
    -
    آمادگی ایجنت و حاکمیت
    -

    تکمیل فازهای ۵ و ۶ — تیم قادر به پیاده‌سازی ایجنت قابل‌آزمون و اعمال حاکمیت داده است. خروجی: سناریوی نمونه Agent + سناریوی آزمون نفوذ دسترسی — آماده برای جلسه دمو کارفرما.

    -
    -
    - -
    -
    M5
    -
    -
    آمادگی محصول
    -

    تکمیل فاز ۷ — تیم قادر به تبدیل معماری به محصول قابل ارائه، عملیات پایدار و مدیریت چرخه عمر است. خروجی: سند معماری محصول + سند SLA و SLO.

    -
    -
    - -
    - ✓ نکته کلیدی: نقطه عطف M4 دقیقاً منطبق بر نیاز کارفرما برای جلسه دمو و آزمون عملی است. یعنی با تکمیل فازهای ۱ تا ۶، تیم آمادگی کامل برای پاسخ به محورهای ۱ تا ۶ نیازمندی‌ها را دارد. فاز ۷ برای پایداری بلندمدت محصول و پاسخ به محور ۷ (SLA و پایلوت) است. -
    -
    -
    - -
    -
    -
    ۱۲
    -
    -

    نگاشت نقشه راه به معماری و نیازمندی‌ها

    -
    Roadmap-to-Architecture & Requirements Mapping
    -
    -
    -
    -

    جدول زیر نشان می‌دهد هر فاز نقشه راه، کدام لایه‌های معماری (ARCH-1405-001) و کدام محورهای نیازمندی (REQ-1405-001) را پوشش می‌دهد:

    - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
    فازلایه‌های معماریمحورهای نیازمندینقش کلیدی
    فاز ۱پایه همه لایه‌هاپیش‌نیاز محور ۲، ۵مهندس داده، مهندس امنیت
    فاز ۲L1 تا L6 (الگوها)پیش‌نیاز همه محورهامهندس نرم‌افزار، معمار
    فاز ۳L4 (هوش و مدل‌ها)محور ۱، ۴مهندس AI
    فاز ۴L1 تا L6 + Yمحور ۳، ۷معمار سیستم، SRE
    فاز ۵L3 (ارکستراسیون)محور ۱ (ایجنت)مهندس AI، معمار
    فاز ۶X (حاکمیت) + L2محور ۲، ۵مهندس امنیت
    فاز ۷L6 + Y + همه لایه‌هامحور ۳، ۶، ۷معمار، مدیر محصول، SRE
    -
    -
    - -
    -
    -
    ۱۳
    -
    -

    جمع‌بندی و مسیر پیشنهادی

    -
    Summary & Recommended Path
    -
    -
    -
    -

    نقشه راه ارائه‌شده، مسیری پیوسته و فارغ از سکو برای کسب دانش فنی لازم جهت پیاده‌سازی معماری و تبدیل آن به محصول است. ویژگی‌های کلیدی:

    - -
      -
    • - هفت فاز پیوسته - از مبانی سیستم‌ها و داده تا معماری کلان، محصول و عملیات — با وابستگی دانشی مشخص -
    • -
    • - فارغ از سکو - هیچ زبان، فریم‌ورک یا استک خاصی توصیه نشده؛ تمرکز بر مفاهیم و الگوهای قابل انتقال -
    • -
    • - استانداردمحوری - تکیه بر BPMN 2.0، OAuth 2.0، OpenID Connect، OWASP، ISO 27001/42001، NIST AI RMF و... -
    • -
    • - الگومحوری - یادگیری الگوهای طراحی و معماری (Hexagonal، Event-Driven، Circuit Breaker، ReAct، Plan-and-Execute و...) -
    • -
    • - خروجی قابل‌آزمون - هر فاز با Deliverable مشخص پایان می‌یابد تا دانش به مهارت تبدیل شود -
    • -
    • - انطباق با نیازمندی‌ها - نقطه عطف M4 دقیقاً منطبق بر آمادگی برای جلسه دمو و آزمون عملی کارفرماست -
    • -
    - -
    - مسیر پیشنهادی: برای شروع، توصیه می‌شود تیم فنی ابتدا فازهای ۱ و ۲ را به‌صورت فشرده مرور کند (به‌ویژه اگر تجربه مهندسی نرم‌افزار دارد)، سپس تمرکز اصلی را بر فازهای ۳، ۴ و ۵ بگذارد که هسته تمایز محصول هستند. فازهای ۶ و ۷ می‌توانند به‌صورت موازی با فازهای ۴ و ۵ پیش بروند تا نقطه عطف M4 در کوتاه‌ترین زمان محقق شود. -
    -
    -
    - -
    -

    🎯 ارزش این نقشه راه

    -

    این نقشه راه، مسیری شفاف، فارغ از سکو و استانداردمحور برای کسب دانش فنی لازم جهت پیاده‌سازی معماری و تبدیل آن به محصول ارائه می‌دهد.

    -

    هر فاز با خروجی قابل‌آزمون پایان می‌یابد و نقطه عطف M4، آمادگی کامل برای جلسه دمو و آزمون عملی کارفرما را تضمین می‌کند.

    -
    - 💎 ارزش پیشنهادی:
    - مسیر پیوسته از پایه تا کلان + فارغ از سکو + استانداردمحور + الگومحور + خروجی قابل‌آزمون + انطباق با نیازمندی‌ها -
    -
    - -
    - این مستند محرمانه بوده و صرفاً جهت ارائه به کارفرمای محترم تهیه شده است. هرگونه کپی‌برداری یا افشا بدون اجازه کتبی ممنوع است. -
    - -
    - -
    - - -
    تاریخ تهیه: آبان ۱۴۰۵  |  نسخه: ۱.۰  |  طبقه‌بندی: محرمانه
    -
    - -
    - - - - -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\xAiApi\wwwroot\Storage\Uploads\Document\xSaherElm_8d5bef83-5974-4a98-a41a-863c459267ff.html - - - - - - -تحلیل و رفع مشکل احراز هویت XApiKey در xIds - - - - -
    - - -
    -
    -
    - -
    -
    xSaherelmWorkspace
    -
    Technical Analysis Document
    -
    -
    -
    -
    شماره مستند: XIDS-AUTH-2026-001
    -
    نسخه: ۱.۰
    -
    موضوع: رفع مشکل احراز هویت XApiKey
    -
    طبقه‌بندی: داخلی — فنی
    -
    -
    - -
    - TECHNICAL DIAGNOSIS & SOLUTION -

    ریشه‌یابی و رفع مشکل احراز هویت با XApiKey در xIds

    -
    - تحلیل جامع کد، شناسایی گلوگاه احراز هویت، و ارائه راه‌حل گام‌به‌گام برای فعال‌سازی کامل - Authentication مبتنی بر API Key در سرور IdentityServer4 -
    -
    -
    - - -
    - -
    - خلاصه اجرایی:
    - پس از بررسی کامل کدهای پروژه xIds، مشخص شد که زیرساخت مدیریت Application و - تولید XApiKey به‌درستی پیاده‌سازی شده است، اما زنجیره احراز هویت مبتنی بر API Key - در سمت سرور IdentityServer4 ناقص مانده است. این سند ابتدا ریشه مشکل را با استناد به کدهای - موجود تشریح می‌کند، سپس راه‌حل کامل گام‌به‌گام را ارائه می‌دهد. -
    - - - - -
    -
    -
    ۱
    -
    -

    وضعیت فعلی سیستم

    -
    Current State Analysis
    -
    -
    -
    -

    - در پروژه xIds، اجزای زیر برای مدیریت Application و API Key پیاده‌سازی شده‌اند: -

    - -

    ۱.۱ — اجزای پیاده‌سازی‌شده

    - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
    جزءمسیر فایلوضعیت
    مدل‌های Application و ApiKeyxIdentityModels/Models/XApplication.cs✓ موجود
    XApplicationProvider (مدیریت API Key)xIds/Providers/XApplicationProvider.cs✓ موجود
    XApiKeyHelper (تولید و هش)xIds/Helpers/XApiKeyHelper.cs✓ موجود
    ApplicationsController (Endpointها)xIds/Controllers/ApplicationsController.cs✓ موجود
    XApiKeyAuthenticationHandlerxIds/Providers/XApiKeyAuthenticationHandler.cs⚠ موجود اما ناقص
    XApiKeyConfigurationxIds/Configurations/XApiKeyConfiguration.cs✓ موجود
    ثبت Scheme در StartupxIds/Startup.cs✓ موجود
    - -

    ۱.۲ — معماری جاری احراز هویت در Startup.cs

    - -
    -// xIds/Startup.cs -services.AddXIdentityServerAuthentication( - configuration: Configuration, - addApiKeyAuthentication: true // ← این خط فعال است -); -
    - -

    - و در XDIHelperExtension.AddXIdentityServerAuthentication: -

    - -
    -var authBuilder = services.AddAuthentication(); - -authBuilder.AddJwtBearer(options => -{ - options.SaveToken = true; - options.RequireHttpsMetadata = false; - options.ForwardDefault = XAuthentication.IDENTITY_SERVER_LOCAL_API; -}) -.AddLocalApi(); - -if (addApiKeyAuthentication) -{ - authBuilder.AddScheme<AuthenticationSchemeOptions, XApiKeyAuthenticationHandler>( - XAuthenticationScheme.XApiKey.GetStringValue(), // "XApiKey" - options => {} - ); -} -
    - -
    - نتیجه: به نظر می‌رسد همه چیز در Startup به‌درستی ثبت شده است. اما در عمل، درخواست‌هایی - که Header X-Api-Key دارند، احراز هویت نمی‌شوند. علت چیست؟ -
    -
    -
    - - - - -
    -
    -
    ۲
    -
    -

    ریشه‌یابی مشکل

    -
    Root Cause Analysis
    -
    -
    -
    -

    - پس از بررسی دقیق کدها، سه ریشه اصلی برای عدم کارکرد احراز هویت با XApiKey شناسایی شد: -

    - - -
    -
    - 🔴 - مشکل ۱: ForwardDefaultSelector به XApiKey توجه نمی‌کند -
    -

    - در AddJwtBearer، تنظیم ForwardDefault روی - XAuthentication.IDENTITY_SERVER_LOCAL_API قرار داده شده است. این یعنی - ASP.NET Core همیشه از Scheme پیش‌فرض (IdentityServerAccessToken) استفاده می‌کند - و هیچ‌گاه به Scheme با نام XApiKey نمی‌رسد. -

    -
    -// xIds/DI/XDIHelperExtension.cs — AddXIdentityServerAuthentication -authBuilder.AddJwtBearer(options => -{ - options.SaveToken = true; - options.RequireHttpsMetadata = false; - options.ForwardDefault = XAuthentication.IDENTITY_SERVER_LOCAL_API; // ← مشکل اصلی اینجاست -}) -
    -
    - - -
    -
    - 🔴 - مشکل ۲: ترتیب ثبت Schemeها اشتباه است -
    -

    - در ASP.NET Core، اولین Scheme ثبت‌شده، Scheme پیش‌فرض است. در کد فعلی، - AddJwtBearer قبل از AddScheme<...XApiKeyAuthenticationHandler> ثبت - می‌شود و این باعث می‌شود حتی اگر Header X-Api-Key ارسال شود، Handler مربوطه - هرگز فراخوانی نگردد. -

    -
    - - -
    -
    - 🔴 - مشکل ۳: XApiKeyAuthenticationHandler به Claimهای Policyهای موجود پاسخ نمی‌دهد -
    -

    - Policyهای موجود در XAuthorizationHelper (مانند ApiKeyAccess و - ApiKeyReadAccess) انتظار Claim از نوع JwtClaimTypes.Scope با مقادیر - read، write، admin یا manage دارند. - اما XApiKeyAuthenticationHandler فعلی در کد، یک Scope ثابت به نام - "apikey" اضافه می‌کند که با هیچ Policy موجودی مطابقت ندارد. -

    -
    -// xIds/Providers/XApiKeyAuthenticationHandler.cs — کد فعلی -var claims = new[] -{ - new Claim(ClaimTypes.Name, validationResult.OwnerId), - new Claim("application_id", validationResult.ApplicationId.ToString()), - new Claim("auth_type", "apikey"), - new Claim(JwtClaimTypes.Scope, "apikey"), // ← هیچ Policyای این Scope را نمی‌شناسد -}; - -// سپس scopes از validationResult اضافه می‌شود، اما با مقادیر "read", "write"... -// که با Policyهای XAuthorizationHelper همخوانی ندارند -
    -
    - -

    ۲.۱ — درخت عیب‌یابی

    - -
    -
    -
    ✗
    -
    -
    درخواست با Header: X-Api-Key: xapp_xxxxx
    -

    Header به درستی در Request وجود دارد.

    -
    -
    -
    -
    ✗
    -
    -
    ASP.NET Core می‌خواهد Scheme پیش‌فرض را انتخاب کند
    -

    به دلیل ForwardDefault = IDENTITY_SERVER_LOCAL_API، همیشه Scheme پیش‌فرض انتخاب می‌شود.

    -
    -
    -
    -
    ✗
    -
    -
    XApiKeyAuthenticationHandler فراخوانی نمی‌شود
    -

    چون هیچ‌گاه انتخاب نمی‌شود، متد HandleAuthenticateAsync اجرا نمی‌گردد.

    -
    -
    -
    -
    ✗
    -
    -
    درخواست با خطای 401 Unauthorized رد می‌شود
    -

    پایان مسیر — احراز هویت شکست خورده است.

    -
    -
    -
    - -
    - ⚠️ خلاصه ریشه مشکل: در معماری فعلی، ASP.NET Core با - ForwardDefault به Scheme پیش‌فرض هدایت می‌شود و هرگز به Scheme - XApiKey نمی‌رسد. علاوه بر این، حتی اگر Handler فراخوانی شود، Claimهای - تولیدشده با Policyهای موجود همخوانی ندارند و در نتیجه Authorization نیز شکست می‌خورد. -
    -
    -
    - - - - -
    -
    -
    ۳
    -
    -

    نمودار جریان فعلی در مقابل جریان مطلوب

    -
    Current vs. Desired Auth Flow
    -
    -
    -
    -

    ۳.۱ — جریان فعلی (معیوب)

    - -
    -
    -
    -
    -
    ۱. Client Request
    -

    ارسال درخواست با Header X-Api-Key

    -
    -
    -
    ▼
    -
    -
    -
    ۲. Default Scheme Selection
    -

    ASP.NET Core به دلیل ForwardDefault، Scheme پیش‌فرض را انتخاب می‌کند

    -
    -
    -
    ▼
    -
    -
    -
    ۳. JwtBearer Handler اجرا می‌شود
    -

    به‌دنبال Bearer Token می‌گردد، پیدا نمی‌کند، شکست می‌خورد

    -
    -
    -
    ▼
    -
    -
    -
    ❌ نتیجه: 401 Unauthorized
    -

    XApiKeyAuthenticationHandler هرگز اجرا نمی‌شود

    -
    -
    -
    -
    - -

    ۳.۲ — جریان مطلوب (پس از راه‌حل)

    - -
    -
    -
    -
    -
    ۱. Client Request
    -

    ارسال درخواست با Header X-Api-Key

    -
    -
    -
    ▼
    -
    -
    -
    ۲. ForwardDefaultSelector اجرا می‌شود
    -

    وجود Header X-Api-Key را تشخیص می‌دهد و Scheme XApiKey را انتخاب می‌کند

    -
    -
    -
    ▼
    -
    -
    -
    ۳. XApiKeyAuthenticationHandler.HandleAuthenticateAsync
    -

    API Key را استخراج و ValidateApiKey را فراخوانی می‌کند

    -
    -
    -
    ▼
    -
    -
    -
    ۴. Claims تولید می‌شوند
    -

    Scopeهای واقعی از validationResult.Scopes به Claims اضافه می‌شوند

    -
    -
    -
    ▼
    -
    -
    -
    ۵. Policy-Based Authorization
    -

    Policyهای ApiKeyAccess و ApiKeyReadAccess با موفقیت بررسی می‌شوند

    -
    -
    -
    ▼
    -
    -
    -
    ✅ نتیجه: 200 OK + Response
    -

    دسترسی به Endpoint مورد نظر با موفقیت انجام می‌شود

    -
    -
    -
    -
    -
    -
    - - - - -
    -
    -
    ۴
    -
    -

    راه‌حل گام‌به‌گام

    -
    Step-by-Step Solution
    -
    -
    -
    - - -
    -
    -
    ۱
    -
    - اصلاح ForwardDefaultSelector در Startup - فایل: xIds/DI/XDIHelperExtension.cs -
    -
    -
    -

    - باید یک ForwardDefaultSelector تنظیم شود که بر اساس وجود Header - X-Api-Key در Request، Scheme صحیح را انتخاب کند. این Selector - برای تمام Schemeها (نه فقط JwtBearer) باید فعال باشد. -

    - -
    -// xIds/DI/XDIHelperExtension.cs — بخش AddXIdentityServerAuthentication - -public static void AddXIdentityServerAuthentication( - this IServiceCollection services, - IConfiguration configuration, - bool addApiKeyAuthentication = false -) -{ - services.AddXIdentityResourceConfiguration(configuration); - - var authBuilder = services.AddAuthentication(); - - // ═══ ۱. ثبت Scheme برای XApiKey (اول از همه) - if (addApiKeyAuthentication) - { - authBuilder.AddScheme<AuthenticationSchemeOptions, XApiKeyAuthenticationHandler>( - XAuthenticationScheme.XApiKey.GetStringValue(), - options => {} - ); - } - - // ═══ ۲. ثبت JwtBearer با ForwardDefaultSelector هوشمند - authBuilder.AddJwtBearer(options => - { - options.SaveToken = true; - options.RequireHTTPSMetadata = false; - options.ForwardDefault = XAuthentication.IDENTITY_SERVER_LOCAL_API; - - // ═══ ۳. انتخاب Scheme بر اساس Header درخواست - options.ForwardDefaultSelector = context => - { - // اگر Header X-Api-Key وجود دارد → از Scheme XApiKey استفاده کن - var apiKeyHeader = XHeader.ApiKey.GetStringValue(); // "X-Api-Key" - if (context.Request.Headers.ContainsKey(apiKeyHeader)) - { - return XAuthenticationScheme.XApiKey.GetStringValue(); - } - - // در غیر این صورت، Scheme پیش‌فرض (LocalApi برای IdentityServer) - return XAuthentication.IDENTITY_SERVER_LOCAL_API; - }; - }) - .AddLocalApi(); -} -
    - -
    - 💡 چرا این راه‌حل کار می‌کند؟ ForwardDefaultSelector - یک delegate است که ASP.NET Core در هر درخواست فراخوانی می‌کند تا Scheme مناسب را - تعیین کند. با بررسی وجود Header، ما به‌صورت پویا Scheme را انتخاب می‌کنیم. -
    -
    -
    - - -
    -
    -
    ۲
    -
    - اصلاح XApiKeyAuthenticationHandler برای تولید Claims صحیح - فایل: xIds/Providers/XApiKeyAuthenticationHandler.cs -
    -
    -
    -

    - Handler فعلی Scope ثابت "apikey" را اضافه می‌کند که با هیچ Policyای - همخوانی ندارد. باید Scopeهای واقعی از validationResult.Scopes - که در XApplicationProvider.ValidateApiKey استخراج شده‌اند، به Claims - اضافه شوند. -

    - -
    -// xIds/Providers/XApiKeyAuthenticationHandler.cs — نسخه اصلاح‌شده - -protected override async Task<AuthenticateResult> HandleAuthenticateAsync() -{ - // ۱. استخراج API Key از Header - var apiKeyHeader = Options.HeaderName ?? XHeader.ApiKey.GetStringValue(); - if (!Request.Headers.ContainsKey(apiKeyHeader)) - { - return AuthenticateResult.NoResult(); - } - - var apiKey = Request.Headers[apiKeyHeader].ToString(); - if (string.IsNullOrEmpty(apiKey)) - { - return AuthenticateResult.NoResult(); - } - - // ۲. استخراج Client IP - var clientIP = Request.HttpContext.Connection.RemoteIpAddress?.ToString(); - - // ۳. اعتبارسنجی API Key از طریق Provider - var validationResult = await applicationProvider.ValidateApiKey( - apiKey: apiKey, - clientIP: clientIP - ); - - if (validationResult.Errors.HasChild()) - { - var message = validationResult.Errors.ToListString('\n'); - return AuthenticateResult.Fail(message); - } - - // ═══ ۴. ساخت Claims — نکته کلیدی ═══ - var claims = new List<Claim> - { - // شناسه کاربر مالک API Key - new Claim(ClaimTypes.Name, validationResult.OwnerId), - new Claim(JwtClaimTypes.Subject, validationResult.OwnerId), - - // شناسه Application - new Claim("application_id", validationResult.ApplicationId.ToString()), - - // نوع احراز هویت برای تشخیص - new Claim("auth_type", "apikey"), - }; - - // ═══ ۵. اضافه کردن Scopeهای واقعی ═══ - // این Scopeها توسط XApplicationProvider از AllowedScopes استخراج شده‌اند - // و با Policyهای XAuthorizationHelper (read, write, admin, manage) همخوانی دارند - if (validationResult.Scopes != null) - { - foreach (var scope in validationResult.Scopes) - { - claims.Add(new Claim(JwtClaimTypes.Scope, scope)); - } - } - - // ۶. ساخت Principal و Ticket - var identity = new ClaimsIdentity(claims, Scheme.Name); - var principal = new ClaimsPrincipal(identity); - var ticket = new AuthenticationTicket(principal, Scheme.Name); - - return AuthenticateResult.Success(ticket); -} -
    - -
    - ✅ نکته کلیدی: validationResult.Scopes مقادیری مانند - read، write، admin، manage دارد که - مستقیماً با Policyهای تعریف‌شده در XAuthorizationHelper مطابقت می‌کند. -
    -
    -
    - - -
    -
    -
    ۳
    -
    - اطمینان از همخوانی Policyها با Scopeهای API Key - فایل: xIdentityHelper/XAuthorizationHelper.cs -
    -
    -
    -

    - در XAuthorizationHelper، Policyهای مربوط به ApiKey تعریف شده‌اند. - این Policyها باید با مقادیر XApiKeyScope در - xIdentityModels/Constants/XApiKeyScope.cs همخوانی داشته باشند. -

    - -
    -// xIdentityModels/Constants/XApiKeyScope.cs -public enum XApiKeyScope -{ - [StringValue("read")] - Read, - - [StringValue("write")] - Write, - - [StringValue("admin")] - Admin, - - [StringValue("manage")] - Manage -} -
    - -

    - و در XAuthorizationHelper: -

    - -
    -// xIdentityHelper/XAuthorizationHelper.cs — Policyهای موجود ApiKey - -// ApiKey Access Policy — دسترسی به هر یک از Scopeها -result.Add(XPolicies.ApiKeyAccess, - new AuthorizationPolicyBuilder() - .RequireClaim( - JwtClaimTypes.Scope, - XApiKeyScope.Read.GetStringValue(), // "read" - XApiKeyScope.Write.GetStringValue(), // "write" - XApiKeyScope.Manage.GetStringValue() // "manage" - ) - .Build() -); - -// ApiKey Read Access Policy -result.Add(XPolicies.ApiKeyReadAccess, - new AuthorizationPolicyBuilder() - .RequireClaim(JwtClaimTypes.Scope, XApiKeyScope.Read.GetStringValue()) - .Build() -); -
    - -
    - 💡 نتیجه: اگر در گام ۲، Scopeهای واقعی از validationResult.Scopes - به Claims اضافه شوند، این Policyها به‌صورت خودکار با موفقیت بررسی می‌شوند و دسترسی - به Endpointهای محافظت‌شده امکان‌پذیر می‌گردد. -
    -
    -
    - - -
    -
    -
    ۴
    -
    - استفاده صحیح در Controllerها - نمونه استفاده صحیح -
    -
    -
    -

    - پس از اصلاحات بالا، برای محافظت از Endpointها با API Key، باید از Policyهای - مربوطه استفاده کنید: -

    - -
    -// نمونه Endpoint محافظت‌شده با API Key -[RequireXPowered] -[HttpPost("ApiKeys/Validate")] -[Authorize(Policy = XPolicies.ApiKeyAccess)] // ← Policy مخصوص API Key -public async Task<ActionResult<XApiKeyValidationResult>> ValidateApiKey( - [FromBody] XApiKeyValidationRequest request, - CancellationToken cancellationToken = default -) -{ - // پیاده‌سازی -} -
    - -
    - ⚠️ توجه مهم: از آنجایی که Policyهای ApiKey بر اساس Scope - تعریف شده‌اند، نباید از Policyهای مبتنی بر Role مانند XPolicies.User - یا XPolicies.EnabledUser استفاده کنید. این Policyها انتظار Role Claim دارند - که API Key ندارد. -
    -
    -
    - - -
    -
    -
    ۵
    -
    - تست و اعتبارسنجی - Validation & Testing -
    -
    -
    -

    - پس از اعمال تغییرات، مسیر تست زیر را دنبال کنید: -

    - -

    گام ۵.۱ — ساخت یک API Key جدید

    -
    -# Request: ساخت API Key جدید برای Application -POST /Applications/{applicationId}/ApiKeys/Create -Content-Type: application/json -Authorization: Bearer {access_token} - -{ - "scopes": ["read", "write"], - "rateLimit": 60, - "expirationMinutes": 43200, - "allowedIPs": ["127.0.0.1"] -} -
    - -

    - پاسخ باید شامل شیء XApiKeyDto باشد. نکته مهم: کلید اصلی (plainKey) فقط - یک‌بار در پاسخ اولیه برگردانده می‌شود و باید آن را در جای امن ذخیره کنید. -

    - -

    گام ۵.۲ — تست Endpoint با API Key

    -
    -# Request: تست Endpoint محافظت‌شده با API Key -GET /Account/Test/HiApiKeyAccess -X-Api-Key: xapp_xxxxxxxxxxxxxxxxxxxxxxxx -X-PoweredBy: {xPoweredValue} -
    - -

    گام ۵.۳ — بررسی نتیجه

    - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
    حالتپاسخ مورد انتظارتشخیص
    API Key معتبر + Scope کافی200 OK✓ صحیح
    API Key نامعتبر401 Unauthorized با پیام «ApiKey not found»✓ صحیح
    API Key منقضی‌شده401 با پیام «ApiKey is Expired»✓ صحیح
    Scope ناکافی403 Forbidden✓ صحیح
    IP غیرمجاز401 با پیام «Client IP not Allowed»✓ صحیح
    Rate Limit رد شده401 با پیام «ApiKey Rate Limit Reached»✓ صحیح
    -
    -
    - - -
    -
    -
    ۶
    -
    - به‌روزرسانی Endpoint «Validate API Key» - اصلاح کنترلر موجود -
    -
    -
    -

    - در ApplicationsController+Custom.cs، متد ValidateApiKey - فعلی از GetUserInfo() استفاده می‌کند که نیازمند احراز هویت با - Bearer Token است. برای پیاده‌سازی درست، باید این Endpoint - خودش با API Key احراز هویت شود (سناریوی self-validation): -

    - -
    -// xIds/Controllers/Applications/ApplicationsController+Custom.cs - -// نسخه اصلاح‌شده — با Policy API Key -[HttpPost("ApiKeys/Validate")] -[AllowAnonymous] // ← چون خودش API Key را در Body می‌فرستد -public async Task<ActionResult<XApiKeyValidationResult>> ValidateApiKey( - [FromBody] XApiKeyValidationRequest request, - CancellationToken cancellationToken = default -) -{ - try - { - // اعتبارسنجی ورودی - await ValidationProvider - .GroupValidationBuilder() - .AddNotNull(request) - .AddNotEmpty(request.ApiKey) - .ValidateGroupAsync(); - - // استخراج ClientIP از Connection واقعی - var clientIP = HttpContext.Connection.RemoteIpAddress?.ToString(); - - // اعتبارسنجی مستقیم - var result = await provider.ValidateApiKey( - apiKey: request.ApiKey, - clientIP: clientIP, - requiredScope: request.RequiredScope, - userInfo: null, // ← userInfo دیگر نیاز نیست - cancellationToken: cancellationToken - ); - - return Ok(result.ToDynamicObject()); - } - catch (Exception ex) - { - var result = GetExceptionActionResult(ex); - return result; - } -} -
    - -
    - 💡 چرا AllowAnonymous؟ چون این Endpoint خودش نقش «اعتبارسنج API Key» را - دارد و نباید قبل از رسیدن به آن، احراز هویت شود. منطق اعتبارسنجی درون خودش انجام می‌شود. -
    -
    -
    - -
    -
    - - - - -
    -
    -
    ۵
    -
    -

    خلاصه تغییرات

    -
    Summary of Changes
    -
    -
    -
    - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
    #فایلتغییراولویت
    ۱xIds/DI/XDIHelperExtension.csافزودن ForwardDefaultSelector برای انتخاب پویا بین JwtBearer و XApiKeyحیاتی
    ۲xIds/Providers/XApiKeyAuthenticationHandler.csحذف Scope ثابت «apikey» و افزودن Scopeهای واقعی از validationResult.Scopesحیاتی
    ۳xIds/Startup.csاطمینان از ترتیب صحیح ثبت Schemeها (نیاز به تغییر مستقیم ندارد اگر از Extension استفاده شود)متوسط
    ۴xIds/Controllers/Applications/ApplicationsController+Custom.csاصلاح ValidateApiKey برای کارکرد مستقلمتوسط
    ۵xIds/Controllers/Account/AccountController+Test.csافزودن تست‌های احراز هویت با API Key (اختیاری، برای تست)توصیه‌شده
    - -
    - ✅ نتیجه نهایی: با اعمال گام‌های ۱ و ۲ (که حیاتی هستند)، مشکل احراز هویت - با XApiKey به‌طور کامل حل می‌شود. گام‌های ۳ تا ۵ برای بهبود و تکمیل توصیه می‌شوند. -
    -
    -
    - - - - -
    -
    -
    ۶
    -
    -

    بهترین شیوه‌ها و توصیه‌های تکمیلی

    -
    Best Practices & Additional Recommendations
    -
    -
    -
    - -

    ۶.۱ — مدیریت صحیح Scopeها در سطح API Key

    -

    - هنگام ساخت API Key، از مقادیر XApiKeyScope استفاده کنید: -

    - -
    -// نمونه ساخت API Key با Scopeهای صحیح -var result = await provider.CreateApiKey( - applicationId: applicationId, - scopes: new[] { "read", "write" }, // ← مطابق XApiKeyScope - allowedIPs: new[] { "192.168.1.100" }, - rateLimit: 60, - expiration: TimeSpan.FromDays(30), - userInfo: userInfo -); -
    - -

    ۶.۲ — تفکیک Policyهای مبتنی بر API Key از Policyهای مبتنی بر Role

    -

    - Policyهای موجود در XPolicies دو دسته هستند: -

    -
      -
    • Policyهای مبتنی بر Scope (مثل ApiKeyAccess, ReadAccess) — برای API Key و Bearer Token
    • -
    • Policyهای مبتنی بر Role (مثل User, Admin) — فقط برای Bearer Token
    • -
    - -
    - ⚠️ توجه: هرگز از Policyهای Role-based برای Endpointهایی که قرار است با - API Key محافظت شوند استفاده نکنید. این Policyها انتظار Claim از نوع role دارند - که API Key ندارد. -
    - -

    ۶.۳ — ذخیره امن Plain Key

    -

    - کلید اصلی (plain key) فقط در لحظه ساخت برگردانده می‌شود. باید در جای امن ذخیره شود. - در صورتی که کاربر آن را گم کند، باید کلید قبلی revoke شده و کلید جدید ساخته شود. -

    - -

    ۶.۴ — Rate Limit و Audit Log

    -

    - در XApiKeyConfiguration، ویژگی‌های زیر فعال هستند: -

    -
      -
    • DefaultRateLimit — محدودیت نرخ پیش‌فرض
    • -
    • EnableAuditLog — برای ثبت استفاده از API Keyها
    • -
    - -

    - توصیه می‌شود در ValidateApiKey پس از اعتبارسنجی موفق، یک رکورد - XApiKeyUsage ثبت کنید تا تاریخچه استفاده قابل ردیابی باشد. -

    - -

    ۶.۵ — Endpointهای توصیه‌شده برای تست

    -

    - برای اطمینان از کارکرد صحیح، این Endpointها را در AccountController+Test.cs - اضافه کنید: -

    - -
    -[RequireXPowered] -[HttpGet("Test/HiApiKeyReadAccess")] -[Authorize(Policy = XPolicies.ApiKeyReadAccess)] -public ActionResult<string> HiApiKeyReadAccess() -{ - return Ok("API Key Read Access Passed ..."); -} - -[RequireXPowered] -[HttpPost("Test/HiApiKeyWriteAccess")] -[Authorize(Policy = XPolicies.ApiKeyWriteAccess)] -public ActionResult<string> HiApiKeyWriteAccess() -{ - return Ok("API Key Write Access Passed ..."); -} -
    -
    -
    - - - - -
    -
    -
    ۷
    -
    -

    جمع‌بندی

    -
    Conclusion
    -
    -
    -
    -

    - مشکل عدم احراز هویت با XApiKey در xIds ریشه در دو نقطه کد کلیدی - دارد که هر دو در این سند شناسایی و راه‌حل آن‌ها ارائه شد: -

    - -
      -
    1. - عدم انتخاب صحیح Scheme در Startup — که با افزودن - ForwardDefaultSelector در AddJwtBearer حل می‌شود. -
    2. -
    3. - عدم تطابق Claims تولیدشده با Policyها — که با افزودن Scopeهای - واقعی از validationResult.Scopes در XApiKeyAuthenticationHandler - حل می‌شود. -
    4. -
    - -

    - با اعمال این دو تغییر ساده اما حیاتی، سیستم احراز هویت مبتنی بر API Key به‌طور کامل فعال - می‌شود و Endpointهای محافظت‌شده با Policyهای ApiKeyAccess، - ApiKeyReadAccess، ApiKeyWriteAccess و - ApiKeyAdminAccess به درستی کار می‌کنند. -

    - -
    - ✅ کلید موفقیت: زیرساخت موجود در xIds برای مدیریت API Key بسیار - کامل و حرفه‌ای است. تنها دو نقطه اتصال کوچک در لایه احراز هویت نیاز به اصلاح داشتند - که در این سند به‌طور کامل تشریح شدند. -
    -
    -
    - -
    - این مستند فنی محرمانه بوده و صرفاً جهت استفاده تیم توسعه xSaherelmWorkspace تهیه شده است. -
    - -
    - - -
    - - -
    - تحلیل و مستندسازی: تیم فنی xSaherelmWorkspace  |  نسخه: ۱.۰  |  - مهر ۱۴۰۵ -
    -
    - -
    - - - - -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\xAiApi\wwwroot\Storage\Uploads\Document\xSaherElm_91592543-a30d-4cd3-8f73-4660ff1c06d1.html - - - - - - -تحلیل نیازمندی‌ها | درخواست شرکت پارسا پلیمر شریف - - - - -
    - -
    -
    -
    - -
    -
    -
    شماره مستند: REQ-1405-001
    -
    نسخه: ۱.۰
    -
    تاریخ تهیه: مهر ۱۴۰۵
    -
    طبقه‌بندی: محرمانه
    -
    -
    - -
    - REQUIREMENTS ANALYSIS -

    تحلیل نیازمندی‌ها

    -

    درخواست شرکت پارسا پلیمر شریف برای راهکار هوش مصنوعی سازمانی

    -
    -
    - -
    - -
    - خلاصه مدیریتی،
    - این مستند به تحلیل دقیق و شفاف درخواست رسمی شرکت پارسا پلیمر شریف (نخستین شرکت دانش‌بنیان ایران، فعال در صنعت تولید کامپاندهای پلیمری) می‌پردازد. هدف درخواست‌کننده، بهره‌گیری تدریجی از هوش مصنوعی در واحدهای مختلف سازمان و ارزیابی محصولات و خدمات ارائه‌دهندگان این حوزه است. در این مستند، هفت محور اصلی درخواست، الزامات آزمون عملی، و انتظارات کلیدی کارفرما به‌صورت دسته‌بندی‌شده تشریح می‌شود تا مبنای تهیه پیشنهاد فنی و تجاری قرار گیرد. -
    - -
    -
    -
    ۱
    -
    -

    شناخت کلی درخواست

    -
    Context & Overview
    -
    -
    -
    -

    شرکت پارسا پلیمر شریف با هدف بهره‌گیری تدریجی از هوش مصنوعی در واحدهای مختلف، از ارائه‌دهندگان راهکارهای هوش مصنوعی درخواست کرده است تا اطلاعات محصولات و خدمات خود را به‌صورت مکتوب ارائه دهند. این درخواست در قالب یک RFP (درخواست پیشنهاد) با رویکردی فنی، دقیق و آزمون‌محور تنظیم شده است.

    - -
    -
    -
    ۷
    -
    محور اصلی درخواست
    -
    -
    -
    آزمون
    عملی
    -
    الزام جلسه دمو
    -
    -
    -
    شفافیت
    کامل
    -
    در قیمت و قابلیت‌ها
    -
    -
    - -
    - نکته کلیدی: لحن و ساختار درخواست نشان می‌دهد تیم فنی/فناوری اطلاعات کارفرما با مفاهیم روز هوش مصنوعی (Agent، Assistant، RAG، مدیریت دسترسی، حاکمیت داده) کاملاً آشناست و به دنبال پاسخ‌های سطحی یا بازاریابی نیست. بنابراین، پیشنهاد ارائه‌شده باید مستند، قابل‌آزمون و شفاف باشد. -
    -
    -
    - -
    -
    -
    ۲
    -
    -

    محور ۱: ماهیت راهکار، مدل‌ها و قابلیت‌های ایجنت

    -
    Solution Nature, Models & Agent Capabilities
    -
    -
    -
    -

    کارفرما خواستار شفاف‌سازی دقیق ماهیت راهکار و تمایز آن از گردش‌کارهای از پیش تعریف‌شده است. نیازمندی‌های صریح این محور به شرح زیر است:

    - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
    ردیفنیازمندیالزام آزمون/اثبات
    ۱-۱مشخص کردن قالب راهکار: چت‌بات، دستیار هوشمند (Assistant)، ایجنت (Agent) یا ترکیبی از آن‌ها و قابلیت‌های هر بخشتوضیح مکتوب + نمایش عملی
    ۱-۲ارائه تعریف دقیق و قابل‌آزمون از Agent و تمایز آن با Assistant یا گردش‌کار از پیش تعریف‌شدهسناریوی چندمرحله‌ای در محیط آزمایشی
    ۱-۳توانایی تبدیل هدف به مراحل اجرایی، انتخاب ابزار مناسب، انجام عملیات و اصلاح مراحل بعدی بر اساس نتیجهاجرای عملی در جلسه دمو
    ۱-۴مشخص کردن نقاط نیازمند دستور یا تأیید انسان (Human-in-the-loop)مستندسازی + نمایش در سناریو
    ۱-۵اعلام مدل‌های قابل استفاده در هر پلن و امکان طراحی دستیار/ایجنت اختصاصی متناسب با فرایندهای سازمانجدول مدل‌ها به تفکیک پلن
    ۱-۶پشتیبانی از به‌روزترین مدل‌های منتشرشده و اعلام بازه زمانی دسترسی سازمانی پس از عرضه مدل/نسخه جدیدتعهد زمان‌بندی مشخص
    - -
    - ⚠️ نکته حساس: کارفرما در جلسه دمو خواستار ارائه یک سناریوی چندمرحله‌ای در محیط آزمایشی است تا نحوه برنامه‌ریزی مراحل، انتخاب و استفاده از ابزارها، اجرای عملیات، واکنش به خطا یا تغییر شرایط، و موارد نیازمند مداخله انسانی به‌صورت قابل مشاهده ارزیابی شود. ادعاهای مکتوب بدون قابلیت نمایش عملی، پذیرفته نخواهد شد. -
    -
    -
    - -
    -
    -
    ۳
    -
    -

    محور ۲: مدیریت کاربران و سطوح دسترسی

    -
    User Management & Access Control
    -
    -
    -
    -

    این محور از حساس‌ترین بخش‌های درخواست است، زیرا کارفرما قصد دارد آزمون نفوذ عملی برای سطوح دسترسی انجام دهد. نیازمندی‌های صریح:

    - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
    ردیفنیازمندیالزام آزمون/اثبات
    ۲-۱سازوکار ایجاد کاربران، تعریف نقش‌ها و مدیریت کاربران واحدهای مختلف سازماننمایش عملی + مستندات
    ۲-۲امکان تعیین فهرست مجاز مدل‌ها، منابع و ابزارها و محدودسازی دسترسی تا سطح سند یا رکوردآزمون با حساب‌های متفاوت
    ۲-۳نحوه اعمال مجوزها در بازیابی اطلاعات، پاسخ‌گویی مدل و اجرای عملیات ایجنتآزمون پرسش یکسان با مجوزهای متفاوت
    ۲-۴سازوکار جلوگیری از افشای اطلاعات خارج از سطح دسترسیآزمون نفوذ (پرسش مستقیم/غیرمستقیم، خلاصه‌سازی، ایجنت)
    - -
    - ⚠️ آزمون نفوذ دسترسی: کارفرما صراحتاً اعلام کرده است که در ارزیابی، پرسش‌های یکسان با حساب‌های دارای مجوزهای متفاوت مطرح خواهد شد تا اطمینان حاصل شود پاسخ‌ها بر مبنای اطلاعات مجاز هر کاربر تولید می‌شوند. همچنین بررسی خواهد شد که کاربران فاقد مجوز نتوانند از طریق پرسش مستقیم یا غیرمستقیم، درخواست خلاصه‌سازی یا استفاده از ایجنت، به اطلاعات خارج از سطح دسترسی خود دست یابند. این یعنی راهکار باید در برابر حملات مبتنی بر مهندسی اجتماعی و دور زدن مجوزها مقاوم باشد. -
    -
    -
    - -
    -
    -
    ۴
    -
    -

    محور ۳: پلن‌ها، مصرف، تعرفه‌ها و API

    -
    Plans, Usage, Pricing & API
    -
    -
    -
    -

    کارفرما روی شفافیت کامل قیمت‌گذاری و مبنای محاسبه تأکید ویژه دارد. نیازمندی‌های صریح:

    - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
    ردیفنیازمندیالزام ارائه
    ۳-۱تفاوت پلن‌های سازمانی و شخصی و مبنای محاسبه هزینه (اشتراک هر کاربر یا اعتبار مصرفی)جدول مقایسه‌ای شفاف
    ۳-۲نحوه تعیین سهمیه درخواست‌ها، سقف مصرف و مدیریت اتمام سهمیهمستندات + مثال عددی
    ۳-۳هزینه یک درخواست معمول با مدل GPT5.6 Sol و مبنای محاسبه آنعدد دقیق + فرمول محاسبه
    ۳-۴گزارش مصرف و هزینه به تفکیک کاربر، مدل و ایجنت و قابلیت‌های بهینه‌سازی مصرفنمایش نمونه گزارش
    ۳-۵با فرض استفاده انحصاری از GPT5.6 Sol، تعداد توکن ماهانه تخصیصی به کل شرکت در هر پلنعدد دقیق به تفکیک پلن
    ۳-۶در صورت اعتباری‌بودن پلن، ظرفیت معادل مصرف ماهانه با این مدل همراه با فرض و مبنای محاسبهسناریوی محاسبه شفاف
    ۳-۷امکان تهیه API و استفاده از حساب/اعتبار اختصاصی سازمان و اینکه تعرفه آن با اشتراک کاربران مشترک است یا مستقلتوضیح مکتوب + شرایط
    - -
    - 💡 نکته کلیدی: اشاره صریح کارفرما به مدل «GPT5.6 Sol» نشان می‌دهد که انتظار دارند ارائه‌دهنده از جدیدترین مدل‌ها پشتیبانی کند و پاسخ دقیق و عددی (نه کلی) بدهد. پاسخ‌های مبهم یا بدون مبنای محاسبه، در ارزیابی رد خواهند شد. -
    -
    -
    - -
    -
    -
    ۵
    -
    -

    محور ۴: رابط کاربری، فایل‌ها و گزارش‌ها

    -
    UI, Files & Reports
    -
    -
    -
    -

    نیازمندی‌های صریح این محور:

    - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
    ردیفنیازمندیالزام ارائه
    ۴-۱ارائه رابط کاربری اختصاصی سازمان و نسخه دسکتاپ و امکانات هرکدامنمایش عملی + مستندات
    ۴-۲دسترسی مستقیم و کنترل‌شده به فایل‌ها و پوشه‌های محلی یا شبکه سازمانآزمون عملی دسترسی
    ۴-۳تحلیل ارتباط میان چند فایلسناریوی عملی
    ۴-۴خروجی‌های متنی، جدولی و نمودارینمونه خروجی
    ۴-۵قابلیت ویرایش گزارش‌ها، ارجاع به منابع و دریافت در قالب‌های Word و Excelنمایش عملی + فایل نمونه
    -
    -
    - -
    -
    -
    ۶
    -
    -

    محور ۵: حاکمیت داده، محرمانگی و معماری استقرار

    -
    Data Governance, Confidentiality & Deployment Architecture
    -
    -
    -
    -

    این محور برای یک شرکت دانش‌بنیان تولیدی (با اطلاعات حساس فرمولاسیون، مشتریان و فرایندها) بسیار حیاتی است. نیازمندی‌های صریح:

    - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
    ردیفنیازمندیالزام ارائه
    ۵-۱محل ذخیره و پردازش اطلاعات سازمان و اینکه چه محتوایی به سرویس‌های ثالث منتقل می‌شودمستندات معماری + دیاگرام
    ۵-۲سیاست استفاده از داده‌ها و مکالمات برای آموزش یا بهبود مدل‌هاسیاست مکتوب و شفاف
    ۵-۳امکان نگهداری داده‌ها و رابط کاربری در زیرساخت شرکت (On-Premise) و استفاده از مدل‌ها/ایجنت‌های خارجی از طریق APIتوضیح معماری + شرایط
    ۵-۴در این ساختار، مالکیت، مجوزهای دسترسی و مسئولیت هر بخش چگونه تعیین می‌شودمستند حقوقی/فنی
    - -
    - ⚠️ حساسیت بالا: انتظار استقرار درون‌سازمانی (On-Premise) و کنترل کامل داده وجود دارد. ارائه‌دهندگانی که فقط راهکار ابری ارائه می‌دهند، باید بتوانند سیاست‌های حاکمیت داده و عدم استفاده از داده برای آموزش مدل را به‌صورت مکتوب و قابل استناد تضمین کنند. -
    -
    -
    - -
    -
    -
    ۷
    -
    -

    محور ۶: پیاده‌سازی، اختصاصی‌سازی، آموزش و پشتیبانی

    -
    Implementation, Customization, Training & Support
    -
    -
    -
    -

    نیازمندی‌های صریح این محور:

    - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
    ردیفنیازمندیالزام ارائه
    ۶-۱حدود سفارشی‌سازی و امکان توسعه توسط تیم داخلی سازمانمستندات + مثال
    ۶-۲هزینه و زمان تهیه سامانه، استقرار و توسعه اختصاصی و نحوه محاسبه آنجدول زمان‌بندی و هزینه
    ۶-۳برنامه آموزش کاربران و مدیران، مستندات تحویلی و شرایط و هزینه پشتیبانیبرنامه مدون
    ۶-۴اینکه تیم سازمان پس از آموزش چه فعالیت‌هایی را می‌تواند مستقل انجام دهدفهرست شفاف
    -
    -
    - -
    -
    -
    ۸
    -
    -

    محور ۷: عملکرد، پایداری و ارزیابی عملی

    -
    Performance, Reliability & Practical Evaluation
    -
    -
    -
    -

    نیازمندی‌های صریح این محور:

    - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
    ردیفنیازمندیالزام ارائه
    ۷-۱زمان پاسخ‌گویی برای درخواست معمول، تحلیل فایل و اجرای ایجنتاعداد دقیق + شرایط اندازه‌گیری
    ۷-۲تعهد سطح خدمت (SLA)سند SLA
    ۷-۳وضعیت قابلیت‌های سامانه هنگام قطع اینترنت بین‌المللسناریوی تاب‌آوری
    ۷-۴شرایط ارائه دمو و اجرای پایلوت محدود (زمان، هزینه، پیش‌نیازها)پیشنهاد مدون پایلوت
    - -
    - 💡 نکته کلیدی: پرسش صریح درباره عملکرد هنگام قطع اینترنت بین‌الملل نشان‌دهنده نیاز به راهکار پایدار داخلی است. ارائه‌دهندگانی که راهکارشان کاملاً وابسته به سرویس‌های ابری خارجی است، باید محدودیت‌ها را شفاف اعلام کنند. -
    -
    -
    - -
    -
    -
    ۹
    -
    -

    الزامات فرایندی و قالب ارائه

    -
    Process Requirements & Submission Format
    -
    -
    -
    -

    علاوه بر محتوای فنی، کارفرما الزامات فرایندی زیر را نیز مشخص کرده است:

    - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
    الزامتوضیح
    قالب ارائهتوضیحات مکتوب، پیشنهاد فنی و تجاری، کاتالوگ یا مستندات موجود
    تفکیک قابلیت‌هاقابلیت‌های موجود / نیازمند سفارشی‌سازی / در برنامه توسعه / غیرقابل ارائه — همراه با محدودیت‌ها و هزینه‌ها
    جلسه دموبررسی موردبه‌مورد تمام محورها همراه با توضیحات و مستندات
    آزمون عملیامکان اجرای آزمون‌های عملی برای قابلیت‌های اجرایی
    سناریوی Agentارائه یک سناریوی چندمرحله‌ای در محیط آزمایشی
    آزمون دسترسیپرسش‌های یکسان با حساب‌های متفاوت + تلاش برای دور زدن مجوزها
    زمان‌بندیاعلام زمان پیشنهادی برای جلسه معرفی و دمو
    -
    -
    - -
    -
    -
    ۱۰
    -
    -

    جمع‌بندی و ویژگی‌های متمایز درخواست

    -
    Summary & Distinctive Characteristics
    -
    -
    -
    -

    این درخواست یک RFP بالغ، فنی و آزمون‌محور است که چند ویژگی متمایز دارد:

    - -
    -
    -

    ویژگی ۱: اثبات عملی، نه ادعا

    -
      -
    • رویکرد سناریوی قابل‌آزمون
    • -
    • دمو عملی و تعاملی
    • -
    • دسترسی آزمون نفوذ
    • -
    -
    -
    -

    ویژگی ۲: حساسیت به حاکمیت داده

    -
      -
    • استقرار درون‌سازمانی
    • -
    • داده کنترل کامل
    • -
    • آموزش مدل شفافیت سیاست
    • -
    -
    -
    - -
    -
    -

    ویژگی ۳: شفافیت مالی

    -
      -
    • قیمت اعداد دقیق
    • -
    • مبنا فرمول محاسبه
    • -
    • گزارش تفکیک مصرف
    • -
    -
    - -
    - -
    - نتیجه کلیدی: تیم ارزیابی کارفرما از اصطلاحات دقیق (Agent در برابر Assistant، Human-in-the-loop، سطح دسترسی تا رکورد، فهرست مجاز مدل‌ها) استفاده می‌کند که نشان‌دهنده وجود تیم فنی قوی و آگاه در سمت کارفرماست. بنابراین، پیشنهاد ارائه‌شده باید در سطحی حرفه‌ای، مستند و قابل دفاع در جلسه دمو باشد. -
    -
    -
    - -
    -
    -
    ۱۱
    -
    -

    گام‌های بعدی پیشنهادی

    -
    Recommended Next Steps
    -
    -
    -
    -

    با توجه به تحلیل فوق، تهیه پیشنهاد فنی و تجاری نیازمند موارد زیر است:

    - -
      -
    • - پاسخ موردبه‌مورد، مستند و قابل‌آزمون به هر ۷ محور - همراه با شواهد و مستندات پشتیبان -
    • -
    • - جدول تفکیک قابلیت‌ها - موجود / سفارشی‌سازی / در توسعه / غیرقابل ارائه — همراه با محدودیت‌ها و هزینه‌ها -
    • -
    • - سناریوی نمونه Agent - برای ارائه و اجرا در جلسه دمو (چندمرحله‌ای، با ابزارها، خطا و مداخله انسانی) -
    • -
    • - شفافیت کامل قیمت‌گذاری - با مبنای محاسبه، اعداد دقیق توکن و هزینه هر درخواست -
    • -
    • - برنامه پایلوت محدود - شامل زمان، هزینه، پیش‌نیازها و معیارهای ارزیابی موفقیت -
    • -
    • - زمان‌بندی جلسه معرفی و دمو - همراه با آمادگی برای آزمون‌های عملی -
    • -
    - -
    - 📞 گام بعدی: پس از تأیید این تحلیل نیازمندی‌ها، مستند پیشنهاد فنی و تجاری (شامل پاسخ به هر ۷ محور، جدول قابلیت‌ها، سناریوی Agent، قیمت‌گذاری شفاف و برنامه پایلوت) تهیه و ارائه خواهد شد. -
    -
    -
    - -
    -

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

    -

    درخواست شرکت پارسا پلیمر شریف، یک RFP فنی، دقیق و آزمون‌محور است که بر شفافیت، اثبات عملی و حاکمیت داده تأکید دارد.

    -

    پیشنهاد ارائه‌شده باید در سطحی حرفه‌ای، مستند و قابل دفاع در جلسه دمو باشد و بتواند در آزمون‌های عملی (سناریوی Agent، آزمون نفوذ دسترسی، عملکرد در قطع اینترنت) پاسخگو باشد.

    -
    - 💎 ارزش پیشنهادی مورد انتظار:
    - شفافیت کامل + قابلیت اثبات عملی + حاکمیت داده + قیمت‌گذاری دقیق + آمادگی پایلوت -
    -
    - -
    - این مستند محرمانه بوده و صرفاً جهت ارائه به کارفرمای محترم تهیه شده است. هرگونه کپی‌برداری یا افشا بدون اجازه کتبی ممنوع است. -
    - -
    - -
    - - -
    تاریخ تهیه: مهر ۱۴۰۵  |  نسخه: ۱.۰  |  طبقه‌بندی: محرمانه
    -
    - -
    - - - - -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\xAiApi\wwwroot\Storage\Uploads\Document\xSaherElm_9e6b15de-b071-4dfe-bbc6-7ecb47d1dc50.html - - - - - - -بررسی فنی و راهنمای جامع ابزار AirLLM - - - -
    -
    -
    -
    - -
    -
    -
    شماره مستند: TECH-1405-002
    -
    نسخه: ۱.۰
    -
    تاریخ تهیه: ۲۸ مهر ۱۴۰۵
    -
    طبقه‌بندی: داخلی / فنی
    -
    -
    -
    -TECHNICAL REVIEW & GUIDE -

    بررسی فنی و راهنمای جامع ابزار AirLLM

    -

    تحلیل معماری، قابلیت‌ها و راهنمای پیاده‌سازی مدل‌های زبانی بزرگ روی سخت‌افزار محدود

    -
    -
    - -
    -
    -همکاران و ذینفعان محترم،
    -این مستند به‌عنوان تحلیلی جامع و مبتنی بر بررسی‌های فنی عمیق، ابزار AirLLM را از منظر معماری، کارایی و نحوه پیاده‌سازی مورد ارزیابی قرار می‌دهد. هدف از تهیه این سند، ارائه شفافیت کامل فنی و تسهیل تصمیم‌گیری برای به‌کارگیری این راهکار در زیرساخت‌های هوش مصنوعی با منابع محدود است. -
    - -
    -
    -
    ۱
    -
    -

    خلاصه اجرایی

    -
    Executive Summary
    -
    -
    -
    -

    ابزار AirLLM یک کتابخانه پیشرفته در حوزه هوش مصنوعی است که با هدف کاهش چشمگیر مصرف حافظه گرافیکی (VRAM) در هنگام استنتاج (Inference) و آموزش (Training) مدل‌های زبانی بزرگ (LLM) طراحی شده است. این ابزار امکان اجرای مدل‌های عظیم (مانند مدل‌های ۷۰ میلیارد پارامتری و بالاتر) را روی کارت‌های گرافیک با ظرفیت حداقل ۴ گیگابایت فراهم می‌کند، بدون آنکه نیاز به کوانتیزاسیون (Quantization)، تقطیر (Distillation) یا هرس کردن (Pruning) مدل باشد.

    -
    -نتیجه کلیدی: با به‌کارگیری AirLLM، محدودیت‌های سخت‌افزاری به حداقل رسیده و امکان استقرار مدل‌های پیشرفته (حتی مدل‌های ۶۷۱ میلیارد پارامتری مانند DeepSeek-V3) روی سخت‌افزارهای سطح متوسط با مصرف حدود ۱۲ گیگابایت VRAM میسر می‌گردد. -
    -
    -
    - -
    -
    -
    ۲
    -
    -

    معماری و مکانیزم عملکرد

    -
    Architecture & Mechanism
    -
    -
    -
    -

    مکانیزم اصلی AirLLM بر پایه تکنیک «بارگذاری لایه‌ای» (Layer-wise Loading) استوار است. به جای بارگذاری کل مدل در حافظه گرافیکی، این ابزار فرآیند را به گام‌های زیر تقسیم می‌کند:

    -
    -گام ۱: تجزیه و ذخیره‌سازی اولیه
    -در اولین اجرا، مدل اصلی از مخزن Hugging Face دریافت شده و به صورت لایه‌به‌لایه در حافظه دیسک (Storage) ذخیره می‌شود. -

    -گام ۲: بارگذاری پویا در GPU
    -در حین فرآیند استنتاج، تنها یک لایه از مدل در هر لحظه روی GPU بارگذاری می‌شود. -

    -گام ۳: محاسبه و انتقال حالت (State)
    -پس از انجام محاسبات روی لایه فعلی، نتایج میانی (Activations) به لایه بعدی منتقل شده و لایه قبلی بلافاصله از VRAM تخلیه می‌شود. -
    -
    -💡 نتیجه معماری: این رویکرد باعث می‌شود حافظه VRAM مورد نیاز، به جای وابستگی به اندازه کل مدل، تنها به اندازه بزرگ‌ترین لایه مدل وابسته باشد که انقلابی در مدیریت منابع محسوب می‌شود. -
    -
    -
    - -
    -
    -
    ۳
    -
    -

    مدل‌های پشتیبانی‌شده و مصرف حافظه

    -
    Supported Models & VRAM Consumption
    -
    -
    -
    -

    این کتابخانه با تقریباً تمام خانواده‌های مدل‌های متن‌باز محبوب سازگاری کامل دارد. جدول زیر نمایی از توانایی AirLLM در مدیریت منابع برای مدل‌های مختلف را نشان می‌دهد:

    - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
    نام مدلاندازه تقریبیحداقل VRAM مورد نیاز
    Qwen3 / Mistral / Phi≈8B~۱ تا ۲ گیگابایت
    Qwen3-30B / Mixtral (MoE)30–47B~۱ تا ۳ گیگابایت
    Qwen3.8-27B (dense VL)27B~۳.۳۳ گیگابایت
    Qwen3.8-Flash-Next (MoE + PLE)~180B~۵.۹۵ گیگابایت
    Llama 3.x 70B (full precision)70B~۴ گیگابایت
    DeepSeek-V3671B~۱۲ گیگابایت
    -
    -
    - -
    -
    -
    ۴
    -
    -

    راهنمای گام‌به‌گام پیاده‌سازی

    -
    Step-by-Step Implementation Guide
    -
    -
    -
    -

    برای استقرار و اجرای این ابزار، مراحل زیر به دقت طراحی و پیاده‌سازی شده‌اند:

    -
    -پیش‌نیاز حیاتی: اطمینان از وجود فضای دیسک کافی در پوشه کش Hugging Face برای ذخیره‌سازی لایه‌های تجزیه‌شده مدل در اولین اجرا. -
    -

    گام ۱: نصب کتابخانه

    -
    pip install airllm
    - -

    گام ۲: مقداردهی اولیه مدل

    -
    from airllm import AutoModel
    -
    -# شناسه مخزن Hugging Face مدل مورد نظر را وارد کنید
    -model = AutoModel.from_pretrained("Qwen/Qwen3-32B")
    -
    -# نکته: برای فعال‌سازی فشرده‌سازی و افزایش سرعت تا ۳ برابر (اختیاری):
    -# model = AutoModel.from_pretrained("model-name", compression='4bit')
    -
    - -

    گام ۳: آماده‌سازی ورودی و اجرای استنتاج

    -
    MAX_LENGTH = 128
    -input_text = ['What is the capital of United States?']
    -
    -input_tokens = model.tokenizer(
    -    input_text,
    -    return_tensors="pt",
    -    return_attention_mask=False,
    -    truncation=True,
    -    max_length=MAX_LENGTH,
    -    padding=False
    -)
    -
    -generation_output = model.generate(
    -    input_tokens['input_ids'].cuda(),
    -    max_new_tokens=20,
    -    use_cache=True,
    -    return_dict_in_generate=True
    -)
    -
    -output = model.tokenizer.decode(generation_output.sequences[0])
    -print(output)
    -
    -
    -
    - -
    -
    -
    ۵
    -
    -

    جمع‌بندی و توصیه‌های فنی

    -
    Conclusion & Technical Recommendations
    -
    -
    -
    -

    با توجه به تحلیل‌های انجام‌شده، به‌کارگیری AirLLM مزایای بی‌نظیری را برای پروژه‌هایی با محدودیت سخت‌افزاری فراهم می‌آورد:

    - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
    مزیتروش سنتی (بارگذاری کامل)روش AirLLM (لایه‌ای)
    مصرف VRAMبسیار بالا (غیرقابل اجرا روی GPUهای ضعیف)بهینه و متناسب با اندازه لایه
    نیاز به کوانتیزاسیونالزامی برای کاهش مصرفغیرالزامی (حفظ دقت کامل)
    سرعت استنتاج (با فشرده‌سازی)پایهتا ۳ برابر سریع‌تر (با 4bit/8bit)
    ارزش خالص فنی—بسیار بالاتر
    - -
    -

    🎯 توصیه نهایی معماری

    -

    با توجه به بررسی‌های جامع فنی، استفاده از AirLLM بهترین انتخاب برای استقرار مدل‌های زبانی بزرگ در محیط‌هایی با محدودیت VRAM است.

    -

    این راهکار نه تنها هزینه‌های زیرساختی را به شکل قابل‌توجهی کاهش می‌دهد، بلکه بدون قربانی کردن دقت مدل (در حالت بدون فشرده‌سازی)، عملکردی پایدار و قابل اتکا ارائه می‌کند.

    -
    -💎 ارزش پیشنهادی:
    -حذف محدودیت سخت‌افزاری + حفظ دقت مدل + امکان فشرده‌سازی اختیاری برای افزایش سرعت + سازگاری گسترده با اکوسیستم Hugging Face -
    -
    -
    -
    - -
    -این مستند محرمانه بوده و صرفاً جهت استفاده داخلی در شرکت فن آوران ساحر علم تهیه شده است. هرگونه کپی‌برداری یا افشا بدون اجازه کتبی ممنوع است. -
    -
    - -
    - - -
    شرکت: فن آوران ساحر علم  |  تاریخ تهیه: ۲۸ مهر ۱۴۰۵  |  نسخه: ۱.۰  |  طبقه‌بندی: داخلی / فنی
    -
    -
    - - - -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\xAiApi\wwwroot\Storage\Uploads\Document\xSaherElm_b85c4c9b-e4d4-48df-97ff-eb50ee55f39b.html - - - - - - - مستندات فنی پیاده‌سازی احراز هویت XApiKey در xIds - - - -
    -
    -
    -
    -
    شماره مستند: TECH-XIDS-APIKEY-001
    -
    نسخه: ۱.۰
    -
    تاریخ تهیه: ۲۰ مهر ۱۴۰۵
    -
    طبقه‌بندی: داخلی - فنی
    -
    -
    -
    -

    راهنمای جامع پیاده‌سازی و عیب‌یابی احراز هویت XApiKey

    -

    پروژه xIds (Identity Server) | ماژول مدیریت Application و API Key

    -
    -
    - -
    - -
    -
    -
    ۱
    -
    -

    مقدمه و بررسی وضعیت فعلی

    -
    -
    -
    -

    - در پروژه xIds، زیرساخت کاملی برای مدیریت XApplication و XApiKey پیاده‌سازی شده است. - کلاس‌های XApplicationProvider و XApiKeyHelper وظیفه تولید، هش کردن و اعتبارسنجی کلیدها را بر عهده دارند. - با این حال، چالش اصلی در لایه Authentication Middleware و نحوه اتصال آن به Policyهای موجود بود. -

    -
    - مشکل شناسایی شده: درخواست‌های ارسالی با هدر X-Api-Key توسط ASP.NET Core نادیده گرفته می‌شدند، زیرا Scheme پیش‌فرض روی JWT Bearer تنظیم شده بود و Handler مخصوص ApiKey فراخوانی نمی‌شد. -
    -
    -
    - -
    -
    -
    ۲
    -
    -

    راه‌حل فنی: اصلاح زنجیره احراز هویت

    -
    -
    -
    -

    برای رفع مشکل، دو تغییر اساسی در فایل xIds/DI/XDIHelperExtension.cs اعمال شد:

    - -

    الف) ثبت Scheme اختصاصی برای XApiKey

    -

    قبل از ثبت JwtBearer، Scheme مربوط به ApiKey ثبت می‌شود تا در لیست Authentication Schemes وجود داشته باشد.

    - -

    ب) استفاده از ForwardDefaultSelector هوشمند

    -

    به جای استفاده ثابت از ForwardDefault، از یک Delegate استفاده می‌کنیم که Header درخواست را بررسی می‌کند.

    - -
    -// xIds/DI/XDIHelperExtension.cs - -public static void AddXIdentityServerAuthentication( - this IServiceCollection services, - IConfiguration configuration, - bool addApiKeyAuthentication = false) -{ - services.AddXIdentityResourceConfiguration(configuration); - var authBuilder = services.AddAuthentication(); - - // 1. ثبت Scheme برای XApiKey (اولویت اول) - if (addApiKeyAuthentication) - { - authBuilder.AddScheme<AuthenticationSchemeOptions, XApiKeyAuthenticationHandler>( - XAuthenticationScheme.XApiKey.GetStringValue(), // "XApiKey" - options => { }); - } - - // 2. ثبت JwtBearer با Selector هوشمند - authBuilder.AddJwtBearer(options => - { - options.SaveToken = true; - options.RequireHttpsMetadata = false; - - // انتخاب دینامیک Scheme بر اساس هدر درخواست - options.ForwardDefaultSelector = context => - { - var apiKeyHeader = XHeader.ApiKey.GetStringValue(); // "X-Api-Key" - if (context.Request.Headers.ContainsKey(apiKeyHeader)) - { - return XAuthenticationScheme.XApiKey.GetStringValue(); - } - // در غیر این صورت، از احراز هویت استاندارد IdentityServer استفاده کن - return XAuthentication.IDENTITY_SERVER_LOCAL_API; - }; - }) - .AddLocalApi(); -} -
    -
    -
    - -
    -
    -
    ۳
    -
    -

    اصلاح Claims تولید شده در Handler

    -
    -
    -
    -

    - در فایل xIds/Providers/XApiKeyAuthenticationHandler.cs، متد HandleAuthenticateAsync باید Claimهای صحیح را تولید کند تا با Policyهای تعریف شده در XAuthorizationHelper همخوانی داشته باشد. -

    -
    - نکته مهم: Policyهای ApiKey بر اساس Scope (مانند read, write, admin) کار می‌کنند، نه Role. بنابراین Claim از نوع JwtClaimTypes.Scope ضروری است. -
    -
    -protected override async Task<AuthenticateResult> HandleAuthenticateAsync() -{ - // ... استخراج و اعتبارسنجی ApiKey ... - - var validationResult = await applicationProvider.ValidateApiKey(apiKey, clientIP); - - if (validationResult.Errors.HasChild()) - return AuthenticateResult.Fail(string.Join(", ", validationResult.Errors)); - - var claims = new List<Claim> - { - new Claim(ClaimTypes.Name, validationResult.OwnerId), - new Claim(JwtClaimTypes.Subject, validationResult.OwnerId), - new Claim("application_id", validationResult.ApplicationId.ToString()), - new Claim("auth_type", "apikey"), - }; - - // افزودن Scopeهای مجاز به Claims - if (validationResult.Scopes != null) - { - foreach (var scope in validationResult.Scopes) - { - claims.Add(new Claim(JwtClaimTypes.Scope, scope)); - } - } - - var identity = new ClaimsIdentity(claims, Scheme.Name); - var principal = new ClaimsPrincipal(identity); - var ticket = new AuthenticationTicket(principal, Scheme.Name); - - return AuthenticateResult.Success(ticket); -} -
    -
    -
    - -
    -
    -
    ۴
    -
    -

    نحوه استفاده در Controllerها

    -
    -
    -
    -

    برای محافظت از Endpointها با ApiKey، از Attributeهای زیر استفاده کنید:

    -
    -[RequireXPowered] -[Authorize(Policy = XPolicies.ApiKeyAccess)] // دسترسی کلی -public async Task<ActionResult> MySecureAction() { ... } - -[Authorize(Policy = XPolicies.ApiKeyReadAccess)] // فقط خواندن -public async Task<ActionResult> GetItems() { ... } -
    -
    - تست موفقیت‌آمیز: اکنون با ارسال هدر X-Api-Key: xapp_... به Endpointهای فوق، احراز هویت انجام شده و دسترسی اعطا می‌شود. -
    -
    -
    - -
    -
    -
    ۵
    -
    -

    چک‌لیست نهایی استقرار

    -
    -
    -
    - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
    ردیفاقداموضعیت
    ۱بررسی ثبت AddXIdentityServerAuthentication در Startup با پارامتر true✅ انجام شد
    ۲اطمینان از وجود Policyهای ApiKeyAccess در XAuthorizationHelper✅ موجود است
    ۳تست ایجاد ApiKey جدید از طریق /Applications/{id}/ApiKeys/Create✅ تست شد
    ۴تست دسترسی به /Account/Test/HiApiKeyAccess با کلید معتبر✅ پاس شد
    -
    -
    - -
    - -
    - -
    تاریخ انتشار: ۲۰ مهر ۱۴۰۵
    -
    -
    - - - -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\xAiApi\wwwroot\Storage\Uploads\Document\xSaherElm_de98d2ce-3d9d-4990-a129-ea2bdd3b5216.html - - - - - - -بررسی فنی و راهنمای جامع ابزار AirLLM - - - -
    -
    -
    -
    - -
    -
    -
    شماره مستند: TECH-1405-002
    -
    نسخه: ۱.۰
    -
    تاریخ تهیه: ۲۸ مهر ۱۴۰۵
    -
    طبقه‌بندی: داخلی / فنی
    -
    -
    -
    -TECHNICAL REVIEW & GUIDE -

    بررسی فنی و راهنمای جامع ابزار AirLLM

    -

    تحلیل معماری، قابلیت‌ها و راهنمای پیاده‌سازی مدل‌های زبانی بزرگ روی سخت‌افزار محدود

    -
    -
    - -
    -
    -همکاران و ذینفعان محترم،
    -این مستند به‌عنوان تحلیلی جامع و مبتنی بر بررسی‌های فنی عمیق، ابزار AirLLM را از منظر معماری، کارایی و نحوه پیاده‌سازی مورد ارزیابی قرار می‌دهد. هدف از تهیه این سند، ارائه شفافیت کامل فنی و تسهیل تصمیم‌گیری برای به‌کارگیری این راهکار در زیرساخت‌های هوش مصنوعی با منابع محدود است. -
    - -
    -
    -
    ۱
    -
    -

    خلاصه اجرایی

    -
    Executive Summary
    -
    -
    -
    -

    ابزار AirLLM یک کتابخانه پیشرفته در حوزه هوش مصنوعی است که با هدف کاهش چشمگیر مصرف حافظه گرافیکی (VRAM) در هنگام استنتاج (Inference) و آموزش (Training) مدل‌های زبانی بزرگ (LLM) طراحی شده است. این ابزار امکان اجرای مدل‌های عظیم (مانند مدل‌های ۷۰ میلیارد پارامتری و بالاتر) را روی کارت‌های گرافیک با ظرفیت حداقل ۴ گیگابایت فراهم می‌کند، بدون آنکه نیاز به کوانتیزاسیون (Quantization)، تقطیر (Distillation) یا هرس کردن (Pruning) مدل باشد.

    -
    -نتیجه کلیدی: با به‌کارگیری AirLLM، محدودیت‌های سخت‌افزاری به حداقل رسیده و امکان استقرار مدل‌های پیشرفته (حتی مدل‌های ۶۷۱ میلیارد پارامتری مانند DeepSeek-V3) روی سخت‌افزارهای سطح متوسط با مصرف حدود ۱۲ گیگابایت VRAM میسر می‌گردد. -
    -
    -
    - -
    -
    -
    ۲
    -
    -

    معماری و مکانیزم عملکرد

    -
    Architecture & Mechanism
    -
    -
    -
    -

    مکانیزم اصلی AirLLM بر پایه تکنیک «بارگذاری لایه‌ای» (Layer-wise Loading) استوار است. به جای بارگذاری کل مدل در حافظه گرافیکی، این ابزار فرآیند را به گام‌های زیر تقسیم می‌کند:

    -
    -گام ۱: تجزیه و ذخیره‌سازی اولیه
    -در اولین اجرا، مدل اصلی از مخزن Hugging Face دریافت شده و به صورت لایه‌به‌لایه در حافظه دیسک (Storage) ذخیره می‌شود. -

    -گام ۲: بارگذاری پویا در GPU
    -در حین فرآیند استنتاج، تنها یک لایه از مدل در هر لحظه روی GPU بارگذاری می‌شود. -

    -گام ۳: محاسبه و انتقال حالت (State)
    -پس از انجام محاسبات روی لایه فعلی، نتایج میانی (Activations) به لایه بعدی منتقل شده و لایه قبلی بلافاصله از VRAM تخلیه می‌شود. -
    -
    -💡 نتیجه معماری: این رویکرد باعث می‌شود حافظه VRAM مورد نیاز، به جای وابستگی به اندازه کل مدل، تنها به اندازه بزرگ‌ترین لایه مدل وابسته باشد که انقلابی در مدیریت منابع محسوب می‌شود. -
    -
    -
    - -
    -
    -
    ۳
    -
    -

    مدل‌های پشتیبانی‌شده و مصرف حافظه

    -
    Supported Models & VRAM Consumption
    -
    -
    -
    -

    این کتابخانه با تقریباً تمام خانواده‌های مدل‌های متن‌باز محبوب سازگاری کامل دارد. جدول زیر نمایی از توانایی AirLLM در مدیریت منابع برای مدل‌های مختلف را نشان می‌دهد:

    - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
    نام مدلاندازه تقریبیحداقل VRAM مورد نیاز
    Qwen3 / Mistral / Phi≈8B~۱ تا ۲ گیگابایت
    Qwen3-30B / Mixtral (MoE)30–47B~۱ تا ۳ گیگابایت
    Qwen3.8-27B (dense VL)27B~۳.۳۳ گیگابایت
    Qwen3.8-Flash-Next (MoE + PLE)~180B~۵.۹۵ گیگابایت
    Llama 3.x 70B (full precision)70B~۴ گیگابایت
    DeepSeek-V3671B~۱۲ گیگابایت
    -
    -
    - -
    -
    -
    ۴
    -
    -

    راهنمای گام‌به‌گام پیاده‌سازی

    -
    Step-by-Step Implementation Guide
    -
    -
    -
    -

    برای استقرار و اجرای این ابزار، مراحل زیر به دقت طراحی و پیاده‌سازی شده‌اند:

    -
    -پیش‌نیاز حیاتی: اطمینان از وجود فضای دیسک کافی در پوشه کش Hugging Face برای ذخیره‌سازی لایه‌های تجزیه‌شده مدل در اولین اجرا. -
    -

    گام ۱: نصب کتابخانه

    -
    pip install airllm
    - -

    گام ۲: مقداردهی اولیه مدل

    -
    from airllm import AutoModel
    -
    -# شناسه مخزن Hugging Face مدل مورد نظر را وارد کنید
    -model = AutoModel.from_pretrained("Qwen/Qwen3-32B")
    -
    -# نکته: برای فعال‌سازی فشرده‌سازی و افزایش سرعت تا ۳ برابر (اختیاری):
    -# model = AutoModel.from_pretrained("model-name", compression='4bit')
    -
    - -

    گام ۳: آماده‌سازی ورودی و اجرای استنتاج

    -
    MAX_LENGTH = 128
    -input_text = ['What is the capital of United States?']
    -
    -input_tokens = model.tokenizer(
    -    input_text,
    -    return_tensors="pt",
    -    return_attention_mask=False,
    -    truncation=True,
    -    max_length=MAX_LENGTH,
    -    padding=False
    -)
    -
    -generation_output = model.generate(
    -    input_tokens['input_ids'].cuda(),
    -    max_new_tokens=20,
    -    use_cache=True,
    -    return_dict_in_generate=True
    -)
    -
    -output = model.tokenizer.decode(generation_output.sequences[0])
    -print(output)
    -
    -
    -
    - -
    -
    -
    ۵
    -
    -

    جمع‌بندی و توصیه‌های فنی

    -
    Conclusion & Technical Recommendations
    -
    -
    -
    -

    با توجه به تحلیل‌های انجام‌شده، به‌کارگیری AirLLM مزایای بی‌نظیری را برای پروژه‌هایی با محدودیت سخت‌افزاری فراهم می‌آورد:

    - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
    مزیتروش سنتی (بارگذاری کامل)روش AirLLM (لایه‌ای)
    مصرف VRAMبسیار بالا (غیرقابل اجرا روی GPUهای ضعیف)بهینه و متناسب با اندازه لایه
    نیاز به کوانتیزاسیونالزامی برای کاهش مصرفغیرالزامی (حفظ دقت کامل)
    سرعت استنتاج (با فشرده‌سازی)پایهتا ۳ برابر سریع‌تر (با 4bit/8bit)
    ارزش خالص فنی—بسیار بالاتر
    - -
    -

    🎯 توصیه نهایی معماری

    -

    با توجه به بررسی‌های جامع فنی، استفاده از AirLLM بهترین انتخاب برای استقرار مدل‌های زبانی بزرگ در محیط‌هایی با محدودیت VRAM است.

    -

    این راهکار نه تنها هزینه‌های زیرساختی را به شکل قابل‌توجهی کاهش می‌دهد، بلکه بدون قربانی کردن دقت مدل (در حالت بدون فشرده‌سازی)، عملکردی پایدار و قابل اتکا ارائه می‌کند.

    -
    -💎 ارزش پیشنهادی:
    -حذف محدودیت سخت‌افزاری + حفظ دقت مدل + امکان فشرده‌سازی اختیاری برای افزایش سرعت + سازگاری گسترده با اکوسیستم Hugging Face -
    -
    -
    -
    - -
    -این مستند محرمانه بوده و صرفاً جهت استفاده داخلی در شرکت فن آوران ساحر علم تهیه شده است. هرگونه کپی‌برداری یا افشا بدون اجازه کتبی ممنوع است. -
    -
    - -
    - - -
    شرکت: فن آوران ساحر علم  |  تاریخ تهیه: ۲۸ مهر ۱۴۰۵  |  نسخه: ۱.۰  |  طبقه‌بندی: داخلی / فنی
    -
    -
    - - diff --git a/Documents/GeneratedContext/xDashboard-xAiApi-20261105_133459.txt b/Documents/GeneratedContext/xDashboard-xAiApi-20261105_133459.txt new file mode 100644 index 0000000..74f7fc4 --- /dev/null +++ b/Documents/GeneratedContext/xDashboard-xAiApi-20261105_133459.txt @@ -0,0 +1,15184 @@ + +### FILE: C:\Users\saherelm\Documents\Projects\xSaherelmWorkspace\xAiApi\Program.cs + +using System.Text; +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) + .ConfigureWebHostDefaults(webBuilder => + { + webBuilder.UseStartup(); + }); + + // + 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 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 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 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 + { + 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(); + + // + // 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( + lifeTime: lifeTime, + repositoryType: repositoryType + ); + + // + // Register Tag Service ... + services.AddXTagService( + lifeTime: lifeTime, + repositoryType: repositoryType + ); + + // + // Register File Service ... + services.AddXFileService( + lifeTime: lifeTime, + repositoryType: repositoryType + ); + + // + // Register AiApi Data Service ... + services.AddXAiDataService( + 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(); + + // + // 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(); + } + + // + // 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(); + + // + // 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 + { + /// + /// Allowed Models to Use ... + /// + public XAiModelDescriptor[] Models { get; set; } = []; + + /// + /// Allowed Prompts to Use ... + /// + public XAiPromptDescriptor[] Prompts { get; set; } = []; + + /// + /// OCR Configuration ... + /// + public XAiOCRDescriptor OCR { get; set; } = new(); + + /// + /// Transcript Configuration ... + /// + public XAiTransciptDescriptor Transcript { get; set; } = new(); + + /// + /// PDF To Image Configuration ... + /// + public XPDFToImageDescriptor PDFToImageDescriptor { get; set; } = new(); + + /// + /// Proxy Configuration ... + /// + /// + public XAiModelProxyConfiguration ProxyConfiguration { get; set; } = new(); + + /// + /// Text Chunker Configuration ... + /// + public XTextChunkerDescriptor TextChunker { get; set; } = new(); + + /// + /// RAG Configuration ... + /// + public XAiDocumentRAGDescriptor RAGDescriptor {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 = "Gemma"; + 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 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 +{ + /// + /// Chat With Documents (In-Memory RAG) Controller ... + /// Flow: Ingest Files -> SessionId -> Ask / AskStream -> Delete Session + /// + [Authorize] + public class ChatWithDocumentsController : XBaseIdentityApiV1Controller + { + /// + /// Default AI Service ... + /// + private readonly IXAiService aiService; + + /// + /// Text Chunker Service ... + /// + private readonly IXTextChunker textChunker; + + /// + /// In Memory Vector Store ... + /// + private readonly IXInMemoryVectorStore vectorStore; + + /// + /// XAiApi Configuration ... + /// + private readonly XAiApiConfiguration apiConfiguration; + + /// + /// Embedding Service ... + /// + private readonly IXAiEmbeddingService embeddingService; + + /// + /// File Context Extractor Service ... + /// + private readonly IXFileContentExtractor fileContentExtractor; + + public ChatWithDocumentsController( + IXAiService aiService, + IXTextChunker textChunker, + IXInMemoryVectorStore vectorStore, + XAppConfiguration appConfiguration, + IXIdentityProvider identityProvider, + XAiApiConfiguration apiConfiguration, + IXAiEmbeddingService embeddingService, + XValidationProvider validationProvider, + ILogger 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 ... + /// + /// Ingest Files into a (new or existing) In-Memory Session: + /// Extract -> Chunk -> Embed -> Store ... + /// + /// + /// Optional: Add to an Existing Session + /// Optional: Session TTL in Minutes (only for new Session) + /// + /// + [HttpPost("Ingest")] + [Consumes("multipart/form-data")] + public async Task> 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(); + 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 ... + /// + /// Ask a Question over Ingested Documents ... + /// + /// + /// + /// + [HttpPost("Ask")] + public async Task> 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; + } + } + + /// + /// Ask a Question over Ingested Documents and Stream Response (SSE) ... + /// First Event Carries Sources, Next Events Carry Text Deltas, Last Event has IsFinal = true ... + /// + /// + /// + /// + [HttpPost("AskStream")] + public async Task AskStream( + [FromBody] 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 ... + /// + /// Retrieve Session Info (without Embeddings) ... + /// + /// + /// + [HttpGet("Session/{id:guid}")] + public async Task> GetSession(Guid id) + { + // + try + { + // + var userInfo = await GetUserInfo(); + if (!vectorStore.TryGet(id, out var session, userInfo.UserId)) + { + XException.NotFound.Throw(); + } + + // + IList 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; + } + } + + /// + /// Remove a Session and Free Memory ... + /// + /// + /// + [HttpDelete("Session/{id:guid}")] + public async Task> 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 ... + /// + /// Extract Plain Text of a File (Text or Audio Transcript) ... + /// + private async Task ExtractText( + IFormFile file, + string mimeType, + CancellationToken cancellationToken + ) + { + // + try + { + // + using var stream = file.OpenReadStream(); + var extraction = await fileContentExtractor.ExtractRichAsync( + fileStream: stream, + mimeType: mimeType, + fileName: file.FileName, + cancellationToken: cancellationToken + ); + + // + var result = extraction?.Text; + if (string.IsNullOrWhiteSpace(result)) + { + result = extraction?.AudioTranscript; + } + + // + return result; + } + catch (OperationCanceledException) + { + throw; + } + catch (Exception ex) + { + Logger.LogWarning(ex, "ChatWithDocuments: Extraction Failed for {FileName}", file.FileName); + return null; + } + } + + /// + /// Embed Chunks in Batches and Build Vectors ... + /// + private async Task> EmbedChunks( + IList chunks, + string fileName, + string mimeType, + CancellationToken cancellationToken + ) + { + // + var result = new List(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 + { + [apiConfiguration.RAGDescriptor.MetadataFileName] = fileName, + [apiConfiguration.RAGDescriptor.MetadataMimeType] = mimeType, + [apiConfiguration.RAGDescriptor.MetadataChunkIndex] = chunk.Index.ToString() + } + }); + } + } + + // + return result; + } + + /// + /// Embed Prompt and Search Session ... + /// + private async Task> 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 ?? []; + } + + /// + /// Map Search Results to Public Sources ... + /// + private IList ToSources( + IEnumerable 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; + } + + /// + /// Write a SSE Event ... + /// + 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 +{ + /// + /// Knowledge (Persistent RAG over XAiVector Table) Controller ... + /// Flow: Ingest Files -> Ask / AskStream (Retrieve from DB -> Generate) -> Documents / Delete + /// + [Authorize] + public class KnowledgeController : XBaseIdentityApiV1Controller + { + /// + /// Persistent RAG Service ... + /// + private readonly IXAiRAGService ragService; + + public KnowledgeController( + IXAiRAGService ragService, + XAppConfiguration appConfiguration, + IXIdentityProvider identityProvider, + ILogger logger, + XValidationProvider validationProvider + ) : base(logger, appConfiguration, identityProvider, validationProvider) + { + this.ragService = ragService; + } + + // + #region Ingest ... + /// + /// Ingest Files into a Knowledge Scope: + /// Extract -> Chunk -> Embed -> Store in XAiVector Table ... + /// + /// + /// Target Scope: User (default) / Project / Conversation / Global (Admin) + /// ProjectId or ConversationId (Required for Project / Conversation) + /// Optional Knowledge Type / Domain + /// Replace Previously Stored Vectors of Same File (default true) + /// + /// + [HttpPost("Ingest")] + [Consumes("multipart/form-data")] + [Authorize(Policy = XPolicies.EnabledAdmin)] + public async Task> Ingest( + [FromForm] IFormFileCollection files, + [FromForm] XAiKnowledgeScope? scope = XAiKnowledgeScope.Global, + [FromForm] Guid? scopeId = null, + [FromForm] string knowledgeType = null, + [FromForm] bool replaceExisting = true, + CancellationToken cancellationToken = default + ) + { + // + try + { + // + // Validate ... + if (!files.HasChild()) + { + XException.InvalidArgs.Throw(); + } + + // + var userInfo = await GetUserInfo(); + var connectionId = GetConnectionId(); + + // + var result = await ragService.IngestAsync( + files: files, + userInfo: userInfo, + connectionId: connectionId, + replaceExisting: replaceExisting, + cancellationToken: cancellationToken, + scope: BuildScope(scope, scopeId, knowledgeType) + ); + + // + return Ok(result); + } + catch (Exception ex) + { + // + var result = GetExceptionActionResult(ex); + return result; + } + } + #endregion + + // + #region Documents ... + /// + /// List Ingested Documents of a Knowledge Scope ... + /// + /// User (default) / Project / Conversation / Global + /// ProjectId or ConversationId (Required for Project / Conversation) + /// Optional Knowledge Type Filter + /// + /// + [HttpGet("Documents")] + [Authorize(Policy = XPolicies.EnabledAdmin)] + public async Task>> 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; + } + } + + /// + /// Remove All Vectors of a Document in a Knowledge Scope ... + /// + /// + /// User (default) / Project / Conversation / Global (Admin) + /// ProjectId or ConversationId (Required for Project / Conversation) + /// + /// Count of Removed Vectors + [HttpDelete("Documents")] + [Authorize(Policy = XPolicies.EnabledAdmin)] + public async Task> 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 ... + /// + /// Build Scope Descriptor from Request Params ... + /// + 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; + } + + /// + /// Write a SSE Event ... + /// + 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 logger, + XValidationProvider validationProvider, + IXAiMcpServerProvider mcpServerProvider + ) : base( + logger, + appConfiguration, + identityProvider, + validationProvider + ) + { + this.mcpServerProvider = mcpServerProvider; + } + + // + #region Provider ... + /// + /// Retrieve Specified MCP Server ... + /// + /// + /// + /// + [HttpGet("{id}")] + [Authorize(Policy = XPolicies.EnabledUser)] + public virtual async Task> 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; + } + } + + /// + /// Add MCP Server ... + /// + /// + /// + /// + [HttpPost] + [Authorize(Policy = XPolicies.EnabledUser)] + public virtual async Task> 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; + } + } + + /// + /// Update Specified MCP Server ... + /// + /// + /// + /// + /// + [HttpPut("{id}")] + [Authorize(Policy = XPolicies.EnabledUser)] + public virtual async Task> 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; + } + } + + /// + /// Remove Specified MCP Server ... + /// + /// + /// + /// + [HttpDelete("{id}")] + [Authorize(Policy = XPolicies.EnabledUser)] + public virtual async Task> 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; + } + } + + /// + /// Enable Specified MCP Server ... + /// + /// + /// + /// + [HttpPost("{id}/Enable")] + [Authorize(Policy = XPolicies.EnabledUser)] + public virtual async Task> 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; + } + } + + /// + /// Disable Specified MCP Server ... + /// + /// + /// + /// + [HttpPost("{id}/Disable")] + [Authorize(Policy = XPolicies.EnabledUser)] + public virtual async Task> 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; + } + } + + /// + /// Toggle Specified MCP Server ... + /// + /// + /// + /// + [HttpPost("{id}/Toggle")] + [Authorize(Policy = XPolicies.EnabledUser)] + public virtual async Task> 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; + } + } + + /// + /// Get all Registered MCP Servers by handling Ownership ... + /// + /// + /// + [HttpGet] + [Authorize(Policy = XPolicies.EnabledUser)] + public virtual async Task>> 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; + } + } + + /// + /// Query Registered MCP Servers by handling Ownership ... + /// + /// + /// + /// + /// + [HttpGet("Query")] + [Authorize(Policy = XPolicies.EnabledUser)] + public virtual async Task>> 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 + + /// + /// Refresh MCP Servers ... + /// + /// + [HttpPost("Refresh")] + [Authorize(Policy = XPolicies.EnabledAdmin)] + public async Task RefreshMcpServers() + { + // + try + { + // + await mcpServerProvider.RefreshAsync(); + + // + 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 +{ + /// + /// Runing when application start ... + /// + [Route("")] + [AllowAnonymous] + public class StartupController : XBaseController + { + + public StartupController( + ILogger logger, + XAppConfiguration appConfiguration, + XValidationProvider validationProvider + ) : base( + logger, + appConfiguration, + validationProvider + ) + { } + + /// + /// Show Configured Welcome Message + /// + /// + [HttpGet("")] + [AllowAnonymous] + public virtual ActionResult Index() + { + // + var controllerName = GetControllerName(); + var message = $"{AppConfiguration.WelcomeMessage}"; + + // + return Ok(message); + } + + /// + /// Global Exception Handler Endpoint (Production) ... + /// Returns a Generic Error without Leaking Exception Details ... + /// + /// + [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 { + /// + /// Test all Authentication Policies ... + /// + public class TestIdentity : XTestIdentityControllerBase { + public TestIdentity ( + ILogger 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 + { + public XAiController( + ILogger 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 : 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 ... + /// + /// Ask Question and Get Response ... + /// + /// + /// + /// + [HttpGet("AskText")] + [Authorize(Policy = XPolicies.EnabledUser)] + public virtual async Task> 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; + } + } + + /// + /// Ask Question and Get Response Stream ... + /// + /// + /// + /// + [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); + } + } + + /// + /// Ask a Question By Rag Retrive From Knowledge ... + /// + /// + /// + /// + [HttpGet("AskTextFromKnowledge")] + [Authorize(Policy = XPolicies.EnabledUser)] + public virtual async Task> 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; + } + } + + /// + /// Ask a Question By Rag Retrive From Knowledge and Stream Response ... + /// + /// + /// + /// + [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); + } + } + + /// + /// Ask Question and Get Response ... + /// + /// + /// + /// + [HttpPost("Ask")] + [Authorize(Policy = XPolicies.EnabledUser)] + public virtual async Task> 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; + } + } + + /// + /// Ask Question and Get Response Stream ... + /// + /// + /// + /// + [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); + } + } + + /// + /// Ask Question with Files and Get Response ... + /// + /// + /// + /// + [HttpPost("AskWithFiles")] + [Consumes("multipart/form-data")] + [Authorize(Policy = XPolicies.EnabledUser)] + public virtual async Task> AskWithFiles( + [FromForm] XAiResponseRequest request, + [FromForm] IFormFileCollection files, + CancellationToken cancellationToken = default + ) + { + // + try + { + // + // Validate ... + if (!request.IsValid()) + { + XException.InvalidArgs.Throw(); + } + + // + var userInfo = await GetUserInfo(); + var connectionId = GetConnectionId(); + + // + var result = await aiService.AskAsync( + files: files, + 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; + } + } + + /// + /// Ask Question with Files and Get Response Stream ... + /// + /// + /// + /// + [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, + 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 ... + /// + /// Retrieve AI Projects ... + /// + /// + /// + /// + [HttpGet("Projects")] + [Authorize(Policy = XPolicies.EnabledUser)] + public async Task>> 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; + } + } + + /// + /// Retrieve Specified AI Project's Conversations ... + /// + /// + /// + /// + [Authorize(Policy = XPolicies.EnabledUser)] + [HttpGet("Projects/{projectId}/Conversations")] + public async Task>> LoadConversations( + [FromRoute] Guid projectId, + CancellationToken cancellationToken = default + ) + { + // + try + { + // + // Validate ... + if (projectId.IsDefaultGuid()) + { + XException.InvalidArgs.Throw(); + } + + // + var userInfo = await GetUserInfo(); + var connectionId = GetConnectionId(); + + // + var result = await aiService.LoadConversations( + projectId: projectId, + connectionId: connectionId, + cancellationToken: cancellationToken + ); + + // + return Ok(result); + } + catch (Exception ex) + { + // + var result = GetExceptionActionResult(ex); + return result; + } + } + + /// + /// Retrieve Specified AI Conversation's Messages ... + /// + /// + /// + /// + [Authorize(Policy = XPolicies.EnabledUser)] + [HttpGet("Conversations/{conversationId}/Messages")] + public async Task>> LoadMessages( + [FromRoute] Guid conversationId, + CancellationToken cancellationToken = default + ) + { + // + try + { + // + // Validate ... + if (conversationId.IsDefaultGuid()) + { + XException.InvalidArgs.Throw(); + } + + // + var result = await aiService.LoadMessages( + conversationId: conversationId, + cancellationToken: cancellationToken + ); + + // + return Ok(result); + } + catch (Exception ex) + { + // + var result = GetExceptionActionResult(ex); + return result; + } + } + #endregion + + // + #region Queries ... + /// + /// Query Projects ... + /// + /// + /// + /// + /// + /// + [HttpGet("Projects/Query")] + [Authorize(Policy = XPolicies.EnabledUser)] + public async Task>> 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; + } + } + + /// + /// Query Conversations ... + /// + /// + /// + /// + /// + [Authorize(Policy = XPolicies.EnabledUser)] + [HttpGet("Projects/{projectId}/Conversations/Query")] + public async Task>> 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; + } + } + + /// + /// Query Messages ... + /// + /// + /// + /// + /// + [Authorize(Policy = XPolicies.EnabledUser)] + [HttpGet("Conversations/{conversationId}/Messages/Query")] + public async Task>> 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 ... + /// + /// Create an AI Project ... + /// + /// + /// + /// + [HttpPost("Projects")] + [Authorize(Policy = XPolicies.EnabledUser)] + public async Task> 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; + } + } + + /// + /// Create an AI Conversation ... + /// + /// + /// + /// + /// + [Authorize(Policy = XPolicies.EnabledUser)] + [HttpPost("Projects/{projectId}/Conversations")] + public async Task> 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; + } + } + #endregion + + // + #region Content Extraction ... + /// + /// Extract Files Content ... + /// + /// + /// + /// + /// + [HttpPost("ExtractContent")] + [Consumes("multipart/form-data")] + [Authorize(Policy = XPolicies.EnabledUser)] + public async Task> 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()]; + } + + // + 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 ... + /// + /// Write Validation Error for Streaming Endpoints (before Stream Starts) ... + /// + /// + [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 +{ + /// + /// Ai Api Database Descriptor ... + /// + public class XAiApiDatabaseDescriptor : XDatabaseDescriptor, IXDatabaseDescriptor + { + 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 +{ + /// + /// Db Context of AiApi ... + /// + 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 + { + /// + /// Extract AI Configuration ... + /// + /// + /// + public static XAiApiConfiguration GetXAiApiConfiguration(this IConfiguration source) + { + // + XAiApiConfiguration result = null; + + // + var section = source.GetSection(ConfigurationNodeNames.AI_API_NODE); + if (!section.IsNull()) + { + result = section.Get(); + } + + // + return result; + } + + /// + /// Register AiApi Configuration ... + /// + /// + /// + public static void AddXAiApiConfiguration( + this IServiceCollection source, + IConfiguration configuration + ) + { + // + var apiConfig = configuration.GetXAiApiConfiguration(); + source.AddXAiApiConfiguration(apiConfig); + } + + /// + /// Register AiApi Configuration ... + /// + /// + /// + public static void AddXAiApiConfiguration( + this IServiceCollection source, + XAiApiConfiguration configuration + ) + { + // + if (!configuration.IsValid()) + { + XException.InvalidConfiguration.Throw(); + } + + // + source.AddSingleton(configuration); + } + + /// + /// Register Rag Service ... + /// + /// + public static void AddXRagService( + this IServiceCollection source + ) + { + // + // Persistent RAG (Knowledge over XAiVector Table) ... + source.AddScoped(); + source.AddScoped(); + } + + /// + /// Register Ai Services ... + /// + /// + public static void AddXAiServices( + this IServiceCollection source + ) + { + // + source.AddScoped(); + source.AddScoped(); + } + + /// + /// Register AiApi File Content Extractor Services ... + /// + /// + public static void AddXAiFileContentExtractors( + this IServiceCollection source + ) + { + // + // Register File Content Extractors ... + source.AddSingleton(); + source.AddSingleton(); + source.AddSingleton(); + source.AddSingleton(); + source.AddSingleton(); + source.AddSingleton(); + source.AddSingleton(); + source.AddSingleton(); + source.AddSingleton(); + source.AddSingleton(); + source.AddSingleton(); + source.AddSingleton(); + source.AddSingleton(); + + // + source.AddSingleton(); + } + + /// + /// Register AiApi Text Chunker Service ... + /// + /// + public static void AddXAiTextChunker( + this IServiceCollection source + ) + { + // + // Stateless -> Singleton ... + source.AddSingleton(); + } + + /// + /// Register In-Memory Vector Store Service ... + /// + public static void AddXAiInMemoryVectorStore(this IServiceCollection source) + { + source.AddSingleton(); + source.AddHostedService(); + } + + /// + /// Register all Services Required for Chat With Documents (In-Memory RAG): + /// Text Chunker + In-Memory Vector Store (+ Cleanup) ... + /// + /// + public static void AddXAiChatWithDocuments(this IServiceCollection source) + { + source.AddXAiInMemoryVectorStore(); + } + + /// + /// Use Model Proxy Provider ... + /// + /// + /// + public static IApplicationBuilder UseXAiModelProxy( + this IApplicationBuilder source + ) + { + return source.UseMiddleware(); + } + + // + #region Private ... + /// + /// a LogTag for Service ... + /// + private static string XLogTag = XAiApiConstants.XDILogTag; + + /// + /// print a log in Console ... + /// + /// + 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 + { + /// + /// Validate Configurations ... + /// + /// + /// + 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; + } + + /// + /// Check TextChunker Descriptor is Valid or not ... + /// + /// + /// + 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; + } + + /// + /// Check Document Ask Request is Valid or not ... + /// + /// + /// + public static bool IsValid(this XAiDocumentAskRequest source) + { + // + var result = + !source.IsNullOrDefault() && + !source.Prompt.IsNullOrEmpty() && + !source.SessionId.IsDefaultGuid(); + + // + return result; + } + + /// + /// Extract Default Model Descriptor ... + /// + /// + /// + public static XAiModelDescriptor GetDefaultModel(this XAiApiConfiguration source) + { + // + XAiModelDescriptor result = null; + + // + if (source.IsValid()) + { + result = source.Models[0]; + } + + // + return result; + } + + /// + /// Retrieve Specified Model from Config ... + /// + /// + /// + /// + 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; + } + + /// + /// Retrieve Introduction Prompt ... + /// + /// + /// + 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; + } + + /// + /// Select Specified Prompts and Parse it's Template + /// and Generate Message ... + /// + /// + /// + /// + /// + public static string GetPrompt( + this XAiApiConfiguration source, + string name = null, + IDictionary @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; + } + + /// + /// Provide HttpClient for Common Usages ... + /// + /// + /// + 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; + } + + /// + /// Instance and Retrieve Chat Client ... + /// + /// + /// + 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; + } + + } +} + +### FILE: C:\Users\saherelm\Documents\Projects\xSaherelmWorkspace\xAiApi\Extensions\XProgramExtensions.cs + +using xIdentityHelper; +using xAiApi.Providers; +using xAiApi.Interfaces; +using xCommons.Extensions; +using xCommons.Authorization; +using System.Collections.Generic; +using Microsoft.AspNetCore.Builder; +using Microsoft.AspNetCore.Authorization; +using Microsoft.AspNetCore.HttpOverrides; +using Microsoft.Extensions.DependencyInjection; + +namespace xAiApi.Extensions +{ + public static class XProgramExtensions + { + /// + /// Register MCP Server Provider ... + /// + /// + public static void AddXAiMcpServerProvider( + this IServiceCollection source + ) + { + source.AddScoped(); + } + + /// + /// Register Authorization Policies + /// + /// + /// + public static void AddXAuthorization( + this IServiceCollection services, + IDictionary policies = null + ) + { + // + 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); + } + } + } + + // + var xPolicies = XAuthorizationHelper.GetXAuthorizationPolicies(); + if (!xPolicies.IsNull()) + { + // + // Fill Policies ... + using (var policiesEnumerator = xPolicies.GetEnumerator()) + { + while (policiesEnumerator.MoveNext()) + { + var policyDescriptor = policiesEnumerator.Current; + options.AddPolicy(policyDescriptor.Key, policyDescriptor.Value); + } + } + } + }); + + // + services.AddSingleton(); + } + + /// + /// Use Forward Headers Options for resolving behind a proxy issues ... + /// + /// + /// + 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 +{ + /// + /// Base Embedding Provider Service ... + /// + public interface IXAiEmbeddingServiceBase // : IXAiServiceBase + { + /// + /// Embedding Specified String ... + /// + /// + /// + /// + Task Embedding( + string content, + CancellationToken cancellationToken = default + ); + + /// + /// Embedding Specified Batch ... + /// + /// + /// + /// + Task> Embeddings( + string[] batch, + CancellationToken cancellationToken = default + ); + + /// + /// Embedding Generator ... + /// + /// + IEmbeddingGenerator> 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; + +namespace xAiApi.Interfaces +{ + /// + /// MCP Manager / Provider ... + /// + public interface IXAiMcpServerProvider + { + // + #region Manager ... + /// + /// Get a List Of Available Tools which Provided using registered Mcp Servers ... + /// + /// + /// + /// + /// + Task> GetAvailableToolsAsync( + bool forceOwner = false, + XUserClaimsInfoDto userInfo = null, + CancellationToken cancellationToken = default + ); + + /// + /// Test Specified Mcp Server ... + /// + /// + /// + /// + Task TestServerAsync( + XAiMcpServerDto server, + CancellationToken cancellationToken = default + ); + + /// + /// Force Refresh Mcp Servers ... + /// + /// + Task RefreshAsync(); + #endregion + + // + #region Actions ... + /// + /// Add an Mcp Server ... + /// + /// + /// + /// + /// + /// + Task AddMcpServer( + XAiMcpServerDto item, + string connectionId = null, + XUserClaimsInfoDto userInfo = null, + CancellationToken cancellationToken = default + ); + + /// + /// Get an Mcp Server ... + /// + /// + /// + /// + /// + Task GetMcpServer( + Guid id, + XUserClaimsInfoDto userInfo = null, + CancellationToken cancellationToken = default + ); + + /// + /// Update Specified Mcp Server ... + /// + /// + /// + /// + /// + /// + /// + Task UpdateMcpServer( + Guid id, + XAiMcpServerDto item, + string connectionId = null, + XUserClaimsInfoDto userInfo = null, + CancellationToken cancellationToken = default + ); + + /// + /// Remove Specified Mcp Server ... + /// + /// + /// + /// + /// + /// + Task RemoveMcpServer( + Guid id, + string connectionId = null, + XUserClaimsInfoDto userInfo = null, + CancellationToken cancellationToken = default + ); + + /// + /// Disable Specified Mcp Server ... + /// + /// + /// + /// + /// + /// + Task DisableMcpServer( + Guid id, + string connectionId = null, + XUserClaimsInfoDto userInfo = null, + CancellationToken cancellationToken = default + ); + + /// + /// Enable Specified Mcp Server ... + /// + /// + /// + /// + /// + /// + Task EnableMcpServer( + Guid id, + string connectionId = null, + XUserClaimsInfoDto userInfo = null, + CancellationToken cancellationToken = default + ); + + /// + /// Toggle Specified Mcp Server ... + /// + /// + /// + /// + /// + /// + Task ToggleMcpServer( + Guid id, + string connectionId = null, + XUserClaimsInfoDto userInfo = null, + CancellationToken cancellationToken = default + ); + + /// + /// Retrieve all Mcp Server ... + /// + /// + /// + /// + /// + Task> GetAll( + bool forceOwner = false, + XUserClaimsInfoDto userInfo = null, + CancellationToken cancellationToken = default + ); + + /// + /// Find Specified Mcp Server ... + /// + /// + /// + /// + /// + /// + Task FindOne( + Expression> predicate, + bool forceOwner = false, + XUserClaimsInfoDto userInfo = null, + CancellationToken cancellationToken = default + ); + + /// + /// Find a Collection of Specified Mcp Servers ... + /// + /// + /// + /// + /// + /// + Task> FindMany( + Expression> predicate, + bool forceOwner = false, + XUserClaimsInfoDto userInfo = null, + CancellationToken cancellationToken = default + ); + + /// + /// Query Registered Mcp Servers ... + /// + /// + /// + /// + /// + /// + Task> 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 +{ + /// + /// Persistent RAG Service over XAiVector Table: + /// Ingest (Extract -> Chunk -> Embed -> Store) and Ask (Embed -> Search -> Generate) ... + /// Isolation is Scope Based (Conversation / Project / User / Global) ... + /// + public interface IXAiRAGService + { + /// + /// Ingest Files into Specified Knowledge Scope: + /// Extract -> Chunk -> Embed -> Store (XAiVector) ... + /// + /// + /// Target Scope (Null = User Scope) + /// + /// + /// + /// + /// + Task IngestAsync( + IFormFileCollection files, + XAiKnowledgeScopeDescriptor scope = null, + XUserClaimsInfoDto userInfo = null, + string connectionId = null, + bool replaceExisting = true, + CancellationToken cancellationToken = default + ); + + /// + /// Embed Prompt and Retrieve Relevant Chunks (Tiered: Conversation -> Project -> User -> Global) ... + /// + /// + /// + /// + /// + Task> RetrieveAsync( + XAiKnowledgeAskRequest request, + XUserClaimsInfoDto userInfo = null, + CancellationToken cancellationToken = default + ); + + /// + /// List Ingested Documents of Specified Scope ... + /// + /// Target Scope (Null = User Scope) + /// + /// + /// + Task> LoadDocumentsAsync( + XAiKnowledgeScopeDescriptor scope = null, + XUserClaimsInfoDto userInfo = null, + CancellationToken cancellationToken = default + ); + + /// + /// Remove All Vectors of a Document in Specified Scope ... + /// + /// + /// Target Scope (Null = User Scope) + /// + /// + /// + /// Count of Removed Vectors + Task RemoveDocumentAsync( + string fileName, + XAiKnowledgeScopeDescriptor scope = null, + XUserClaimsInfoDto userInfo = null, + string connectionId = null, + CancellationToken cancellationToken = default + ); + + /// + /// Migrate Legacy Vectors of Owner ("{ownerId}/{fileName}#i") into User Scope ("user/{ownerId}/{fileName}#i") ... + /// Idempotent: Returns 0 when Nothing Left to Migrate ... + /// + /// + /// + /// Count of Migrated Vectors + Task MigrateLegacyVectorsAsync( + XUserClaimsInfoDto userInfo = null, + CancellationToken cancellationToken = default + ); + + /// + /// Map Search Results to Public Sources ... + /// + /// + /// + IList ToSources( + IEnumerable 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 +{ + /// + /// Describe a Base Service Actions of any Ai Based Services ... + /// + public interface IXAiServiceBase : IDisposable + { + /// + /// Chat Options ... + /// + ChatOptions Options { get; } + + /// + /// Descriptor of Models which used in Service ... + /// + XAiModelDescriptor Descriptor { get; } + + // + #region Actions ... + /// + /// Base Method for Communicate with LLM ... + /// + /// + /// + /// + /// + Task AskTextAsync( + string prompt, + XUserClaimsInfoDto userInfo = null, + CancellationToken cancellationToken = default + ); + + /// + /// Base Method for Communicate with LLM ... + /// + /// + /// + /// + /// + IAsyncEnumerable AskTextAsEnumerable( + string prompt, + XUserClaimsInfoDto userInfo = null, + CancellationToken cancellationToken = default + ); + + /// + /// Ask a Question By Providing Vector Search Result ... + /// + /// + /// + /// + /// + /// + Task AskTextByContextAsync( + string prompt, + IList context = null, + XUserClaimsInfoDto userInfo = null, + CancellationToken cancellationToken = default + ); + + /// + /// Ask a Question By By Providing Vector Search Result and Stream Response ... + /// + /// + /// + /// + /// + /// + IAsyncEnumerable AskTextByContextAsEnumerable( + string prompt, + IList context = null, + XUserClaimsInfoDto userInfo = null, + CancellationToken cancellationToken = default + ); + + /// + /// Ask a Question By Rag Retrive From Knowledge ... + /// + /// + /// + /// + /// + /// + /// + /// + Task AskTextFromKnowledgeAsync( + string prompt, + string type = null, + int? topK = null, + float? minScore = null, + XUserClaimsInfoDto userInfo = null, + CancellationToken cancellationToken = default + ); + + /// + /// Ask a Question By Rag Retrive From Knowledge and Stream Response ... + /// + /// + /// + /// + /// + /// + /// + /// + IAsyncEnumerable AskTextFromKnowledgeAsEnumerable( + string prompt, + string type = null, + int? topK = null, + float? minScore = null, + XUserClaimsInfoDto userInfo = null, + CancellationToken cancellationToken = default + ); + + /// + /// Ask a Question as Prompt and Retrieve Response ... + /// + /// + /// + /// + /// + /// + /// + /// + /// + /// + /// + /// + Task AskAsync( + string prompt, + string type = null, + int? topK = null, + float? minScore = null, + Guid? projectId = null, + Guid? conversationId = null, + string connectionId = null, + IFormFileCollection files = null, + XUserClaimsInfoDto userInfo = null, + CancellationToken cancellationToken = default + ); + + /// + /// Ask a Question as Prompt and Retrieve Response as Async Enumerable ... + /// + /// + /// + /// + /// + /// + /// + /// + /// + /// + /// + /// + IAsyncEnumerable AskAsEnumerable( + string prompt, + string type = null, + int? topK = null, + float? minScore = null, + Guid? projectId = null, + Guid? conversationId = null, + string connectionId = null, + IFormFileCollection files = null, + XUserClaimsInfoDto userInfo = null, + CancellationToken cancellationToken = default + ); + #endregion + + // + #region Loaders ... + /// + /// Load AI Projects ... + /// + /// + /// + /// + /// + /// + Task> LoadProjects( + string ownerId, + string connectionId = null, + bool includeDefaults = false, + CancellationToken cancellationToken = default + ); + + /// + /// Load Conversations of Specified AI Project ... + /// + /// + /// + /// + /// + Task> LoadConversations( + Guid projectId, + string connectionId = null, + CancellationToken cancellationToken = default + ); + + /// + /// Load Messages of Specified Conversation ... + /// + /// + /// + /// + Task> LoadMessages( + Guid conversationId, + CancellationToken cancellationToken = default + ); + #endregion + + // + #region Queries ... + /// + /// Query Projects ... + /// + /// + /// + /// + /// + Task> QueryProjects( + string ownerId, + XQuery query, + CancellationToken cancellationToken = default + ); + + /// + /// Query Conversations ... + /// + /// + /// + /// + /// + /// + Task> QueryConversations( + string ownerId, + Guid projectId, + XQuery query, + CancellationToken cancellationToken = default + ); + + /// + /// Query Messages ... + /// + /// + /// + /// + /// + /// + Task> QueryMessages( + string ownerId, + Guid conversationId, + XQuery query, + CancellationToken cancellationToken = default + ); + #endregion + + // + #region Creators ... + /// + /// Create an AI Project ... + /// + /// + /// + /// + /// + /// + Task CreateProject( + string ownerId, + XAiProjectDto item, + string connectionId = null, + CancellationToken cancellationToken = default + ); + + /// + /// Create an AI Conversation ... + /// + /// + /// + /// + /// + /// + /// + Task CreateConversation( + string ownerId, + Guid projectId, + XAiConversationDto item, + string connectionId = null, + CancellationToken cancellationToken = default + ); + #endregion + + // + #region Content Extraction ... + /// + /// Try to Extract Files Content ... + /// + /// + /// + /// + /// + Task 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 vectors, + string ownerId = null, + TimeSpan? ttl = null + ); + bool Replace( + Guid sessionId, + IEnumerable vectors, + string ownerId = null + ); + bool Add( + Guid sessionId, + IEnumerable vectors, + string ownerId = null + ); + IList Search( + Guid sessionId, + ReadOnlyMemory 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 +{ + /// + /// a Service for Splitting Long Texts into Overlapping Chunks + /// which Suitable for Embedding ... + /// + public interface IXTextChunker + { + /// + /// Split Text into Chunks ... + /// + /// Source Text + /// Source Name (e.g. File Name) used for Identifier + /// + IList Chunk( + string text, + string source = null + ); + + /// + /// Split Text into Chunks and Return only Texts ... + /// + /// + /// + IList 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 +{ + /// + /// Extractor for source code files ... + /// (C#, Python, JavaScript, TypeScript, Java, Go, Rust, ...) + /// + 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 +{ + /// + /// Extractor for EPUB electronic publication format + /// (application/epub+zip) + /// + 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 +{ + /// + /// a Base Service for Extracting File Content ... + /// + public interface IXFileContentExtractorBase + { + /// + /// Check if this extractor supports the specified MIME type ... + /// + bool CanExtract(string mimeType); + + /// + /// Extract text content from file stream ... + /// + Task ExtractAsync( + Stream fileStream, + string mimeType, + CancellationToken cancellationToken = default + ); + + /// + /// Extract content from stream as Rich Result ... + /// + /// + /// + /// + /// + /// + Task ExtractRichAsync( + Stream fileStream, + string fileName, + string mimeType, + CancellationToken cancellationToken = default + ); + } + + /// + /// a Service for Extracting File Content ... + /// + public interface IXFileContentExtractor + { + /// + /// Check if this extractor supports the specified MIME type ... + /// + /// + /// + /// + bool CanExtract( + string mimeType, + string[] extractors = null + ); + + /// + /// Extract text content from file stream ... + /// + /// + /// + /// + /// + /// + Task ExtractAsync( + Stream fileStream, + string mimeType, + string[] extractors = null, + CancellationToken cancellationToken = default + ); + + /// + /// Extract content from stream as Rich Result ... + /// + /// + /// + /// + /// + /// + /// + Task 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 +{ + /// + /// Extractor for HTML documents (text/html, application/xhtml+xml) + /// + 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 +{ + /// + /// Extractor for OpenDocument Format (ODF) documents + /// (ODT: OpenDocument Text, ODS: OpenDocument Spreadsheet, ODP: OpenDocument Presentation) + /// + 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 +{ + /// + /// Extractor for all PowerPoint Presentation formats + /// (OpenXML: pptx, ppsx, potx, pptm, ppsm, potm | Legacy Binary: ppt, pps, pot) + /// + public interface IXPowerPointFileContentExtractor : IXFileContentExtractorBase + { } +} + +### FILE: C:\Users\saherelm\Documents\Projects\xSaherelmWorkspace\xAiApi\Interfaces\Extractors\IXRtfFileContentExtractor.cs + +namespace xAiApi.Interfaces.Extractors +{ + /// + /// Extractor for Rich Text Format (RTF) documents + /// (application/rtf, text/rtf) + /// + 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 logger; + + public XAiModelProxyMiddleware( + RequestDelegate next, + XAiApiConfiguration configuration, + IHttpClientFactory httpClientFactory, + ILogger logger + ) + { + // + this.next = next; + this.logger = logger; + this.configuration = configuration; + this.httpClientFactory = httpClientFactory; + } + + /// + /// Handle Routing ... + /// + /// + /// + 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(nullable: false), + Deleted = table.Column(nullable: false), + OwnerId = table.Column(maxLength: 255, nullable: false), + Title = table.Column(maxLength: 255, nullable: false), + CreatedOn = table.Column(nullable: false), + UpdatedAt = table.Column(nullable: false), + ProjectId = table.Column(nullable: false) + }, + constraints: table => + { + table.PrimaryKey("PK_AiConversations", x => x.Id); + }); + + migrationBuilder.CreateTable( + name: "AiMcpServers", + columns: table => new + { + Id = table.Column(nullable: false), + Deleted = table.Column(nullable: false), + OwnerId = table.Column(maxLength: 255, nullable: false), + Scope = table.Column(nullable: false), + Name = table.Column(maxLength: 255, nullable: false), + Description = table.Column(maxLength: 1000, nullable: true), + Enabled = table.Column(nullable: false), + EnvironmentVariables = table.Column(nullable: true), + Endpoint = table.Column(maxLength: 1000, nullable: true), + Headers = table.Column(nullable: true), + TimeoutSeconds = table.Column(nullable: false), + CreatedOn = table.Column(nullable: false), + UpdatedAt = table.Column(nullable: false) + }, + constraints: table => + { + table.PrimaryKey("PK_AiMcpServers", x => x.Id); + }); + + migrationBuilder.CreateTable( + name: "AiMessages", + columns: table => new + { + Id = table.Column(nullable: false), + Deleted = table.Column(nullable: false), + OwnerId = table.Column(maxLength: 255, nullable: false), + Content = table.Column(nullable: false), + Role = table.Column(nullable: false), + CreatedOn = table.Column(nullable: false), + UpdatedAt = table.Column(nullable: false), + ConversationId = table.Column(maxLength: 255, nullable: false), + MetaDatas = table.Column(nullable: true) + }, + constraints: table => + { + table.PrimaryKey("PK_AiMessages", x => x.Id); + }); + + migrationBuilder.CreateTable( + name: "AiProjects", + columns: table => new + { + Id = table.Column(nullable: false), + Deleted = table.Column(nullable: false), + OwnerId = table.Column(maxLength: 255, nullable: false), + Title = table.Column(maxLength: 255, nullable: false), + Description = table.Column(maxLength: 1000, nullable: true), + Prompt = table.Column(nullable: true), + CreatedOn = table.Column(nullable: false), + UpdatedAt = table.Column(nullable: false) + }, + constraints: table => + { + table.PrimaryKey("PK_AiProjects", x => x.Id); + }); + + migrationBuilder.CreateTable( + name: "AiVectors", + columns: table => new + { + Id = table.Column(nullable: false), + Deleted = table.Column(nullable: false), + Text = table.Column(nullable: true), + Identifier = table.Column(nullable: true), + Type = table.Column(maxLength: 100, nullable: true), + Embedding = table.Column(nullable: true), + Metadata = table.Column(nullable: true) + }, + constraints: table => + { + table.PrimaryKey("PK_AiVectors", x => x.Id); + }); + + migrationBuilder.CreateTable( + name: "Files", + columns: table => new + { + Id = table.Column(nullable: false), + Deleted = table.Column(nullable: false), + Type = table.Column(nullable: false), + OwnerId = table.Column(maxLength: 255, nullable: false), + Name = table.Column(maxLength: 255, nullable: false), + Path = table.Column(nullable: false), + Thumb = table.Column(nullable: true), + ThumbPath = table.Column(nullable: true), + UploadedOn = table.Column(nullable: false), + FileName = table.Column(nullable: true), + References = table.Column(nullable: true) + }, + constraints: table => + { + table.PrimaryKey("PK_Files", x => x.Id); + }); + + migrationBuilder.CreateTable( + name: "Strings", + columns: table => new + { + Id = table.Column(nullable: false) + .Annotation("Sqlite:Autoincrement", true), + Deleted = table.Column(nullable: false), + Language = table.Column(maxLength: 10, nullable: false), + ResourceTitle = table.Column(maxLength: 255, nullable: false), + TranslatedValue = table.Column(nullable: false) + }, + constraints: table => + { + table.PrimaryKey("PK_Strings", x => x.Id); + }); + + migrationBuilder.CreateTable( + name: "Tags", + columns: table => new + { + Id = table.Column(nullable: false) + .Annotation("Sqlite:Autoincrement", true), + Deleted = table.Column(nullable: false), + Tag = table.Column(maxLength: 255, nullable: false), + References = table.Column(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 + +// +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("Id") + .ValueGeneratedOnAdd() + .HasColumnType("TEXT"); + + b.Property("CreatedOn") + .HasColumnType("TEXT"); + + b.Property("Deleted") + .HasColumnType("INTEGER"); + + b.Property("OwnerId") + .IsRequired() + .HasColumnType("TEXT") + .HasMaxLength(255); + + b.Property("ProjectId") + .HasColumnType("TEXT"); + + b.Property("Title") + .IsRequired() + .HasColumnType("TEXT") + .HasMaxLength(255); + + b.Property("UpdatedAt") + .HasColumnType("TEXT"); + + b.HasKey("Id"); + + b.ToTable("AiConversations"); + }); + + modelBuilder.Entity("xAiModels.Models.Entities.XAiMcpServer", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("TEXT"); + + b.Property("CreatedOn") + .HasColumnType("TEXT"); + + b.Property("Deleted") + .HasColumnType("INTEGER"); + + b.Property("Description") + .HasColumnType("TEXT") + .HasMaxLength(1000); + + b.Property("Enabled") + .HasColumnType("INTEGER"); + + b.Property("Endpoint") + .HasColumnType("TEXT") + .HasMaxLength(1000); + + b.Property("EnvironmentVariables") + .HasColumnType("TEXT"); + + b.Property("Headers") + .HasColumnType("TEXT"); + + b.Property("Name") + .IsRequired() + .HasColumnType("TEXT") + .HasMaxLength(255); + + b.Property("OwnerId") + .IsRequired() + .HasColumnType("TEXT") + .HasMaxLength(255); + + b.Property("Scope") + .HasColumnType("INTEGER"); + + b.Property("TimeoutSeconds") + .HasColumnType("INTEGER"); + + b.Property("UpdatedAt") + .HasColumnType("TEXT"); + + b.HasKey("Id"); + + b.ToTable("AiMcpServers"); + }); + + modelBuilder.Entity("xAiModels.Models.Entities.XAiMessage", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("TEXT"); + + b.Property("Content") + .IsRequired() + .HasColumnType("TEXT"); + + b.Property("ConversationId") + .HasColumnType("TEXT") + .HasMaxLength(255); + + b.Property("CreatedOn") + .HasColumnType("TEXT"); + + b.Property("Deleted") + .HasColumnType("INTEGER"); + + b.Property("MetaDatas") + .HasColumnType("TEXT"); + + b.Property("OwnerId") + .IsRequired() + .HasColumnType("TEXT") + .HasMaxLength(255); + + b.Property("Role") + .HasColumnType("INTEGER"); + + b.Property("UpdatedAt") + .HasColumnType("TEXT"); + + b.HasKey("Id"); + + b.ToTable("AiMessages"); + }); + + modelBuilder.Entity("xAiModels.Models.Entities.XAiProject", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("TEXT"); + + b.Property("CreatedOn") + .HasColumnType("TEXT"); + + b.Property("Deleted") + .HasColumnType("INTEGER"); + + b.Property("Description") + .HasColumnType("TEXT") + .HasMaxLength(1000); + + b.Property("OwnerId") + .IsRequired() + .HasColumnType("TEXT") + .HasMaxLength(255); + + b.Property("Prompt") + .HasColumnType("TEXT"); + + b.Property("Title") + .IsRequired() + .HasColumnType("TEXT") + .HasMaxLength(255); + + b.Property("UpdatedAt") + .HasColumnType("TEXT"); + + b.HasKey("Id"); + + b.ToTable("AiProjects"); + }); + + modelBuilder.Entity("xAiModels.Models.Entities.XAiVector", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("TEXT"); + + b.Property("Deleted") + .HasColumnType("INTEGER"); + + b.Property("Embedding") + .HasColumnType("TEXT"); + + b.Property("Identifier") + .HasColumnType("TEXT"); + + b.Property("Metadata") + .HasColumnType("TEXT"); + + b.Property("Text") + .HasColumnType("TEXT"); + + b.Property("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("Id") + .ValueGeneratedOnAdd() + .HasColumnType("TEXT"); + + b.Property("Deleted") + .HasColumnType("INTEGER"); + + b.Property("FileName") + .HasColumnType("TEXT"); + + b.Property("Name") + .IsRequired() + .HasColumnType("TEXT") + .HasMaxLength(255); + + b.Property("OwnerId") + .IsRequired() + .HasColumnType("TEXT") + .HasMaxLength(255); + + b.Property("Path") + .IsRequired() + .HasColumnType("TEXT"); + + b.Property("References") + .HasColumnType("TEXT"); + + b.Property("Thumb") + .HasColumnType("TEXT"); + + b.Property("ThumbPath") + .HasColumnType("TEXT"); + + b.Property("Type") + .HasColumnType("INTEGER"); + + b.Property("UploadedOn") + .HasColumnType("TEXT"); + + b.HasKey("Id"); + + b.ToTable("Files"); + }); + + modelBuilder.Entity("xStringService.Models.Entities.XString", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("INTEGER"); + + b.Property("Deleted") + .HasColumnType("INTEGER"); + + b.Property("Language") + .IsRequired() + .HasColumnType("TEXT") + .HasMaxLength(10); + + b.Property("ResourceTitle") + .IsRequired() + .HasColumnType("TEXT") + .HasMaxLength(255); + + b.Property("TranslatedValue") + .IsRequired() + .HasColumnType("TEXT"); + + b.HasKey("Id"); + + b.ToTable("Strings"); + }); + + modelBuilder.Entity("xTagService.Models.Entities.XTag", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("INTEGER"); + + b.Property("Deleted") + .HasColumnType("INTEGER"); + + b.Property("References") + .HasColumnType("TEXT"); + + b.Property("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 + +// +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("Id") + .ValueGeneratedOnAdd() + .HasColumnType("TEXT"); + + b.Property("CreatedOn") + .HasColumnType("TEXT"); + + b.Property("Deleted") + .HasColumnType("INTEGER"); + + b.Property("OwnerId") + .IsRequired() + .HasColumnType("TEXT") + .HasMaxLength(255); + + b.Property("ProjectId") + .HasColumnType("TEXT"); + + b.Property("Title") + .IsRequired() + .HasColumnType("TEXT") + .HasMaxLength(255); + + b.Property("UpdatedAt") + .HasColumnType("TEXT"); + + b.HasKey("Id"); + + b.ToTable("AiConversations"); + }); + + modelBuilder.Entity("xAiModels.Models.Entities.XAiMcpServer", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("TEXT"); + + b.Property("CreatedOn") + .HasColumnType("TEXT"); + + b.Property("Deleted") + .HasColumnType("INTEGER"); + + b.Property("Description") + .HasColumnType("TEXT") + .HasMaxLength(1000); + + b.Property("Enabled") + .HasColumnType("INTEGER"); + + b.Property("Endpoint") + .HasColumnType("TEXT") + .HasMaxLength(1000); + + b.Property("EnvironmentVariables") + .HasColumnType("TEXT"); + + b.Property("Headers") + .HasColumnType("TEXT"); + + b.Property("Name") + .IsRequired() + .HasColumnType("TEXT") + .HasMaxLength(255); + + b.Property("OwnerId") + .IsRequired() + .HasColumnType("TEXT") + .HasMaxLength(255); + + b.Property("Scope") + .HasColumnType("INTEGER"); + + b.Property("TimeoutSeconds") + .HasColumnType("INTEGER"); + + b.Property("UpdatedAt") + .HasColumnType("TEXT"); + + b.HasKey("Id"); + + b.ToTable("AiMcpServers"); + }); + + modelBuilder.Entity("xAiModels.Models.Entities.XAiMessage", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("TEXT"); + + b.Property("Content") + .IsRequired() + .HasColumnType("TEXT"); + + b.Property("ConversationId") + .HasColumnType("TEXT") + .HasMaxLength(255); + + b.Property("CreatedOn") + .HasColumnType("TEXT"); + + b.Property("Deleted") + .HasColumnType("INTEGER"); + + b.Property("MetaDatas") + .HasColumnType("TEXT"); + + b.Property("OwnerId") + .IsRequired() + .HasColumnType("TEXT") + .HasMaxLength(255); + + b.Property("Role") + .HasColumnType("INTEGER"); + + b.Property("UpdatedAt") + .HasColumnType("TEXT"); + + b.HasKey("Id"); + + b.ToTable("AiMessages"); + }); + + modelBuilder.Entity("xAiModels.Models.Entities.XAiProject", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("TEXT"); + + b.Property("CreatedOn") + .HasColumnType("TEXT"); + + b.Property("Deleted") + .HasColumnType("INTEGER"); + + b.Property("Description") + .HasColumnType("TEXT") + .HasMaxLength(1000); + + b.Property("OwnerId") + .IsRequired() + .HasColumnType("TEXT") + .HasMaxLength(255); + + b.Property("Prompt") + .HasColumnType("TEXT"); + + b.Property("Title") + .IsRequired() + .HasColumnType("TEXT") + .HasMaxLength(255); + + b.Property("UpdatedAt") + .HasColumnType("TEXT"); + + b.HasKey("Id"); + + b.ToTable("AiProjects"); + }); + + modelBuilder.Entity("xAiModels.Models.Entities.XAiVector", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("TEXT"); + + b.Property("Deleted") + .HasColumnType("INTEGER"); + + b.Property("Embedding") + .HasColumnType("TEXT"); + + b.Property("Identifier") + .HasColumnType("TEXT"); + + b.Property("Metadata") + .HasColumnType("TEXT"); + + b.Property("Text") + .HasColumnType("TEXT"); + + b.Property("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("Id") + .ValueGeneratedOnAdd() + .HasColumnType("TEXT"); + + b.Property("Deleted") + .HasColumnType("INTEGER"); + + b.Property("FileName") + .HasColumnType("TEXT"); + + b.Property("Name") + .IsRequired() + .HasColumnType("TEXT") + .HasMaxLength(255); + + b.Property("OwnerId") + .IsRequired() + .HasColumnType("TEXT") + .HasMaxLength(255); + + b.Property("Path") + .IsRequired() + .HasColumnType("TEXT"); + + b.Property("References") + .HasColumnType("TEXT"); + + b.Property("Thumb") + .HasColumnType("TEXT"); + + b.Property("ThumbPath") + .HasColumnType("TEXT"); + + b.Property("Type") + .HasColumnType("INTEGER"); + + b.Property("UploadedOn") + .HasColumnType("TEXT"); + + b.HasKey("Id"); + + b.ToTable("Files"); + }); + + modelBuilder.Entity("xStringService.Models.Entities.XString", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("INTEGER"); + + b.Property("Deleted") + .HasColumnType("INTEGER"); + + b.Property("Language") + .IsRequired() + .HasColumnType("TEXT") + .HasMaxLength(10); + + b.Property("ResourceTitle") + .IsRequired() + .HasColumnType("TEXT") + .HasMaxLength(255); + + b.Property("TranslatedValue") + .IsRequired() + .HasColumnType("TEXT"); + + b.HasKey("Id"); + + b.ToTable("Strings"); + }); + + modelBuilder.Entity("xTagService.Models.Entities.XTag", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("INTEGER"); + + b.Property("Deleted") + .HasColumnType("INTEGER"); + + b.Property("References") + .HasColumnType("TEXT"); + + b.Property("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 +{ + /// + /// Result of Ingesting Documents into an In-Memory Session ... + /// + public class XAiDocumentIngestResult + { + /// + /// Session Identifier which must be used in Ask Requests ... + /// + public Guid SessionId { get; set; } + + /// + /// Count of Successfully Processed Files ... + /// + public int FilesCount { get; set; } + + /// + /// Count of Chunks (Vectors) Added to Session ... + /// + public int ChunksCount { get; set; } + + /// + /// Total Vectors Count in Session after Ingest ... + /// + public int TotalVectorsCount { get; set; } + + /// + /// Files which Skipped (Unsupported / Empty / Failed) ... + /// + public IList SkippedFiles { get; set; } = new List(); + + /// + /// Session Expiration Time (UTC) based on Last Access ... + /// + public DateTime ExpiresAtUtc { get; set; } + } + + /// + /// Request for Asking a Question over Ingested Documents ... + /// + public class XAiDocumentAskRequest + { + /// + /// Session Identifier ... + /// + public Guid SessionId { get; set; } + + /// + /// User Question ... + /// + public string Prompt { get; set; } + + /// + /// Count of Top Chunks used as Context (Optional) ... + /// + public int? TopK { get; set; } + + /// + /// Minimum Similarity Score of Chunks (Optional) ... + /// + public float? MinScore { get; set; } + } + + /// + /// a Source Chunk which used for Generating Answer ... + /// + public class XAiDocumentSource + { + /// + /// Doc and Chunk Identifier (e.g. "file.pdf#3") ... + /// + public string Identifier { get; set; } + + /// + /// Source File Name ... + /// + public string FileName { get; set; } + + /// + /// Chunk Index in Source File ... + /// + public int? ChunkIndex { get; set; } + + /// + /// Similarity Score ... + /// + public float Score { get; set; } + + /// + /// Short Snippet of Chunk Text ... + /// + public string Snippet { get; set; } + + /// + /// Knowledge Scope the Chunk Retrieved from (Null for Session Based Documents) ... + /// + public string Scope { get; set; } + + /// + /// Knowledge Type of the Chunk ... + /// + public string Type { get; set; } + } + + /// + /// Answer of a Chat With Documents Request ... + /// + public class XAiDocumentAnswer + { + /// + /// Session Identifier ... + /// + public Guid SessionId { get; set; } + + /// + /// Generated Answer ... + /// + public string Answer { get; set; } + + /// + /// True when no Relevant Chunk Found in Session ... + /// + public bool NoContextFound { get; set; } + + /// + /// Sources used for Generating Answer ... + /// + public IList Sources { get; set; } = new List(); + } + + /// + /// Streaming Chunk of a Chat With Documents Answer ... + /// + public class XAiDocumentAnswerChunk + { + /// + /// Text Delta ... + /// + public string Text { get; set; } + + /// + /// True for Last Chunk ... + /// + public bool IsFinal { get; set; } + + /// + /// True when no Relevant Chunk Found in Session ... + /// + public bool NoContextFound { get; set; } + + /// + /// Sources (Only Filled in First Chunk) ... + /// + public IList Sources { get; set; } + } + + /// + /// Public Info of a Document Session (without Embeddings) ... + /// + 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 Files { get; set; } = new List(); + } + + /// + /// Document RAG Configuration ... + /// + 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 ... + /// + /// Max Files Accepted in a Single Ingest Request (0 = Unlimited) ... + /// + public int MaxFilesPerIngest { get; set; } = 20; + + /// + /// Max Size of a Single File in Bytes (0 = Unlimited) ... + /// + public long MaxFileSizeBytes { get; set; } = 25 * 1024 * 1024; + + /// + /// Max Distinct Documents Allowed in a Non-Global Scope (0 = Unlimited) ... + /// + 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 Vectors { get; set; } = new List(); + 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 +{ + /// + /// Describes Target Knowledge Base Scope of an Operation ... + /// + public class XAiKnowledgeScopeDescriptor + { + /// + /// Scope Kind ... + /// + public XAiKnowledgeScope Scope { get; set; } = XAiKnowledgeScope.User; + + /// + /// Scope Identifier (ProjectId / ConversationId) - Null for Global and User ... + /// + public Guid? ScopeId { get; set; } + + /// + /// Optional Knowledge Type / Domain Filter ... + /// + public string Type { get; set; } + + /// + /// Create User Scope Knowledge Descriptor ... + /// + /// + /// + public static XAiKnowledgeScopeDescriptor User( + string type = null + ) => new() + { + // + Type = type ?? XAiModelsConstants.XAiDefaultKnowledgeType, + ScopeId = null, + Scope = XAiKnowledgeScope.User, + }; + + /// + /// Create Global Scope Knowledge Descriptor ... + /// + /// + /// + public static XAiKnowledgeScopeDescriptor Global( + string type = null + ) => new() + { + Type = type ?? XAiModelsConstants.XAiDefaultKnowledgeType, + ScopeId = null, + Scope = XAiKnowledgeScope.Global, + }; + + /// + /// Create Project Scope Knowledge Descriptor ... + /// + /// + /// + /// + public static XAiKnowledgeScopeDescriptor Project( + Guid projectId, + string type = null + ) => new() + { + Type = type ?? XAiModelsConstants.XAiDefaultKnowledgeType, + ScopeId = projectId, + Scope = XAiKnowledgeScope.Project, + }; + + /// + /// Create Conversational Scope Knowledge Descriptor ... + /// + /// + /// + /// + public static XAiKnowledgeScopeDescriptor Conversation( + Guid conversationId, + string type = null + ) => new() + { + Type = type ?? XAiModelsConstants.XAiDefaultKnowledgeType, + ScopeId = conversationId, + Scope = XAiKnowledgeScope.Conversation, + }; + } + + /// + /// Result of Ingesting Files into Persistent Knowledge Base (XAiVector Table) ... + /// + public class XAiKnowledgeIngestResult + { + /// + /// Target Scope ... + /// + public XAiKnowledgeScope Scope { get; set; } + + /// + /// Target Scope Identifier (Null for Global) ... + /// + public Guid? ScopeId { get; set; } + + /// + /// Knowledge Type of Ingested Vectors ... + /// + public string Type { get; set; } + + /// + /// Count of Successfully Ingested Files ... + /// + public int FilesCount { get; set; } + + /// + /// Count of Stored Chunks (Vectors) in this Request ... + /// + public int ChunksCount { get; set; } + + /// + /// Count of Removed Stale Vectors (Re-Ingest) ... + /// + public int ReplacedCount { get; set; } + + /// + /// Skipped Files (Empty, Unsupported or Extraction Failed) ... + /// + public IList SkippedFiles { get; set; } = new List(); + + /// + /// Ingested Documents Info ... + /// + public IList Documents { get; set; } = new List(); + } + + /// + /// Ask Request over Persistent Knowledge Base ... + /// Retrieval is Tiered: Conversation -> Project -> User -> Global (Each Tier Fills Remaining TopK) ... + /// + public class XAiKnowledgeAskRequest + { + /// + /// Question ... + /// + public string Prompt { get; set; } + + /// + /// Optional: Conversation Scope (Caller must be Conversation Owner) ... + /// When Provided, Conversation's Project is used for Second Tier Automatically ... + /// + public Guid? ConversationId { get; set; } + + /// + /// Optional: Project Scope (Caller must be Project Owner) ... + /// + public Guid? ProjectId { get; set; } + + /// + /// Include Personal (User) Knowledge Tier (default true) ... + /// + public bool IncludeUser { get; set; } = true; + + /// + /// Include Global Knowledge Tier (default true) ... + /// + public bool IncludeGlobal { get; set; } = true; + + /// + /// Optional: Restrict Retrieval to a Knowledge Type / Domain ... + /// + public string Type { get; set; } + + /// + /// Optional: Restrict Retrieval to a Specific File Name ... + /// + public string FileName { get; set; } + + /// + /// Optional: Max Retrieved Chunks ... + /// + public int? TopK { get; set; } + + /// + /// Optional: Minimum Cosine Similarity Score ... + /// + public float? MinScore { get; set; } + } + + /// + /// Ingested Document Info ... + /// + public class XAiKnowledgeDocumentInfo + { + /// + /// Scope ... + /// + public XAiKnowledgeScope Scope { get; set; } + + /// + /// Scope Identifier (Null for Global) ... + /// + public Guid? ScopeId { get; set; } + + /// + /// Knowledge Type ... + /// + public string Type { get; set; } + + /// + /// File Name ... + /// + public string FileName { get; set; } + + /// + /// Mime Type ... + /// + public string MimeType { get; set; } + + /// + /// Ingesting User Identifier ... + /// + public string OwnerId { get; set; } + + /// + /// Count of Stored Chunks ... + /// + public int ChunksCount { get; set; } + + /// + /// Ingestion Time (UTC) ... + /// + public DateTime? IngestedAtUtc { get; set; } + } + + /// + /// Public Vector Info (Export) ... + /// + 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 Metadata { get; set; } + + /// + /// Embedding (Only Filled when Requested) ... + /// + public float[] Embedding { get; set; } + } +} + + +### FILE: C:\Users\saherelm\Documents\Projects\xSaherelmWorkspace\xAiApi\Models\XAiMcpServerDescriptor.cs + +namespace xAiApi.Models +{ + /// + /// Describe an Mcp Server for Seeding ... + /// + 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 + { + /// + /// Enable Proxy or not ... + /// + /// + public bool Enabled { get; set; } = false; + + /// + /// Proxy Prefix ... + /// + /// + 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 + { + /// + /// Provides Trained Data Path ... + /// + public string DataPath { get; set; } + + /// + /// The Engine for Doing OCR ... + /// + public EngineMode EngineMode { get; set; } + + /// + /// Enable OCR Fallback using Model ... + /// + public bool EnableOcrFallback { get; set; } + + /// + /// Default OCR Language ... + /// + 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\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 +{ + /// + /// a Shared Context Between Actions for Generation ... + /// + public class XPreparedChatContext + { + /// + /// Specified Related Project, if Exists ... + /// + public XAiProjectDto Project { get; set; } = null; + + /// + /// Specified Related Conversation, if Exists ... + /// + public XAiConversationDto Conversation { get; set; } = null; + + /// + /// Specified Message History, if Exists ... + /// + public IList History { get; set; } = []; + + /// + /// Specified Vector Search Conext, if Exists ... + /// + public IList Context { get; set; } = []; + + /// + /// Specified Persisted Prompt, if Exists ... + /// + public XAiMessageDto PersistedPromptMessage { get; set; } = null; + } +} + +### FILE: C:\Users\saherelm\Documents\Projects\xSaherelmWorkspace\xAiApi\Models\XTextChunk.cs + +namespace xAiApi.Models +{ + /// + /// Represents a Chunk of a Text which Produced by Text Chunker ... + /// + public class XTextChunk + { + /// + /// Zero Based Index of Chunk in Source Text ... + /// + public int Index { get; set; } + + /// + /// Chunk Text Content ... + /// + public string Text { get; set; } = string.Empty; + + /// + /// Source Name (e.g. File Name) which Chunk Extracted From ... + /// + public string Source { get; set; } + + /// + /// Doc and Chunk Identifier (e.g. "file.pdf#3") ... + /// + public string Identifier { get; set; } + + /// + /// Start Offset of Chunk in Normalized Source Text ... + /// + public int StartOffset { get; set; } + + /// + /// Length of Chunk Text ... + /// + public int Length => Text?.Length ?? 0; + } +} + +### FILE: C:\Users\saherelm\Documents\Projects\xSaherelmWorkspace\xAiApi\Models\XTextChunkerDescriptor.cs + +namespace xAiApi.Models +{ + /// + /// Text Chunker Descriptor ... + /// + public class XTextChunkerDescriptor + { + /// + /// Maximum Characters Count of each Chunk ... + /// + public int ChunkSize { get; set; } = 800; + + /// + /// Characters Count which Shared between two Consecutive Chunks ... + /// + public int ChunkOverlap { get; set; } = 150; + + /// + /// Chunks Smaller than this Size will be Merged into Previous Chunk ... + /// + public int MinChunkSize { get; set; } = 50; + + /// + /// Chunck Identifier Separator ... + /// + public string ChunkIdentifierSeparator { get; set; } = "#"; + + /// + /// Normalize Line Endings and Repeated Whitespaces before Chunking ... + /// + 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 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 +{ + /// + /// Base Embedding Provider Service ... + /// + 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 logger; + private readonly IXFileContentExtractor fileContentExtractor; + + protected XAiEmbeddingServiceBase( + IXAiDataProvider dataProvider, + XAiApiConfiguration configuration, + XValidationProvider validationProvider, + ILogger 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; + } + + /// + /// Embedding Specified String ... + /// + /// + /// + /// + public virtual async Task Embedding( + string content, + CancellationToken cancellationToken = default + ) + { + // + // Validate ... + if (content.IsNullOrEmpty()) + { + XException.InvalidArgs.Throw(); + } + + // + var generator = GetEmbeddingGenerator(); + + // + GeneratedEmbeddings> 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; + } + + /// + /// Embedding Specified Batch ... + /// + /// + /// + /// + public virtual async Task> Embeddings( + string[] batch, + CancellationToken cancellationToken = default + ) + { + // + // Validate ... + if (!batch.HasChild() || + !batch.All(x => !x.IsNullOrEmpty()) + ) + { + XException.InvalidArgs.Throw(); + } + + // + using var generator = GetEmbeddingGenerator(); + + // + GeneratedEmbeddings> 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; + } + + /// + /// Embedding Generator ... + /// + /// + public IEmbeddingGenerator> GetEmbeddingGenerator() + { + // + IEmbeddingGenerator> 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 xAiModels.Extensions; +using xExceptions.Constants; +using xAiModels.Models.Dtos; +using xIdentityModels.Models; +using System.Threading.Tasks; +using System.Linq.Expressions; +using xAiModels.Providers.Hubs; +using xAiModels.Models.Entities; +using xAiModels.Interfaces.Dtos; +using xIdentityHelper.Extensions; +using System.Collections.Generic; +using xIdentityService.Interfaces; +using ModelContextProtocol.Client; +using Microsoft.Extensions.Logging; +using Microsoft.AspNetCore.SignalR; +using xAiModels.Interfaces.Entities; +using xAiModels.Interfaces.Enrichers; + +namespace xAiApi.Providers +{ + /// + /// MCP Manager / Provider ... + /// + public class XAiMcpServerProvider : IXAiMcpServerProvider, IAsyncDisposable + { + private readonly IHubContext hub; + private readonly IXIdentityProvider identityProvider; + private readonly ILogger logger; + private readonly XValidationProvider validationProvider; + private readonly IXAiMcpServerEnricher mcpServerEnricher; + private readonly IXAiMcpServerServiceProvider mcpServerServiceProvider; + private readonly IXAiMcpServerRepositoryProvider mcpServerRepositoryProvider; + + private readonly Dictionary clients = []; + private readonly Dictionary mcpServers = []; + private readonly Dictionary> tools = []; + private readonly SemaphoreSlim initLock = new(1, 1); + private bool isInitialized = false; + + public XAiMcpServerProvider( + IHubContext hub, + IXIdentityProvider identityProvider, + ILogger logger, + XValidationProvider validationProvider, + IXAiMcpServerEnricher mcpServerEnricher, + IXAiMcpServerServiceProvider mcpServerServiceProvider, + IXAiMcpServerRepositoryProvider mcpServerRepositoryProvider + ) + { + // + this.hub = hub; + this.logger = logger; + 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 ... + /// + /// Get a List Of Available Tools which Provided using registered Mcp Servers ... + /// + /// + /// + /// + /// + public async Task> 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; + } + + // + // Check Initialization ... + if (isInitialized) + { + // + var selectedServers = mcpServers + .Where(s => + s.Value.OwnerId == userInfo.UserId || + s.Value.Scope == XAiMcpServerUsageScope.All + ) + .Select(s => s.Key); + var result = tools + .Where(c => selectedServers.Contains(c.Key)) + .SelectMany(c => c.Value); + return [.. result]; + } + + // + await initLock.WaitAsync(cancellationToken); + try + { + // + if (isInitialized) + { + // + var selectedServers = mcpServers + .Where(s => + s.Value.OwnerId == userInfo.UserId || + s.Value.Scope == XAiMcpServerUsageScope.All + ) + .Select(s => s.Key); + var result = tools + .Where(c => selectedServers.Contains(c.Key)) + .SelectMany(c => c.Value); + return [.. result]; + } + + // + var servers = await mcpServerServiceProvider + .FindManyAsync( + orderBuilder: null, + includeBuilder: null, + ignoreSoftDeleteds: true, + predicate: x => x.Enabled, + cancellationToken: cancellationToken + ); + if (servers.HasChild()) + { + // + var tasks = servers + .Select(s => + ConnectAndValidateAsync(s, cancellationToken)); + await Task.WhenAll(tasks); + } + + // + isInitialized = true; + return [.. tools.Values.SelectMany(t => t)]; + } + finally + { + initLock.Release(); + } + } + + /// + /// Test Specified Mcp Server ... + /// + /// + /// + /// + public async Task TestServerAsync( + XAiMcpServerDto server, + CancellationToken cancellationToken = default + ) + { + // + try + { + // + using var cts = CancellationTokenSource.CreateLinkedTokenSource(cancellationToken); + cts.CancelAfter(TimeSpan.FromSeconds(server.TimeoutSeconds)); + + // + var client = await CreateClientAsync(server, cts.Token); + 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} ..."; + } + } + + /// + /// Force Refresh Mcp Servers ... + /// + /// + public async Task RefreshAsync() + { + // + 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(cancellationToken: CancellationToken.None); + } + #endregion + + // + #region Actions ... + /// + /// Add an Mcp Server ... + /// + /// + /// + /// + /// + /// + public async Task 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 + { + await ConnectAndValidateAsync(result, cancellationToken); + } + finally + { + initLock.Release(); + } + } + + // + return result; + } + + /// + /// Get an Mcp Server ... + /// + /// + /// + /// + /// + public async Task 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; + } + + /// + /// Update Specified Mcp Server ... + /// + /// + /// + /// + /// + /// + /// + public async Task 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 + { + // + // Remove Exists ... + tools.Remove(result.Id); + clients.Remove(result.Id); + mcpServers.Remove(result.Id); + + // + // Update ... + await ConnectAndValidateAsync(result, cancellationToken); + } + finally + { + initLock.Release(); + } + } + + // + return result; + } + + /// + /// Remove Specified Mcp Server ... + /// + /// + /// + /// + /// + /// + public async Task 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 Exists ... + tools.Remove(result.Id); + clients.Remove(result.Id); + mcpServers.Remove(result.Id); + } + finally + { + initLock.Release(); + } + } + + // + return result; + } + + /// + /// Disable Specified Mcp Server ... + /// + /// + /// + /// + /// + /// + public async Task 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 Exists ... + tools.Remove(exists.Id); + clients.Remove(exists.Id); + mcpServers.Remove(exists.Id); + } + finally + { + initLock.Release(); + } + } + + // + return result; + } + + /// + /// Enable Specified Mcp Server ... + /// + /// + /// + /// + /// + /// + public async Task 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 + { + await ConnectAndValidateAsync(exists, cancellationToken); + } + finally + { + initLock.Release(); + } + } + + // + return result; + } + + /// + /// Toggle Specified Mcp Server ... + /// + /// + /// + /// + /// + /// + public async Task 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) + { + await ConnectAndValidateAsync(exists, cancellationToken); + } + else + { + // + // Remove Exists ... + tools.Remove(exists.Id); + clients.Remove(exists.Id); + mcpServers.Remove(exists.Id); + } + } + finally + { + initLock.Release(); + } + } + + // + return result; + } + + /// + /// Retrieve all Mcp Server ... + /// + /// + /// + /// + /// + public async Task> 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(); + Func, IOrderedQueryable> 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; + } + + /// + /// Find Specified Mcp Server ... + /// + /// + /// + /// + /// + /// + public async Task FindOne( + Expression> 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> 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; + } + + /// + /// Find a Collection of Specified Mcp Servers ... + /// + /// + /// + /// + /// + /// + public async Task> FindMany( + Expression> 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> 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; + } + + /// + /// Query Registered Mcp Servers ... + /// + /// + /// + /// + /// + /// + public async Task> 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> 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 ParseJsonDict(string json) + => json.IsNullOrEmpty() ? null + : JsonSerializer.Deserialize>(json); + + private static List ParseJsonList(string json) + => json.IsNullOrEmpty() ? null + : JsonSerializer.Deserialize>(json); + + private static async Task CreateClientAsync( + XAiMcpServerDto s, + CancellationToken cancellationToken + ) + { + // + IClientTransport transport = new HttpClientTransport(new HttpClientTransportOptions + { + Endpoint = new Uri(s.Endpoint!), + AdditionalHeaders = ParseJsonDict(s.Headers), + TransportMode = HttpTransportMode.AutoDetect + }); + + // + return await McpClient + .CreateAsync( + transport, + cancellationToken: cancellationToken + ); + } + + private async Task ConnectAndValidateAsync( + XAiMcpServerDto descriptor, + CancellationToken cancellationToken + ) + { + // + try + { + // + using var cts = CancellationTokenSource.CreateLinkedTokenSource(cancellationToken); + cts.CancelAfter(TimeSpan.FromSeconds(descriptor.TimeoutSeconds)); + + // + var client = await CreateClientAsync(descriptor, cts.Token); + await client.PingAsync(cancellationToken: cts.Token); + var serverTools = await client + .ListToolsAsync(cancellationToken: cts.Token); + + // + clients[descriptor.Id] = client; + tools[descriptor.Id] = serverTools; + mcpServers[descriptor.Id] = descriptor; + + // + logger.LogInformation( + "MCP '{Name}': {Count} Tools Detected ...", + descriptor.Name, + serverTools.Count + ); + } + catch (Exception ex) + { + // + logger.LogWarning(ex, + "MCP '{Name}': Connection Established Failed, Ignored ...", + descriptor.Name + ); + } + } + #endregion + + // + #region Hub Actions ... + /// + /// Send Custom Push Message ... + /// + /// + /// + /// + /// + /// + public async Task SendPush( + string action, + string payLoad, + string connectionId = null, + CancellationToken cancellationToken = default + ) + { + // + try + { + // + // Collect Allowed Actions ... + var actions = new List + { + 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 +{ + /// + /// 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 ... + /// + public class XAiRAGService : IXAiRAGService + { + private readonly IXTextChunker textChunker; + private readonly IXFileProvider fileProvider; + private readonly IXAiDataProvider dataProvider; + private readonly ILogger logger; + private readonly XAiApiConfiguration configuration; + private readonly IXAiEmbeddingService embeddingService; + private readonly IXFileContentExtractor fileContentExtractor; + + /// + /// Characters which are not Allowed in File Name Part of Identifier ... + /// + private static readonly char[] UnsafeFileNameChars = ['/', '\\', '#']; + + public XAiRAGService( + IXTextChunker textChunker, + IXFileProvider fileProvider, + IXAiDataProvider dataProvider, + ILogger 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 ... + /// + /// Ingest Files into Specified Knowledge Scope: + /// Extract -> Chunk -> Embed -> Store (XAiVector) ... + /// + /// + /// + /// + /// + /// + /// + /// + public async Task 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 ... + /// + /// Embed Prompt and Retrieve Relevant Chunks (Tiered: Conversation -> Project -> User -> Global) ... + /// Each Tier Fills Remaining TopK; Duplicates are Removed ... + /// + /// + /// + /// + /// + public async Task> 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(); + var seen = new HashSet(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 ... + /// + /// List Ingested Documents of Specified Scope ... + /// + /// + /// + /// + /// + public async Task> 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; + } + + /// + /// Remove All Vectors of a Document in Specified Scope ... + /// + /// + /// + /// + /// + /// + /// Count of Removed Vectors + public async Task 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; + } + + /// + /// 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 ... + /// + /// + /// + /// Count of Migrated Vectors + public async Task 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(); + 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; + } + + /// + /// Map Search Results to Public Sources ... + /// + /// + /// + public IList ToSources( + IEnumerable 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 ... + /// + /// Extract Plain Text of a File (Text or Audio Transcript) ... + /// + private async Task ExtractText( + IFormFile file, + string mimeType, + CancellationToken cancellationToken + ) + { + // + try + { + // + using var stream = file.OpenReadStream(); + var extraction = await fileContentExtractor.ExtractRichAsync( + fileStream: stream, + mimeType: mimeType, + fileName: file.FileName, + cancellationToken: cancellationToken + ); + + // + var result = extraction?.Text; + if (string.IsNullOrWhiteSpace(result)) + { + result = extraction?.AudioTranscript; + } + + // + return result; + } + catch (OperationCanceledException) + { + throw; + } + catch (Exception ex) + { + logger.LogWarning(ex, "Knowledge: Extraction Failed for {FileName}", file.FileName); + return null; + } + } + + /// + /// Embed Chunks in Batches and Build Vectors (with Scope Metadata) ... + /// + private async Task> EmbedChunks( + XAiKnowledgeScopeDescriptor scope, + IList chunks, + string type, + string ownerId, + string fileName, + string mimeType, + string ingestedAtUtc, + CancellationToken cancellationToken + ) + { + // + var rag = configuration.RAGDescriptor; + var batchSize = Math.Max(1, rag.EmbeddingBatchSize); + var result = new List(chunks.Count); + + // + for (var offset = 0; offset < chunks.Count; offset += batchSize) + { + // + cancellationToken.ThrowIfCancellationRequested(); + + // + var batch = chunks.Skip(offset).Take(batchSize).ToList(); + var embeddings = await embeddingService.Embeddings( + batch: batch.Select(c => c.Text).ToArray(), + cancellationToken: cancellationToken + ); + + // + if (embeddings.IsNullOrDefault() || embeddings.Count != batch.Count) + { + XException.ActionFailed.Throw(); + } + + // + for (var i = 0; i < batch.Count; i++) + { + // + var chunk = batch[i]; + result.Add(new XAiVectorDto + { + // + Type = type, + Text = chunk.Text, + Embedding = embeddings[i], + Identifier = chunk.Identifier, + Metadata = new Dictionary + { + [rag.MetadataFileName] = fileName, + [rag.MetadataMimeType] = mimeType, + [rag.MetadataChunkIndex] = chunk.Index.ToString(), + [XAiModelsConstants.XAiKnowledgeMetadataType] = type, + [XAiModelsConstants.XAiKnowledgeMetadataOwnerId] = ownerId, + [XAiModelsConstants.XAiKnowledgeMetadataScope] = scope.Scope.ToString(), + [XAiModelsConstants.XAiKnowledgeMetadataScopeId] = scope.ScopeId?.ToString("D") ?? string.Empty, + [XAiModelsConstants.XAiKnowledgeMetadataIngestedAtUtc] = ingestedAtUtc + } + }); + } + } + + // + return result; + } + + // + #region Scope ... + /// + /// Normalize Scope (Null => User, Clear ScopeId for User/Global, Require ScopeId for Project/Conversation) ... + /// + private 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; + } + + /// + /// Ensure Caller has Access to Scope: + /// User: Own Data | Global: Read = Everyone, Write = Admin + /// Project / Conversation: Caller must be Owner ... + /// + 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; + } + } + + /// + /// Ensure Caller Owns Project ... + /// + private async Task 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; + } + + /// + /// Ensure Caller Owns Conversation ... + /// + private async Task 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; + } + + /// + /// Resolve Retrieval Tiers (Ordered): Conversation -> Project -> User -> Global ... + /// + private async Task> ResolveTiers( + XAiKnowledgeAskRequest request, + XUserClaimsInfoDto userInfo, + CancellationToken cancellationToken + ) + { + // + var result = new List(); + 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; + } + + /// + /// Scope Prefix (Always Ends with Separator so "a" never Matches "ab"): + /// "conversation/{id}/" | "project/{id}/" | "user/{ownerId}/" | "global/" ... + /// + 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; + } + + /// + /// Document Chunk Prefix: "{scopePrefix}{fileName}#" ... + /// Separator Suffix Prevents "a.pdf" from Matching "a.pdf.bak" ... + /// + private string GetDocumentChunkPrefix( + string scopePrefix, + string fileName + ) + { + return $"{scopePrefix}{fileName}{configuration.TextChunker.ChunkIdentifierSeparator}"; + } + + /// + /// Normalize File Name for Identifier (Strip Client Path, Replace Separators) ... + /// + 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; + } + + /// + /// Load Distinct Document Names of a Scope ... + /// + private async Task> LoadDocumentNames( + string scopePrefix, + CancellationToken cancellationToken + ) + { + // + var vectors = await dataProvider.LoadVectorsAsync( + includeEmbedding: false, + identifierPrefix: scopePrefix, + cancellationToken: cancellationToken + ); + + // + var rag = configuration.RAGDescriptor; + var result = new HashSet( + (vectors ?? []) + .Select(v => v.Metadata.GetMetadata(rag.MetadataFileName)) + .Where(n => !n.IsNullOrEmpty()), + StringComparer.Ordinal + ); + + // + return result; + } + + /// + /// Is Valid User ... + /// + private static bool IsValidUser(XUserClaimsInfoDto userInfo) + { + return !userInfo.IsNullOrDefault() && !userInfo.UserId.IsNullOrEmpty(); + } + + /// + /// Is Caller Admin ... + /// + 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 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 xModels.Dtos; +using xAiApi.Models; +using System.Threading; +using xAiApi.Constants; +using xAiModels.Models; +using xAiApi.Interfaces; +using xAiApi.Extensions; +using xCommons.Providers; +using xCommons.Extensions; +using xAiModels.Constants; +using xAiModels.Interfaces; +using xAiModels.Extensions; +using xAiApi.Configurations; +using xExceptions.Constants; +using xAiModels.Models.Dtos; +using xAiService.Extensions; +using System.Threading.Tasks; +using xIdentityModels.Models; +using Microsoft.Extensions.AI; +using Microsoft.AspNetCore.Http; +using System.Collections.Generic; +using Microsoft.Extensions.Logging; +using xAiApi.Interfaces.Extractors; +using System.Runtime.CompilerServices; + +namespace xAiApi.Providers +{ + /// + /// Base Ai Service ... + /// + public abstract class XAIServiceBase : IXAiServiceBase + { + /// + /// Chat Options ... + /// + public ChatOptions Options { get; } + + /// + /// Descriptor of Models which used in Service ... + /// + public XAiModelDescriptor Descriptor { get; } + + private readonly IXAiRAGService ragProvider; + private readonly IXAiDataProvider dataProvider; + private readonly ILogger logger; + private readonly XAiApiConfiguration configuration; + private readonly XValidationProvider validationProvider; + private readonly IXAiMcpServerProvider mcpServerProvider; + private readonly IXFileContentExtractor fileContentExtractor; + + // + private readonly bool useProvidedMcpServers; + + protected XAIServiceBase( + IXAiRAGService ragProvider, + IXAiDataProvider dataProvider, + ILogger 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 ... + /// + /// Base Method for Communicate with LLM ... + /// + /// + /// + /// + /// + public virtual async Task 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 .Cast()]; + } + + // + 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; + } + + /// + /// Base Method for Communicate with LLM ... + /// + /// + /// + /// + /// + public virtual async IAsyncEnumerable 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()]; + } + + // + 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; + } + } + + /// + /// Ask a Question By Providing Vector Search Result ... + /// + /// + /// + /// + /// + /// + public virtual async Task AskTextByContextAsync( + string prompt, + IList 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()]; + } + + // + 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; + } + + /// + /// Ask a Question By By Providing Vector Search Result and Stream Response ... + /// + /// + /// + /// + /// + /// + public virtual async IAsyncEnumerable AskTextByContextAsEnumerable( + string prompt, + IList 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()]; + } + + // + 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; + } + } + + /// + /// Ask a Question By Rag Retrive From Knowledge ... + /// + /// + /// + /// + /// + /// + /// + /// + public virtual async Task 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, + resolveConversation: 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()]; + } + + // + var response = await client + .GetResponseAsync( + options: Options, + messages: prep.History, + cancellationToken: cancellationToken + ); + if (!response.IsValid()) + { + client.Dispose(); + XException.ActionFailed.Throw(); + } + + // + return response.Text; + } + + /// + /// Ask a Question By Rag Retrive From Knowledge and Stream Response ... + /// + /// + /// + /// + /// + /// + /// + /// + public virtual async IAsyncEnumerable 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, + resolveConversation: 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()]; + } + + // + 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; + } + } + + /// + /// Ask a Question as Prompt and Retrieve Response ... + /// + /// + /// + /// + /// + /// + /// + /// + /// + /// + /// + /// + public virtual async Task AskAsync( + string prompt, + string type = null, + int? topK = null, + float? minScore = null, + Guid? projectId = null, + Guid? conversationId = null, + string connectionId = null, + IFormFileCollection files = null, + XUserClaimsInfoDto userInfo = null, + CancellationToken cancellationToken = default + ) + { + // + // Validate Args ... + validationProvider + .GroupValidationBuilder() + .AddNotEmpty(prompt) + .AddNotNull(userInfo) + .AddNotEmpty(userInfo.UserId) + .ValidateGroup(); + + // + var prep = await PrepareChatRequirementsAsync( + type: type, + topK: topK, + files: files, + prompt: prompt, + minScore: minScore, + userInfo: userInfo, + persistPrompt: true, + projectId: projectId, + resolveConversation: true, + connectionId: connectionId, + conversationId: conversationId, + 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()]; + } + + // + 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; + } + + /// + /// Ask a Question as Prompt and Retrieve Response as Async Enumerable ... + /// + /// + /// + /// + /// + /// + /// + /// + /// + /// + /// + /// + public virtual async IAsyncEnumerable AskAsEnumerable( + string prompt, + string type = null, + int? topK = null, + float? minScore = null, + Guid? projectId = null, + Guid? conversationId = null, + string connectionId = null, + IFormFileCollection files = null, + XUserClaimsInfoDto userInfo = null, + [EnumeratorCancellation] + CancellationToken cancellationToken = default + ) + { + // + // Validate Args ... + validationProvider + .GroupValidationBuilder() + .AddNotEmpty(prompt) + .AddNotNull(userInfo) + .AddNotEmpty(userInfo.UserId) + .ValidateGroup(); + + // + var prep = await PrepareChatRequirementsAsync( + type: type, + topK: topK, + files: files, + prompt: prompt, + minScore: minScore, + userInfo: userInfo, + persistPrompt: true, + projectId: projectId, + resolveConversation: true, + connectionId: connectionId, + conversationId: conversationId, + 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()]; + } + + // + 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 ... + /// + /// Load AI Projects ... + /// + /// + /// + /// + /// + /// + public virtual async Task> LoadProjects( + string ownerId, + string connectionId = null, + bool includeDefaults = false, + CancellationToken cancellationToken = default + ) + { + // + // Validate Args ... + if (ownerId.IsNullOrEmpty()) + { + XException.InvalidArgs.Throw(); + } + + // + var result = await dataProvider.LoadProjects( + ownerId: ownerId, + fillConversations: false, + connectionId: connectionId, + fillConversationMessages: false, + cancellationToken: cancellationToken + ); + + // + // Handle Defaults Including ... + if (includeDefaults) + { + // + // Here we have to fill Conversations of Default Project ... + var defaultProjectId = result.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; + } + + /// + /// Load Conversations of Specified AI Project ... + /// + /// + /// + /// + /// + public virtual async Task> LoadConversations( + Guid projectId, + string connectionId = null, + CancellationToken cancellationToken = default + ) + { + // + // Validate Args ... + if (projectId.IsDefaultGuid()) + { + XException.InvalidArgs.Throw(); + } + + // + var result = await dataProvider.LoadConversations( + fillMessages: false, + projectId: projectId, + connectionId: connectionId, + cancellationToken: cancellationToken + ); + + // + return result; + } + + /// + /// Load Messages of Specified Conversation ... + /// + /// + /// + /// + public virtual async Task> LoadMessages( + Guid conversationId, + CancellationToken cancellationToken = default + ) + { + // + // Validate Args ... + if (conversationId.IsDefaultGuid()) + { + XException.InvalidArgs.Throw(); + } + + // + var result = await dataProvider.LoadMessages( + conversationId: conversationId, + cancellationToken: cancellationToken + ); + + // + return result; + } + #endregion + + // + #region Queries ... + /// + /// Query Projects ... + /// + /// + /// + /// + /// + public virtual async Task> QueryProjects( + string ownerId, + XQuery query, + CancellationToken cancellationToken = default + ) + { + // + // Validate ... + if (ownerId.IsNullOrEmpty()) + { + XException.InvalidArgs.Throw(); + } + + // + var result = await dataProvider.QueryProjects( + query: query, + ownerId: ownerId, + cancellationToken: cancellationToken + ); + + // + return result; + } + + /// + /// Query Conversations ... + /// + /// + /// + /// + /// + /// + public virtual async Task> QueryConversations( + string ownerId, + Guid projectId, + XQuery query, + CancellationToken cancellationToken = default + ) + { + // + // Validate ... + if (ownerId.IsNullOrEmpty() || + projectId.IsDefaultGuid()) + { + XException.InvalidArgs.Throw(); + } + + // + // Retrieve Project ... + var project = await dataProvider.GetProject( + id: projectId, + fillConversations: false, + fillConversationMessages: false, + cancellationToken: cancellationToken + ); + if (project.IsNullOrDefault()) + { + XException.NotFound.Throw(); + } + + // + // Validate Owner ... + if (ownerId != project.OwnerId) + { + XException.NotAllowed.Throw(); + } + + // + var result = await dataProvider.QueryConversations( + query: query, + ownerId: ownerId, + projectId: projectId, + cancellationToken: cancellationToken + ); + + // + return result; + } + + /// + /// Query Messages ... + /// + /// + /// + /// + /// + /// + public virtual async Task> QueryMessages( + string ownerId, + Guid conversationId, + XQuery query, + CancellationToken cancellationToken = default + ) + { + // + // Validate ... + if (ownerId.IsNullOrEmpty() || + conversationId.IsDefaultGuid()) + { + XException.InvalidArgs.Throw(); + } + + // + // Retrieve Conversation ... + var conversation = await dataProvider.GetConversation( + id: conversationId, + fillMessages: false, + cancellationToken: cancellationToken + ); + if (conversation.IsNullOrDefault()) + { + XException.NotFound.Throw(); + } + + // + // Validate Owner ... + if (ownerId != conversation.OwnerId) + { + XException.NotAllowed.Throw(); + } + + // + var result = await dataProvider.QueryMessages( + query: query, + ownerId: ownerId, + conversationId: conversationId, + cancellationToken: cancellationToken + ); + + // + return result; + } + #endregion + + // + #region Creators ... + /// + /// Create an AI Project ... + /// + /// + /// + /// + /// + /// + public virtual async Task CreateProject( + string ownerId, + XAiProjectDto item, + string connectionId = null, + CancellationToken cancellationToken = default + ) + { + // + var result = await dataProvider.CreateProject( + item: item, + ownerId: ownerId, + connectionId: connectionId, + cancellationToken: cancellationToken + ); + + // + return result; + } + + /// + /// Create an AI Conversation ... + /// + /// + /// + /// + /// + /// + /// + public virtual async Task CreateConversation( + string ownerId, + Guid projectId, + XAiConversationDto item, + string connectionId = null, + CancellationToken cancellationToken = default + ) + { + // + var result = await dataProvider.CreateConversation( + item: item, + ownerId: ownerId, + projectId: projectId, + connectionId: connectionId, + cancellationToken: cancellationToken + ); + + // + return result; + } + #endregion + + // + #region Content Extraction ... + /// + /// Try to Extract Files Content ... + /// + /// + /// + /// + /// + public async Task ExtractContent( + IFormFileCollection files, + string[] extractors = null, + CancellationToken cancellationToken = default + ) + { + // + if (!files.HasChild()) + { + XException.InvalidArgs.Throw(); + } + + // + var extractionResults = new List(); + foreach (var file in files) + { + // + if (file.IsNull() || file.Length == 0) + { + continue; + } + + // + var mimeType = file.ContentType?.ToLowerInvariant() ?? string.Empty; + if (!fileContentExtractor.CanExtract(mimeType, extractors)) + { + continue; + } + + // + try + { + // + using var stream = file.OpenReadStream(); + + // + var fr = await fileContentExtractor.ExtractRichAsync( + fileStream: stream, + mimeType: mimeType, + extractors: extractors, + fileName: file.FileName, + cancellationToken: cancellationToken + ); + + // + if (fr.IsValid()) + { + extractionResults.Add(fr); + } + } + catch (OperationCanceledException) + { + throw; + } + catch + { + continue; + } + } + + // + var result = string.Empty; + if (extractionResults.HasChild()) + { + // + extractionResults.ForEach(er => + { + result += $"File {er.FileName} Content:{Environment.NewLine}{er.Text ?? er.AudioTranscript}{Environment.NewLine}----"; + }); + } + + // + return result; + } + #endregion + + /// + /// Base Dispose Action ... + /// + /// + public virtual void Dispose() + { } + + // + #region Private ... + /// + /// Prepare a Message History List for LLM Communication based on Prompt ... + /// + /// + /// + /// + private IList GetHistory( + string prompt = null, + bool forcePrompt = true + ) + { + // + // Validate Args ... + if (prompt.IsNullOrEmpty()) + { + XException.InvalidArgs.Throw(); + } + + // + // User Prompt ... + var promptMessage = new ChatMessage( + ChatRole.User, + prompt + ); + + // + // Preparing Introduction Prompt ... + var introductionPrompt = new ChatMessage( + ChatRole.System, + configuration.GetPrompt() + ); + + // + List result = + [ + introductionPrompt, + ]; + if (forcePrompt && + prompt is not null && + !string.IsNullOrWhiteSpace(prompt)) + { + result.Add(promptMessage); + } + + // + return result; + } + + /// + /// Build Chat History for RAG: + /// [System: Introduction + ChatWithDocuments Prompt + Context Block] + [User: Prompt] ... + /// + /// + /// + /// + private IList GetHistory( + string prompt, + IEnumerable context + ) + { + // + var introductionPrompt = configuration.GetPrompt(); + var ragPrompt = configuration.GetPrompt(XAiApiConstants.XAiApiRagPromptName); + if (ragPrompt.IsNullOrEmpty()) + { + XException.InvalidConfiguration.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}"; + } + + // + List result = + [ + new ChatMessage(ChatRole.System, systemText), + new ChatMessage(ChatRole.User, prompt), + ]; + + // + return result; + } + + /// + /// Implementing Memory Strategy here ... + /// + /// + /// + /// + /// + /// + private async Task> PrepareMemory( + XAiProjectDto project, + IEnumerable messages, + IEnumerable context = null, + CancellationToken cancellationToken = default + ) + { + // + var result = new List(); + + // + 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}"; + } + + // + // Apply Project Prompt as System Text ... + if (!project.IsNullOrDefault() && + !project.Prompt.IsNullOrEmpty()) + { + systemText += $"{project.Prompt}{Environment.NewLine}"; + } + + // + // Add System Message ... + result.Add(new ChatMessage(ChatRole.System, systemText)); + + // + // Attach Message ... + if (messages.HasChild()) + { + // + // TODO: Here we can Implement Memory Management based on + // Last nth of Messages, or Summarization of Messages, etc ... + result = [..result, ..messages + .OrderBy(m => m.CreatedOn) + .Select(m => m.ToChatMessages())]; + } + + // + return result; + } + + /// + /// Convert Context Chunks to a Numbered Text Block ... + /// + /// + /// + private string BuildContextBlock( + IEnumerable context + ) + { + // + var result = "(no context)"; + + // + var items = context? + .Where(c => + !c.IsNullOrDefault() && + !c.Text.IsNullOrEmpty() + ) + .ToList() ?? []; + if (!items.HasChild()) + { + return result; + } + + // + var index = 1; + var builder = new System.Text.StringBuilder(); + foreach (var item in items) + { + // + var identifier = item.Identifier.IsNullOrEmpty() + ? item.Id.ToString() + : item.Identifier; + + // + builder.AppendLine($"[{index}] Source: [{identifier}] (score: {item.Score:0.000})"); + builder.AppendLine(item.Text.Trim()); + builder.AppendLine("----"); + + // + index++; + } + + // + result = builder.ToString(); + + // + return result; + } + + /// + /// Normalizing Rag Params ... + /// + /// + /// + /// + private void NormalizeRagParams( + ref int? topK, + ref float? minScore, + ref string type + ) + { + // + var rag = configuration.RAGDescriptor; + + // + // TopK ... + if (!topK.HasValue || topK.Value < 1) + { + topK = rag.DefaultTopK; + } + else if (topK.Value > rag.MaxTopK) + { + topK = rag.MaxTopK; + } + + // + // Min Score ... + if (!minScore.HasValue || minScore.Value < 0 || minScore.Value > 1) + { + minScore = rag.DefaultMinScore; + } + + // + // Type ... + if (type.IsNullOrEmpty()) + { + type = XAiModelsConstants.XAiDefaultKnowledgeType; + } + } + + /// + /// Retrieve Prepared Chat Context ... + /// + /// + /// + /// + /// + /// + /// + /// + /// + /// + /// + /// + /// + /// + private async Task PrepareChatRequirementsAsync( + int? topK, + string type, + string prompt, + float? minScore, + Guid? projectId, + bool persistPrompt, + string connectionId, + Guid? conversationId, + bool resolveConversation, + IFormFileCollection files, + XUserClaimsInfoDto userInfo, + IList additionalContents = null, + CancellationToken cancellationToken = default + ) + { + // + // 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 + ) + { + // + try + { + // + var ingestResult = await ragProvider + .IngestAsync( + files: files, + userInfo: userInfo, + replaceExisting: true, + connectionId: connectionId, + scope: XAiKnowledgeScopeDescriptor + .Conversation( + type: type, + conversationId: conversationId.Value + ), + cancellationToken: cancellationToken + ); + if (ingestResult.SkippedFiles.HasChild()) + { + // + logger.LogWarning( + "Ingest skipped {Count} file(s): {Files}", + ingestResult.SkippedFiles.Count, + string.Join(", ", ingestResult.SkippedFiles)); + } + } + catch (OperationCanceledException) + { + throw; + } + catch (Exception ex) + { + // + logger.LogError(ex, + "Ingest failed for prompt '{Prompt}'. Continuing without attachments.", + prompt + ); + } + } + + // + // Request Knowledge ... + var knowledgeRequest = new XAiKnowledgeAskRequest + { + TopK = topK, + Type = type, + Prompt = prompt, + IncludeUser = true, + MinScore = minScore, + IncludeGlobal = true, + ProjectId = resolveConversation ? projectId : null, + ConversationId = resolveConversation ? conversationId : null, + }; + var context = await ragProvider + .RetrieveAsync( + userInfo: userInfo, + request: knowledgeRequest, + cancellationToken: cancellationToken + ); + + // + // Prepare History and Persisted Prompt Message ... + IList 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; + } + #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 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 sessions = new ConcurrentDictionary(); + 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 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 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 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 Search( + Guid sessionId, + ReadOnlyMemory queryEmbedding, + int topK = 5, + float minScore = 0f, + string ownerId = null + ) + { + // + var result = new List(); + 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 Copy( + IEnumerable vectors + ) + { + return vectors == null ? new List() : 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 +{ + /// + /// Periodically Removes Expired Document Sessions from In-Memory Vector Store ... + /// + public class XInMemoryVectorStoreCleanupService : BackgroundService + { + /// + /// Default Cleanup Interval ... + /// + public static readonly TimeSpan DefaultInterval = TimeSpan.FromMinutes(5); + + private readonly TimeSpan interval; + private readonly IXInMemoryVectorStore vectorStore; + private readonly ILogger logger; + + public XInMemoryVectorStoreCleanupService( + IXInMemoryVectorStore vectorStore, + ILogger logger + ) + { + this.logger = logger; + this.vectorStore = vectorStore; + this.interval = DefaultInterval; + } + + /// + /// Cleanup Loop ... + /// + /// + /// + 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 +{ + /// + /// Splits Long Texts into Overlapping Chunks using a Hierarchical Strategy: + /// Paragraphs -> Sentences -> Words -> Hard Cut ... + /// + public class XTextChunker : IXTextChunker + { + /// + /// Default Options which used when no Options Provided ... + /// + private readonly XAiApiConfiguration configuration; + + /// + /// Matches Paragraph Boundaries (two or more Line Breaks) ... + /// + private static readonly Regex ParagraphSplitter = new( + @"\n\s*\n+", + RegexOptions.Compiled + ); + + /// + /// Matches Sentence Boundaries, Supports Latin, Persian and CJK Terminators ... + /// + private static readonly Regex SentenceSplitter = new( + @"(?<=[\.\!\?؟。!?])\s+|(?<=\n)", + RegexOptions.Compiled + ); + + /// + /// Matches Repeated Horizontal Whitespaces ... + /// + private static readonly Regex HorizontalWhitespace = new( + @"[ \t\f\v\u00A0]{2,}", + RegexOptions.Compiled + ); + + /// + /// Matches Three or more Line Breaks ... + /// + 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; + } + + /// + /// Split Text into Chunks ... + /// + /// + /// + /// + public IList Chunk( + string text, + string source = null + ) + { + // + var result = new List(); + 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; + } + + /// + /// Split Text into Chunks and Return only Texts ... + /// + /// + /// + public IList ChunkTexts(string text) + { + // + var result = Chunk(text, null) + .Select(c => c.Text) + .ToList(); + + // + return result; + } + + // + #region Private ... + /// + /// Internal Text Unit with its Offset in Normalized Source ... + /// + private readonly struct Unit + { + public Unit(string text, int offset) + { + Text = text; + Offset = offset; + } + + public string Text { get; } + public int Offset { get; } + } + + /// + /// Normalize Line Endings and Whitespaces ... + /// + /// + /// + 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; + } + + /// + /// Create Chunk Model ... + /// + /// + /// + /// + /// + /// + 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; + } + + /// + /// Split Text into Atomic Units; each Unit Guaranteed to fit in ChunkSize ... + /// + /// + /// + private List BuildUnits(string text) + { + // + var result = new List(); + + // + 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; + } + + /// + /// Split Text by Regex while Tracking Offsets, Skipping Empty Parts ... + /// + /// + /// + /// + /// + private IEnumerable 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; + } + } + } + + /// + /// Trim Unit Text while Adjusting its Offset ... + /// + /// + /// + /// + 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; + } + + /// + /// Cut a Unit into Pieces no Longer than Max Size, Preferring Whitespace Boundaries ... + /// + /// + /// + /// + private IEnumerable 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++; + } + } + } + + /// + /// Accumulate Units into Chunks up to ChunkSize, Carrying Overlap to Next Chunk ... + /// + /// + /// + private List Accumulate(List units) + { + // + var result = new List(); + if (!units.HasChild()) + { + return result; + } + + // + var buffer = new StringBuilder(); + var buffered = new List(); + 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; + } + + /// + /// Map Trailing Overlap Length of Buffered Units back to Source Offset ... + /// Units Joined by Single Space Separator in Buffer ... + /// + /// + /// + /// + private int ComputeOverlapOffset( + List 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; + } + + /// + /// Take Trailing Overlap from Text, Aligned to Word Boundary ... + /// + /// + /// + /// + 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(); + } + + /// + /// Merge Chunks Smaller than MinChunkSize into their Predecessor ... + /// + /// + /// + private List MergeSmallChunks(List chunks) + { + // + if (configuration.TextChunker.MinChunkSize <= 0 || chunks.Count < 2) + { + return chunks; + } + + // + var result = new List(); + 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; + } + + /// + /// Characters Considered as Word Boundaries ... + /// + 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 +{ + /// + /// Extracts text content from Audio files ... + /// + public class XAudioFileContentExtractor : IXAudioFileContentExtractor + { + /// + /// Supported MIME Types ... + /// + 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; + } + + /// + /// Check if this extractor supports the specified MIME type ... + /// + public bool CanExtract(string mimeType) + { + // + return SupportedMimeTypes.Contains( + mimeType?.ToLowerInvariant() ?? string.Empty + ); + } + + /// + /// Extract text content from file stream ... + /// + public async Task ExtractAsync( + Stream fileStream, + string mimeType, + CancellationToken cancellationToken = default + ) + { + // + var result = await ExtractRichAsync( + fileStream, + "audio", + mimeType, + cancellationToken + ); + + // + return result.AudioTranscript; + } + + /// + /// Extract content from stream as Rich Result ... + /// + /// + /// + /// + /// + /// + public async Task 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 ... + /// + /// Audio Format Converting to WAV 16kHz Mono 16-bit PCM ... + /// + private async Task 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; + } + + /// + /// Retrieve File Extension based on mime type ... + /// + /// + /// + 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 +{ + /// + /// Extractor for source code files ... + /// (C#, Python, JavaScript, TypeScript, Java, Go, Rust, ...) + /// + public class XCodeFileContentExtractor : IXCodeFileContentExtractor + { + /// + /// Supported MIME Types ... + /// + 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", + ]; + + /// + /// Check if this extractor supports the specified MIME type ... + /// + /// + /// + public bool CanExtract(string mimeType) + { + // + return SupportedMimeTypes.Contains( + mimeType?.ToLowerInvariant() ?? string.Empty + ); + } + + /// + /// Extract text content from file stream ... + /// + /// + /// + /// + /// + public async Task ExtractAsync( + Stream fileStream, + string mimeType, + CancellationToken cancellationToken = default + ) + { + // + var result = await ExtractRichAsync( + fileStream, + string.Empty, + mimeType, + cancellationToken + ); + + // + return result.Text; + } + + /// + /// Extract content from stream as Rich Result ... + /// + /// + /// + /// + /// + /// + public async Task 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 +{ + /// + /// Extracts text content from DOCX files using DocumentFormat.OpenXml ... + /// + public class XDocxFileContentExtractor : IXDocxFileContentExtractor + { + /// + /// Supported MIME Types ... + /// + private static readonly string[] SupportedMimeTypes = + [ + "application/vnd.openxmlformats-officedocument.wordprocessingml.document" + ]; + + /// + /// Check if this extractor supports the specified MIME type ... + /// + public bool CanExtract(string mimeType) + { + // + return SupportedMimeTypes.Contains( + mimeType?.ToLowerInvariant() ?? string.Empty + ); + } + + /// + /// Extract text content from file stream ... + /// + public async Task 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(); + foreach (var paragraph in paragraphs) + { + // + var text = paragraph.InnerText?.Trim(); + if (!string.IsNullOrEmpty(text)) + { + stringBuilder.AppendLine(text); + } + } + } + } + + // + return stringBuilder.ToString(); + } + + /// + /// Extract content from stream as Rich Result ... + /// + /// + /// + /// + /// + /// + public async Task 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 +{ + /// + /// Extractor for EPUB electronic publication format + /// (application/epub+zip) + /// + public class XEpubFileContentExtractor : IXEpubFileContentExtractor + { + /// + /// Supported MIME Types ... + /// + private static readonly string[] SupportedMimeTypes = + [ + "application/epub+zip" + ]; + + /// + /// Check if this extractor supports the specified MIME type ... + /// + /// + /// + public bool CanExtract(string mimeType) + { + // + return SupportedMimeTypes.Contains( + mimeType?.ToLowerInvariant() ?? string.Empty + ); + } + + /// + /// Extract text content from file stream ... + /// + /// + /// + /// + /// + public async Task ExtractAsync( + Stream fileStream, + string mimeType, + CancellationToken cancellationToken = default + ) + { + // + var result = await ExtractRichAsync( + fileStream, + "book.epub", + mimeType, + cancellationToken + ); + + // + return result.Text; + } + + /// + /// Extract content from stream as Rich Result ... + /// + /// + /// + /// + /// + /// + public async Task 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; + } + + /// + /// Extract Epub Content ... + /// + /// + /// + /// + private async Task 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; + } + + /// + /// Extract Text Content from HTML ... + /// + /// + /// + 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 + { + /// + /// Supported MIME Types ... + /// + private static readonly string[] SupportedMimeTypes = + [ + "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet", // .xlsx + "application/vnd.ms-excel" // .xls + ]; + + /// + /// Check if this extractor supports the specified MIME type ... + /// + public bool CanExtract(string mimeType) + { + // + return SupportedMimeTypes.Contains( + mimeType?.ToLowerInvariant() ?? string.Empty + ); + } + + /// + /// Extract text content from file stream ... + /// + public async Task 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(); + } + + /// + /// Extract content from stream as Rich Result ... + /// + /// + /// + /// + /// + /// + public async Task 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 +{ + /// + /// Composite extractor that delegates to appropriate extractor + /// based on MIME type ... + /// + public class XFileContentExtractor : IXFileContentExtractor + { + // + private readonly IList _extractors = []; + + public XFileContentExtractor( + IEnumerable availableExtractors + ) + { + // + _extractors = [.. availableExtractors + .Where(e => e.GetType() != typeof(XFileContentExtractor))]; + } + + /// + /// Check if this extractor supports the specified MIME type ... + /// + /// + /// + /// + public bool CanExtract( + string mimeType, + string[] extractors = null + ) + { + // + return GetExtractors(extractors) + .Any(e => e.CanExtract(mimeType)); + } + + /// + /// Extract text content from file stream ... + /// + /// + /// + /// + /// + /// + public async Task 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; + } + + /// + /// Extract content from stream as Rich Result ... + /// + /// + /// + /// + /// + /// + /// + public async Task 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; + } + + /// + /// Extract Provided Extractors ... + /// + /// + /// + private IList GetExtractors(string[] extractors = null) + { + // + var result = new List(); + + // + 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 +{ + /// + /// Extractor for HTML documents (text/html, application/xhtml+xml) + /// + public class XHtmlFileContentExtractor : IXHtmlFileContentExtractor + { + /// + /// Supported MIME Types ... + /// + private static readonly string[] SupportedMimeTypes = + [ + "text/html", + "application/xhtml+xml" + ]; + + /// + /// Check if this extractor supports the specified MIME type ... + /// + /// + /// + public bool CanExtract(string mimeType) + { + // + return SupportedMimeTypes.Contains( + mimeType?.ToLowerInvariant() ?? string.Empty + ); + } + + /// + /// Extract text content from file stream ... + /// + /// + /// + /// + /// + public async Task ExtractAsync( + Stream fileStream, + string mimeType, + CancellationToken cancellationToken = default + ) + { + // + var result = await ExtractRichAsync( + fileStream, + "document.html", + mimeType, + cancellationToken + ); + + // + return result.Text; + } + + /// + /// Extract content from stream as Rich Result ... + /// + /// + /// + /// + /// + /// + public async Task 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; + } + + /// + /// Extract Html Content as Text ... + /// + /// + /// + /// + private async Task 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(); + } + + /// + /// Remove Noisy Nodes ... + /// + /// + 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(); + } + } + } + + /// + /// Extract Title ... + /// + /// + /// + private string ExtractTitle(HtmlDocument html) + { + // + var titleNode = html.DocumentNode + .SelectSingleNode("//title"); + + // + var result = titleNode?.InnerText?.Trim() ?? string.Empty; + + // + return result; + } + + /// + /// Clean Text ... + /// + /// + /// + 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 + { + /// + /// Supported MIME Types ... + /// + private static readonly string[] SupportedMimeTypes = + [ + "image/png", + "image/jpeg", + "image/jpg", + "image/gif", + "image/webp", + "image/bmp" + ]; + + /// + /// AI Api Configuration ... + /// + 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; + } + + /// + /// Check if this extractor supports the specified MIME type ... + /// + public bool CanExtract(string mimeType) + { + // + return SupportedMimeTypes.Contains( + mimeType?.ToLowerInvariant() ?? string.Empty + ); + } + + /// + /// Extract text content from file stream ... + /// + public async Task ExtractAsync( + Stream fileStream, + string mimeType, + CancellationToken cancellationToken = default + ) + { + // + var result = await ExtractRichAsync( + fileStream, + "image", + mimeType, + cancellationToken + ); + + // + return result.Text; + } + + /// + /// Extract content from stream as Rich Result ... + /// + /// + /// + /// + /// + /// + public async Task 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; + } + + /// + /// Do OCR on Image for Text Extraction ... + /// + private async Task 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 +{ + /// + /// Extractor for OpenDocument Format (ODF) documents + /// (ODT: OpenDocument Text, ODS: OpenDocument Spreadsheet, ODP: OpenDocument Presentation) + /// + public class XOpenDocumentFileContentExtractor : IXOpenDocumentFileContentExtractor + { + /// + /// Supported MIME Types ... + /// + private static readonly string[] SupportedMimeTypes = + [ + "application/vnd.oasis.opendocument.text", // .odt + "application/vnd.oasis.opendocument.spreadsheet", // .ods + "application/vnd.oasis.opendocument.presentation" // .odp + ]; + + /// + /// Check if this extractor supports the specified MIME type ... + /// + /// + /// + public bool CanExtract(string mimeType) + { + // + return SupportedMimeTypes.Contains( + mimeType?.ToLowerInvariant() ?? string.Empty + ); + } + + /// + /// Extract text content from file stream ... + /// + public async Task ExtractAsync( + Stream fileStream, + string mimeType, + CancellationToken cancellationToken = default + ) + { + // + var result = await ExtractRichAsync( + fileStream, + "document.rtf", + mimeType, + cancellationToken + ); + + // + return result.Text; + } + + /// + /// Extract content from stream as Rich Result ... + /// + /// + /// + /// + /// + /// + public async Task 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; + } + + /// + /// Check Mime Type ... + /// + /// + /// + private bool IsOdt(string mimeType) + { + // + var result = mimeType? + .ToLowerInvariant() == "application/vnd.oasis.opendocument.text"; + + // + return result; + } + + /// + /// Check Mime Type ... + /// + /// + /// + private bool IsOds(string mimeType) + { + // + var result = mimeType? + .ToLowerInvariant() == "application/vnd.oasis.opendocument.spreadsheet"; + + // + return result; + } + + /// + /// Check Mime Type ... + /// + /// + /// + private bool IsOdp(string mimeType) + { + // + var result = mimeType? + .ToLowerInvariant() == "application/vnd.oasis.opendocument.presentation"; + + // + return result; + } + + /// + /// Extract ODT File Content ... + /// + /// + /// + /// + private async Task 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(); + 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; + } + + /// + /// Extract ODS File Content ... + /// + /// + /// + /// + private async Task 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(); + 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; + } + + /// + /// Extract ODS File Content ... + /// + /// + /// + /// + private async Task 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(); + + // + 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 +{ + /// + /// Extracts content from PDF files using PdfPig ... + /// + public class XPdfFileContentExtractor : IXPdfFileContentExtractor + { + /// + /// Supported MIME Types ... + /// + private static readonly string[] SupportedMimeTypes = + [ + "application/pdf" + ]; + + /// + /// Api Configuration ... + /// + private readonly XAiApiConfiguration configuration; + + public XPdfFileContentExtractor(XAiApiConfiguration configuration) + { + this.configuration = configuration; + } + + /// + /// Check if this extractor supports the specified MIME type ... + /// + /// + /// + public bool CanExtract(string mimeType) + { + // + return SupportedMimeTypes.Contains( + mimeType?.ToLowerInvariant() ?? string.Empty + ); + } + + /// + /// Extract text content from file stream ... + /// + /// + /// + /// + /// + public async Task ExtractAsync( + Stream fileStream, + string mimeType, + CancellationToken cancellationToken = default + ) + { + // + var result = await ExtractRichAsync( + fileStream, + "document.pdf", + mimeType, + cancellationToken + ); + + // + return result.Text; + } + + /// + /// Extract content from stream as Rich Result ... + /// + /// + /// + /// + /// + /// + public async Task 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; + } + + /// + /// Extract Text From PDF Files using Common way ... + /// + /// + /// + /// + private async Task 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; + } + + /// + /// Check Extracted Content is Sufficient or not ... + /// if not try to Falling Back using Images ... + /// + /// + /// + 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; + } + + /// + /// Fallback Converts PDF Pages to Images ... + /// + /// + /// + /// + /// + /// + private async Task 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 +{ + /// + /// Extracts content from plain text files (txt, md, csv, json, xml) ... + /// + public class XPlainTextFileContentExtractor : IXPlainTextFileContentExtractor + { + /// + /// Supported MIME Types ... + /// + private static readonly string[] SupportedMimeTypes = + [ + "text/plain", + "text/markdown", + "text/csv", + "text/xml", + "application/json", + "application/xml" + ]; + + /// + /// Check if this extractor supports the specified MIME type ... + /// + /// + /// + public bool CanExtract(string mimeType) + { + // + return SupportedMimeTypes.Contains( + mimeType?.ToLowerInvariant() ?? string.Empty + ); + } + + /// + /// Extract text content from file stream ... + /// + public async Task ExtractAsync( + Stream fileStream, + string mimeType, + CancellationToken cancellationToken = default + ) + { + // + using var reader = new StreamReader(fileStream); + return await reader.ReadToEndAsync(); + } + + /// + /// Extract content from stream as Rich Result ... + /// + /// + /// + /// + /// + /// + public async Task 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 +{ + /// + /// Extracts content from all PowerPoint formats + /// (OpenXML: pptx/ppsx/potx/pptm/ppsm/potm | Legacy Binary: ppt/pps/pot) + /// + public class XPowerPointFileContentExtractor : IXPowerPointFileContentExtractor + { + /// + /// Supported MIME Types ... + /// + 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" + ]; + + /// + /// Check if this extractor supports the specified MIME type ... + /// + public bool CanExtract(string mimeType) + { + // + return SupportedMimeTypes.Contains( + mimeType?.ToLowerInvariant() ?? string.Empty + ); + } + + /// + /// Extract text content from file stream ... + /// + public async Task ExtractAsync( + Stream fileStream, + string mimeType, + CancellationToken cancellationToken = default + ) + { + // + var result = await ExtractRichAsync( + fileStream: fileStream, + fileName: "presentation", + mimeType: mimeType, + cancellationToken: cancellationToken + ); + return result.Text; + } + + /// + /// Extract content from stream as Rich Result ... + /// + /// + /// + /// + /// + /// + public async Task 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; + } + + /// + /// Check Open XML Format ... + /// + /// + /// + 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; + } + + /// + /// Check Legacy Format ... + /// + /// + /// + private bool IsLegacyFormat(string mimeType) + { + // + var result = mimeType?.ToLowerInvariant() == "application/vnd.ms-powerpoint"; + return result; + } + + /// + /// Extract an Slide Title ... + /// + /// + /// + private string GetSlideTitle(SlidePart slidePart) + { + // + var result = string.Empty; + + // + // Title placeholder has specific type + var titleShape = slidePart.Slide + .Descendants() + .FirstOrDefault(s => s.NonVisualShapeProperties? + .NonVisualDrawingProperties? + .Name?.Value? + .StartsWith("Title", StringComparison.OrdinalIgnoreCase) == true + ); + if (titleShape != null) + { + // + var titleText = titleShape + .Descendants() + .Select(t => t.Text?.Trim()) + .Where(t => !string.IsNullOrWhiteSpace(t)); + result = string.Join(" ", titleText); + } + + // + return result; + } + + /// + /// Extract Speaker Notes ... + /// + /// + /// + private string GetSpeakerNotes(SlidePart slidePart) + { + // + var result = string.Empty; + + // + var notesSlidePart = slidePart.NotesSlidePart; + if (notesSlidePart?.NotesSlide == null) + { + return result; + } + + // + var notesTexts = notesSlidePart.NotesSlide + .Descendants() + .Select(t => t.Text?.Trim()) + .Where(t => !string.IsNullOrWhiteSpace(t)) + .ToList(); + + // + result = notesTexts.Count > 0 + ? string.Join(Environment.NewLine, notesTexts) + : null; + + // + return result; + } + + /// + /// Extract OpenXML Tables ... + /// + /// + /// + private static string ExtractOpenXmlTables(SlidePart slidePart) + { + // + var sb = new StringBuilder(); + + // + var tableElements = slidePart.Slide + .Descendants(); + + // + var tableIndex = 0; + foreach (var table in tableElements) + { + // + tableIndex++; + sb.AppendLine($" Table {tableIndex}:"); + + // + foreach (var row in table + .Descendants()) + { + // + var cells = row + .Descendants() + .Select(c => string.Join(" ", c + .Descendants() + .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; + } + + /// + /// Extract Open XML Format ... + /// + /// + /// + /// + private async Task 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() + .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; + } + + /// + /// Extract Legacy Format ... + /// + /// + /// + /// + private async Task 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(); + 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 +{ + /// + /// Extractor for Rich Text Format (RTF) documents + /// (application/rtf, text/rtf) + /// + public class XRtfFileContentExtractor : IXRtfFileContentExtractor + { + /// + /// Supported MIME Types ... + /// + private static readonly string[] SupportedMimeTypes = + [ + "text/rtf", + "application/rtf", + ]; + + /// + /// Check if this extractor supports the specified MIME type ... + /// + /// + /// + public bool CanExtract(string mimeType) + { + // + return SupportedMimeTypes.Contains( + mimeType?.ToLowerInvariant() ?? string.Empty + ); + } + + /// + /// Extract text content from file stream ... + /// + /// + /// + /// + /// + public async Task ExtractAsync( + Stream fileStream, + string mimeType, + CancellationToken cancellationToken = default + ) + { + // + var result = await ExtractRichAsync( + fileStream, + "document.rtf", + mimeType, + cancellationToken + ); + + // + return result.Text; + } + + /// + /// Extract content from stream as Rich Result ... + /// + /// + /// + /// + /// + /// + public async Task 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; + } + + /// + /// Extract RTF Content ... + /// + /// + /// + /// + private async Task 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; + } + + /// + /// Converts Html to Text ... + /// + /// + /// + 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 +{ + /// + /// Extracts content from files using Vision Model ... + /// + public class XVisionFileContentExtractor : IXVisionFileContentExtractor + { + /// + /// Supported MIME Types ... + /// + 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(); + } + } + + /// + /// Check if this extractor supports the specified MIME type ... + /// + public bool CanExtract(string mimeType) + { + // + return SupportedMimeTypes.Contains( + mimeType?.ToLowerInvariant() ?? string.Empty + ); + } + + /// + /// Extract text content from file stream ... + /// + public async Task ExtractAsync( + Stream fileStream, + string mimeType, + CancellationToken cancellationToken = default + ) + { + var result = await ExtractRichAsync(fileStream, "file", mimeType, cancellationToken); + return result.Text; + } + + /// + /// Extract content from stream as Rich Result ... + /// + /// + /// + /// + /// + /// + public async Task 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 ... + /// + /// Request for Doing OCR on Given Data Contents ... + /// + /// + /// + /// + public virtual async Task RequestOCRAsync( + IList 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; + } + + /// + /// Request for Doing OCR on Given Data Contents as Stream ... + /// + /// + /// + /// + public virtual async IAsyncEnumerable RequestOCRAsEnumerable( + IList 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 + } +} diff --git a/Documents/GeneratedContext/xDashboard-xAiMcpServer-20261104_113311.txt b/Documents/GeneratedContext/xDashboard-xAiMcpServer-20261105_133500.txt similarity index 79% rename from Documents/GeneratedContext/xDashboard-xAiMcpServer-20261104_113311.txt rename to Documents/GeneratedContext/xDashboard-xAiMcpServer-20261105_133500.txt index 492cca2..25016a2 100644 --- a/Documents/GeneratedContext/xDashboard-xAiMcpServer-20261104_113311.txt +++ b/Documents/GeneratedContext/xDashboard-xAiMcpServer-20261105_133500.txt @@ -1,14 +1,9 @@ -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\xAiMcpServer\Program.cs +### FILE: C:\Users\saherelm\Documents\Projects\xSaherelmWorkspace\xAiMcpServer\Program.cs -using System; -using System.Linq; -using System.Threading.Tasks; -using System.Collections.Generic; +using System.Text; using Microsoft.AspNetCore.Hosting; using Microsoft.Extensions.Hosting; -using Microsoft.Extensions.Logging; -using Microsoft.Extensions.Configuration; namespace xAiMcpServer { @@ -16,19 +11,29 @@ namespace xAiMcpServer { public static void Main(string[] args) { + // + Encoding.RegisterProvider(CodePagesEncodingProvider.Instance); + + // CreateHostBuilder(args).Build().Run(); } - public static IHostBuilder CreateHostBuilder(string[] args) => - Host.CreateDefaultBuilder(args) + public static IHostBuilder CreateHostBuilder(string[] args) + { + // + var result = Host.CreateDefaultBuilder(args) .ConfigureWebHostDefaults(webBuilder => { webBuilder.UseStartup(); }); + + // + return result; + } } } -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\xAiMcpServer\Startup.cs +### FILE: C:\Users\saherelm\Documents\Projects\xSaherelmWorkspace\xAiMcpServer\Startup.cs using System; using System.IO; @@ -38,6 +43,7 @@ using Newtonsoft.Json; using System.Reflection; using xIdentityService.DI; using xCommons.Extensions; +using xAiService.Extensions; using xCommons.Configurations; using Microsoft.AspNetCore.Builder; using Microsoft.AspNetCore.Hosting; @@ -60,6 +66,10 @@ namespace xAiMcpServer public void ConfigureServices(IServiceCollection services) { + // + // Register MCP Handler ... + services.AddXAiMcpHandler(); + // // Register Validation Provider and all XCommons Module Services ... services.AddXCommons(Configuration); @@ -118,7 +128,10 @@ namespace xAiMcpServer ); } - public void Configure(IApplicationBuilder app, IWebHostEnvironment env) + public void Configure( + IApplicationBuilder app, + IWebHostEnvironment env + ) { // // Configure the HTTP request pipeline ... @@ -168,15 +181,36 @@ namespace xAiMcpServer } } -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\xAiMcpServer\Controllers\StartupController.cs +### FILE: C:\Users\saherelm\Documents\Projects\xSaherelmWorkspace\xAiMcpServer\Controllers\McpController.cs + +using xCommons.Providers; +using xAiService.Interfaces; +using xAiService.Controllers; +using xCommons.Configurations; +using xIdentityService.Interfaces; +using Microsoft.Extensions.Logging; + +namespace xAiMcpServer.Controllers +{ + public class McpController : XAiMcpControllerBase + { + public McpController( + IXAiMcpHandler mcpHandler, + ILogger logger, + XAppConfiguration appConfiguration, + IXIdentityProvider identityProvider, + XValidationProvider validationProvider + ) : base(mcpHandler, appConfiguration, identityProvider, logger, validationProvider) + { } + } +} + +### FILE: C:\Users\saherelm\Documents\Projects\xSaherelmWorkspace\xAiMcpServer\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; @@ -216,25 +250,10 @@ namespace xAiApi.Controllers // return Ok(message); } - - /// - /// Global Exception Handler Endpoint (Production) ... - /// Returns a Generic Error without Leaking Exception Details ... - /// - /// - [AllowAnonymous] - [Route("error")] - [ApiExplorerSettings(IgnoreApi = true)] - public virtual ActionResult Error() - { - // - var error = XException.ActionFailed.ToXError(); - return StatusCode(StatusCodes.Status500InternalServerError, error); - } } } -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\xAiMcpServer\DI\DiExtensions.cs +### FILE: C:\Users\saherelm\Documents\Projects\xSaherelmWorkspace\xAiMcpServer\DI\DiExtensions.cs using xIdentityHelper; using xCommons.Extensions; @@ -322,3 +341,26 @@ namespace xAiMcpServer.DI } } } + +### FILE: C:\Users\saherelm\Documents\Projects\xSaherelmWorkspace\xAiMcpServer\Tools\XEchoTools.cs + + +using xAiModels.Attributes; + +namespace xAiMcpServer.Tools +{ + [XAiMcpToolType] + public static class XEchoTools + { + [XAiMcpTool(Description = "Echoes the string back to the client give message in string")] + public static string Echo( + [XAiMcpToolParam(Description = "string value which specified message")] + string message + ) + { + // + var result = $"hello {message}"; + return result; + } + } +} diff --git a/Documents/GeneratedContext/xDashboard-xAiModels-20261104_113311.txt b/Documents/GeneratedContext/xDashboard-xAiModels-20261105_133500.txt similarity index 93% rename from Documents/GeneratedContext/xDashboard-xAiModels-20261104_113311.txt rename to Documents/GeneratedContext/xDashboard-xAiModels-20261105_133500.txt index fd81bf4..b83c8d0 100644 --- a/Documents/GeneratedContext/xDashboard-xAiModels-20261104_113311.txt +++ b/Documents/GeneratedContext/xDashboard-xAiModels-20261105_133500.txt @@ -1,5 +1,86 @@ -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\Modules\xAiModels\Configurations\XAiModelMappersProfile.cs +### FILE: C:\Users\saherelm\Documents\Projects\xSaherelmWorkspace\Modules\xAiModels\Attributes\XAiMcpToolAttribute.cs + +using System; + +namespace xAiModels.Attributes +{ + /// + /// Decorate and Describe Specified MCP Tool to LLM ... + /// + [AttributeUsage(AttributeTargets.Method, AllowMultiple = false, Inherited = false)] + public class XAiMcpToolAttribute : Attribute + { + /// + /// Tools Unique Name (Default: Method Name) ... + /// + /// + public string Name { get; } + + /// + /// Tools Description for LLM ... + /// + /// + public string Description { get; set; } + + public XAiMcpToolAttribute(string name = null) + { + Name = name; + } + } +} + +### FILE: C:\Users\saherelm\Documents\Projects\xSaherelmWorkspace\Modules\xAiModels\Attributes\XAiMcpToolParamAttribute.cs + +using System; + +namespace xAiModels.Attributes +{ + /// + /// Describe Specific Tools Parameter Metadata ... + /// + [AttributeUsage(AttributeTargets.Parameter, AllowMultiple = false, Inherited = false)] + public sealed class XAiMcpToolParamAttribute : Attribute + { + /// + /// Parameter Name in JSON (Default Parameter Name) ... + /// + /// + public string Name { get; } + + /// + /// Describe Parameter to LLM ... + /// + /// + public string Description { get; set; } + + /// + /// Specified this Parameter is Required or not (Default is true) ... + /// + /// + public bool Required { get; set; } = true; + + public XAiMcpToolParamAttribute(string name = null) + { + Name = name; + } + } +} + +### FILE: C:\Users\saherelm\Documents\Projects\xSaherelmWorkspace\Modules\xAiModels\Attributes\XAiMcpToolTypeAttribute.cs + +using System; + +namespace xAiModels.Attributes +{ + /// + /// Decorate Tools Classes ... + /// + [AttributeUsage(AttributeTargets.Class, AllowMultiple = false, Inherited = false)] + public class XAiMcpToolTypeAttribute : Attribute { } +} + +### FILE: C:\Users\saherelm\Documents\Projects\xSaherelmWorkspace\Modules\xAiModels\Configurations\XAiModelMappersProfile.cs using AutoMapper; using xAiModels.Models.Dtos; @@ -39,7 +120,7 @@ namespace xAiModels.Configurations } } -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\Modules\xAiModels\Configurations\Entities\XAiConversationEntityConfiguration.cs +### FILE: C:\Users\saherelm\Documents\Projects\xSaherelmWorkspace\Modules\xAiModels\Configurations\Entities\XAiConversationEntityConfiguration.cs using System; using xAiModels.Constants; @@ -59,7 +140,7 @@ namespace xAiModels.Configurations.Entities } } -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\Modules\xAiModels\Configurations\Entities\XAiMcpServerEntityConfiguration .cs +### FILE: C:\Users\saherelm\Documents\Projects\xSaherelmWorkspace\Modules\xAiModels\Configurations\Entities\XAiMcpServerEntityConfiguration .cs using System; using xAiModels.Constants; @@ -79,7 +160,7 @@ namespace xAiModels.Configurations.Entities } } -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\Modules\xAiModels\Configurations\Entities\XAiMessageEntityConfiguration.cs +### FILE: C:\Users\saherelm\Documents\Projects\xSaherelmWorkspace\Modules\xAiModels\Configurations\Entities\XAiMessageEntityConfiguration.cs using System; using xAiModels.Constants; @@ -99,7 +180,7 @@ namespace xAiModels.Configurations.Entities } } -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\Modules\xAiModels\Configurations\Entities\XAiProjectEntityConfiguration.cs +### FILE: C:\Users\saherelm\Documents\Projects\xSaherelmWorkspace\Modules\xAiModels\Configurations\Entities\XAiProjectEntityConfiguration.cs using System; using xAiModels.Constants; @@ -119,7 +200,7 @@ namespace xAiModels.Configurations.Entities } } -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\Modules\xAiModels\Configurations\Entities\XAiVectorEntityConfiguration.cs +### FILE: C:\Users\saherelm\Documents\Projects\xSaherelmWorkspace\Modules\xAiModels\Configurations\Entities\XAiVectorEntityConfiguration.cs using System; using xAiModels.Constants; @@ -148,7 +229,7 @@ namespace xAiModels.Configurations.Entities } } -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\Modules\xAiModels\Constants\ConfigurationNodeNames.cs +### FILE: C:\Users\saherelm\Documents\Projects\xSaherelmWorkspace\Modules\xAiModels\Constants\ConfigurationNodeNames.cs namespace xAiModels.Constants { @@ -158,7 +239,7 @@ namespace xAiModels.Constants } } -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\Modules\xAiModels\Constants\XAiChatRole.cs +### FILE: C:\Users\saherelm\Documents\Projects\xSaherelmWorkspace\Modules\xAiModels\Constants\XAiChatRole.cs using xExceptions.Attributes; @@ -188,7 +269,7 @@ namespace xAiModels.Constants } } -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\Modules\xAiModels\Constants\XAiDataProviderConstants.cs +### FILE: C:\Users\saherelm\Documents\Projects\xSaherelmWorkspace\Modules\xAiModels\Constants\XAiDataProviderConstants.cs using xExceptions.Attributes; @@ -248,7 +329,7 @@ namespace xAiModels.Constants } } -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\Modules\xAiModels\Constants\XAiKnowledgeScope.cs +### FILE: C:\Users\saherelm\Documents\Projects\xSaherelmWorkspace\Modules\xAiModels\Constants\XAiKnowledgeScope.cs using xExceptions.Attributes; @@ -286,7 +367,7 @@ namespace xAiModels.Constants } } -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\Modules\xAiModels\Constants\XAiMcpServerUsageScope.cs +### FILE: C:\Users\saherelm\Documents\Projects\xSaherelmWorkspace\Modules\xAiModels\Constants\XAiMcpServerUsageScope.cs using xExceptions.Attributes; @@ -302,7 +383,7 @@ namespace xAiModels.Constants } } -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\Modules\xAiModels\Constants\XAiModelProviderType.cs +### FILE: C:\Users\saherelm\Documents\Projects\xSaherelmWorkspace\Modules\xAiModels\Constants\XAiModelProviderType.cs namespace xAiModels.Constants { @@ -319,7 +400,7 @@ namespace xAiModels.Constants } } -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\Modules\xAiModels\Constants\XAiModelsConstants.cs +### FILE: C:\Users\saherelm\Documents\Projects\xSaherelmWorkspace\Modules\xAiModels\Constants\XAiModelsConstants.cs namespace xAiModels.Constants { @@ -422,43 +503,7 @@ namespace xAiModels.Constants } } -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\Modules\xAiModels\Controllers\XAiMcpServerControllerBase.cs - -using System; -using System.Linq; -using xCommons.Providers; -using xAiModels.Models.Dtos; -using xDataService.Interfaces; -using xCommons.Configurations; -using xDataService.Controllers; -using xAiModels.Models.Entities; -using Microsoft.Extensions.Logging; -using Microsoft.EntityFrameworkCore.Query; - -namespace xAiModels.Controllers -{ - public abstract class XAiMcpServerControllerBase : XBaseServiceController - { - protected XAiMcpServerControllerBase( - ILogger logger, - XAppConfiguration appConfiguration, - XValidationProvider validationProvider, - IXBaseRepositoryService repositoryService, - Func, IOrderedQueryable> defaultOrderBuilder = null, - Func, IIncludableQueryable> defaultIncludeBuilder = null - ) : base( - logger, - appConfiguration, - validationProvider, - repositoryService, - defaultOrderBuilder, - defaultIncludeBuilder - ) - { } - } -} - -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\Modules\xAiModels\DI\XDIHelperExtension.cs +### FILE: C:\Users\saherelm\Documents\Projects\xSaherelmWorkspace\Modules\xAiModels\DI\XDIHelperExtension.cs using System; using xDataService.Db; @@ -984,7 +1029,7 @@ namespace xAiModels.DI } } -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\Modules\xAiModels\Extensions\ChatResponseExtensions.cs +### FILE: C:\Users\saherelm\Documents\Projects\xSaherelmWorkspace\Modules\xAiModels\Extensions\ChatResponseExtensions.cs using xCommons.Extensions; using Microsoft.Extensions.AI; @@ -1013,7 +1058,7 @@ namespace xAiModels.Extensions } } -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\Modules\xAiModels\Extensions\ChatRoleExtensions.cs +### FILE: C:\Users\saherelm\Documents\Projects\xSaherelmWorkspace\Modules\xAiModels\Extensions\ChatRoleExtensions.cs using xAiModels.Constants; using xCommons.Extensions; @@ -1193,7 +1238,7 @@ namespace xAiModels.Extensions } } -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\Modules\xAiModels\Extensions\XAiModelsExtensions.cs +### FILE: C:\Users\saherelm\Documents\Projects\xSaherelmWorkspace\Modules\xAiModels\Extensions\XAiModelsExtensions.cs using System; using System.Linq; @@ -1724,7 +1769,7 @@ namespace xAiModels.Extensions } } -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\Modules\xAiModels\Extensions\XEmbeddingExtensions.cs +### FILE: C:\Users\saherelm\Documents\Projects\xSaherelmWorkspace\Modules\xAiModels\Extensions\XEmbeddingExtensions.cs using System; using xCommons.Extensions; @@ -1781,7 +1826,7 @@ namespace xAiModels.Extensions } } -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\Modules\xAiModels\Helpers\VectorHelper.cs +### FILE: C:\Users\saherelm\Documents\Projects\xSaherelmWorkspace\Modules\xAiModels\Helpers\VectorHelper.cs using System; using xCommons.Extensions; @@ -1858,7 +1903,7 @@ namespace xAiModels.Helpers } } -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\Modules\xAiModels\Helpers\XAiModelsHelper.cs +### FILE: C:\Users\saherelm\Documents\Projects\xSaherelmWorkspace\Modules\xAiModels\Helpers\XAiModelsHelper.cs using System; using GraphQL.Types; @@ -3211,7 +3256,7 @@ namespace xAiModels.Helpers } } -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\Modules\xAiModels\Interfaces\IXAiConversationTitleResourceProvider.cs +### FILE: C:\Users\saherelm\Documents\Projects\xSaherelmWorkspace\Modules\xAiModels\Interfaces\IXAiConversationTitleResourceProvider.cs using xStringService.Interfaces; @@ -3221,7 +3266,7 @@ namespace xAiModels.Interfaces { } } -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\Modules\xAiModels\Interfaces\IXAiDataProvider.cs +### FILE: C:\Users\saherelm\Documents\Projects\xSaherelmWorkspace\Modules\xAiModels\Interfaces\IXAiDataProvider.cs using System; using xModels.Dtos; @@ -3606,7 +3651,7 @@ namespace xAiModels.Interfaces } } -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\Modules\xAiModels\Interfaces\IXAiProjectDescriptionResourceProvider.cs +### FILE: C:\Users\saherelm\Documents\Projects\xSaherelmWorkspace\Modules\xAiModels\Interfaces\IXAiProjectDescriptionResourceProvider.cs using xStringService.Interfaces; @@ -3616,7 +3661,7 @@ namespace xAiModels.Interfaces { } } -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\Modules\xAiModels\Interfaces\IXAiProjectTitleResourceProvider.cs +### FILE: C:\Users\saherelm\Documents\Projects\xSaherelmWorkspace\Modules\xAiModels\Interfaces\IXAiProjectTitleResourceProvider.cs using xStringService.Interfaces; @@ -3626,7 +3671,7 @@ namespace xAiModels.Interfaces { } } -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\Modules\xAiModels\Interfaces\Dtos\IXAiConversationDtoHub.cs +### FILE: C:\Users\saherelm\Documents\Projects\xSaherelmWorkspace\Modules\xAiModels\Interfaces\Dtos\IXAiConversationDtoHub.cs using System; using xAiModels.Models.Dtos; @@ -3639,7 +3684,7 @@ namespace xAiModels.Interfaces.Dtos { } } -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\Modules\xAiModels\Interfaces\Dtos\IXAiConversationRepositoryService.cs +### FILE: C:\Users\saherelm\Documents\Projects\xSaherelmWorkspace\Modules\xAiModels\Interfaces\Dtos\IXAiConversationRepositoryService.cs using System; using System.Threading; @@ -3710,7 +3755,7 @@ namespace xAiModels.Interfaces.Dtos } } -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\Modules\xAiModels\Interfaces\Dtos\IXAiConversationServiceProvider.cs +### FILE: C:\Users\saherelm\Documents\Projects\xSaherelmWorkspace\Modules\xAiModels\Interfaces\Dtos\IXAiConversationServiceProvider.cs using System; using xAiModels.Models.Dtos; @@ -3724,7 +3769,7 @@ namespace xAiModels.Interfaces.Dtos { } } -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\Modules\xAiModels\Interfaces\Dtos\IXAiMcpServerDtoHub.cs +### FILE: C:\Users\saherelm\Documents\Projects\xSaherelmWorkspace\Modules\xAiModels\Interfaces\Dtos\IXAiMcpServerDtoHub.cs using System; using xAiModels.Models.Dtos; @@ -3737,7 +3782,7 @@ namespace xAiModels.Interfaces.Dtos { } } -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\Modules\xAiModels\Interfaces\Dtos\IXAiMcpServerRepositoryService.cs +### FILE: C:\Users\saherelm\Documents\Projects\xSaherelmWorkspace\Modules\xAiModels\Interfaces\Dtos\IXAiMcpServerRepositoryService.cs using System; using xAiModels.Models.Dtos; @@ -3750,7 +3795,7 @@ namespace xAiModels.Interfaces.Dtos { } } -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\Modules\xAiModels\Interfaces\Dtos\IXAiMcpServerServiceProvider.cs +### FILE: C:\Users\saherelm\Documents\Projects\xSaherelmWorkspace\Modules\xAiModels\Interfaces\Dtos\IXAiMcpServerServiceProvider.cs using System; using xAiModels.Models.Dtos; @@ -3764,7 +3809,7 @@ namespace xAiModels.Interfaces.Dtos { } } -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\Modules\xAiModels\Interfaces\Dtos\IXAiMessageDtoHub.cs +### FILE: C:\Users\saherelm\Documents\Projects\xSaherelmWorkspace\Modules\xAiModels\Interfaces\Dtos\IXAiMessageDtoHub.cs using System; using xAiModels.Models.Dtos; @@ -3777,7 +3822,7 @@ namespace xAiModels.Interfaces.Dtos { } } -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\Modules\xAiModels\Interfaces\Dtos\IXAiMessageRepositoryService.cs +### FILE: C:\Users\saherelm\Documents\Projects\xSaherelmWorkspace\Modules\xAiModels\Interfaces\Dtos\IXAiMessageRepositoryService.cs using System; using System.Threading; @@ -3840,7 +3885,7 @@ namespace xAiModels.Interfaces.Dtos } } -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\Modules\xAiModels\Interfaces\Dtos\IXAiMessageServiceProvider.cs +### FILE: C:\Users\saherelm\Documents\Projects\xSaherelmWorkspace\Modules\xAiModels\Interfaces\Dtos\IXAiMessageServiceProvider.cs using System; using xAiModels.Models.Dtos; @@ -3854,7 +3899,7 @@ namespace xAiModels.Interfaces.Dtos { } } -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\Modules\xAiModels\Interfaces\Dtos\IXAiProjectDtoHub.cs +### FILE: C:\Users\saherelm\Documents\Projects\xSaherelmWorkspace\Modules\xAiModels\Interfaces\Dtos\IXAiProjectDtoHub.cs using System; using xAiModels.Models.Dtos; @@ -3867,7 +3912,7 @@ namespace xAiModels.Interfaces.Dtos { } } -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\Modules\xAiModels\Interfaces\Dtos\IXAiProjectRepositoryService.cs +### FILE: C:\Users\saherelm\Documents\Projects\xSaherelmWorkspace\Modules\xAiModels\Interfaces\Dtos\IXAiProjectRepositoryService.cs using System; using System.Threading; @@ -3946,7 +3991,7 @@ namespace xAiModels.Interfaces.Dtos } } -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\Modules\xAiModels\Interfaces\Dtos\IXAiProjectServiceProvider.cs +### FILE: C:\Users\saherelm\Documents\Projects\xSaherelmWorkspace\Modules\xAiModels\Interfaces\Dtos\IXAiProjectServiceProvider.cs using System; using xAiModels.Models.Dtos; @@ -3960,7 +4005,7 @@ namespace xAiModels.Interfaces.Dtos { } } -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\Modules\xAiModels\Interfaces\Dtos\IXAiVectorDtoHub.cs +### FILE: C:\Users\saherelm\Documents\Projects\xSaherelmWorkspace\Modules\xAiModels\Interfaces\Dtos\IXAiVectorDtoHub.cs using System; using xAiModels.Models.Dtos; @@ -3973,7 +4018,7 @@ namespace xAiModels.Interfaces.Dtos { } } -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\Modules\xAiModels\Interfaces\Dtos\IXAiVectorRepositoryService.cs +### FILE: C:\Users\saherelm\Documents\Projects\xSaherelmWorkspace\Modules\xAiModels\Interfaces\Dtos\IXAiVectorRepositoryService.cs using System; using xAiModels.Models.Dtos; @@ -3987,7 +4032,7 @@ namespace xAiModels.Interfaces.Dtos } } -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\Modules\xAiModels\Interfaces\Dtos\IXAiVectorServiceProvider.cs +### FILE: C:\Users\saherelm\Documents\Projects\xSaherelmWorkspace\Modules\xAiModels\Interfaces\Dtos\IXAiVectorServiceProvider.cs using System; using xAiModels.Models.Dtos; @@ -4001,7 +4046,7 @@ namespace xAiModels.Interfaces.Dtos { } } -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\Modules\xAiModels\Interfaces\Enrichers\IXAiConversationEnricher.cs +### FILE: C:\Users\saherelm\Documents\Projects\xSaherelmWorkspace\Modules\xAiModels\Interfaces\Enrichers\IXAiConversationEnricher.cs using System.Threading; using xAiModels.Models.Dtos; @@ -4073,7 +4118,7 @@ namespace xAiModels.Interfaces.Enrichers } } -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\Modules\xAiModels\Interfaces\Enrichers\IXAiMcpServerEnricher.cs +### FILE: C:\Users\saherelm\Documents\Projects\xSaherelmWorkspace\Modules\xAiModels\Interfaces\Enrichers\IXAiMcpServerEnricher.cs using System.Threading; using System.Threading.Tasks; @@ -4107,7 +4152,7 @@ namespace xAiModels.Interfaces.Enrichers } } -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\Modules\xAiModels\Interfaces\Enrichers\IXAiMessageEnricher.cs +### FILE: C:\Users\saherelm\Documents\Projects\xSaherelmWorkspace\Modules\xAiModels\Interfaces\Enrichers\IXAiMessageEnricher.cs using System.Threading; using xAiModels.Models.Dtos; @@ -4168,7 +4213,7 @@ namespace xAiModels.Interfaces.Enrichers } } -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\Modules\xAiModels\Interfaces\Enrichers\IXAiProjectEnricher.cs +### FILE: C:\Users\saherelm\Documents\Projects\xSaherelmWorkspace\Modules\xAiModels\Interfaces\Enrichers\IXAiProjectEnricher.cs using System.Threading; using xAiModels.Models.Dtos; @@ -4245,7 +4290,7 @@ namespace xAiModels.Interfaces.Enrichers } } -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\Modules\xAiModels\Interfaces\Enrichers\IXAiVectorEnricher.cs +### FILE: C:\Users\saherelm\Documents\Projects\xSaherelmWorkspace\Modules\xAiModels\Interfaces\Enrichers\IXAiVectorEnricher.cs using System.Threading; using xAiModels.Models.Dtos; @@ -4306,7 +4351,7 @@ namespace xAiModels.Interfaces.Enrichers } } -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\Modules\xAiModels\Interfaces\Entities\IXAiConversationEntityHub.cs +### FILE: C:\Users\saherelm\Documents\Projects\xSaherelmWorkspace\Modules\xAiModels\Interfaces\Entities\IXAiConversationEntityHub.cs using System; using xPushService.Interfaces; @@ -4318,7 +4363,7 @@ namespace xAiModels.Interfaces.Entities { } } -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\Modules\xAiModels\Interfaces\Entities\IXAiConversationGraphQLTypeHelper.cs +### FILE: C:\Users\saherelm\Documents\Projects\xSaherelmWorkspace\Modules\xAiModels\Interfaces\Entities\IXAiConversationGraphQLTypeHelper.cs using System; using xDataService.Interfaces; @@ -4330,7 +4375,7 @@ namespace xAiModels.Interfaces.Entities { } } -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\Modules\xAiModels\Interfaces\Entities\IXAiConversationKeyGenerator.cs +### FILE: C:\Users\saherelm\Documents\Projects\xSaherelmWorkspace\Modules\xAiModels\Interfaces\Entities\IXAiConversationKeyGenerator.cs using System; using xDataService.Interfaces; @@ -4342,7 +4387,7 @@ namespace xAiModels.Interfaces.Entities { } } -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\Modules\xAiModels\Interfaces\Entities\IXAiConversationRepository.cs +### FILE: C:\Users\saherelm\Documents\Projects\xSaherelmWorkspace\Modules\xAiModels\Interfaces\Entities\IXAiConversationRepository.cs using System; using xDataService.Interfaces; @@ -4354,7 +4399,7 @@ namespace xAiModels.Interfaces.Entities { } } -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\Modules\xAiModels\Interfaces\Entities\IXAiConversationRepositoryEvents.cs +### FILE: C:\Users\saherelm\Documents\Projects\xSaherelmWorkspace\Modules\xAiModels\Interfaces\Entities\IXAiConversationRepositoryEvents.cs using xDataService.Interfaces; using xAiModels.Models.Entities; @@ -4365,7 +4410,7 @@ namespace xAiModels.Interfaces.Entities { } } -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\Modules\xAiModels\Interfaces\Entities\IXAiConversationRepositoryProvider.cs +### FILE: C:\Users\saherelm\Documents\Projects\xSaherelmWorkspace\Modules\xAiModels\Interfaces\Entities\IXAiConversationRepositoryProvider.cs using System; using xPushService.Interfaces; @@ -4378,7 +4423,7 @@ namespace xAiModels.Interfaces.Entities { } } -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\Modules\xAiModels\Interfaces\Entities\IXAiConversationSeeder.cs +### FILE: C:\Users\saherelm\Documents\Projects\xSaherelmWorkspace\Modules\xAiModels\Interfaces\Entities\IXAiConversationSeeder.cs using System; using xDataService.Interfaces; @@ -4390,7 +4435,7 @@ namespace xAiModels.Interfaces.Entities { } } -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\Modules\xAiModels\Interfaces\Entities\IXAiDocumentEntityHub.cs +### FILE: C:\Users\saherelm\Documents\Projects\xSaherelmWorkspace\Modules\xAiModels\Interfaces\Entities\IXAiDocumentEntityHub.cs using System; using System.Collections.Generic; @@ -4405,7 +4450,7 @@ namespace xAiModels.Interfaces.Entities } } -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\Modules\xAiModels\Interfaces\Entities\IXAiMcpServerEntityHub.cs +### FILE: C:\Users\saherelm\Documents\Projects\xSaherelmWorkspace\Modules\xAiModels\Interfaces\Entities\IXAiMcpServerEntityHub.cs using System; using xPushService.Interfaces; @@ -4417,7 +4462,7 @@ namespace xAiModels.Interfaces.Entities { } } -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\Modules\xAiModels\Interfaces\Entities\IXAiMcpServerGraphQLTypeHelper.cs +### FILE: C:\Users\saherelm\Documents\Projects\xSaherelmWorkspace\Modules\xAiModels\Interfaces\Entities\IXAiMcpServerGraphQLTypeHelper.cs using System; using xDataService.Interfaces; @@ -4429,7 +4474,7 @@ namespace xAiModels.Interfaces.Entities { } } -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\Modules\xAiModels\Interfaces\Entities\IXAiMcpServerKeyGenerator.cs +### FILE: C:\Users\saherelm\Documents\Projects\xSaherelmWorkspace\Modules\xAiModels\Interfaces\Entities\IXAiMcpServerKeyGenerator.cs using System; using xDataService.Interfaces; @@ -4441,7 +4486,7 @@ namespace xAiModels.Interfaces.Entities { } } -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\Modules\xAiModels\Interfaces\Entities\IXAiMcpServerRepository.cs +### FILE: C:\Users\saherelm\Documents\Projects\xSaherelmWorkspace\Modules\xAiModels\Interfaces\Entities\IXAiMcpServerRepository.cs using System; using xDataService.Interfaces; @@ -4452,7 +4497,7 @@ namespace xAiModels.Interfaces.Entities public interface IXAiMcpServerRepository : IXBaseRepository { } } -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\Modules\xAiModels\Interfaces\Entities\IXAiMcpServerRepositoryEvents.cs +### FILE: C:\Users\saherelm\Documents\Projects\xSaherelmWorkspace\Modules\xAiModels\Interfaces\Entities\IXAiMcpServerRepositoryEvents.cs using xDataService.Interfaces; using xAiModels.Models.Entities; @@ -4463,7 +4508,7 @@ namespace xAiModels.Interfaces.Entities { } } -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\Modules\xAiModels\Interfaces\Entities\IXAiMcpServerRepositoryProvider.cs +### FILE: C:\Users\saherelm\Documents\Projects\xSaherelmWorkspace\Modules\xAiModels\Interfaces\Entities\IXAiMcpServerRepositoryProvider.cs using System; using xPushService.Interfaces; @@ -4476,7 +4521,7 @@ namespace xAiModels.Interfaces.Entities { } } -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\Modules\xAiModels\Interfaces\Entities\IXAiMcpServerSeeder.cs +### FILE: C:\Users\saherelm\Documents\Projects\xSaherelmWorkspace\Modules\xAiModels\Interfaces\Entities\IXAiMcpServerSeeder.cs using System; using xDataService.Interfaces; @@ -4488,7 +4533,7 @@ namespace xAiModels.Interfaces.Entities { } } -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\Modules\xAiModels\Interfaces\Entities\IXAiMessageEntityHub.cs +### FILE: C:\Users\saherelm\Documents\Projects\xSaherelmWorkspace\Modules\xAiModels\Interfaces\Entities\IXAiMessageEntityHub.cs using System; using xPushService.Interfaces; @@ -4500,7 +4545,7 @@ namespace xAiModels.Interfaces.Entities { } } -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\Modules\xAiModels\Interfaces\Entities\IXAiMessageGraphQLTypeHelper.cs +### FILE: C:\Users\saherelm\Documents\Projects\xSaherelmWorkspace\Modules\xAiModels\Interfaces\Entities\IXAiMessageGraphQLTypeHelper.cs using System; using xDataService.Interfaces; @@ -4512,7 +4557,7 @@ namespace xAiModels.Interfaces.Entities { } } -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\Modules\xAiModels\Interfaces\Entities\IXAiMessageKeyGenerator.cs +### FILE: C:\Users\saherelm\Documents\Projects\xSaherelmWorkspace\Modules\xAiModels\Interfaces\Entities\IXAiMessageKeyGenerator.cs using System; using xDataService.Interfaces; @@ -4524,7 +4569,7 @@ namespace xAiModels.Interfaces.Entities { } } -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\Modules\xAiModels\Interfaces\Entities\IXAiMessageRepository.cs +### FILE: C:\Users\saherelm\Documents\Projects\xSaherelmWorkspace\Modules\xAiModels\Interfaces\Entities\IXAiMessageRepository.cs using System; using xDataService.Interfaces; @@ -4536,7 +4581,7 @@ namespace xAiModels.Interfaces.Entities { } } -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\Modules\xAiModels\Interfaces\Entities\IXAiMessageRepositoryEvents.cs +### FILE: C:\Users\saherelm\Documents\Projects\xSaherelmWorkspace\Modules\xAiModels\Interfaces\Entities\IXAiMessageRepositoryEvents.cs using xDataService.Interfaces; using xAiModels.Models.Entities; @@ -4547,7 +4592,7 @@ namespace xAiModels.Interfaces.Entities { } } -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\Modules\xAiModels\Interfaces\Entities\IXAiMessageRepositoryProvider.cs +### FILE: C:\Users\saherelm\Documents\Projects\xSaherelmWorkspace\Modules\xAiModels\Interfaces\Entities\IXAiMessageRepositoryProvider.cs using System; using xPushService.Interfaces; @@ -4560,7 +4605,7 @@ namespace xAiModels.Interfaces.Entities { } } -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\Modules\xAiModels\Interfaces\Entities\IXAiMessageSeeder.cs +### FILE: C:\Users\saherelm\Documents\Projects\xSaherelmWorkspace\Modules\xAiModels\Interfaces\Entities\IXAiMessageSeeder.cs using System; using xDataService.Interfaces; @@ -4572,7 +4617,7 @@ namespace xAiModels.Interfaces.Entities { } } -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\Modules\xAiModels\Interfaces\Entities\IXAiProjectEntityHub.cs +### FILE: C:\Users\saherelm\Documents\Projects\xSaherelmWorkspace\Modules\xAiModels\Interfaces\Entities\IXAiProjectEntityHub.cs using System; using xPushService.Interfaces; @@ -4584,7 +4629,7 @@ namespace xAiModels.Interfaces.Entities { } } -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\Modules\xAiModels\Interfaces\Entities\IXAiProjectGraphQLTypeHelper.cs +### FILE: C:\Users\saherelm\Documents\Projects\xSaherelmWorkspace\Modules\xAiModels\Interfaces\Entities\IXAiProjectGraphQLTypeHelper.cs using System; using xDataService.Interfaces; @@ -4596,7 +4641,7 @@ namespace xAiModels.Interfaces.Entities { } } -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\Modules\xAiModels\Interfaces\Entities\IXAiProjectKeyGenerator.cs +### FILE: C:\Users\saherelm\Documents\Projects\xSaherelmWorkspace\Modules\xAiModels\Interfaces\Entities\IXAiProjectKeyGenerator.cs using System; using xDataService.Interfaces; @@ -4608,7 +4653,7 @@ namespace xAiModels.Interfaces.Entities { } } -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\Modules\xAiModels\Interfaces\Entities\IXAiProjectRepository.cs +### FILE: C:\Users\saherelm\Documents\Projects\xSaherelmWorkspace\Modules\xAiModels\Interfaces\Entities\IXAiProjectRepository.cs using System; using xDataService.Interfaces; @@ -4620,7 +4665,7 @@ namespace xAiModels.Interfaces.Entities { } } -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\Modules\xAiModels\Interfaces\Entities\IXAiProjectRepositoryEvents.cs +### FILE: C:\Users\saherelm\Documents\Projects\xSaherelmWorkspace\Modules\xAiModels\Interfaces\Entities\IXAiProjectRepositoryEvents.cs using xDataService.Interfaces; using xAiModels.Models.Entities; @@ -4631,7 +4676,7 @@ namespace xAiModels.Interfaces.Entities { } } -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\Modules\xAiModels\Interfaces\Entities\IXAiProjectRepositoryProvider.cs +### FILE: C:\Users\saherelm\Documents\Projects\xSaherelmWorkspace\Modules\xAiModels\Interfaces\Entities\IXAiProjectRepositoryProvider.cs using System; using xPushService.Interfaces; @@ -4644,7 +4689,7 @@ namespace xAiModels.Interfaces.Entities { } } -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\Modules\xAiModels\Interfaces\Entities\IXAiProjectSeeder.cs +### FILE: C:\Users\saherelm\Documents\Projects\xSaherelmWorkspace\Modules\xAiModels\Interfaces\Entities\IXAiProjectSeeder.cs using System; using xDataService.Interfaces; @@ -4656,7 +4701,7 @@ namespace xAiModels.Interfaces.Entities { } } -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\Modules\xAiModels\Interfaces\Entities\IXAiVectorEntityHub.cs +### FILE: C:\Users\saherelm\Documents\Projects\xSaherelmWorkspace\Modules\xAiModels\Interfaces\Entities\IXAiVectorEntityHub.cs using System; using xPushService.Interfaces; @@ -4668,7 +4713,7 @@ namespace xAiModels.Interfaces.Entities { } } -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\Modules\xAiModels\Interfaces\Entities\IXAiVectorGraphQLTypeHelper.cs +### FILE: C:\Users\saherelm\Documents\Projects\xSaherelmWorkspace\Modules\xAiModels\Interfaces\Entities\IXAiVectorGraphQLTypeHelper.cs using System; using xDataService.Interfaces; @@ -4680,7 +4725,7 @@ namespace xAiModels.Interfaces.Entities { } } -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\Modules\xAiModels\Interfaces\Entities\IXAiVectorKeyGenerator.cs +### FILE: C:\Users\saherelm\Documents\Projects\xSaherelmWorkspace\Modules\xAiModels\Interfaces\Entities\IXAiVectorKeyGenerator.cs using System; using xDataService.Interfaces; @@ -4692,7 +4737,7 @@ namespace xAiModels.Interfaces.Entities { } } -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\Modules\xAiModels\Interfaces\Entities\IXAiVectorRepository.cs +### FILE: C:\Users\saherelm\Documents\Projects\xSaherelmWorkspace\Modules\xAiModels\Interfaces\Entities\IXAiVectorRepository.cs using System; using xDataService.Interfaces; @@ -4704,7 +4749,7 @@ namespace xAiModels.Interfaces.Entities { } } -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\Modules\xAiModels\Interfaces\Entities\IXAiVectorRepositoryEvents.cs +### FILE: C:\Users\saherelm\Documents\Projects\xSaherelmWorkspace\Modules\xAiModels\Interfaces\Entities\IXAiVectorRepositoryEvents.cs using xDataService.Interfaces; using xAiModels.Models.Entities; @@ -4715,7 +4760,7 @@ namespace xAiModels.Interfaces.Entities { } } -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\Modules\xAiModels\Interfaces\Entities\IXAiVectorRepositoryProvider.cs +### FILE: C:\Users\saherelm\Documents\Projects\xSaherelmWorkspace\Modules\xAiModels\Interfaces\Entities\IXAiVectorRepositoryProvider.cs using System; using xPushService.Interfaces; @@ -4728,7 +4773,7 @@ namespace xAiModels.Interfaces.Entities { } } -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\Modules\xAiModels\Interfaces\Entities\IXAiVectorSeeder.cs +### FILE: C:\Users\saherelm\Documents\Projects\xSaherelmWorkspace\Modules\xAiModels\Interfaces\Entities\IXAiVectorSeeder.cs using System; using xDataService.Interfaces; @@ -4740,7 +4785,25 @@ namespace xAiModels.Interfaces.Entities { } } -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\Modules\xAiModels\Models\XAiModelDescriptor.cs +### FILE: C:\Users\saherelm\Documents\Projects\xSaherelmWorkspace\Modules\xAiModels\Models\XAiMcpToolDescriptor.cs + +using System; +using System.Threading; +using Newtonsoft.Json.Linq; +using System.Threading.Tasks; + +namespace xAiModels.Models +{ + public class XAiMcpToolDescriptor + { + public string Name { get; set; } + public string Description { get; set; } + public JObject InputSchema { get; set; } + public Func> Execute { get; set; } + } +} + +### FILE: C:\Users\saherelm\Documents\Projects\xSaherelmWorkspace\Modules\xAiModels\Models\XAiModelDescriptor.cs using xAiModels.Constants; @@ -4778,7 +4841,7 @@ namespace xAiModels.Models } } -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\Modules\xAiModels\Models\XAiPromptDescriptor.cs +### FILE: C:\Users\saherelm\Documents\Projects\xSaherelmWorkspace\Modules\xAiModels\Models\XAiPromptDescriptor.cs namespace xAiModels.Models { @@ -4830,7 +4893,7 @@ namespace xAiModels.Models } } -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\Modules\xAiModels\Models\XAiResonseMessage.cs +### FILE: C:\Users\saherelm\Documents\Projects\xSaherelmWorkspace\Modules\xAiModels\Models\XAiResonseMessage.cs using System; using xModels.Base; @@ -4849,7 +4912,7 @@ namespace xAiModels.Models } } -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\Modules\xAiModels\Models\XAiResponseRequest.cs +### FILE: C:\Users\saherelm\Documents\Projects\xSaherelmWorkspace\Modules\xAiModels\Models\XAiResponseRequest.cs using System; using xAiModels.Constants; @@ -4893,7 +4956,7 @@ namespace xAiModels.Models } } -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\Modules\xAiModels\Models\XFileExtractionResult.cs +### FILE: C:\Users\saherelm\Documents\Projects\xSaherelmWorkspace\Modules\xAiModels\Models\XFileExtractionResult.cs using System.Collections.Generic; @@ -4967,7 +5030,7 @@ namespace xAiModels.Models } } -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\Modules\xAiModels\Models\Dtos\XAiConversationDto.cs +### FILE: C:\Users\saherelm\Documents\Projects\xSaherelmWorkspace\Modules\xAiModels\Models\Dtos\XAiConversationDto.cs using System; using xModels.Base; @@ -5044,7 +5107,7 @@ namespace xAiModels.Models.Dtos } } -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\Modules\xAiModels\Models\Dtos\XAiMcpServerDto.cs +### FILE: C:\Users\saherelm\Documents\Projects\xSaherelmWorkspace\Modules\xAiModels\Models\Dtos\XAiMcpServerDto.cs using System; using xModels.Base; @@ -5106,7 +5169,7 @@ namespace xAiModels.Models.Dtos } } -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\Modules\xAiModels\Models\Dtos\XAiMessageDto.cs +### FILE: C:\Users\saherelm\Documents\Projects\xSaherelmWorkspace\Modules\xAiModels\Models\Dtos\XAiMessageDto.cs using System; using xModels.Base; @@ -5198,7 +5261,7 @@ namespace xAiModels.Models.Dtos } } -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\Modules\xAiModels\Models\Dtos\XAiProjectDto.cs +### FILE: C:\Users\saherelm\Documents\Projects\xSaherelmWorkspace\Modules\xAiModels\Models\Dtos\XAiProjectDto.cs using System; using xModels.Base; @@ -5265,7 +5328,7 @@ namespace xAiModels.Models.Dtos } } -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\Modules\xAiModels\Models\Dtos\XAiVectorDto.cs +### FILE: C:\Users\saherelm\Documents\Projects\xSaherelmWorkspace\Modules\xAiModels\Models\Dtos\XAiVectorDto.cs using System; using xModels.Base; @@ -5305,7 +5368,7 @@ namespace xAiModels.Models.Dtos } } -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\Modules\xAiModels\Models\Dtos\XAiVectorSearchResult.cs +### FILE: C:\Users\saherelm\Documents\Projects\xSaherelmWorkspace\Modules\xAiModels\Models\Dtos\XAiVectorSearchResult.cs using System; using System.Collections.Generic; @@ -5323,7 +5386,7 @@ namespace xAiModels.Models.Dtos } } -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\Modules\xAiModels\Models\Entities\XAiConversation.cs +### FILE: C:\Users\saherelm\Documents\Projects\xSaherelmWorkspace\Modules\xAiModels\Models\Entities\XAiConversation.cs using System; using xModels.Base; @@ -5369,7 +5432,7 @@ namespace xAiModels.Models.Entities } } -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\Modules\xAiModels\Models\Entities\XAiMcpServer.cs +### FILE: C:\Users\saherelm\Documents\Projects\xSaherelmWorkspace\Modules\xAiModels\Models\Entities\XAiMcpServer.cs using System; using xModels.Base; @@ -5439,7 +5502,7 @@ namespace xAiModels.Models.Entities } } -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\Modules\xAiModels\Models\Entities\XAiMessage.cs +### FILE: C:\Users\saherelm\Documents\Projects\xSaherelmWorkspace\Modules\xAiModels\Models\Entities\XAiMessage.cs using System; using xModels.Base; @@ -5527,7 +5590,7 @@ namespace xAiModels.Models.Entities } } -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\Modules\xAiModels\Models\Entities\XAiProject.cs +### FILE: C:\Users\saherelm\Documents\Projects\xSaherelmWorkspace\Modules\xAiModels\Models\Entities\XAiProject.cs using System; using xModels.Base; @@ -5578,7 +5641,7 @@ namespace xAiModels.Models.Entities } } -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\Modules\xAiModels\Models\Entities\XAiVector.cs +### FILE: C:\Users\saherelm\Documents\Projects\xSaherelmWorkspace\Modules\xAiModels\Models\Entities\XAiVector.cs using xModels.Base; using System.ComponentModel.DataAnnotations; @@ -5616,7 +5679,7 @@ namespace xAiModels.Models.Entities } } -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\Modules\xAiModels\Providers\XAiConversationEntityRegisterar.cs +### FILE: C:\Users\saherelm\Documents\Projects\xSaherelmWorkspace\Modules\xAiModels\Providers\XAiConversationEntityRegisterar.cs using System; using xDataService.Providers; @@ -5654,7 +5717,7 @@ namespace xAiModels.Providers } } -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\Modules\xAiModels\Providers\XAiConversationTitleResourceProvider.cs +### FILE: C:\Users\saherelm\Documents\Projects\xSaherelmWorkspace\Modules\xAiModels\Providers\XAiConversationTitleResourceProvider.cs using xAiModels.Constants; using xAiModels.Interfaces; @@ -5678,7 +5741,7 @@ namespace xAiModels.Providers } } -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\Modules\xAiModels\Providers\XAiDataProvider.cs +### FILE: C:\Users\saherelm\Documents\Projects\xSaherelmWorkspace\Modules\xAiModels\Providers\XAiDataProvider.cs using System; using System.Linq; @@ -8131,7 +8194,7 @@ namespace xAiModels.Providers } } -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\Modules\xAiModels\Providers\XAiMcpServerEntityRegisterar .cs +### FILE: C:\Users\saherelm\Documents\Projects\xSaherelmWorkspace\Modules\xAiModels\Providers\XAiMcpServerEntityRegisterar .cs using System; using xDataService.Providers; @@ -8169,7 +8232,7 @@ namespace xAiModels.Providers } } -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\Modules\xAiModels\Providers\XAiMessageEntityRegisterar.cs +### FILE: C:\Users\saherelm\Documents\Projects\xSaherelmWorkspace\Modules\xAiModels\Providers\XAiMessageEntityRegisterar.cs using System; using xDataService.Providers; @@ -8207,7 +8270,7 @@ namespace xAiModels.Providers } } -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\Modules\xAiModels\Providers\XAiProjectDescriptionResourceProvider.cs +### FILE: C:\Users\saherelm\Documents\Projects\xSaherelmWorkspace\Modules\xAiModels\Providers\XAiProjectDescriptionResourceProvider.cs using xAiModels.Constants; using xAiModels.Interfaces; @@ -8231,7 +8294,7 @@ namespace xAiModels.Providers } } -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\Modules\xAiModels\Providers\XAiProjectEntityRegisterar.cs +### FILE: C:\Users\saherelm\Documents\Projects\xSaherelmWorkspace\Modules\xAiModels\Providers\XAiProjectEntityRegisterar.cs using System; using xDataService.Providers; @@ -8269,7 +8332,7 @@ namespace xAiModels.Providers } } -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\Modules\xAiModels\Providers\XAiProjectTitleResourceProvider.cs +### FILE: C:\Users\saherelm\Documents\Projects\xSaherelmWorkspace\Modules\xAiModels\Providers\XAiProjectTitleResourceProvider.cs using xAiModels.Constants; using xAiModels.Interfaces; @@ -8293,7 +8356,7 @@ namespace xAiModels.Providers } } -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\Modules\xAiModels\Providers\XAiVectorEntityRegisterar.cs +### FILE: C:\Users\saherelm\Documents\Projects\xSaherelmWorkspace\Modules\xAiModels\Providers\XAiVectorEntityRegisterar.cs using System; using xDataService.Providers; @@ -8331,7 +8394,7 @@ namespace xAiModels.Providers } } -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\Modules\xAiModels\Providers\Dtos\XAiConversationDtoHub.cs +### FILE: C:\Users\saherelm\Documents\Projects\xSaherelmWorkspace\Modules\xAiModels\Providers\Dtos\XAiConversationDtoHub.cs using System; using xPushService.Base; @@ -8351,7 +8414,7 @@ namespace xAiModels.Providers.Dtos } } -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\Modules\xAiModels\Providers\Dtos\XAiConversationRepositoryService.cs +### FILE: C:\Users\saherelm\Documents\Projects\xSaherelmWorkspace\Modules\xAiModels\Providers\Dtos\XAiConversationRepositoryService.cs using System; using System.Linq; @@ -8561,7 +8624,7 @@ namespace xAiModels.Providers.Dtos } } -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\Modules\xAiModels\Providers\Dtos\XAiConversationServiceProvider.cs +### FILE: C:\Users\saherelm\Documents\Projects\xSaherelmWorkspace\Modules\xAiModels\Providers\Dtos\XAiConversationServiceProvider.cs using System; using xPushService.Base; @@ -8591,7 +8654,7 @@ namespace xAiModels.Providers.Dtos } } -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\Modules\xAiModels\Providers\Dtos\XAiMcpServerDtoHub.cs +### FILE: C:\Users\saherelm\Documents\Projects\xSaherelmWorkspace\Modules\xAiModels\Providers\Dtos\XAiMcpServerDtoHub.cs using System; using xPushService.Base; @@ -8611,7 +8674,7 @@ namespace xAiModels.Providers.Dtos } } -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\Modules\xAiModels\Providers\Dtos\XAiMcpServerRepositoryService.cs +### FILE: C:\Users\saherelm\Documents\Projects\xSaherelmWorkspace\Modules\xAiModels\Providers\Dtos\XAiMcpServerRepositoryService.cs using System; using xAiModels.Models.Dtos; @@ -8640,7 +8703,7 @@ namespace xAiModels.Providers.Dtos } } -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\Modules\xAiModels\Providers\Dtos\XAiMcpServerServiceProvider.cs +### FILE: C:\Users\saherelm\Documents\Projects\xSaherelmWorkspace\Modules\xAiModels\Providers\Dtos\XAiMcpServerServiceProvider.cs using System; using xPushService.Base; @@ -8665,7 +8728,7 @@ namespace xAiModels.Providers.Dtos } } -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\Modules\xAiModels\Providers\Dtos\XAiMessageDtoHub.cs +### FILE: C:\Users\saherelm\Documents\Projects\xSaherelmWorkspace\Modules\xAiModels\Providers\Dtos\XAiMessageDtoHub.cs using System; using xPushService.Base; @@ -8685,7 +8748,7 @@ namespace xAiModels.Providers.Dtos } } -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\Modules\xAiModels\Providers\Dtos\XAiMessageRepositoryService.cs +### FILE: C:\Users\saherelm\Documents\Projects\xSaherelmWorkspace\Modules\xAiModels\Providers\Dtos\XAiMessageRepositoryService.cs using System; using System.Linq; @@ -8853,7 +8916,7 @@ namespace xAiModels.Providers.Dtos } } -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\Modules\xAiModels\Providers\Dtos\XAiMessageServiceProvider.cs +### FILE: C:\Users\saherelm\Documents\Projects\xSaherelmWorkspace\Modules\xAiModels\Providers\Dtos\XAiMessageServiceProvider.cs using System; using xPushService.Base; @@ -8883,7 +8946,7 @@ namespace xAiModels.Providers.Dtos } } -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\Modules\xAiModels\Providers\Dtos\XAiProjectDtoHub.cs +### FILE: C:\Users\saherelm\Documents\Projects\xSaherelmWorkspace\Modules\xAiModels\Providers\Dtos\XAiProjectDtoHub.cs using System; using xPushService.Base; @@ -8903,7 +8966,7 @@ namespace xAiModels.Providers.Dtos } } -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\Modules\xAiModels\Providers\Dtos\XAiProjectRepositoryService.cs +### FILE: C:\Users\saherelm\Documents\Projects\xSaherelmWorkspace\Modules\xAiModels\Providers\Dtos\XAiProjectRepositoryService.cs using System; using System.Linq; @@ -9228,7 +9291,7 @@ namespace xAiModels.Providers.Dtos } } -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\Modules\xAiModels\Providers\Dtos\XAiProjectServiceProvider.cs +### FILE: C:\Users\saherelm\Documents\Projects\xSaherelmWorkspace\Modules\xAiModels\Providers\Dtos\XAiProjectServiceProvider.cs using System; using xPushService.Base; @@ -9258,7 +9321,7 @@ namespace xAiModels.Providers.Dtos } } -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\Modules\xAiModels\Providers\Dtos\XAiVectorDtoHub.cs +### FILE: C:\Users\saherelm\Documents\Projects\xSaherelmWorkspace\Modules\xAiModels\Providers\Dtos\XAiVectorDtoHub.cs using System; using xPushService.Base; @@ -9278,7 +9341,7 @@ namespace xAiModels.Providers.Dtos } } -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\Modules\xAiModels\Providers\Dtos\XAiVectorRepositoryService.cs +### FILE: C:\Users\saherelm\Documents\Projects\xSaherelmWorkspace\Modules\xAiModels\Providers\Dtos\XAiVectorRepositoryService.cs using System; using xAiModels.Models.Dtos; @@ -9305,7 +9368,7 @@ namespace xAiModels.Providers.Dtos } } -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\Modules\xAiModels\Providers\Dtos\XAiVectorServiceProvider.cs +### FILE: C:\Users\saherelm\Documents\Projects\xSaherelmWorkspace\Modules\xAiModels\Providers\Dtos\XAiVectorServiceProvider.cs using System; using xPushService.Base; @@ -9335,7 +9398,7 @@ namespace xAiModels.Providers.Dtos } } -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\Modules\xAiModels\Providers\Enrichers\XAiConversationEnricher.cs +### FILE: C:\Users\saherelm\Documents\Projects\xSaherelmWorkspace\Modules\xAiModels\Providers\Enrichers\XAiConversationEnricher.cs using System.Linq; using xModels.Dtos; @@ -9536,7 +9599,7 @@ namespace xAiModels.Providers.Enrichers } } -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\Modules\xAiModels\Providers\Enrichers\XAiMcpServerEnricher.cs +### FILE: C:\Users\saherelm\Documents\Projects\xSaherelmWorkspace\Modules\xAiModels\Providers\Enrichers\XAiMcpServerEnricher.cs using System.Linq; using xModels.Dtos; @@ -9618,7 +9681,7 @@ namespace xAiModels.Providers.Enrichers } } -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\Modules\xAiModels\Providers\Enrichers\XAiMessageEnricher.cs +### FILE: C:\Users\saherelm\Documents\Projects\xSaherelmWorkspace\Modules\xAiModels\Providers\Enrichers\XAiMessageEnricher.cs using System.Linq; using xModels.Dtos; @@ -9768,7 +9831,7 @@ namespace xAiModels.Providers.Enrichers } } -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\Modules\xAiModels\Providers\Enrichers\XAiProjectEnricher.cs +### FILE: C:\Users\saherelm\Documents\Projects\xSaherelmWorkspace\Modules\xAiModels\Providers\Enrichers\XAiProjectEnricher.cs using System.Linq; using xModels.Dtos; @@ -10075,7 +10138,7 @@ namespace xAiModels.Providers.Enrichers } } -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\Modules\xAiModels\Providers\Enrichers\XAiVectorEnricher.cs +### FILE: C:\Users\saherelm\Documents\Projects\xSaherelmWorkspace\Modules\xAiModels\Providers\Enrichers\XAiVectorEnricher.cs using System.Linq; using System.Threading; @@ -10192,7 +10255,7 @@ namespace xAiModels.Providers.Enrichers } } -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\Modules\xAiModels\Providers\Entities\XAiConversationEFRepository.cs +### FILE: C:\Users\saherelm\Documents\Projects\xSaherelmWorkspace\Modules\xAiModels\Providers\Entities\XAiConversationEFRepository.cs using System; using xDataService.Db; @@ -10222,7 +10285,7 @@ namespace xAiModels.Providers.Entities } } -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\Modules\xAiModels\Providers\Entities\XAiConversationEntityHub.cs +### FILE: C:\Users\saherelm\Documents\Projects\xSaherelmWorkspace\Modules\xAiModels\Providers\Entities\XAiConversationEntityHub.cs using System; using xPushService.Base; @@ -10241,7 +10304,7 @@ namespace xAiModels.Providers.Entities } } -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\Modules\xAiModels\Providers\Entities\XAiConversationInMemoryRepository.cs +### FILE: C:\Users\saherelm\Documents\Projects\xSaherelmWorkspace\Modules\xAiModels\Providers\Entities\XAiConversationInMemoryRepository.cs using System; using xDataService.Providers; @@ -10266,7 +10329,7 @@ namespace xAiModels.Providers.Entities } } -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\Modules\xAiModels\Providers\Entities\XAiConversationKeyGenerator.cs +### FILE: C:\Users\saherelm\Documents\Projects\xSaherelmWorkspace\Modules\xAiModels\Providers\Entities\XAiConversationKeyGenerator.cs using xDataService.Providers; using xAiModels.Models.Entities; @@ -10278,7 +10341,7 @@ namespace xAiModels.Providers.Entities { } } -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\Modules\xAiModels\Providers\Entities\XAiConversationMongoRepository.cs +### FILE: C:\Users\saherelm\Documents\Projects\xSaherelmWorkspace\Modules\xAiModels\Providers\Entities\XAiConversationMongoRepository.cs using System; using xDataService.Providers; @@ -10307,7 +10370,7 @@ namespace xAiModels.Providers.Entities } } -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\Modules\xAiModels\Providers\Entities\XAiConversationRepositoryEvents.cs +### FILE: C:\Users\saherelm\Documents\Projects\xSaherelmWorkspace\Modules\xAiModels\Providers\Entities\XAiConversationRepositoryEvents.cs using xDataService.Providers; using xAiModels.Models.Entities; @@ -10319,7 +10382,7 @@ namespace xAiModels.Providers.Entities { } } -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\Modules\xAiModels\Providers\Entities\XAiConversationRepositoryProvider.cs +### FILE: C:\Users\saherelm\Documents\Projects\xSaherelmWorkspace\Modules\xAiModels\Providers\Entities\XAiConversationRepositoryProvider.cs using System; using xPushService.Base; @@ -10348,7 +10411,7 @@ namespace xAiModels.Providers.Entities } } -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\Modules\xAiModels\Providers\Entities\XAiConversationSeederBase.cs +### FILE: C:\Users\saherelm\Documents\Projects\xSaherelmWorkspace\Modules\xAiModels\Providers\Entities\XAiConversationSeederBase.cs using System; using xDataService.Providers; @@ -10375,7 +10438,7 @@ namespace xAiModels.Providers.Entities } } -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\Modules\xAiModels\Providers\Entities\XAiMcpServerEFRepository.cs +### FILE: C:\Users\saherelm\Documents\Projects\xSaherelmWorkspace\Modules\xAiModels\Providers\Entities\XAiMcpServerEFRepository.cs using System; using xDataService.Db; @@ -10400,7 +10463,7 @@ namespace xAiModels.Providers.Entities } } -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\Modules\xAiModels\Providers\Entities\XAiMcpServerEntityHub.cs +### FILE: C:\Users\saherelm\Documents\Projects\xSaherelmWorkspace\Modules\xAiModels\Providers\Entities\XAiMcpServerEntityHub.cs using System; using xPushService.Base; @@ -10419,7 +10482,7 @@ namespace xAiModels.Providers.Entities } } -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\Modules\xAiModels\Providers\Entities\XAiMcpServerInMemoryRepository.cs +### FILE: C:\Users\saherelm\Documents\Projects\xSaherelmWorkspace\Modules\xAiModels\Providers\Entities\XAiMcpServerInMemoryRepository.cs using System; using xDataService.Providers; @@ -10440,7 +10503,7 @@ namespace xAiModels.Providers.Entities } } -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\Modules\xAiModels\Providers\Entities\XAiMcpServerKeyGenerator.cs +### FILE: C:\Users\saherelm\Documents\Projects\xSaherelmWorkspace\Modules\xAiModels\Providers\Entities\XAiMcpServerKeyGenerator.cs using xDataService.Providers; using xAiModels.Models.Entities; @@ -10452,7 +10515,7 @@ namespace xAiModels.Providers.Entities { } } -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\Modules\xAiModels\Providers\Entities\XAiMcpServerMongoRepository.cs +### FILE: C:\Users\saherelm\Documents\Projects\xSaherelmWorkspace\Modules\xAiModels\Providers\Entities\XAiMcpServerMongoRepository.cs using System; using System.Collections.Generic; @@ -10478,7 +10541,7 @@ namespace xAiModels.Providers.Entities } } -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\Modules\xAiModels\Providers\Entities\XAiMcpServerRepositoryEvents.cs +### FILE: C:\Users\saherelm\Documents\Projects\xSaherelmWorkspace\Modules\xAiModels\Providers\Entities\XAiMcpServerRepositoryEvents.cs using xDataService.Providers; using xAiModels.Models.Entities; @@ -10490,7 +10553,7 @@ namespace xAiModels.Providers.Entities { } } -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\Modules\xAiModels\Providers\Entities\XAiMcpServerRepositoryProvider.cs +### FILE: C:\Users\saherelm\Documents\Projects\xSaherelmWorkspace\Modules\xAiModels\Providers\Entities\XAiMcpServerRepositoryProvider.cs using System; using xPushService.Base; @@ -10514,7 +10577,7 @@ namespace xAiModels.Providers.Entities } } -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\Modules\xAiModels\Providers\Entities\XAiMcpServerSeederBase.cs +### FILE: C:\Users\saherelm\Documents\Projects\xSaherelmWorkspace\Modules\xAiModels\Providers\Entities\XAiMcpServerSeederBase.cs using System; using xDataService.Providers; @@ -10541,7 +10604,7 @@ namespace xAiModels.Providers.Entities } } -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\Modules\xAiModels\Providers\Entities\XAiMessageEFRepository.cs +### FILE: C:\Users\saherelm\Documents\Projects\xSaherelmWorkspace\Modules\xAiModels\Providers\Entities\XAiMessageEFRepository.cs using System; using xDataService.Db; @@ -10571,7 +10634,7 @@ namespace xAiModels.Providers.Entities } } -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\Modules\xAiModels\Providers\Entities\XAiMessageEntityHub.cs +### FILE: C:\Users\saherelm\Documents\Projects\xSaherelmWorkspace\Modules\xAiModels\Providers\Entities\XAiMessageEntityHub.cs using System; using xPushService.Base; @@ -10590,7 +10653,7 @@ namespace xAiModels.Providers.Entities } } -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\Modules\xAiModels\Providers\Entities\XAiMessageInMemoryRepository.cs +### FILE: C:\Users\saherelm\Documents\Projects\xSaherelmWorkspace\Modules\xAiModels\Providers\Entities\XAiMessageInMemoryRepository.cs using System; using xDataService.Providers; @@ -10615,7 +10678,7 @@ namespace xAiModels.Providers.Entities } } -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\Modules\xAiModels\Providers\Entities\XAiMessageKeyGenerator.cs +### FILE: C:\Users\saherelm\Documents\Projects\xSaherelmWorkspace\Modules\xAiModels\Providers\Entities\XAiMessageKeyGenerator.cs using xDataService.Providers; using xAiModels.Models.Entities; @@ -10627,7 +10690,7 @@ namespace xAiModels.Providers.Entities { } } -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\Modules\xAiModels\Providers\Entities\XAiMessageMongoRepository.cs +### FILE: C:\Users\saherelm\Documents\Projects\xSaherelmWorkspace\Modules\xAiModels\Providers\Entities\XAiMessageMongoRepository.cs using System; using xDataService.Providers; @@ -10656,7 +10719,7 @@ namespace xAiModels.Providers.Entities } } -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\Modules\xAiModels\Providers\Entities\XAiMessageRepositoryEvents.cs +### FILE: C:\Users\saherelm\Documents\Projects\xSaherelmWorkspace\Modules\xAiModels\Providers\Entities\XAiMessageRepositoryEvents.cs using xDataService.Providers; using xAiModels.Models.Entities; @@ -10668,7 +10731,7 @@ namespace xAiModels.Providers.Entities { } } -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\Modules\xAiModels\Providers\Entities\XAiMessageRepositoryProvider.cs +### FILE: C:\Users\saherelm\Documents\Projects\xSaherelmWorkspace\Modules\xAiModels\Providers\Entities\XAiMessageRepositoryProvider.cs using System; using xPushService.Base; @@ -10697,7 +10760,7 @@ namespace xAiModels.Providers.Entities } } -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\Modules\xAiModels\Providers\Entities\XAiMessageSeederBase.cs +### FILE: C:\Users\saherelm\Documents\Projects\xSaherelmWorkspace\Modules\xAiModels\Providers\Entities\XAiMessageSeederBase.cs using System; using xDataService.Providers; @@ -10724,7 +10787,7 @@ namespace xAiModels.Providers.Entities } } -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\Modules\xAiModels\Providers\Entities\XAiProjectEFRepository.cs +### FILE: C:\Users\saherelm\Documents\Projects\xSaherelmWorkspace\Modules\xAiModels\Providers\Entities\XAiProjectEFRepository.cs using System; using xDataService.Db; @@ -10754,7 +10817,7 @@ namespace xAiModels.Providers.Entities } } -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\Modules\xAiModels\Providers\Entities\XAiProjectEntityHub.cs +### FILE: C:\Users\saherelm\Documents\Projects\xSaherelmWorkspace\Modules\xAiModels\Providers\Entities\XAiProjectEntityHub.cs using System; using xPushService.Base; @@ -10773,7 +10836,7 @@ namespace xAiModels.Providers.Entities } } -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\Modules\xAiModels\Providers\Entities\XAiProjectInMemoryRepository.cs +### FILE: C:\Users\saherelm\Documents\Projects\xSaherelmWorkspace\Modules\xAiModels\Providers\Entities\XAiProjectInMemoryRepository.cs using System; using xDataService.Providers; @@ -10798,7 +10861,7 @@ namespace xAiModels.Providers.Entities } } -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\Modules\xAiModels\Providers\Entities\XAiProjectKeyGenerator.cs +### FILE: C:\Users\saherelm\Documents\Projects\xSaherelmWorkspace\Modules\xAiModels\Providers\Entities\XAiProjectKeyGenerator.cs using xDataService.Providers; using xAiModels.Models.Entities; @@ -10810,7 +10873,7 @@ namespace xAiModels.Providers.Entities { } } -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\Modules\xAiModels\Providers\Entities\XAiProjectMongoRepository.cs +### FILE: C:\Users\saherelm\Documents\Projects\xSaherelmWorkspace\Modules\xAiModels\Providers\Entities\XAiProjectMongoRepository.cs using System; using xDataService.Providers; @@ -10839,7 +10902,7 @@ namespace xAiModels.Providers.Entities } } -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\Modules\xAiModels\Providers\Entities\XAiProjectRepositoryEvents.cs +### FILE: C:\Users\saherelm\Documents\Projects\xSaherelmWorkspace\Modules\xAiModels\Providers\Entities\XAiProjectRepositoryEvents.cs using xDataService.Providers; using xAiModels.Models.Entities; @@ -10851,7 +10914,7 @@ namespace xAiModels.Providers.Entities { } } -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\Modules\xAiModels\Providers\Entities\XAiProjectRepositoryProvider.cs +### FILE: C:\Users\saherelm\Documents\Projects\xSaherelmWorkspace\Modules\xAiModels\Providers\Entities\XAiProjectRepositoryProvider.cs using System; using xPushService.Base; @@ -10880,7 +10943,7 @@ namespace xAiModels.Providers.Entities } } -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\Modules\xAiModels\Providers\Entities\XAiProjectSeederBase.cs +### FILE: C:\Users\saherelm\Documents\Projects\xSaherelmWorkspace\Modules\xAiModels\Providers\Entities\XAiProjectSeederBase.cs using System; using xDataService.Providers; @@ -10907,7 +10970,7 @@ namespace xAiModels.Providers.Entities } } -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\Modules\xAiModels\Providers\Entities\XAiVectorEFRepository.cs +### FILE: C:\Users\saherelm\Documents\Projects\xSaherelmWorkspace\Modules\xAiModels\Providers\Entities\XAiVectorEFRepository.cs using System; using xDataService.Db; @@ -10937,7 +11000,7 @@ namespace xAiModels.Providers.Entities } } -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\Modules\xAiModels\Providers\Entities\XAiVectorEntityHub.cs +### FILE: C:\Users\saherelm\Documents\Projects\xSaherelmWorkspace\Modules\xAiModels\Providers\Entities\XAiVectorEntityHub.cs using System; using xPushService.Base; @@ -10956,7 +11019,7 @@ namespace xAiModels.Providers.Entities } } -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\Modules\xAiModels\Providers\Entities\XAiVectorInMemoryRepository.cs +### FILE: C:\Users\saherelm\Documents\Projects\xSaherelmWorkspace\Modules\xAiModels\Providers\Entities\XAiVectorInMemoryRepository.cs using System; using xDataService.Providers; @@ -10981,7 +11044,7 @@ namespace xAiModels.Providers.Entities } } -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\Modules\xAiModels\Providers\Entities\XAiVectorKeyGenerator.cs +### FILE: C:\Users\saherelm\Documents\Projects\xSaherelmWorkspace\Modules\xAiModels\Providers\Entities\XAiVectorKeyGenerator.cs using xDataService.Providers; using xAiModels.Models.Entities; @@ -10993,7 +11056,7 @@ namespace xAiModels.Providers.Entities { } } -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\Modules\xAiModels\Providers\Entities\XAiVectorMongoRepository.cs +### FILE: C:\Users\saherelm\Documents\Projects\xSaherelmWorkspace\Modules\xAiModels\Providers\Entities\XAiVectorMongoRepository.cs using System; using xDataService.Providers; @@ -11022,7 +11085,7 @@ namespace xAiModels.Providers.Entities } } -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\Modules\xAiModels\Providers\Entities\XAiVectorRepositoryEvents.cs +### FILE: C:\Users\saherelm\Documents\Projects\xSaherelmWorkspace\Modules\xAiModels\Providers\Entities\XAiVectorRepositoryEvents.cs using xDataService.Providers; using xAiModels.Models.Entities; @@ -11034,7 +11097,7 @@ namespace xAiModels.Providers.Entities { } } -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\Modules\xAiModels\Providers\Entities\XAiVectorRepositoryProvider.cs +### FILE: C:\Users\saherelm\Documents\Projects\xSaherelmWorkspace\Modules\xAiModels\Providers\Entities\XAiVectorRepositoryProvider.cs using System; using xPushService.Base; @@ -11063,7 +11126,7 @@ namespace xAiModels.Providers.Entities } } -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\Modules\xAiModels\Providers\Entities\XAiVectorSeederBase.cs +### FILE: C:\Users\saherelm\Documents\Projects\xSaherelmWorkspace\Modules\xAiModels\Providers\Entities\XAiVectorSeederBase.cs using System; using xDataService.Providers; @@ -11090,7 +11153,7 @@ namespace xAiModels.Providers.Entities } } -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\Modules\xAiModels\Providers\GraphQL\XAiConversationGraphQLTypeHelper.cs +### FILE: C:\Users\saherelm\Documents\Projects\xSaherelmWorkspace\Modules\xAiModels\Providers\GraphQL\XAiConversationGraphQLTypeHelper.cs using System; using xAiModels.Constants; @@ -11114,7 +11177,7 @@ namespace xAiModels.Providers.GraphQL } } -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\Modules\xAiModels\Providers\GraphQL\XAiConversationGraphQuery.cs +### FILE: C:\Users\saherelm\Documents\Projects\xSaherelmWorkspace\Modules\xAiModels\Providers\GraphQL\XAiConversationGraphQuery.cs using System; using GraphQL.Types; @@ -11140,7 +11203,7 @@ namespace xAiModels.Providers.GraphQL } } -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\Modules\xAiModels\Providers\GraphQL\XAiConversationGraphSchema.cs +### FILE: C:\Users\saherelm\Documents\Projects\xSaherelmWorkspace\Modules\xAiModels\Providers\GraphQL\XAiConversationGraphSchema.cs using System; using GraphQL.Types; @@ -11156,7 +11219,7 @@ namespace xAiModels.Providers.GraphQL } } -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\Modules\xAiModels\Providers\GraphQL\XAiConversationGraphType.cs +### FILE: C:\Users\saherelm\Documents\Projects\xSaherelmWorkspace\Modules\xAiModels\Providers\GraphQL\XAiConversationGraphType.cs using System; using xDataService.GraphQL; @@ -11177,7 +11240,7 @@ namespace xAiModels.Providers.GraphQL } } -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\Modules\xAiModels\Providers\GraphQL\XAiMcpServerGraphQLTypeHelper.cs +### FILE: C:\Users\saherelm\Documents\Projects\xSaherelmWorkspace\Modules\xAiModels\Providers\GraphQL\XAiMcpServerGraphQLTypeHelper.cs using System; using xAiModels.Constants; @@ -11201,7 +11264,7 @@ namespace xAiModels.Providers.GraphQL } } -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\Modules\xAiModels\Providers\GraphQL\XAiMcpServerGraphQuery.cs +### FILE: C:\Users\saherelm\Documents\Projects\xSaherelmWorkspace\Modules\xAiModels\Providers\GraphQL\XAiMcpServerGraphQuery.cs using System; using GraphQL.Types; @@ -11227,7 +11290,7 @@ namespace xAiModels.Providers.GraphQL } } -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\Modules\xAiModels\Providers\GraphQL\XAiMcpServerGraphSchema.cs +### FILE: C:\Users\saherelm\Documents\Projects\xSaherelmWorkspace\Modules\xAiModels\Providers\GraphQL\XAiMcpServerGraphSchema.cs using System; using GraphQL.Types; @@ -11243,7 +11306,7 @@ namespace xAiModels.Providers.GraphQL } } -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\Modules\xAiModels\Providers\GraphQL\XAiMcpServerGraphType.cs +### FILE: C:\Users\saherelm\Documents\Projects\xSaherelmWorkspace\Modules\xAiModels\Providers\GraphQL\XAiMcpServerGraphType.cs using System; using xDataService.GraphQL; @@ -11269,7 +11332,7 @@ namespace xAiModels.Providers.GraphQL } } -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\Modules\xAiModels\Providers\GraphQL\XAiMessageGraphQLTypeHelper.cs +### FILE: C:\Users\saherelm\Documents\Projects\xSaherelmWorkspace\Modules\xAiModels\Providers\GraphQL\XAiMessageGraphQLTypeHelper.cs using System; using xAiModels.Constants; @@ -11293,7 +11356,7 @@ namespace xAiModels.Providers.GraphQL } } -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\Modules\xAiModels\Providers\GraphQL\XAiMessageGraphQuery.cs +### FILE: C:\Users\saherelm\Documents\Projects\xSaherelmWorkspace\Modules\xAiModels\Providers\GraphQL\XAiMessageGraphQuery.cs using System; using GraphQL.Types; @@ -11319,7 +11382,7 @@ namespace xAiModels.Providers.GraphQL } } -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\Modules\xAiModels\Providers\GraphQL\XAiMessageGraphSchema.cs +### FILE: C:\Users\saherelm\Documents\Projects\xSaherelmWorkspace\Modules\xAiModels\Providers\GraphQL\XAiMessageGraphSchema.cs using System; using GraphQL.Types; @@ -11335,7 +11398,7 @@ namespace xAiModels.Providers.GraphQL } } -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\Modules\xAiModels\Providers\GraphQL\XAiMessageGraphType.cs +### FILE: C:\Users\saherelm\Documents\Projects\xSaherelmWorkspace\Modules\xAiModels\Providers\GraphQL\XAiMessageGraphType.cs using System; using xDataService.GraphQL; @@ -11358,7 +11421,7 @@ namespace xAiModels.Providers.GraphQL } } -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\Modules\xAiModels\Providers\GraphQL\XAiProjectGraphQLTypeHelper.cs +### FILE: C:\Users\saherelm\Documents\Projects\xSaherelmWorkspace\Modules\xAiModels\Providers\GraphQL\XAiProjectGraphQLTypeHelper.cs using System; using xAiModels.Constants; @@ -11382,7 +11445,7 @@ namespace xAiModels.Providers.GraphQL } } -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\Modules\xAiModels\Providers\GraphQL\XAiProjectGraphQuery.cs +### FILE: C:\Users\saherelm\Documents\Projects\xSaherelmWorkspace\Modules\xAiModels\Providers\GraphQL\XAiProjectGraphQuery.cs using System; using GraphQL.Types; @@ -11408,7 +11471,7 @@ namespace xAiModels.Providers.GraphQL } } -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\Modules\xAiModels\Providers\GraphQL\XAiProjectGraphSchema.cs +### FILE: C:\Users\saherelm\Documents\Projects\xSaherelmWorkspace\Modules\xAiModels\Providers\GraphQL\XAiProjectGraphSchema.cs using System; using GraphQL.Types; @@ -11424,7 +11487,7 @@ namespace xAiModels.Providers.GraphQL } } -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\Modules\xAiModels\Providers\GraphQL\XAiProjectGraphType.cs +### FILE: C:\Users\saherelm\Documents\Projects\xSaherelmWorkspace\Modules\xAiModels\Providers\GraphQL\XAiProjectGraphType.cs using System; using xDataService.GraphQL; @@ -11446,7 +11509,7 @@ namespace xAiModels.Providers.GraphQL } } -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\Modules\xAiModels\Providers\GraphQL\XAiVectorGraphQLTypeHelper.cs +### FILE: C:\Users\saherelm\Documents\Projects\xSaherelmWorkspace\Modules\xAiModels\Providers\GraphQL\XAiVectorGraphQLTypeHelper.cs using System; using xAiModels.Constants; @@ -11470,7 +11533,7 @@ namespace xAiModels.Providers.GraphQL } } -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\Modules\xAiModels\Providers\GraphQL\XAiVectorGraphQuery.cs +### FILE: C:\Users\saherelm\Documents\Projects\xSaherelmWorkspace\Modules\xAiModels\Providers\GraphQL\XAiVectorGraphQuery.cs using System; using GraphQL.Types; @@ -11496,7 +11559,7 @@ namespace xAiModels.Providers.GraphQL } } -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\Modules\xAiModels\Providers\GraphQL\XAiVectorGraphSchema.cs +### FILE: C:\Users\saherelm\Documents\Projects\xSaherelmWorkspace\Modules\xAiModels\Providers\GraphQL\XAiVectorGraphSchema.cs using System; using GraphQL.Types; @@ -11512,7 +11575,7 @@ namespace xAiModels.Providers.GraphQL } } -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\Modules\xAiModels\Providers\GraphQL\XAiVectorGraphType.cs +### FILE: C:\Users\saherelm\Documents\Projects\xSaherelmWorkspace\Modules\xAiModels\Providers\GraphQL\XAiVectorGraphType.cs using System; using xDataService.GraphQL; @@ -11531,7 +11594,7 @@ namespace xAiModels.Providers.GraphQL } } -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\Modules\xAiModels\Providers\Hubs\XAiDataProviderHub.cs +### FILE: C:\Users\saherelm\Documents\Projects\xSaherelmWorkspace\Modules\xAiModels\Providers\Hubs\XAiDataProviderHub.cs using System.Threading; using xPushService.Base; diff --git a/Documents/GeneratedContext/xDashboard-xAiService-20261104_113312.txt b/Documents/GeneratedContext/xDashboard-xAiService-20261104_113312.txt deleted file mode 100644 index 324b7a6..0000000 --- a/Documents/GeneratedContext/xDashboard-xAiService-20261104_113312.txt +++ /dev/null @@ -1,84 +0,0 @@ - -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\Modules\xAiService\Constants\ConfigurationNodeNames.cs - -namespace xAiService.Constants -{ - public partial struct ConfigurationNodeNames - { - public const string AI_SERVICE_NODE = "AIServiceConfiguration"; - } -} - -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\Modules\xAiService\Constants\XAiServiceConstants.cs - -namespace xAiService.Constants -{ - public struct XAiServiceConstants - { - // - // Service Extensions Log Tag ... - public const string XAiServiceDILogTag = "XAiService"; - - // - // File Provider Identifiers ... - public const string XAiProjectFilesIdentifier = "AiPrjF"; - public const string XAiMessageFilesIdentifier = "AiMsgF"; - public const string XMetaDataFileIdsIdentifier = "FileIds"; - public const string XAiConversationFilesIdentifier = "AiCnvrF"; - } -} - -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\Modules\xAiService\DI\XDIHelperExtension.cs - -namespace xAiService.DI -{ - public static partial class XDIHelperExtension - { } -} - -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\Modules\xAiService\Extensions\XAiServiceExtensions.cs - -using xCommons.Extensions; -using xExceptions.Constants; -using xIdentityModels.Models; - -namespace xAiService.Extensions -{ - public static class XAiServiceExtensions - { - /// - /// Validate User Info ... - /// - /// - /// - public static bool IsValid(this XUserClaimsInfoDto source) - { - // - var result = - !source.IsNullOrDefault() && - !source.UserId.IsNullOrEmpty() && - !source.AccessToken.IsNullOrEmpty(); - - // - return result; - } - - /// - /// Validate User Info ... - /// - /// - /// - public static void Validate( - this XUserClaimsInfoDto source, - XException invalidException = XException.InvalidArgs - ) - { - // - var isValid = source.IsValid(); - if (!isValid) - { - invalidException.Throw(); - } - } - } -} diff --git a/Documents/GeneratedContext/xDashboard-xAiService-20261105_133500.txt b/Documents/GeneratedContext/xDashboard-xAiService-20261105_133500.txt new file mode 100644 index 0000000..a2b455c --- /dev/null +++ b/Documents/GeneratedContext/xDashboard-xAiService-20261105_133500.txt @@ -0,0 +1,1036 @@ + +### FILE: C:\Users\saherelm\Documents\Projects\xSaherelmWorkspace\Modules\xAiService\Constants\ConfigurationNodeNames.cs + +namespace xAiService.Constants +{ + public partial struct ConfigurationNodeNames + { + public const string AI_SERVICE_NODE = "AIServiceConfiguration"; + } +} + +### FILE: C:\Users\saherelm\Documents\Projects\xSaherelmWorkspace\Modules\xAiService\Constants\XAiServiceConstants.cs + +namespace xAiService.Constants +{ + public struct XAiServiceConstants + { + // + // Service Extensions Log Tag ... + public const string XAiServiceDILogTag = "XAiService"; + + // + // File Provider Identifiers ... + public const string XAiProjectFilesIdentifier = "AiPrjF"; + public const string XAiMessageFilesIdentifier = "AiMsgF"; + public const string XMetaDataFileIdsIdentifier = "FileIds"; + public const string XAiConversationFilesIdentifier = "AiCnvrF"; + } +} + +### FILE: C:\Users\saherelm\Documents\Projects\xSaherelmWorkspace\Modules\xAiService\Controllers\XAiMcpControllerBase.cs + +using System.Threading; +using xCommons.Providers; +using Newtonsoft.Json.Linq; +using xAiService.Interfaces; +using System.Threading.Tasks; +using xCommons.Configurations; +using Microsoft.AspNetCore.Mvc; +using Microsoft.AspNetCore.Http; +using xIdentityService.Interfaces; +using Microsoft.Extensions.Logging; +using xIdentityService.Controllers; +using Microsoft.AspNetCore.Authorization; + +namespace xAiService.Controllers +{ + [Route("mcp")] + [AllowAnonymous] + public abstract class XAiMcpControllerBase : XBaseIdentityApiV1Controller + { + private readonly IXAiMcpHandler mcpHandler; + + protected XAiMcpControllerBase( + IXAiMcpHandler mcpHandler, + XAppConfiguration appConfiguration, + IXIdentityProvider identityProvider, + ILogger logger, + XValidationProvider validationProvider + ) : base(logger, appConfiguration, identityProvider, validationProvider) + { + this.mcpHandler = mcpHandler; + } + + /// + /// Handle MCP ... + /// + /// + /// + /// + [HttpPost] + public async Task HandleMcp( + [FromBody] JObject request, + CancellationToken cancellationToken = default + ) + { + // + var response = await mcpHandler.ProcessAsync( + request, + cancellationToken + ); + + // + return Ok(response); + } + + /// + /// Handle SSE EndPoint ... + /// + /// + /// + [HttpGet("sse")] + public async Task SseEndpoint( + CancellationToken cancellationToken = default + ) + { + // + Response.Headers.Add("Content-Type", "text/event-stream"); + Response.Headers.Add("Cache-Control", "no-cache"); + + // + await Response + .WriteAsync( + "event: endpoint\ndata: /mcp\n\n", + cancellationToken + ); + + // + await Response.Body.FlushAsync(cancellationToken); + + // + while (!cancellationToken.IsCancellationRequested) + { + await Task.Delay(1000, cancellationToken); + } + } + } +} + +### FILE: C:\Users\saherelm\Documents\Projects\xSaherelmWorkspace\Modules\xAiService\DI\XDIHelperExtension.cs + +namespace xAiService.DI +{ + public static partial class XDIHelperExtension + { } +} + +### FILE: C:\Users\saherelm\Documents\Projects\xSaherelmWorkspace\Modules\xAiService\Extensions\DIExtensions.cs + +using System; +using System.Linq; +using System.Reflection; +using xAiService.Services; +using xAiService.Interfaces; +using Microsoft.Extensions.DependencyInjection; + +namespace xAiService.Extensions +{ + public static class DIExtensions + { + /// + /// Register XAiMcpHandler Service ... + /// + /// + public static void AddXAiMcpHandler( + this IServiceCollection source + ) + { + // + // Register MCP Tool Scanner ... + source.AddSingleton(sp => + { + // + // Scan All Exists Assemblies ... + var asms = AppDomain.CurrentDomain + .GetAssemblies() + .Where(a => !a.IsDynamic && + a.GetName().Name != null && + a.GetName().Name!.StartsWith("xAi", StringComparison.OrdinalIgnoreCase)) + .Append(Assembly.GetEntryAssembly()!) + .ToArray(); + + // + return new XAiMcpToolScanner(asms); + }); + + // + // 2) Register MCP Handler ... + source.AddScoped(); + } + } +} + +### FILE: C:\Users\saherelm\Documents\Projects\xSaherelmWorkspace\Modules\xAiService\Extensions\XAiServiceExtensions.cs + +using xCommons.Extensions; +using xExceptions.Constants; +using xIdentityModels.Models; + +namespace xAiService.Extensions +{ + public static class XAiServiceExtensions + { + /// + /// Validate User Info ... + /// + /// + /// + public static bool IsValid(this XUserClaimsInfoDto source) + { + // + var result = + !source.IsNullOrDefault() && + !source.UserId.IsNullOrEmpty() && + !source.AccessToken.IsNullOrEmpty(); + + // + return result; + } + + /// + /// Validate User Info ... + /// + /// + /// + public static void Validate( + this XUserClaimsInfoDto source, + XException invalidException = XException.InvalidArgs + ) + { + // + var isValid = source.IsValid(); + if (!isValid) + { + invalidException.Throw(); + } + } + } +} + +### FILE: C:\Users\saherelm\Documents\Projects\xSaherelmWorkspace\Modules\xAiService\Helpers\XAiMcpArgumentHelper.cs + +using System; +using Newtonsoft.Json.Linq; + +namespace xAiService.Helpers +{ + public static class XAiMcpArgumentHelper + { + /// + /// Bind Parameters ... + /// + /// + /// + /// + public static object Bind( + JToken token, + Type targetType + ) + { + // + var underlying = Nullable.GetUnderlyingType(targetType) ?? targetType; + + // + // Null Handling ... + if (token == null || token.Type == JTokenType.Null || token.Type == JTokenType.Undefined) + { + // + if (!targetType.IsValueType || Nullable.GetUnderlyingType(targetType) != null) + { + return null; + } + + // + return Activator.CreateInstance(targetType); + } + + // + // Primitive Types ... + + // + if (underlying == typeof(string)) + { + return token.ToString(); + } + + // + if (underlying == typeof(int)) + { + return token.Value(); + } + + // + if (underlying == typeof(long)) + { + return token.Value(); + } + + // + if (underlying == typeof(short)) + { + return token.Value(); + } + + // + if (underlying == typeof(float)) + { + return token.Value(); + } + + // + if (underlying == typeof(double)) + { + return token.Value(); + } + + // + if (underlying == typeof(decimal)) + { + return token.Value(); + } + + // + if (underlying == typeof(bool)) + { + return token.Value(); + } + + // + if (underlying == typeof(Guid)) + { + return token.Value(); + } + + // + if (underlying == typeof(DateTime)) + { + return token.Value(); + } + + // + // Enum ... + if (underlying.IsEnum) + { + return Enum.Parse(underlying, token.ToString(), ignoreCase: true); + } + + // + // Arrays ... + if (underlying.IsArray && token is JArray jarr) + { + // + var elementType = underlying.GetElementType(); + var arr = Array.CreateInstance(elementType, jarr.Count); + for (var i = 0; i < jarr.Count; i++) + { + arr.SetValue(Bind(jarr[i], elementType), i); + } + + // + return arr; + } + + // + // Fallback: JSON Deserialize + return token.ToObject(underlying); + } + } +} + +### FILE: C:\Users\saherelm\Documents\Projects\xSaherelmWorkspace\Modules\xAiService\Helpers\XAiMcpResultExtractionHelper.cs + +using System; +using Newtonsoft.Json; +using Newtonsoft.Json.Linq; +using System.Threading.Tasks; + +namespace xAiService.Helpers +{ + public static class XAiMcpResultExtractionHelper + { + /// + /// Extract Specified Object Result of Method Invoking ... + /// + /// + /// + /// + public static async Task ExtractAsync( + object raw, + Type returnType + ) + { + // + // Task / Task + if (raw is Task task) + { + // + await task.ConfigureAwait(false); + if (returnType.IsGenericType && + returnType.GetGenericTypeDefinition() == typeof(Task<>)) + { + // + var value = returnType.GetProperty("Result").GetValue(task); + return Format(value); + } + + // + return string.Empty; + } + + // + // ValueTask (non-generic) + if (returnType == typeof(ValueTask)) + { + // + await ((ValueTask)raw).ConfigureAwait(false); + return string.Empty; + } + + // + // ValueTask ... + if (returnType.IsGenericType && + returnType.GetGenericTypeDefinition() == typeof(ValueTask<>)) + { + // + var asTask = (Task)returnType.GetMethod("AsTask").Invoke(raw, null); + await asTask.ConfigureAwait(false); + var value = asTask.GetType().GetProperty("Result").GetValue(asTask); + + // + return Format(value); + } + + // + // void / T Syncron ... + return Format(raw); + } + + // + #region Private ... + /// + /// Format Extracted Response ... + /// /// + /// + /// + private static string Format(object value) + { + // + if (value == null) + { + return string.Empty; + } + + // + if (value is string s) + { + return s; + } + + // + if (value is JToken jt) + { + return jt.ToString(Formatting.None); + } + + // + if (value.GetType().IsPrimitive || value is decimal) + { + return value.ToString(); + } + + // + return JToken.FromObject(value).ToString(Formatting.None); + } + #endregion + } +} + +### FILE: C:\Users\saherelm\Documents\Projects\xSaherelmWorkspace\Modules\xAiService\Interfaces\IXAiMcpHandler.cs + +using System.Threading; +using Newtonsoft.Json.Linq; +using System.Threading.Tasks; + +namespace xAiService.Interfaces +{ + public interface IXAiMcpHandler + { + /// + /// Process Specified JSON-RPC Request ... + /// + /// + /// + /// + Task ProcessAsync( + JObject request, + CancellationToken cancellationToken = default + ); + } +} + +### FILE: C:\Users\saherelm\Documents\Projects\xSaherelmWorkspace\Modules\xAiService\Services\XAiMcpHandler.cs + +using System; +using System.Threading; +using xAiModels.Models; +using Newtonsoft.Json.Linq; +using xAiService.Interfaces; +using System.Threading.Tasks; +using System.Collections.Generic; + +namespace xAiService.Services +{ + public class XAiMcpHandler : IXAiMcpHandler + { + // + private readonly XAiMcpToolScanner scanner; + private readonly IServiceProvider serviceProvider; + private readonly Dictionary tools = new(); + + public XAiMcpHandler( + XAiMcpToolScanner scanner, + IServiceProvider serviceProvider + ) + { + // + this.scanner = scanner; + this.serviceProvider = serviceProvider; + + // + RegisterTools(); + } + + /// + /// Process Specified JSON-RPC Request ... + /// + /// + /// + /// + public async Task ProcessAsync( + JObject request, + CancellationToken cancellationToken = default + ) + { + // + var method = request["method"]?.ToString(); + var id = request["id"]; + + // + return method switch + { + // + "initialize" => HandleInitialize(id), + "tools/list" => HandleToolsList(id), + "tools/call" => await HandleToolCallAsync(request, id, cancellationToken), + "ping" => HandlePing(id), + _ => CreateError(id, -32601, $"Method not found: {method}") + }; + } + + // + #region Private ... + private JObject HandleInitialize(JToken id) + { + return CreateResult(id, new JObject + { + ["protocolVersion"] = "2024-11-05", + ["capabilities"] = new JObject + { + ["tools"] = new JObject { ["listChanged"] = true } + }, + ["serverInfo"] = new JObject + { + ["name"] = "xAiMcpServer", + ["version"] = "1.0.0" + } + }); + } + + private JObject HandleToolsList(JToken id) + { + var jsonTools = new JArray(); + foreach (var tool in tools.Values) + { + jsonTools.Add(new JObject + { + ["name"] = tool.Name, + ["description"] = tool.Description, + ["inputSchema"] = tool.InputSchema + }); + } + + // + return CreateResult(id, new JObject { ["tools"] = jsonTools }); + } + + private async Task HandleToolCallAsync( + JObject request, + JToken id, + CancellationToken ct + ) + { + // + var toolName = request["params"]?["name"]?.ToString(); + var args = request["params"]?["arguments"] as JObject; + + // + if (!tools.ContainsKey(toolName)) + { + return CreateError(id, -32602, $"Tool not found: {toolName}"); + } + + // + var result = await tools[toolName].Execute(args, ct); + return CreateResult(id, new JObject + { + ["content"] = new JArray + { + new JObject + { + ["type"] = "text", + ["text"] = result + } + } + }); + } + + private JObject CreateResult( + JToken id, + JObject result + ) + { + // + return new JObject + { + ["jsonrpc"] = "2.0", + ["id"] = id, + ["result"] = result + }; + } + + private JObject CreateError( + JToken id, + int code, + string message + ) + { + // + return new JObject + { + ["jsonrpc"] = "2.0", + ["id"] = id, + ["error"] = new JObject + { + ["code"] = code, + ["message"] = message + } + }; + } + + private void RegisterTools() + { + // + // 1) Manually Register Tools ... + RegisterManualTools(); + + // + // 2) Register Scanned Tools uding Reflection ... + foreach (var blueprint in scanner.Blueprints) + { + // + // Prevent Double Registration if Name Exists ... + if (tools.ContainsKey(blueprint.Name)) + { + continue; + } + + // + tools[blueprint.Name] = blueprint.ToDescriptor(serviceProvider); + } + } + + private void RegisterManualTools() + { + // Manually Tools Registration ... + // tools["search_knowledge"] = new XAiMcpToolDescriptor + // { + // Name = "search_knowledge", + // Description = "Search in knowledge base", + // InputSchema = new JObject + // { + // ["type"] = "object", + // ["properties"] = new JObject + // { + // ["query"] = new JObject { ["type"] = "string" } + // }, + // ["required"] = new JArray("query") + // }, + // Execute = async (args, ct) => + // { + // var query = args?["query"]?.ToString() ?? ""; + // return $"Results for: {query}"; + // } + // }; + } + + private JObject HandlePing(JToken id) + { + return CreateResult(id, new JObject()); + } + #endregion + } +} + +### FILE: C:\Users\saherelm\Documents\Projects\xSaherelmWorkspace\Modules\xAiService\Services\XAiMcpToolBlueprint.cs + +using System; +using xAiModels.Models; +using System.Threading; +using System.Reflection; +using xAiService.Helpers; +using Newtonsoft.Json.Linq; +using System.Threading.Tasks; + +namespace xAiService.Services +{ + public class XAiMcpToolBlueprint + { + public string Name { get; set; } + public string Description { get; set; } + public JObject InputSchema { get; set; } + + internal MethodInfo Method { get; set; } + internal Type DeclaringType { get; set; } + + /// + /// Create an Specific Descriptor which can Execute on Current IServiceProvider ... + /// + /// + /// + public XAiMcpToolDescriptor ToDescriptor(IServiceProvider serviceProvider) + { + // + var result = new XAiMcpToolDescriptor + { + Name = Name, + Description = Description, + InputSchema = InputSchema, + Execute = BuildExecute(serviceProvider) + }; + + // + return result; + } + + /// + /// Build Tools Execution for MCP Method ... + /// + /// + /// + private Func> BuildExecute( + IServiceProvider serviceProvider + ) + { + // + var method = Method; + var declaringType = DeclaringType; + return async (args, ct) => + { + // + try + { + // + // 1. Make/Retrieve Instance ... + var instance = method.IsStatic + ? null + : (serviceProvider.GetService(declaringType) + ?? Activator.CreateInstance(declaringType)); + + // + // 2. Binding Method Arguments ... + var parameters = method.GetParameters(); + var values = new object[parameters.Length]; + for (var i = 0; i < parameters.Length; i++) + { + // + var p = parameters[i]; + + // + // Handle CancellationToken Token ... + if (p.ParameterType == typeof(CancellationToken)) + { + values[i] = ct; + continue; + } + + // + // Retrieve Param Attribute ... + var attr = p.GetCustomAttribute(); + var jsonName = attr?.Name ?? p.Name; + values[i] = XAiMcpArgumentHelper.Bind(args?[jsonName], p.ParameterType); + } + + // + // 3. Invoke and Await ... + object raw; + try + { + raw = method.Invoke(instance, values); + } + catch (TargetInvocationException tie) when (tie.InnerException != null) + { + throw tie.InnerException; + } + + // + // 4. Extract Invoking Result ... + return await XAiMcpResultExtractionHelper.ExtractAsync(raw, method.ReturnType); + } + catch (Exception ex) + { + return $"Error: {ex.Message}"; + } + }; + } + } +} + +### FILE: C:\Users\saherelm\Documents\Projects\xSaherelmWorkspace\Modules\xAiService\Services\XAiMcpToolScanner.cs + +using System; +using System.Linq; +using System.Threading; +using System.Reflection; +using Newtonsoft.Json.Linq; +using xAiModels.Attributes; +using System.ComponentModel; +using System.Collections.Generic; + +namespace xAiService.Services +{ + public class XAiMcpToolScanner + { + private readonly Assembly[] assemblies; + private readonly Lazy> blueprints; + + public XAiMcpToolScanner(IEnumerable assemblies) + { + // + this.assemblies = assemblies? + .Where(a => a != null && !a.IsDynamic) + .Distinct() + .ToArray() ?? []; + + // + blueprints = new Lazy>( + Scan, + LazyThreadSafetyMode.ExecutionAndPublication + ); + } + + public IReadOnlyList Blueprints => blueprints.Value; + + // + #region Private ... + private IReadOnlyList Scan() + { + // + var result = new List(); + var seenNames = new HashSet(StringComparer.Ordinal); + foreach (var asm in assemblies) + { + // + foreach (var type in SafeGetTypes(asm)) + { + // + if (type.GetCustomAttribute() == null) { + continue; + } + + // + foreach (var method in type.GetMethods( + BindingFlags.Public | + BindingFlags.Instance | + BindingFlags.Static)) + { + // + var attr = method.GetCustomAttribute(); + if (attr == null) + { + continue; + } + + // + var name = string.IsNullOrWhiteSpace(attr.Name) + ? method.Name + : attr.Name.Trim(); + + if (!seenNames.Add(name)) + { + // + throw new InvalidOperationException( + $"Duplicate MCP tool name '{name}' detected in {type.FullName}.{method.Name}."); + } + + // + var description = attr.Description + ?? method.GetCustomAttribute()?.Description + ?? string.Empty; + + // + result.Add(new XAiMcpToolBlueprint + { + Name = name, + Method = method, + DeclaringType = type, + Description = description, + InputSchema = BuildInputSchema(method) + }); + } + } + } + + return result; + } + + private static JObject BuildInputSchema(MethodInfo method) + { + // + var properties = new JObject(); + var required = new JArray(); + + // + foreach (var p in method.GetParameters()) + { + // + // CancellationToken doesnt exists in Schema ... + if (p.ParameterType == typeof(CancellationToken)) + { + continue; + } + + // + var attr = p.GetCustomAttribute(); + var jsonName = attr?.Name ?? p.Name; + var description = attr?.Description + ?? p.GetCustomAttribute()?.Description + ?? string.Empty; + + // + var propSchema = new JObject + { + ["type"] = MapJsonType(p.ParameterType) + }; + + // + if (!string.IsNullOrWhiteSpace(description)) + { + propSchema["description"] = description; + } + + // + // Define Items Array ... + var underlying = Nullable.GetUnderlyingType(p.ParameterType) ?? p.ParameterType; + if (underlying.IsArray) + { + // + propSchema["items"] = new JObject + { + ["type"] = MapJsonType(underlying.GetElementType()) + }; + } + + // + properties[jsonName] = propSchema; + + // Check is Required ... + var isRequired = attr?.Required ?? true; + if (isRequired) + { + required.Add(jsonName); + } + } + + // + var result = new JObject + { + ["type"] = "object", + ["required"] = required, + ["properties"] = properties, + }; + + // + return result; + } + + private static string MapJsonType(Type type) + { + // + var t = Nullable.GetUnderlyingType(type) ?? type; + + // + if (t == typeof(string) || t == typeof(char) || t == typeof(Guid) || t == typeof(DateTime)) + { + return "string"; + } + + // + if (t == typeof(int) || t == typeof(long) || t == typeof(short) || t == typeof(byte)) + { + return "integer"; + } + + // + if (t == typeof(float) || t == typeof(double) || t == typeof(decimal)) + { + return "number"; + } + + // + if (t == typeof(bool)) + { + return "boolean"; + } + + // + if (t.IsArray || typeof(System.Collections.IEnumerable).IsAssignableFrom(t)) + { + return "array"; + } + + // + if (t.IsEnum) + { + return "string"; + } + + // + return "object"; + } + + private static IEnumerable SafeGetTypes(Assembly asm) + { + // + try + { + return asm.GetTypes(); + } + catch (ReflectionTypeLoadException ex) + { + return ex.Types.Where(t => t != null)!; + } + } + #endregion + } +} diff --git a/Documents/OpenApi/HoppScotch/xAiMcpServer.json b/Documents/OpenApi/HoppScotch/xAiMcpServer.json new file mode 100644 index 0000000..e862c98 --- /dev/null +++ b/Documents/OpenApi/HoppScotch/xAiMcpServer.json @@ -0,0 +1,86 @@ +{ + "v": 12, + "name": "xAiMcpServer", + "folders": [], + "requests": [ + { + "v": "17", + "name": "Initialize", + "method": "POST", + "endpoint": "<>", + "params": [], + "headers": [], + "preRequestScript": "", + "testScript": "", + "auth": { + "authType": "inherit", + "authActive": true + }, + "body": { + "contentType": "application/json", + "body": "{\n \"jsonrpc\": \"2.0\",\n \"id\": 1,\n \"method\": \"initialize\",\n \"params\": {\n \"protocolVersion\": \"2025-06-18\",\n \"capabilities\": {},\n \"clientInfo\": {\n \"name\": \"postman-test-client\",\n \"version\": \"1.0.0\"\n }\n }\n}" + }, + "requestVariables": [], + "responses": {}, + "description": null + }, + { + "v": "17", + "name": "Retrieve Tools List", + "method": "POST", + "endpoint": "<>", + "params": [], + "headers": [], + "preRequestScript": "", + "testScript": "", + "auth": { + "authType": "inherit", + "authActive": true + }, + "body": { + "contentType": "application/json", + "body": "{\n \"jsonrpc\": \"2.0\",\n \"id\": 2,\n \"method\": \"tools/list\",\n \"params\": {}\n}" + }, + "requestVariables": [], + "responses": {}, + "description": null + }, + { + "v": "17", + "name": "Tool Calling", + "method": "POST", + "endpoint": "<>", + "params": [], + "headers": [], + "preRequestScript": "", + "testScript": "", + "auth": { + "authType": "inherit", + "authActive": true + }, + "body": { + "contentType": "application/json", + "body": "{\n\t\"jsonrpc\": \"2.0\",\n\t\"id\": 2,\n\t\"method\": \"tools/call\",\n\t\"params\": {\n\t\t\"name\": \"Echo\",\n\t\t\"arguments\": { \"message\": \"Hadi Khazaee Asl\" }\n\t}\n}\n" + }, + "requestVariables": [], + "responses": {}, + "description": null + } + ], + "headers": [], + "auth": { + "authType": "none", + "authActive": true + }, + "variables": [ + { + "key": "xBaseUrl", + "currentValue": "", + "initialValue": "https://localhost:7001/mcp", + "secret": false + } + ], + "description": "", + "preRequestScript": "", + "testScript": "" +} \ No newline at end of file diff --git a/Documents/Resources/Json/Requests.md b/Documents/Resources/Json/Requests.md index 1f5d5db..4609633 100644 --- a/Documents/Resources/Json/Requests.md +++ b/Documents/Resources/Json/Requests.md @@ -187,3 +187,49 @@ Response: } ] ``` + +## MCP Server + +### Add + +Request: + +```json +{ + "scope": 1, + "headers": "", + "enabled": true, + "timeoutSeconds": 30, + "name": "XAiMcpServer", + "environmentVariables": "", + "description": "a Simple MCP Server ...", + "endpoint": "https://localhost:7001/mcp", +} +``` + +Response: + +```json +{ + "ownerId": "b5713f9f-34f4-49b2-9680-b71e2b2de969", + "owner": { + "avatar": null, + "userId": "b5713f9f-34f4-49b2-9680-b71e2b2de969", + "username": "admin", + "lastname": "Khazaee Asl", + "firstname": "Hadi" + }, + "scope": 1, + "name": "XAiMcpServer", + "description": "a Simple MCP Server ...", + "enabled": true, + "environmentVariables": "", + "endpoint": "https://localhost:7001/mcp", + "headers": "", + "timeoutSeconds": 30, + "createdOn": "2026-11-05T09:30:12.3783202Z", + "updatedAt": "0001-01-01T00:00:00", + "id": "fc583f76-ae11-4f63-8d4c-72927345e4e4", + "deleted": false +} +``` diff --git a/Documents/Resources/Prompts/Create Html Report.txt b/Documents/Resources/Prompts/Create Html Report.txt new file mode 100644 index 0000000..d0cb6bc --- /dev/null +++ b/Documents/Resources/Prompts/Create Html Report.txt @@ -0,0 +1 @@ +بر اساس غالبی که در HTML_REPORT_TEMPLATE.txt برات ارسال کردم یک فایل اچ تی ام ال تولید کن که موارد زیر در اون وجود داشته باشه: diff --git a/Modules/xAiModels b/Modules/xAiModels index 25534f0..2d44ec8 160000 --- a/Modules/xAiModels +++ b/Modules/xAiModels @@ -1 +1 @@ -Subproject commit 25534f0273177acb73ad85523a1368a7efbcad42 +Subproject commit 2d44ec87445ff5a6c4cb7353716878ca95f7d496 diff --git a/Modules/xAiService b/Modules/xAiService index 2b99958..e9a5e24 160000 --- a/Modules/xAiService +++ b/Modules/xAiService @@ -1 +1 @@ -Subproject commit 2b99958f4c671eb6dee9a1f1955cda79ef4f1e16 +Subproject commit e9a5e24943b10f4cae92c7088930d70a75efd377 diff --git a/Modules/xCommons b/Modules/xCommons index 6a55b4e..9c426f5 160000 --- a/Modules/xCommons +++ b/Modules/xCommons @@ -1 +1 @@ -Subproject commit 6a55b4e814b76e21f91692ae3479e359a34049f2 +Subproject commit 9c426f52ab4893730a64fad094863722bd39fad5 diff --git a/xAiApi b/xAiApi index c7efdd5..97acf0a 160000 --- a/xAiApi +++ b/xAiApi @@ -1 +1 @@ -Subproject commit c7efdd5525a8af7627f73cdc034c93b7308a3d48 +Subproject commit 97acf0a123624c60f9fd90f41aa4a8ac757c22f6 diff --git a/xAiMcpServer b/xAiMcpServer index 37cba11..c686750 160000 --- a/xAiMcpServer +++ b/xAiMcpServer @@ -1 +1 @@ -Subproject commit 37cba11e5d09252f62506aa0e9fdf994180d7acf +Subproject commit c686750e2aaa9c84f5079e7709dd8e92310b2aa7 diff --git a/xApi b/xApi index 32ffdd3..30a54fa 160000 --- a/xApi +++ b/xApi @@ -1 +1 @@ -Subproject commit 32ffdd3e5e78e25891fd5daaba4d8e15b3186ada +Subproject commit 30a54fac8b5214f5f15c3c92be8025eb0ac6ba34