From 708e2f8a4f6dd1636d8f6862b867219d134b3a93 Mon Sep 17 00:00:00 2001 From: Hadi Khazaee Asl Date: Sun, 8 Nov 2026 22:56:10 +0330 Subject: [PATCH] add using XLoggingService ... --- ... and Handle Logging Requests 14050817.html | 1003 + .../xDashboard-xAiApi-20261108_143748.txt | 39230 ---------------- .../xDashboard-xAiApi-20261108_223839.txt | 32433 +++++++++++++ ...ashboard-xAiMcpServer-20261108_223851.txt} | 49 +- ... xDashboard-xAiModels-20261108_223851.txt} | 396 +- ...xDashboard-xAiService-20261108_223852.txt} | 38 +- ...hboard-xLoggingService-20261108_223911.txt | 906 + Modules/xLoggingService | 2 +- xAiApi | 2 +- xAiMcpServer | 2 +- xApi | 2 +- xIds | 2 +- 12 files changed, 34593 insertions(+), 39472 deletions(-) create mode 100644 Documents/Docs/Developer/Adding OpenTelemetry, Sentry and Handle Logging Requests 14050817.html delete mode 100644 Documents/GeneratedContext/xDashboard-xAiApi-20261108_143748.txt create mode 100644 Documents/GeneratedContext/xDashboard-xAiApi-20261108_223839.txt rename Documents/GeneratedContext/{xDashboard-xAiMcpServer-20261108_143749.txt => xDashboard-xAiMcpServer-20261108_223851.txt} (96%) rename Documents/GeneratedContext/{xDashboard-xAiModels-20261108_143749.txt => xDashboard-xAiModels-20261108_223851.txt} (93%) rename Documents/GeneratedContext/{xDashboard-xAiService-20261108_143750.txt => xDashboard-xAiService-20261108_223852.txt} (95%) create mode 100644 Documents/GeneratedContext/xDashboard-xLoggingService-20261108_223911.txt diff --git a/Documents/Docs/Developer/Adding OpenTelemetry, Sentry and Handle Logging Requests 14050817.html b/Documents/Docs/Developer/Adding OpenTelemetry, Sentry and Handle Logging Requests 14050817.html new file mode 100644 index 0000000..6612547 --- /dev/null +++ b/Documents/Docs/Developer/Adding OpenTelemetry, Sentry and Handle Logging Requests 14050817.html @@ -0,0 +1,1003 @@ + + + + + +گزارش فنی: ارتقای xLoggingService با OpenTelemetry، میدل‌ور و Sentry + + + + +
+ +
+
+
+ +
+
+
شماره مستند: XLOG-OBS-1405-001
+
نسخه: ۱.۰
+
تاریخ تهیه: آبان ۱۴۰۵
+
طبقه‌بندی: فنی
+
+
+ +
+ TECHNICAL REPORT +

ارتقای xLoggingService با OpenTelemetry، میدل‌ور و Sentry

+

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

+
+
+ +
+ +
+ خلاصه مدیریتی،
+ این مستند به‌عنوان راهنمای فنی برای ارتقای ماژول xLoggingService تهیه شده است. هدف، افزودن سه قابلیت کلیدی به این ماژول است: (۱) یکپارچه‌سازی با OpenTelemetry برای رهگیری توزیع‌شده (Distributed Tracing)، (۲) ایجاد یک میدل‌ور (Middleware) برای لاگ کردن خودکار درخواست‌ها و خطاها با استفاده از سرویس لاگر موجود، و (۳) پیاده‌سازی گام‌به‌گام Sentry برای ثبت و رهگیری خطاها در سطح پروژه. هر بخش شامل توضیحات فنی، نمونه کد و نکات پیاده‌سازی است. +
+ + +
+
+
۱
+
+

یکپارچه‌سازی OpenTelemetry با xLoggingService

+
OpenTelemetry Integration for Distributed Tracing
+
+
+
+

+ OpenTelemetry یک چارچوب متن‌باز و استاندارد صنعتی برای جمع‌آوری داده‌های تلمتری (Logs، Metrics و Traces) است. با افزودن OpenTelemetry به xLoggingService، می‌توان لاگ‌ها را به‌صورت خودکار با TraceId و SpanId غنی‌سازی کرد و آن‌ها را در کنار سایر سیگنال‌های نظارتی (مانند Jaeger یا Zipkin) مشاهده نمود. این کار باعث می‌شود که بتوان یک درخواست را در سراسر سرویس‌های مختلف ردیابی کرد. +

+ +
+ 💡 نکته کلیدی: در SDK دات‌نت، با فراخوانی WithLogging، به‌طور خودکار OpenTelemetryLoggerProvider ثبت می‌شود و لاگ‌های ILogger با ActivityContext (شامل TraceId و SpanId) غنی می‌شوند. همبستگی لاگ‌ها با Traceها به‌صورت خودکار انجام می‌شود و نیاز به اقدام اضافی نیست. [reference:0][reference:1] +
+ +

گام‌های پیاده‌سازی

+ +

گام ۱: نصب پکیج‌های موردنیاز

+
dotnet add package OpenTelemetry.Extensions.Hosting
+dotnet add package OpenTelemetry.Exporter.OpenTelemetryProtocol
+dotnet add package OpenTelemetry.Instrumentation.AspNetCore
+ +

گام ۲: پیکربندی در Program.cs

+

در فایل Program.cs، سرویس OpenTelemetry را به‌صورت زیر پیکربندی کنید. توجه داشته باشید که WithLogging برای یکپارچه‌سازی لاگ‌ها و WithTracing برای رهگیری توزیع‌شده استفاده می‌شود.

+ +
var builder = WebApplication.CreateBuilder(args);
+
+// پاک کردن ارائه‌دهندگان پیش‌فرض لاگ (اختیاری)
+builder.Logging.ClearProviders();
+
+builder.Services.AddOpenTelemetry()
+    .ConfigureResource(resource => resource
+        .AddService("xLoggingService"))
+    .WithLogging(logging => logging
+        .AddOtlpExporter())   // ارسال لاگ‌ها به OTLP
+    .WithTracing(tracing => tracing
+        .AddAspNetCoreInstrumentation()
+        .AddHttpClientInstrumentation()
+        .AddOtlpExporter());  // ارسال Traceها به OTLP
+
+var app = builder.Build();
+
+// ... ادامه پیکربندی برنامه
+
+app.Run();
+ +

گام ۳: اطمینان از همبستگی لاگ‌ها با Traceها

+

+ پس از پیکربندی، هر لاگی که توسط ILogger (و در نتیجه XLogger شما) ثبت شود، به‌طور خودکار دارای فیلدهای TraceId و SpanId خواهد بود. این امر باعث می‌شود که در ابزارهای مشاهده‌پذیری (Observability) بتوانید لاگ‌های مرتبط با یک Trace خاص را فیلتر کنید. +

+ +
+ ✅ نتیجه: با این یکپارچه‌سازی، ماژول xLoggingService شما نه‌تنها لاگ‌ها را به فایل و دیتابیس می‌فرستد، بلکه آن‌ها را به‌صورت استاندارد به هر بک‌اند سازگار با OTLP (مانند Jaeger، Grafana Tempo یا یک کلکتور OpenTelemetry) ارسال می‌کند. این کار امکان رهگیری کامل درخواست‌ها در معماری میکروسرویس را فراهم می‌آورد. +
+
+
+ + +
+
+
۲
+
+

ایجاد میدل‌ور برای لاگ درخواست‌ها و خطاها

+
Request & Exception Logging Middleware
+
+
+
+

+ یکی از بهترین روش‌ها برای ثبت خودکار درخواست‌های HTTP و خطاهای رخ‌داده، استفاده از یک میدل‌ور اختصاصی است. این میدل‌ور با استفاده از ILogger (که به xLoggingService متصل است) عمل کرده و از پراکندگی try-catch در کنترلرها جلوگیری می‌کند. در دات‌نت ۸ و ۹، پیاده‌سازی IExceptionHandler توصیه می‌شود؛ زیرا مدیریت متمرکز و سازگاری با میدل‌ور پیش‌فرض UseExceptionHandler را فراهم می‌کند. [reference:2] +

+ +

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

+ +

گام ۱: ایجاد کلاس میدل‌ور

+
using System.Diagnostics;
+using Microsoft.AspNetCore.Http;
+using Microsoft.Extensions.Logging;
+using System.Threading.Tasks;
+
+namespace xLoggingService.Middleware
+{
+    public class XRequestLoggingMiddleware
+    {
+        private readonly RequestDelegate _next;
+        private readonly ILogger _logger;
+
+        public XRequestLoggingMiddleware(
+            RequestDelegate next,
+            ILogger logger)
+        {
+            _next = next;
+            _logger = logger;
+        }
+
+        public async Task InvokeAsync(HttpContext context)
+        {
+            var stopwatch = Stopwatch.StartNew();
+            try
+            {
+                // لاگ شروع درخواست
+                _logger.LogInformation(
+                    "Handling request: {Method} {Path}",
+                    context.Request.Method,
+                    context.Request.Path);
+
+                await _next(context);
+
+                // لاگ پایان موفق درخواست
+                stopwatch.Stop();
+                _logger.LogInformation(
+                    "Finished handling request: {Method} {Path} in {Elapsed}ms",
+                    context.Request.Method,
+                    context.Request.Path,
+                    stopwatch.ElapsedMilliseconds);
+            }
+            catch (Exception ex)
+            {
+                // لاگ خطا با جزئیات کامل
+                stopwatch.Stop();
+                _logger.LogError(ex,
+                    "Request failed: {Method} {Path} after {Elapsed}ms",
+                    context.Request.Method,
+                    context.Request.Path,
+                    stopwatch.ElapsedMilliseconds);
+
+                throw; // پرتاب مجدد برای مدیریت توسط میدل‌ورهای بالادستی
+            }
+        }
+    }
+}
+ +

گام ۲: ثبت میدل‌ور در Program.cs

+

میدل‌ور را در خط لوله پردازش درخواست‌ها (Request Pipeline) ثبت کنید. بهتر است آن را در ابتدای خط لوله قرار دهید تا همه درخواست‌ها را پوشش دهد.

+ +
var app = builder.Build();
+
+// ثبت میدل‌ور سفارشی
+app.UseMiddleware<XRequestLoggingMiddleware>();
+
+// ... سایر میدل‌ورها (مانند UseRouting، UseAuthentication و ...)
+
+app.MapControllers();
+app.Run();
+ +
+ 💡 نکته: اگر از IExceptionHandler استفاده می‌کنید، می‌توانید لاگ خطا را در متد TryHandleAsync انجام دهید. در این صورت، برای جلوگیری از ثبت دوباره خطا توسط میدل‌ور پیش‌فرض، می‌توانید دسته‌بندی Microsoft.AspNetCore.Diagnostics.ExceptionHandlerMiddleware را در تنظیمات لاگ فیلتر کنید. [reference:3] +
+ +
+ ✅ نتیجه: با این میدل‌ور، تمامی درخواست‌های HTTP به‌صورت خودکار در سرویس لاگر شما ثبت می‌شوند. در صورت بروز خطا، جزئیات کامل (شامل Exception و مدت زمان اجرا) لاگ شده و از پراکندگی کدهای try-catch جلوگیری می‌شود. +
+
+
+ + +
+
+
۳
+
+

پیاده‌سازی گام‌به‌گام Sentry برای رهگیری خطاها

+
Step-by-Step Sentry Integration
+
+
+
+

+ Sentry یک پلتفرم قدرتمند برای پایش خطاها (Error Monitoring) و رهگیری عملکرد (Performance Tracing) است. با یکپارچه‌سازی Sentry در پروژه، خطاهای مدیریت‌نشده به‌صورت خودکار ثبت شده و همراه با جزئیات کامل (Stack Trace، Breadcrumbs و Context) در داشبورد Sentry نمایش داده می‌شوند. در ادامه، مراحل پیاده‌سازی به‌صورت گام‌به‌گام شرح داده می‌شود. +

+ +
+ ⚠️ پیش‌نیاز: قبل از شروع، یک حساب کاربری در Sentry.io ایجاد کنید و یک پروژه جدید از نوع ASP.NET Core بسازید تا DSN (Data Source Name) خود را دریافت کنید. +
+ +

گام ۱: نصب پکیج Sentry

+
dotnet add package Sentry.AspNetCore -v 6.1.0
+ +

گام ۲: پیکربندی Sentry در Program.cs

+

سرویس Sentry را با استفاده از متد UseSentry پیکربندی کنید. این متد به‌گونه‌ای طراحی شده که به‌طور خودکار خطاهای مدیریت‌نشده را شکار کند. [reference:4]

+ +
var builder = WebApplication.CreateBuilder(args);
+
+builder.WebHost.UseSentry(options =>
+{
+    options.Dsn = Environment.GetEnvironmentVariable("SENTRY_DSN")
+                  ?? "___YOUR_DSN___";
+    options.Debug = true; // فقط در محیط توسعه
+    options.SendDefaultPii = true; // ارسال اطلاعات کاربر (اختیاری)
+    options.TracesSampleRate = 1.0; // در تولید به 0.1 تا 0.2 کاهش دهید
+    options.MinimumBreadcrumbLevel = LogLevel.Debug;
+    options.MinimumEventLevel = LogLevel.Warning;
+});
+
+var app = builder.Build();
+// ...
+app.Run();
+ +

گام ۳: پیکربندی از طریق appsettings.json (جایگزین)

+

می‌توانید تنظیمات را در فایل appsettings.json نیز قرار دهید. این روش انعطاف‌پذیری بیشتری برای محیط‌های مختلف فراهم می‌کند. [reference:5]

+ +
{
+  "Sentry": {
+    "Dsn": "___YOUR_DSN___",
+    "SendDefaultPii": true,
+    "MinimumBreadcrumbLevel": "Debug",
+    "MinimumEventLevel": "Warning",
+    "AttachStacktrace": true,
+    "Debug": false,
+    "TracesSampleRate": 1.0,
+    "Environment": "production",
+    "Release": "my-app@1.0.0"
+  }
+}
+ +

گام ۴: آپلود نمادهای دیباگ (Symbols) برای Stack Trace خوانا

+

+ بدون آپلود فایل‌های PDB، Stack Trace تنها نام متدها را نشان می‌دهد و فاقد شماره خط و نام فایل خواهد بود. برای رفع این مشکل، خواص MSBuild زیر را به فایل .csproj اضافه کنید. [reference:6] +

+ +
<PropertyGroup Condition="'$(Configuration)' == 'Release'">
+  <SentryOrg>___ORG_SLUG___</SentryOrg>
+  <SentryProject>___PROJECT_SLUG___</SentryProject>
+  <SentryUploadSymbols>true</SentryUploadSymbols>
+  <SentryUploadSources>true</SentryUploadSources>
+  <SentryCreateRelease>true</SentryCreateRelease>
+  <SentrySetCommits>true</SentrySetCommits>
+</PropertyGroup>
+

برای آپلود، باید متغیر محیطی SENTRY_AUTH_TOKEN را در CI/CD تنظیم کنید. [reference:7]

+ +

گام ۵: تأیید و تست

+

یک خطای آزمایشی ایجاد کنید تا از صحت پیکربندی مطمئن شوید. [reference:8]

+ +
// یک Endpoint موقت برای تست
+app.MapGet("/sentry-test", () =>
+{
+    throw new Exception("Sentry test error — delete me");
+});
+ +

سپس به داشبورد Sentry (بخش Issues) بروید. خطا باید ظرف حدود ۳۰ ثانیه نمایش داده شود. [reference:9]

+ +
+ ⚠️ نکته امنیتی: هرگز DSN را به‌صورت مستقیم در کد منبع قرار ندهید. از متغیرهای محیطی یا appsettings.json (با تنظیمات مناسب) استفاده کنید. همچنین SENTRY_AUTH_TOKEN باید به‌عنوان یک Secret در CI/CD نگهداری شود. +
+ +
+ ✅ نتیجه: با پیاده‌سازی Sentry، خطاهای پروژه به‌صورت خودکار در داشبورد Sentry ثبت می‌شوند. این امر امکان شناسایی سریع مشکلات، مشاهده Stack Trace خوانا و رهگیری خطاها در محیط تولید را فراهم می‌کند. +
+
+
+ + +
+
+
۴
+
+

جمع‌بندی و مقایسه یکپارچه‌سازی‌ها

+
Summary of Integrations
+
+
+
+

جدول زیر خلاصه‌ای از سه قابلیت اضافه‌شده و مزایای کلیدی هر یک را نشان می‌دهد:

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
قابلیتهدف اصلیمزیت کلیدیوضعیت پیاده‌سازی
OpenTelemetryرهگیری توزیع‌شده (Distributed Tracing)همبستگی خودکار لاگ‌ها با Traceها و ارسال به بک‌اندهای استانداردآماده
میدل‌ور لاگینگثبت خودکار درخواست‌ها و خطاهاحذف try-catch تکراری و ثبت متمرکز رخدادهاآماده
Sentryپایش و رهگیری خطاهاStack Trace خوانا، هشدارهای خودکار و داشبورد مدیریت خطاآماده
نتیجه نهاییمشاهده‌پذیری کامل (Full Observability)ترکیب Logs، Metrics و Traces در یک اکوسیستم یکپارچهتکمیل
+ +
+

🎯 جمع‌بندی نهایی

+

+ با پیاده‌سازی این سه قابلیت، ماژول xLoggingService از یک لاگر ساده به یک راه‌حل کامل مشاهده‌پذیری (Observability) ارتقا می‌یابد. OpenTelemetry امکان رهگیری توزیع‌شده را فراهم می‌کند، میدل‌ور لاگینگ ثبت خودکار درخواست‌ها را تضمین می‌کند و Sentry پایش خطاها را در سطح تولید ممکن می‌سازد. این ترکیب، تشخیص و رفع مشکلات را به‌طور چشمگیری تسریع کرده و به تیم توسعه کمک می‌کند تا با اطمینان بیشتری نرم‌افزار را در محیط عملیاتی اجرا کند. +

+
+ 💎 ارزش پیشنهادی:
+ رهگیری توزیع‌شده + لاگ خودکار درخواست‌ها + پایش هوشمند خطاها = مشاهده‌پذیری کامل و کاهش زمان رفع اشکال +
+
+
+
+ + +
+
+
۵
+
+

منابع و مستندات

+
References
+
+
+
+
    +
  • + OpenTelemetry .NET SDK Documentation + راهنمای رسمی پیکربندی OpenTelemetry با WithLogging و WithTracing +
    منبع: https://github.com/open-telemetry/opentelemetry-dotnet
    +
  • +
  • + Microsoft Learn: Error Handling in ASP.NET Core + مدیریت خطا و پیاده‌سازی IExceptionHandler +
    منبع: https://learn.microsoft.com/aspnet/core/fundamentals/error-handling
    +
  • +
  • + Sentry .NET SDK Documentation + راهنمای گام‌به‌گام نصب و پیکربندی Sentry در ASP.NET Core +
    منبع: https://docs.sentry.io/platforms/dotnet/
    +
  • +
  • + Sentry for AI: .NET SDK Skill Guide + دستورالعمل جامع پیکربندی Sentry شامل Symbol Upload و گزینه‌های پیشرفته +
    منبع: https://github.com/getsentry/sentry-for-ai
    +
  • +
+
+
+ +
+ این مستند فنی بوده و برای تیم توسعه xLoggingService تهیه شده است. هرگونه بازتولید یا انتشار بدون اجازه کتبی ممنوع است. +
+ +
+ +
+ + +
تاریخ تهیه: آبان ۱۴۰۵  |  نسخه: ۱.۰  |  طبقه‌بندی: فنی
+
+ +
+ + + \ No newline at end of file diff --git a/Documents/GeneratedContext/xDashboard-xAiApi-20261108_143748.txt b/Documents/GeneratedContext/xDashboard-xAiApi-20261108_143748.txt deleted file mode 100644 index 20cc18a..0000000 --- a/Documents/GeneratedContext/xDashboard-xAiApi-20261108_143748.txt +++ /dev/null @@ -1,39230 +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; -using xAiService.DI; - -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(); - - // - // Register XAiMcpClient ... - services.AddXAiMcpClient(); - - // - // Persistent RAG (Knowledge over XAiVector Table) ... - services.AddXRagService(); - - // - // Register Default AI Services ... - services.AddXAiServices(); - } - - public void Configure(IApplicationBuilder app, IWebHostEnvironment env) - { - // - // Configure the HTTP request pipeline. - // Order: Exception Handling -> Https -> Static Files -> Swagger (Dev) -> Cors - // -> Model Proxy (Terminal for /{RoutePrefix}) -> Routing -> AuthN -> AuthZ -> Endpoints ... - var isDevelopmentEnvironment = env.IsDevelopment(); - if (isDevelopmentEnvironment) - { - app.UseDeveloperExceptionPage(); - } - else - { - app.UseExceptionHandler(XAiModelsConstants.XAiErrorRoute); - app.UseHsts(); - } - - // - // 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(); - - /// - /// DateTime Configuration ... - /// - /// - public XDateTimeDescriptor DateTime { 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 = "Arion"; - 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\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( - CancellationToken cancellationToken = default - ) - { - // - try - { - // - var userInfo = await GetUserInfo(); - - // - await mcpServerProvider.RefreshAsync( - userInfo: userInfo, - cancellationToken: cancellationToken - ); - - // - return Ok(); - } catch(Exception ex) - { - // - var result = GetExceptionActionResult(ex); - return result; - } - } - } -} - -### FILE: C:\Users\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 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\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; - } - - // public static IList ToAITools(this IList source) - // { - // // - // var result = new List(); - - // // - // foreach (var tool in source) - // { - // // - // var declaration = AIFunctionFactory.CreateDeclaration( - // name: tool.Name, - // jsonSchema: tool.InputSchema, - // description: tool.Description - // ); - - // // - // result.Add(declaration); - // } - - // // - // return result; - // } - } -} - -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\xAiApi\Extensions\XProgramExtensions.cs - -using System.Linq; -using xIdentityHelper; -using xAiApi.Providers; -using xAiApi.Interfaces; -using xCommons.Extensions; -using xCommons.Authorization; -using System.Collections.Generic; -using xIdentityService.Interfaces; -using Microsoft.AspNetCore.Builder; -using Microsoft.AspNetCore.Authorization; -using Microsoft.AspNetCore.HttpOverrides; -using Microsoft.Extensions.DependencyInjection; - -namespace xAiApi.Extensions -{ - public static class XProgramExtensions - { - /// - /// 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 - ) - { - // - var policyHandler = services.GetRegisteredService(); - services.AddAuthorization(options => - { - // - if (!policies.IsNull()) - { - // - // Fill Policies ... - using (var policiesEnumerator = policies.GetEnumerator()) - { - while (policiesEnumerator.MoveNext()) - { - var policyDescriptor = policiesEnumerator.Current; - options.AddPolicy(policyDescriptor.Key, policyDescriptor.Value); - - // - // Add Policy to Policy Handler ... - if (!policyHandler.IsNull()) - { - // - // Check Policy is RequiredRole Policy ... - var roleRequirements = policyDescriptor.Value.Requirements - .OfType() - .FirstOrDefault(); - if (!roleRequirements.IsNull() && - roleRequirements.Roles.HasChild()) - { - // - policyHandler.AddPolicy( - policy: policyDescriptor.Key.ToNormalString(), - requiredRoles: roleRequirements.Roles.Select(r => r.ToNormalString()) - ); - } - } - } - } - } - - // - var xPolicies = XAuthorizationHelper.GetXAuthorizationPolicies(); - if (!xPolicies.IsNull()) - { - // - // Fill Policies ... - using (var policiesEnumerator = xPolicies.GetEnumerator()) - { - while (policiesEnumerator.MoveNext()) - { - // - var policyDescriptor = policiesEnumerator.Current; - - // - // Add Policy to Authorization ... - options.AddPolicy(policyDescriptor.Key, policyDescriptor.Value); - - // - // Add Policy to Policy Handler ... - if (!policyHandler.IsNull()) - { - // - // Check Policy is RequiredRole Policy ... - var roleRequirements = policyDescriptor.Value.Requirements - .OfType() - .FirstOrDefault(); - if (!roleRequirements.IsNull() && - roleRequirements.Roles.HasChild()) - { - // - policyHandler.AddPolicy( - policy: policyDescriptor.Key.ToNormalString(), - requiredRoles: roleRequirements.Roles.Select(r => r.ToNormalString()) - ); - } - } - } - } - } - }); - - // - 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 xModels.Dtos; -using System.Threading; -using xAiModels.Models.Dtos; -using xIdentityModels.Models; -using System.Threading.Tasks; -using System.Linq.Expressions; -using xAiModels.Models.Entities; -using System.Collections.Generic; -using ModelContextProtocol.Client; -using Microsoft.Extensions.AI; - -namespace xAiApi.Interfaces -{ - /// - /// 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, - string connectionId = null, - XUserClaimsInfoDto userInfo = null, - CancellationToken cancellationToken = default - ); - - /// - /// Force Refresh Mcp Servers ... - /// - /// - /// - /// - Task RefreshAsync( - XUserClaimsInfoDto userInfo = null, - CancellationToken cancellationToken = default - ); - #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\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, - 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, - bool extractFileContents = false, - bool addFilesToKnowledge = true, - 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, - bool extractFileContents = false, - bool addFilesToKnowledge = true, - 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\XDateTimeDescriptor.cs - -namespace xAiApi.Models -{ - public class XDateTimeDescriptor - { - /// - /// Adding Current DateTime to Prompt ... - /// - public bool InjectIntoSystemPrompt { get; set; } = true; - - /// - /// Time Zone ... - /// - public string DefaultTimezone { get; set; } = "Asia/Tehran"; - - /// - /// Georgian Date Format ... - /// - public string GregorianFormat { get; set; } = "yyyy-MM-dd HH:mm:ss"; - - /// - /// Include Persian Calendar ... - /// - public bool IncludePersianCalendar { get; set; } = true; - - /// - /// Include Day of Week ... - /// - public bool IncludeDayOfWeek { get; set; } = true; - - /// - /// Include Unix Timestamp ... - /// - public bool IncludeUnixTimestamp { get; set; } = false; - } -} - -### 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 xAiService.Services; -using xAiModels.Extensions; -using xAiService.Extensions; -using xExceptions.Constants; -using xAiModels.Models.Dtos; -using xIdentityModels.Models; -using System.Threading.Tasks; -using System.Linq.Expressions; -using xCommons.Configurations; -using Microsoft.Extensions.AI; -using xAiModels.Providers.Hubs; -using xAiModels.Models.Entities; -using xAiModels.Interfaces.Dtos; -using xIdentityHelper.Extensions; -using System.Collections.Generic; -using xIdentityService.Interfaces; -using Microsoft.Extensions.Logging; -using Microsoft.AspNetCore.SignalR; -using xAiModels.Interfaces.Entities; -using System.Collections.Concurrent; -using xAiModels.Interfaces.Enrichers; - -namespace xAiApi.Providers -{ - /// - /// MCP Manager / Provider ... - /// - public class XAiMcpServerProvider : IXAiMcpServerProvider, IAsyncDisposable - { - // - private readonly XAiMcpSessionStore sessionStore; - private readonly XAiMcpHttpTransport mcpTransport; - - // - private readonly XAppConfiguration configuration; - 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 ConcurrentDictionary mcpServers = []; - private readonly ConcurrentDictionary<(Guid, string), DateTime> clientExpirations = new(); - private readonly ConcurrentDictionary<(Guid ServerId, string UserId), XAiMcpClient> clients = new(); - private readonly ConcurrentDictionary<(Guid ServerId, string UserId), IList> tools = new(); - - // - private bool isInitialized = false; - private readonly SemaphoreSlim initLock = new(1, 1); - - public XAiMcpServerProvider( - XAiMcpSessionStore sessionStore, - XAppConfiguration configuration, - XAiMcpHttpTransport mcpTransport, - IHubContext hub, - IXIdentityProvider identityProvider, - ILogger logger, - XValidationProvider validationProvider, - IXAiMcpServerEnricher mcpServerEnricher, - IXAiMcpServerServiceProvider mcpServerServiceProvider, - IXAiMcpServerRepositoryProvider mcpServerRepositoryProvider - ) - { - this.configuration = configuration; - // - this.hub = hub; - this.logger = logger; - this.sessionStore = sessionStore; - this.mcpTransport = mcpTransport; - this.identityProvider = identityProvider; - this.mcpServerEnricher = mcpServerEnricher; - this.validationProvider = validationProvider; - this.mcpServerServiceProvider = mcpServerServiceProvider; - this.mcpServerRepositoryProvider = mcpServerRepositoryProvider; - } - - public async ValueTask DisposeAsync() - { - // - foreach (var client in clients.Values) - { - try - { - await client.DisposeAsync(); - } - catch { } - } - initLock.Dispose(); - } - - // - #region Manager ... - /// - /// 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; - } - - // - // Load Servers Metadata ... - await EnsureServersLoadedAsync(cancellationToken); - - // - // Extract Accessible Mcp Servers ... - var accessibleServers = mcpServers.Values - .Where(s => s.OwnerId == userInfo.UserId || - s.Scope == XAiMcpServerUsageScope.All) - .ToList(); - - // - // Create User Speciic Client Connection ... - foreach (var server in accessibleServers) - { - // - // Create User Specific Client Key ... - var key = (server.Id, userInfo.UserId); - - // - // Check Expiration ... - if (clients.ContainsKey(key) && - clientExpirations.TryGetValue(key, out var exp) && - exp < DateTime.UtcNow) - { - // - // Remove Expired Client and Tools ... - if (clients.TryRemove(key, out var old)) - { - // - try - { - await old.DisposeAsync(); - } - catch { } - } - - // - tools.TryRemove(key, out _); - clientExpirations.TryRemove(key, out _); - } - - // - if (clients.ContainsKey(key)) - { - continue; - } - - // - await initLock.WaitAsync(cancellationToken); - try - { - // - if (!clients.ContainsKey(key)) - { - // - await ConnectAndValidateAsync( - descriptor: server, - userInfo: userInfo, - cancellationToken: cancellationToken - ); - } - } - finally - { - initLock.Release(); - } - } - - // - // Extract User Specified Mcp Client Tools ... - var result = tools - .Where(kv => kv.Key.UserId == userInfo.UserId) - .SelectMany(kv => kv.Value) - .ToList(); - - // - return result; - } - - /// - /// Test Specified Mcp Server ... - /// - /// - /// - /// - /// - /// - public async Task TestServerAsync( - XAiMcpServerDto server, - string connectionId = null, - XUserClaimsInfoDto userInfo = null, - CancellationToken cancellationToken = default - ) - { - // - try - { - // - using var cts = CancellationTokenSource.CreateLinkedTokenSource(cancellationToken); - cts.CancelAfter(TimeSpan.FromSeconds(server.TimeoutSeconds)); - - // - var client = CreateClientAsync(server, connectionId, userInfo); - // await client.PingAsync(cancellationToken: cts.Token); - var serverTools = await client.ListToolsAsync(cancellationToken: cts.Token); - - // - var names = string.Join(", ", serverTools.Select(t => t.Name)); - return $"✓ Server: '{server.Name}' is Ready to Use, {serverTools.Count} Tools: {names}"; - } - catch (Exception ex) - { - // - return $"✗ Error: {ex.Message} ..."; - } - } - - /// - /// Force Refresh Mcp Servers ... - /// - /// - /// - /// - public async Task RefreshAsync( - XUserClaimsInfoDto userInfo = null, - CancellationToken cancellationToken = default - ) - { - // - if (!userInfo.IsAdmin()) - { - XException.NotAllowed.Throw(); - } - - // - logger.LogInformation("MCP: Reinitialize Mcp Servers ..."); - foreach (var client in clients.Values) - { - try - { - await client.DisposeAsync(); - } - catch { } - } - tools.Clear(); - clients.Clear(); - mcpServers.Clear(); - - // - isInitialized = false; - await GetAvailableToolsAsync( - userInfo: userInfo, - cancellationToken: cancellationToken - ); - } - #endregion - - // - #region Actions ... - /// - /// 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 - { - // - mcpServers[result.Id] = result; - await ConnectAndValidateAsync(result, connectionId, userInfo); - } - 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 - { - // - mcpServers[result.Id] = result; - - // - // Remove Exists ... - var keysToRemove = clients.Keys - .Where(k => k.ServerId == result.Id) - .ToList(); - foreach (var key in keysToRemove) - { - // - if (clients.TryRemove(key, out var old)) - { - try - { - await old.DisposeAsync(); - } - catch { } - } - tools.TryRemove(key, out _); - } - - // - // Reconnect ... - await ConnectAndValidateAsync(result, connectionId, userInfo, cancellationToken); - } - finally - { - initLock.Release(); - } - } - - // - return result; - } - - /// - /// 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 Server Descriptor ... - mcpServers.TryRemove(result.Id, out _); - - // - // Disconnect all Connections ... - var keysToRemove = clients.Keys - .Where(k => k.ServerId == result.Id) - .ToList(); - foreach (var key in keysToRemove) - { - // - if (clients.TryRemove(key, out var c)) - { - // - try - { - await c.DisposeAsync(); - } - catch { } - } - - // - tools.TryRemove(key, out _); - } - } - finally - { - initLock.Release(); - } - } - - // - return result; - } - - /// - /// 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 Server Descriptor ... - mcpServers.TryRemove(exists.Id, out _); - - // - // Disconnect all Connections ... - var keysToRemove = clients.Keys - .Where(k => k.ServerId == exists.Id) - .ToList(); - foreach (var key in keysToRemove) - { - // - if (clients.TryRemove(key, out var c)) - { - // - try - { - await c.DisposeAsync(); - } - catch { } - } - - // - tools.TryRemove(key, out _); - } - } - finally - { - initLock.Release(); - } - } - - // - return result; - } - - /// - /// 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 - { - // - mcpServers[exists.Id] = exists; - await ConnectAndValidateAsync(exists, connectionId, userInfo, 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) - { - // - mcpServers[exists.Id] = exists; - await ConnectAndValidateAsync(exists, connectionId, userInfo, cancellationToken); - } - else - { - // - // Remove Server Descriptor ... - mcpServers.TryRemove(exists.Id, out _); - - // - // Disconnect all Connections ... - var keysToRemove = clients.Keys - .Where(k => k.ServerId == exists.Id) - .ToList(); - foreach (var key in keysToRemove) - { - // - if (clients.TryRemove(key, out var c)) - { - // - try - { - await c.DisposeAsync(); - } - catch { } - } - - // - tools.TryRemove(key, out _); - } - } - } - finally - { - initLock.Release(); - } - } - - // - return result; - } - - /// - /// 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 XAiMcpClient CreateClientAsync( - XAiMcpServerDto descriptor, - string connectionId = null, - XUserClaimsInfoDto userInfo = null - ) - { - // - var result = new XAiMcpClient( - logger: logger, - userInfo: userInfo, - transport: mcpTransport, - serverId: descriptor.Id, - sessionStore: sessionStore, - connectionId: connectionId, - appConfiguration: configuration, - endpoint: new Uri(descriptor.Endpoint) - ); - - // - return result; - } - - private async Task ConnectAndValidateAsync( - XAiMcpServerDto descriptor, - string connectionId = null, - XUserClaimsInfoDto userInfo = null, - CancellationToken cancellationToken = default - ) - { - // - try - { - // - // Create Specified Cancellation Token ... - using var cts = CancellationTokenSource - .CreateLinkedTokenSource(cancellationToken); - cts.CancelAfter(TimeSpan.FromSeconds(descriptor.TimeoutSeconds)); - - // - var client = CreateClientAsync( - userInfo: userInfo, - descriptor: descriptor, - connectionId: connectionId - ); - - // - await client.InitializeAsync(cts.Token); - - // - var clientTools = await client.ListToolsAsync(cts.Token); - var aiTools = clientTools.ToAITools(client); - - // - // Key for Cache ... - var key = (descriptor.Id, userInfo.UserId); - - // - tools[key] = aiTools; - clients[key] = client; - mcpServers[descriptor.Id] = descriptor; - clientExpirations[key] = DateTime.UtcNow.AddMinutes(15); - - // - logger.LogInformation( - "MCP '{Name}': {Count} Tools Detected for {UserId} ...", - descriptor.Name, - aiTools.Count, - userInfo.UserId - ); - } catch(Exception ex) - { - // - logger.LogWarning(ex, - "MCP '{Name}': Connection Established Failed, Ignored ...", - descriptor.Name - ); - } - } - - private async Task EnsureServersLoadedAsync(CancellationToken cancellationToken) - { - // - if (isInitialized) - { - return; - } - - // - await initLock.WaitAsync(cancellationToken); - try - { - // - if (isInitialized) - { - return; - } - - // - var servers = await mcpServerServiceProvider.FindManyAsync( - orderBuilder: null, - includeBuilder: null, - ignoreSoftDeleteds: true, - predicate: x => x.Enabled, - cancellationToken: cancellationToken - ); - - // - if (servers.HasChild()) - { - // - foreach (var s in servers) - { - // - mcpServers[s.Id] = s; - } - } - - // - isInitialized = true; - } - finally - { - initLock.Release(); - } - } - #endregion - - // - #region Hub Actions ... - /// - /// 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\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, - IXAiMcpServerProvider mcpServerProvider, - IXFileContentExtractor fileContentExtractor - ) : base( - ragProvider, - dataProvider, - logger, - configuration, - validationProvider, - mcpServerProvider, - fileContentExtractor, - XAiApiConstants.XAiDefaultModelName - ) - { } - } -} - -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\xAiApi\Providers\XAIServiceBase.cs - -using System; -using System.Linq; -using System.Text; -using xModels.Dtos; -using xAiApi.Models; -using System.Threading; -using xAiApi.Constants; -using xAiModels.Models; -using TimeZoneConverter; -using xAiApi.Interfaces; -using xAiApi.Extensions; -using xCommons.Providers; -using xCommons.Extensions; -using xAiModels.Constants; -using xAiModels.Interfaces; -using xAiModels.Extensions; -using System.Globalization; -using xAiApi.Configurations; -using xExceptions.Constants; -using xAiModels.Models.Dtos; -using xAiService.Extensions; -using System.Threading.Tasks; -using xIdentityModels.Models; -using Microsoft.Extensions.AI; -using Microsoft.AspNetCore.Http; -using System.Collections.Generic; -using Microsoft.Extensions.Logging; -using xAiApi.Interfaces.Extractors; -using System.Runtime.CompilerServices; - -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]; - } - - // - 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, - additionalContents: null, - addFilesToKnowledge: false, - resolveConversation: false, - extractFileContents: false, - cancellationToken: cancellationToken - ); - - // - using var client = Descriptor.GetClient(); - - // - // Handle Provided MCP Servers ... - if (useProvidedMcpServers) - { - // - var availableTools = await mcpServerProvider - .GetAvailableToolsAsync( - userInfo: userInfo, - cancellationToken: cancellationToken - ); - - // - Options.Tools = [.. availableTools.Cast()]; - } - - // - 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, - additionalContents: null, - resolveConversation: false, - addFilesToKnowledge: false, - extractFileContents: false, - cancellationToken: cancellationToken - ); - - // - using var client = Descriptor.GetClient(); - - // - // Handle Provided MCP Servers ... - if (useProvidedMcpServers) - { - // - var availableTools = await mcpServerProvider - .GetAvailableToolsAsync( - userInfo: userInfo, - cancellationToken: cancellationToken - ); - - // - Options.Tools = [.. availableTools.Cast()]; - } - - // - 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, - bool extractFileContents = false, - bool addFilesToKnowledge = true, - IFormFileCollection files = null, - XUserClaimsInfoDto userInfo = null, - CancellationToken cancellationToken = default - ) - { - // - // Validate Args ... - validationProvider - .GroupValidationBuilder() - .AddNotEmpty(prompt) - .AddNotNull(userInfo) - .AddNotEmpty(userInfo.UserId) - .ValidateGroup(); - - // - var prep = await PrepareChatRequirementsAsync( - type: type, - topK: topK, - files: files, - prompt: prompt, - minScore: minScore, - userInfo: userInfo, - persistPrompt: true, - projectId: projectId, - additionalContents: null, - resolveConversation: true, - connectionId: connectionId, - conversationId: conversationId, - cancellationToken: cancellationToken, - extractFileContents: extractFileContents, - addFilesToKnowledge: addFilesToKnowledge - ); - - // - using var client = Descriptor.GetClient(); - - // - // Handle Provided MCP Servers ... - if (useProvidedMcpServers) - { - // - var availableTools = await mcpServerProvider - .GetAvailableToolsAsync( - userInfo: userInfo, - cancellationToken: cancellationToken - ); - - // - Options.Tools = [.. availableTools.Cast()]; - } - - // - 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, - bool extractFileContents = false, - bool addFilesToKnowledge = true, - IFormFileCollection files = null, - XUserClaimsInfoDto userInfo = null, - [EnumeratorCancellation] - CancellationToken cancellationToken = default - ) - { - // - // Validate Args ... - validationProvider - .GroupValidationBuilder() - .AddNotEmpty(prompt) - .AddNotNull(userInfo) - .AddNotEmpty(userInfo.UserId) - .ValidateGroup(); - - // - var prep = await PrepareChatRequirementsAsync( - type: type, - topK: topK, - files: files, - prompt: prompt, - minScore: minScore, - userInfo: userInfo, - persistPrompt: true, - projectId: projectId, - additionalContents: null, - resolveConversation: true, - connectionId: connectionId, - conversationId: conversationId, - cancellationToken: cancellationToken, - extractFileContents: extractFileContents, - addFilesToKnowledge: addFilesToKnowledge - ); - - // - using var client = Descriptor.GetClient(); - - // - // Handle Provided MCP Servers ... - if (useProvidedMcpServers) - { - // - var availableTools = await mcpServerProvider - .GetAvailableToolsAsync( - userInfo: userInfo, - cancellationToken: cancellationToken - ); - - // - Options.Tools = [.. availableTools.Cast()]; - } - - // - 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, - ]; - - // - // Prepare Datetime ... - var datetimeContext = BuildDateTimeContext(); - if (!datetimeContext.IsNullOrEmpty()) - { - // - result.Add(new ChatMessage( - ChatRole.Assistant, - datetimeContext - )); - } - - // - if (forcePrompt && - prompt is not null && - !prompt.IsNullOrEmpty()) - { - result.Add(promptMessage); - } - - // - return result; - } - - /// - /// 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 datetimeContext = BuildDateTimeContext(); - var contextBlock = BuildContextBlock(context); - var systemText = introductionPrompt; - if (context.HasChild() && - !contextBlock.IsNullOrEmpty() - ) - { - // - systemText = - $"{introductionPrompt}{Environment.NewLine}{Environment.NewLine}"; - - // - if (!datetimeContext.IsNullOrEmpty()) - { - // - systemText += $"{datetimeContext}{Environment.NewLine}{Environment.NewLine}"; - } - - // - systemText += - $"{ragPrompt}{Environment.NewLine}{Environment.NewLine}" + - $"Context:{Environment.NewLine}{contextBlock}"; - } - - // - List 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}"; - } - - // - // Prepare Datetime ... - var datetimeContext = BuildDateTimeContext(); - if (!datetimeContext.IsNullOrEmpty()) - { - // - systemText += - $"{datetimeContext}{Environment.NewLine}{Environment.NewLine}"; - } - - // - // Apply Project Prompt as System Text ... - if (!project.IsNullOrDefault() && - !project.Prompt.IsNullOrEmpty()) - { - systemText += $"{project.Prompt}{Environment.NewLine}{Environment.NewLine}"; - } - - // - // Add System Message ... - result.Add(new ChatMessage(ChatRole.System, systemText)); - - // - // Attach Message ... - if (messages.HasChild()) - { - // - // TODO: Here we can Implement Memory Management based on - // Last nth of Messages, or Summarization of Messages, etc ... - result = [..result, ..messages - .OrderBy(m => m.CreatedOn) - .Select(m => m.ToChatMessages())]; - } - - // - return result; - } - - /// - /// 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, - bool extractFileContents = true, - bool addFilesToKnowledge = false, - 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 && - addFilesToKnowledge - ) - { - // - try - { - // - var ingestResult = await ragProvider - .IngestAsync( - files: files, - userInfo: userInfo, - replaceExisting: true, - connectionId: connectionId, - scope: XAiKnowledgeScopeDescriptor - .Conversation( - type: type, - conversationId: conversationId.Value - ), - cancellationToken: cancellationToken - ); - if (ingestResult.SkippedFiles.HasChild()) - { - // - logger.LogWarning( - "Ingest skipped {Count} file(s): {Files}", - ingestResult.SkippedFiles.Count, - string.Join(", ", ingestResult.SkippedFiles)); - } - } - catch (OperationCanceledException) - { - throw; - } - catch (Exception ex) - { - // - logger.LogError(ex, - "Ingest failed for prompt '{Prompt}'. Continuing without attachments.", - prompt - ); - } - } - - // - // If there isn't Files need to add Files to Knowledge ... - if (files.HasChild() && - !addFilesToKnowledge - ) - { - // - // Extract File Content and add them to Additional Contents ... - foreach (var file in files) - { - // - var mimeType = file.ContentType?.ToLowerInvariant() ?? string.Empty; - if (mimeType.IsNullOrEmpty() || - !fileContentExtractor.CanExtract(mimeType)) - { - continue; - } - - // - using var stream = file.OpenReadStream(); - - // - // Extract File Content if necessary ... - if (extractFileContents) - { - // - var content = await fileContentExtractor.ExtractAsync( - fileStream: stream, - mimeType: mimeType, - cancellationToken: cancellationToken - ); - if (!content.IsNullOrEmpty()) - { - // - var fileContent = new TextContent($"File:{Environment.NewLine}{file.FileName}{Environment.NewLine}{content}"); - additionalContents = [.. additionalContents, fileContent]; - } - } - else - { - // - var fileContent = await DataContent.LoadFromAsync(stream, mimeType, cancellationToken); - additionalContents = [.. additionalContents, fileContent]; - } - } - } - - // - // Request Knowledge ... - var knowledgeRequest = new XAiKnowledgeAskRequest - { - TopK = topK, - Type = type, - Prompt = prompt, - IncludeUser = true, - MinScore = minScore, - IncludeGlobal = true, - ProjectId = resolveConversation ? projectId : null, - ConversationId = resolveConversation ? conversationId : null, - }; - var context = await ragProvider - .RetrieveAsync( - userInfo: userInfo, - request: knowledgeRequest, - cancellationToken: cancellationToken - ); - - // - // Prepare History and Persisted Prompt Message ... - IList history; - XAiMessageDto persistedPromptMessage = null; - if (persistPrompt) - { - // - // Retrieve Conversation Message ... - var messages = await dataProvider - .LoadMessages( - conversationId: conversationId.Value, - cancellationToken: cancellationToken - ); - - // - // Prepare History based on Memory Strategies ... - history = await PrepareMemory( - context: context, - project: project, - messages: messages, - cancellationToken: cancellationToken - ); - - // - // Persist Prompt Message ... - persistedPromptMessage = await dataProvider.AddMessage( - item: new XAiMessageDto - { - Content = prompt, - Role = XAiChatRole.User, - OwnerId = userInfo.UserId, - CreatedOn = DateTime.UtcNow, - ConversationId = conversationId.Value, - ConversationTitle = conversation.Title, - }, - connectionId: connectionId, - conversationId: conversationId.Value, - cancellationToken: cancellationToken - ); - - // - history - .Add(persistedPromptMessage - .ToChatMessages(additionalContents: additionalContents)); - } - else - { - // - history = GetHistory(prompt, context); - } - - // - // Prepare Result ... - var result = new XPreparedChatContext - { - Project = project, - Context = context, - History = history, - Conversation = conversation, - PersistedPromptMessage = persistedPromptMessage, - }; - - // - return result; - } - - private string BuildDateTimeContext() - { - // - var cfg = configuration.DateTime; - if (cfg == null || !cfg.InjectIntoSystemPrompt) - { - return string.Empty; - } - - // - try - { - // - var tz = ResolveTimezone(cfg.DefaultTimezone); - var nowUtc = DateTime.UtcNow; - var nowLocal = TimeZoneInfo.ConvertTimeFromUtc(nowUtc, tz); - - // - var sb = new StringBuilder(); - sb.AppendLine("[CURRENT DATETIME — for your reference]"); - sb.AppendLine($"Now (local, {tz.Id}): {nowLocal.ToString(cfg.GregorianFormat)}"); - - // - if (cfg.IncludeDayOfWeek) - { - sb.AppendLine($"Day of week: {nowLocal:dddd}"); - } - - // - if (cfg.IncludePersianCalendar) - { - // - var pc = new PersianCalendar(); - sb.AppendLine($"Now (Persian): {pc.GetYear(nowLocal):D4}/{pc.GetMonth(nowLocal):D2}/{pc.GetDayOfMonth(nowLocal):D2} {nowLocal:HH:mm:ss}"); - } - - // - if (cfg.IncludeUnixTimestamp) - { - sb.AppendLine($"Unix timestamp: {new DateTimeOffset(nowUtc).ToUnixTimeSeconds()}"); - } - - // - sb.AppendLine("Use this information when the user asks about 'today', 'now', 'this week', relative dates, or any time-sensitive calculations."); - return sb.ToString().TrimEnd(); - } - catch - { - return string.Empty; - } - } - - private static TimeZoneInfo ResolveTimezone(string id) - { - // - if (id.IsNullOrEmpty()) - { - return TimeZoneInfo.Utc; - } - - // - try - { - return TZConvert.GetTimeZoneInfo(id); - } - catch - { - return TimeZoneInfo.Utc; - } - } - #endregion - } -} - -### FILE: C:\Users\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, - 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\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-20261108_223839.txt b/Documents/GeneratedContext/xDashboard-xAiApi-20261108_223839.txt new file mode 100644 index 0000000..518e1c0 --- /dev/null +++ b/Documents/GeneratedContext/xDashboard-xAiApi-20261108_223839.txt @@ -0,0 +1,32433 @@ + +### 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 xAiService.DI; +using xTagService.DI; +using System.Net.Http; +using xAiApi.Database; +using xHttpService.DI; +using xPushService.DI; +using xFileService.DI; +using xDataService.DI; +using Newtonsoft.Json; +using System.Reflection; +using xAiApi.Extensions; +using xStringService.DI; +using xLoggingService.DI; +using xStorageService.DI; +using xIdentityService.DI; +using xDataService.Models; +using xCommons.Extensions; +using xAiModels.Constants; +using xPushService.Helpers; +using xCommons.Configurations; +using System.Collections.Generic; +using Microsoft.AspNetCore.Builder; +using Microsoft.AspNetCore.Hosting; +using Microsoft.Extensions.Hosting; +using Newtonsoft.Json.Serialization; +using Microsoft.Extensions.Configuration; +using Microsoft.Extensions.DependencyInjection; +using IdentityModel.AspNetCore.OAuth2Introspection; + +namespace xAiApi +{ + public class Startup + { + // + #region Props ... + public IConfiguration Configuration { get; } + private readonly List 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 Logging Service ... + services.AddXLoggingService(Configuration); + + // + // Register Allowed Origins ... + services.AddXCors(appConfiguration.AllowedOrigins); + + // + // Register Swagger ... + var xmlFile = $"{Assembly.GetExecutingAssembly().GetName().Name}.xml"; + var xmlPath = Path.Combine(AppContext.BaseDirectory, xmlFile); + services.AddXSwagger(Configuration, xmlFilePath: xmlPath); + + // + // Register HttpService ... + services.AddXHttpService(Configuration); + + // + // Add Api V1 Versioning ... + services.AddXApiV1Versioning(); + + // + // OAuthIntrospectin Http Client Handler ... + // this is for handling SSLErrors ... + services.AddHttpClient(OAuth2IntrospectionDefaults.BackChannelHttpClientName) + .ConfigurePrimaryHttpMessageHandler(() => + { + return new HttpClientHandler + { + ServerCertificateCustomValidationCallback = (sender, certificate, chain, sslPolicyErrors) => true + }; + }); + + // + // Register Authorizations ... + services.AddXAuthorization(); + + // + services.AddControllers() + .AddNewtonsoftJson(x => + { + x.SerializerSettings.ReferenceLoopHandling = ReferenceLoopHandling.Ignore; + x.SerializerSettings.ContractResolver = new CamelCasePropertyNamesContractResolver(); + }); + + // + var lifeTime = ServiceLifetime.Scoped; + var repositoryType = xDataService.Constants.XRepositoryType.EF; + + // + // Register XIdentity Service ... + services.AddXIdentityService( + lifeTime: lifeTime, + configuration: Configuration + ); + + // + // Storage Service ... + services.AddXStorageService(Configuration); + + // + // Push Service ... + services.AddXPushService( + lifeTime: lifeTime, + config: Configuration + ); + + // + // Preparing DataBases ... + if (databases.HasChild()) + { + // + databases + .ToList() + .ForEach(database => + { + // + // Register DataBase ... + services.AddXDatabase( + lifeTime: lifeTime, + descriptor: database, + configuration: Configuration + ); + }); + } + + // + // Register String Service ... + services.AddXStringService( + 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(); + + // + // Register XAiMcpClient ... + services.AddXAiMcpClient(); + + // + // Persistent RAG (Knowledge over XAiVector Table) ... + services.AddXRagService(); + + // + // Register Default AI Services ... + services.AddXAiServices(); + } + + public void Configure( + IApplicationBuilder app, + IWebHostEnvironment env + ) + { + // + // Configure the HTTP request pipeline. + // Order: Exception Handling -> Https -> Static Files -> Swagger (Dev) -> Cors + // -> Model Proxy (Terminal for /{RoutePrefix}) -> Routing -> AuthN -> AuthZ -> Endpoints ... + var isDevelopmentEnvironment = env.IsDevelopment(); + if (isDevelopmentEnvironment) + { + app.UseDeveloperExceptionPage(); + } + else + { + app.UseExceptionHandler(XAiModelsConstants.XAiErrorRoute); + app.UseHsts(); + } + + // + // Setting Environment in App Confiuration ... + app.AddEnvironmentToXAppConfiguration(env.EnvironmentName); + + // + // Force Https Redirection ... + app.UseHttpsRedirection(); + + // + // Use Storage Service (Prepare Folders + Static Files) ... + // Must be before Routing so Static Files Short Circuit Pipeline ... + app.UseXStorageService(); + + // + // Use Swagger Middleware (Only in Development) ... + if (isDevelopmentEnvironment) + { + app.UseXSwagger(); + } + + // + // Using Cors (before Proxy so Browser Requests get CORS Headers) ... + app.UseXCors(); + + // + // Enable Model Proxy (Handles its own Authentication) ... + app.UseXAiModelProxy(); + + // + // Using Routing ... + app.UseRouting(); + + // + // 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(); + + /// + /// DateTime Configuration ... + /// + /// + public XDateTimeDescriptor DateTime { get; set; } = new(); + } +} + +### FILE: C:\Users\SaherElm\Documents\Projects\xSaherelmWorkspace\xAiApi\Constants\ConfigurationNodeNames.cs + +namespace xAiApi.Constants +{ + public partial struct ConfigurationNodeNames + { + public const string AI_API_NODE = "AiApiConfiguration"; + } +} + +### FILE: C:\Users\SaherElm\Documents\Projects\xSaherelmWorkspace\xAiApi\Constants\XAiApiConstants.cs + +namespace xAiApi.Constants +{ + public struct XAiApiConstants + { + // + // Database Descriptor ... + public const string XAiApiDbIdentifier = "xAiApiDb"; + public const string XAiApiMigrationsAssemblyIdentifier = "xAiApi"; + + // + public const string XDILogTag = "XAiApi"; + + // + public const string XAiApiRagPromptName = "ChatWithDocuments"; + public const string XAiApiIntroductionPromptName = "Introduction"; + public const string XAiApiContentExtractionPromptName = "ContentExtraction"; + + // + public const string XAiDefaultModelName = "Arion"; + public const string XAiEmbeddingModelName = "Embed"; + public const string XAiDefaultVisionModelName = "Qwen"; + public const string XAiDefaultThinkingModelName = "Qwen"; + public const string XAiEmbeddingPromptName = "Embedding"; + } +} + +### FILE: C:\Users\SaherElm\Documents\Projects\xSaherelmWorkspace\xAiApi\Controllers\AccountController.cs + +using xCommons.Providers; +using xCommons.Configurations; +using xIdentityHelper.Controllers; +using xIdentityService.Interfaces; +using Microsoft.Extensions.Logging; + +namespace xAiApi.Controllers +{ + public partial class AccountController : XAccountControllerBase + { + // + #region Constructor ... + public AccountController( + ILogger 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( + CancellationToken cancellationToken = default + ) + { + // + try + { + // + var userInfo = await GetUserInfo(); + + // + await mcpServerProvider.RefreshAsync( + userInfo: userInfo, + cancellationToken: cancellationToken + ); + + // + return Ok(); + } catch(Exception ex) + { + // + var result = GetExceptionActionResult(ex); + return result; + } + } + } +} + +### FILE: C:\Users\SaherElm\Documents\Projects\xSaherelmWorkspace\xAiApi\Controllers\StartupController.cs + +using xCommons.Providers; +using xCommons.Extensions; +using xCommons.Controllers; +using xExceptions.Constants; +using xCommons.Configurations; +using Microsoft.AspNetCore.Mvc; +using Microsoft.AspNetCore.Http; +using Microsoft.Extensions.Logging; +using Microsoft.AspNetCore.Authorization; + +namespace xAiApi.Controllers +{ + /// + /// 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; + } + + // public static IList ToAITools(this IList source) + // { + // // + // var result = new List(); + + // // + // foreach (var tool in source) + // { + // // + // var declaration = AIFunctionFactory.CreateDeclaration( + // name: tool.Name, + // jsonSchema: tool.InputSchema, + // description: tool.Description + // ); + + // // + // result.Add(declaration); + // } + + // // + // return result; + // } + } +} + +### FILE: C:\Users\SaherElm\Documents\Projects\xSaherelmWorkspace\xAiApi\Extensions\XProgramExtensions.cs + +using System.Linq; +using xIdentityHelper; +using xAiApi.Providers; +using xAiApi.Interfaces; +using xCommons.Extensions; +using xCommons.Authorization; +using System.Collections.Generic; +using xIdentityService.Interfaces; +using Microsoft.AspNetCore.Builder; +using Microsoft.AspNetCore.Authorization; +using Microsoft.AspNetCore.HttpOverrides; +using Microsoft.Extensions.DependencyInjection; + +namespace xAiApi.Extensions +{ + public static class XProgramExtensions + { + /// + /// 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 + ) + { + // + var policyHandler = services.GetRegisteredService(); + services.AddAuthorization(options => + { + // + if (!policies.IsNull()) + { + // + // Fill Policies ... + using (var policiesEnumerator = policies.GetEnumerator()) + { + while (policiesEnumerator.MoveNext()) + { + var policyDescriptor = policiesEnumerator.Current; + options.AddPolicy(policyDescriptor.Key, policyDescriptor.Value); + + // + // Add Policy to Policy Handler ... + if (!policyHandler.IsNull()) + { + // + // Check Policy is RequiredRole Policy ... + var roleRequirements = policyDescriptor.Value.Requirements + .OfType() + .FirstOrDefault(); + if (!roleRequirements.IsNull() && + roleRequirements.Roles.HasChild()) + { + // + policyHandler.AddPolicy( + policy: policyDescriptor.Key.ToNormalString(), + requiredRoles: roleRequirements.Roles.Select(r => r.ToNormalString()) + ); + } + } + } + } + } + + // + var xPolicies = XAuthorizationHelper.GetXAuthorizationPolicies(); + if (!xPolicies.IsNull()) + { + // + // Fill Policies ... + using (var policiesEnumerator = xPolicies.GetEnumerator()) + { + while (policiesEnumerator.MoveNext()) + { + // + var policyDescriptor = policiesEnumerator.Current; + + // + // Add Policy to Authorization ... + options.AddPolicy(policyDescriptor.Key, policyDescriptor.Value); + + // + // Add Policy to Policy Handler ... + if (!policyHandler.IsNull()) + { + // + // Check Policy is RequiredRole Policy ... + var roleRequirements = policyDescriptor.Value.Requirements + .OfType() + .FirstOrDefault(); + if (!roleRequirements.IsNull() && + roleRequirements.Roles.HasChild()) + { + // + policyHandler.AddPolicy( + policy: policyDescriptor.Key.ToNormalString(), + requiredRoles: roleRequirements.Roles.Select(r => r.ToNormalString()) + ); + } + } + } + } + } + }); + + // + 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; +using Microsoft.Extensions.AI; + +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, + string connectionId = null, + XUserClaimsInfoDto userInfo = null, + CancellationToken cancellationToken = default + ); + + /// + /// Force Refresh Mcp Servers ... + /// + /// + /// + /// + Task RefreshAsync( + XUserClaimsInfoDto userInfo = null, + CancellationToken cancellationToken = default + ); + #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, + bool extractFileContents = false, + bool addFilesToKnowledge = true, + 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, + bool extractFileContents = false, + bool addFilesToKnowledge = true, + 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\20261103185805_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\20261103185805_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("20261103185805_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\XDateTimeDescriptor.cs + +namespace xAiApi.Models +{ + public class XDateTimeDescriptor + { + /// + /// Adding Current DateTime to Prompt ... + /// + public bool InjectIntoSystemPrompt { get; set; } = true; + + /// + /// Time Zone ... + /// + public string DefaultTimezone { get; set; } = "Asia/Tehran"; + + /// + /// Georgian Date Format ... + /// + public string GregorianFormat { get; set; } = "yyyy-MM-dd HH:mm:ss"; + + /// + /// Include Persian Calendar ... + /// + public bool IncludePersianCalendar { get; set; } = true; + + /// + /// Include Day of Week ... + /// + public bool IncludeDayOfWeek { get; set; } = true; + + /// + /// Include Unix Timestamp ... + /// + public bool IncludeUnixTimestamp { get; set; } = false; + } +} + +### FILE: C:\Users\SaherElm\Documents\Projects\xSaherelmWorkspace\xAiApi\Models\XPDFToImageDescriptor.cs + +namespace xAiApi.Models +{ + public class XPDFToImageDescriptor + { + public int Dpi { get; set; } = 300; + public int Width { get; set; } = 0; + public int Height { get; set; } = 0; + public bool UseTiling { get; set; } = false; + public bool WithFormFill { get; set; } = false; + public bool WithAspectRatio { get; set; } = false; + public bool WithAnnotations { get; set; } = false; + public bool DpiRelativeToBounds { get; set; } = false; + + public int MaxImageWidth { get; set; } = 2000; + public int MinTextLengthThreshold { get; set; } = 50; + public int MaxPagesForImageFallback { get; set; } = 0; + } +} + +### FILE: C:\Users\SaherElm\Documents\Projects\xSaherelmWorkspace\xAiApi\Models\XPreparedChatContext.cs + +using xAiModels.Models.Dtos; +using Microsoft.Extensions.AI; +using System.Collections.Generic; + +namespace xAiApi.Models +{ + /// + /// 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 xAiService.Services; +using xAiModels.Extensions; +using xAiService.Extensions; +using xExceptions.Constants; +using xAiModels.Models.Dtos; +using xIdentityModels.Models; +using System.Threading.Tasks; +using System.Linq.Expressions; +using xCommons.Configurations; +using Microsoft.Extensions.AI; +using xAiModels.Providers.Hubs; +using xAiModels.Models.Entities; +using xAiModels.Interfaces.Dtos; +using xIdentityHelper.Extensions; +using System.Collections.Generic; +using xIdentityService.Interfaces; +using Microsoft.Extensions.Logging; +using Microsoft.AspNetCore.SignalR; +using xAiModels.Interfaces.Entities; +using System.Collections.Concurrent; +using xAiModels.Interfaces.Enrichers; + +namespace xAiApi.Providers +{ + /// + /// MCP Manager / Provider ... + /// + public class XAiMcpServerProvider : IXAiMcpServerProvider, IAsyncDisposable + { + // + private readonly XAiMcpSessionStore sessionStore; + private readonly XAiMcpHttpTransport mcpTransport; + + // + private readonly XAppConfiguration configuration; + 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 ConcurrentDictionary mcpServers = []; + private readonly ConcurrentDictionary<(Guid, string), DateTime> clientExpirations = new(); + private readonly ConcurrentDictionary<(Guid ServerId, string UserId), XAiMcpClient> clients = new(); + private readonly ConcurrentDictionary<(Guid ServerId, string UserId), IList> tools = new(); + + // + private bool isInitialized = false; + private readonly SemaphoreSlim initLock = new(1, 1); + + public XAiMcpServerProvider( + XAiMcpSessionStore sessionStore, + XAppConfiguration configuration, + XAiMcpHttpTransport mcpTransport, + IHubContext hub, + IXIdentityProvider identityProvider, + ILogger logger, + XValidationProvider validationProvider, + IXAiMcpServerEnricher mcpServerEnricher, + IXAiMcpServerServiceProvider mcpServerServiceProvider, + IXAiMcpServerRepositoryProvider mcpServerRepositoryProvider + ) + { + this.configuration = configuration; + // + this.hub = hub; + this.logger = logger; + this.sessionStore = sessionStore; + this.mcpTransport = mcpTransport; + this.identityProvider = identityProvider; + this.mcpServerEnricher = mcpServerEnricher; + this.validationProvider = validationProvider; + this.mcpServerServiceProvider = mcpServerServiceProvider; + this.mcpServerRepositoryProvider = mcpServerRepositoryProvider; + } + + public async ValueTask DisposeAsync() + { + // + foreach (var client in clients.Values) + { + try + { + await client.DisposeAsync(); + } + catch { } + } + initLock.Dispose(); + } + + // + #region Manager ... + /// + /// 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; + } + + // + // Load Servers Metadata ... + await EnsureServersLoadedAsync(cancellationToken); + + // + // Extract Accessible Mcp Servers ... + var accessibleServers = mcpServers.Values + .Where(s => s.OwnerId == userInfo.UserId || + s.Scope == XAiMcpServerUsageScope.All) + .ToList(); + + // + // Create User Speciic Client Connection ... + foreach (var server in accessibleServers) + { + // + // Create User Specific Client Key ... + var key = (server.Id, userInfo.UserId); + + // + // Check Expiration ... + if (clients.ContainsKey(key) && + clientExpirations.TryGetValue(key, out var exp) && + exp < DateTime.UtcNow) + { + // + // Remove Expired Client and Tools ... + if (clients.TryRemove(key, out var old)) + { + // + try + { + await old.DisposeAsync(); + } + catch { } + } + + // + tools.TryRemove(key, out _); + clientExpirations.TryRemove(key, out _); + } + + // + if (clients.ContainsKey(key)) + { + continue; + } + + // + await initLock.WaitAsync(cancellationToken); + try + { + // + if (!clients.ContainsKey(key)) + { + // + await ConnectAndValidateAsync( + descriptor: server, + userInfo: userInfo, + cancellationToken: cancellationToken + ); + } + } + finally + { + initLock.Release(); + } + } + + // + // Extract User Specified Mcp Client Tools ... + var result = tools + .Where(kv => kv.Key.UserId == userInfo.UserId) + .SelectMany(kv => kv.Value) + .ToList(); + + // + return result; + } + + /// + /// Test Specified Mcp Server ... + /// + /// + /// + /// + /// + /// + public async Task TestServerAsync( + XAiMcpServerDto server, + string connectionId = null, + XUserClaimsInfoDto userInfo = null, + CancellationToken cancellationToken = default + ) + { + // + try + { + // + using var cts = CancellationTokenSource.CreateLinkedTokenSource(cancellationToken); + cts.CancelAfter(TimeSpan.FromSeconds(server.TimeoutSeconds)); + + // + var client = CreateClientAsync(server, connectionId, userInfo); + // await client.PingAsync(cancellationToken: cts.Token); + var serverTools = await client.ListToolsAsync(cancellationToken: cts.Token); + + // + var names = string.Join(", ", serverTools.Select(t => t.Name)); + return $"✓ Server: '{server.Name}' is Ready to Use, {serverTools.Count} Tools: {names}"; + } + catch (Exception ex) + { + // + return $"✗ Error: {ex.Message} ..."; + } + } + + /// + /// Force Refresh Mcp Servers ... + /// + /// + /// + /// + public async Task RefreshAsync( + XUserClaimsInfoDto userInfo = null, + CancellationToken cancellationToken = default + ) + { + // + if (!userInfo.IsAdmin()) + { + XException.NotAllowed.Throw(); + } + + // + logger.LogInformation("MCP: Reinitialize Mcp Servers ..."); + foreach (var client in clients.Values) + { + try + { + await client.DisposeAsync(); + } + catch { } + } + tools.Clear(); + clients.Clear(); + mcpServers.Clear(); + + // + isInitialized = false; + await GetAvailableToolsAsync( + userInfo: userInfo, + cancellationToken: cancellationToken + ); + } + #endregion + + // + #region Actions ... + /// + /// 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 + { + // + mcpServers[result.Id] = result; + await ConnectAndValidateAsync(result, connectionId, userInfo); + } + 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 + { + // + mcpServers[result.Id] = result; + + // + // Remove Exists ... + var keysToRemove = clients.Keys + .Where(k => k.ServerId == result.Id) + .ToList(); + foreach (var key in keysToRemove) + { + // + if (clients.TryRemove(key, out var old)) + { + try + { + await old.DisposeAsync(); + } + catch { } + } + tools.TryRemove(key, out _); + } + + // + // Reconnect ... + await ConnectAndValidateAsync(result, connectionId, userInfo, cancellationToken); + } + finally + { + initLock.Release(); + } + } + + // + return result; + } + + /// + /// 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 Server Descriptor ... + mcpServers.TryRemove(result.Id, out _); + + // + // Disconnect all Connections ... + var keysToRemove = clients.Keys + .Where(k => k.ServerId == result.Id) + .ToList(); + foreach (var key in keysToRemove) + { + // + if (clients.TryRemove(key, out var c)) + { + // + try + { + await c.DisposeAsync(); + } + catch { } + } + + // + tools.TryRemove(key, out _); + } + } + finally + { + initLock.Release(); + } + } + + // + return result; + } + + /// + /// 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 Server Descriptor ... + mcpServers.TryRemove(exists.Id, out _); + + // + // Disconnect all Connections ... + var keysToRemove = clients.Keys + .Where(k => k.ServerId == exists.Id) + .ToList(); + foreach (var key in keysToRemove) + { + // + if (clients.TryRemove(key, out var c)) + { + // + try + { + await c.DisposeAsync(); + } + catch { } + } + + // + tools.TryRemove(key, out _); + } + } + finally + { + initLock.Release(); + } + } + + // + return result; + } + + /// + /// 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 + { + // + mcpServers[exists.Id] = exists; + await ConnectAndValidateAsync(exists, connectionId, userInfo, 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) + { + // + mcpServers[exists.Id] = exists; + await ConnectAndValidateAsync(exists, connectionId, userInfo, cancellationToken); + } + else + { + // + // Remove Server Descriptor ... + mcpServers.TryRemove(exists.Id, out _); + + // + // Disconnect all Connections ... + var keysToRemove = clients.Keys + .Where(k => k.ServerId == exists.Id) + .ToList(); + foreach (var key in keysToRemove) + { + // + if (clients.TryRemove(key, out var c)) + { + // + try + { + await c.DisposeAsync(); + } + catch { } + } + + // + tools.TryRemove(key, out _); + } + } + } + finally + { + initLock.Release(); + } + } + + // + return result; + } + + /// + /// 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 XAiMcpClient CreateClientAsync( + XAiMcpServerDto descriptor, + string connectionId = null, + XUserClaimsInfoDto userInfo = null + ) + { + // + var result = new XAiMcpClient( + logger: logger, + userInfo: userInfo, + transport: mcpTransport, + serverId: descriptor.Id, + sessionStore: sessionStore, + connectionId: connectionId, + appConfiguration: configuration, + endpoint: new Uri(descriptor.Endpoint) + ); + + // + return result; + } + + private async Task ConnectAndValidateAsync( + XAiMcpServerDto descriptor, + string connectionId = null, + XUserClaimsInfoDto userInfo = null, + CancellationToken cancellationToken = default + ) + { + // + try + { + // + // Create Specified Cancellation Token ... + using var cts = CancellationTokenSource + .CreateLinkedTokenSource(cancellationToken); + cts.CancelAfter(TimeSpan.FromSeconds(descriptor.TimeoutSeconds)); + + // + var client = CreateClientAsync( + userInfo: userInfo, + descriptor: descriptor, + connectionId: connectionId + ); + + // + await client.InitializeAsync(cts.Token); + + // + var clientTools = await client.ListToolsAsync(cts.Token); + var aiTools = clientTools.ToAITools(client); + + // + // Key for Cache ... + var key = (descriptor.Id, userInfo.UserId); + + // + tools[key] = aiTools; + clients[key] = client; + mcpServers[descriptor.Id] = descriptor; + clientExpirations[key] = DateTime.UtcNow.AddMinutes(15); + + // + logger.LogInformation( + "MCP '{Name}': {Count} Tools Detected for {UserId} ...", + descriptor.Name, + aiTools.Count, + userInfo.UserId + ); + } catch(Exception ex) + { + // + logger.LogWarning(ex, + "MCP '{Name}': Connection Established Failed, Ignored ...", + descriptor.Name + ); + } + } + + private async Task EnsureServersLoadedAsync(CancellationToken cancellationToken) + { + // + if (isInitialized) + { + return; + } + + // + await initLock.WaitAsync(cancellationToken); + try + { + // + if (isInitialized) + { + return; + } + + // + var servers = await mcpServerServiceProvider.FindManyAsync( + orderBuilder: null, + includeBuilder: null, + ignoreSoftDeleteds: true, + predicate: x => x.Enabled, + cancellationToken: cancellationToken + ); + + // + if (servers.HasChild()) + { + // + foreach (var s in servers) + { + // + mcpServers[s.Id] = s; + } + } + + // + isInitialized = true; + } + finally + { + initLock.Release(); + } + } + #endregion + + // + #region Hub Actions ... + /// + /// 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 System.Text; +using xModels.Dtos; +using xAiApi.Models; +using System.Threading; +using xAiApi.Constants; +using xAiModels.Models; +using TimeZoneConverter; +using xAiApi.Interfaces; +using xAiApi.Extensions; +using xCommons.Providers; +using xCommons.Extensions; +using xAiModels.Constants; +using xAiModels.Interfaces; +using xAiModels.Extensions; +using System.Globalization; +using xAiApi.Configurations; +using xExceptions.Constants; +using xAiModels.Models.Dtos; +using xAiService.Extensions; +using System.Threading.Tasks; +using xIdentityModels.Models; +using Microsoft.Extensions.AI; +using Microsoft.AspNetCore.Http; +using System.Collections.Generic; +using Microsoft.Extensions.Logging; +using xAiApi.Interfaces.Extractors; +using System.Runtime.CompilerServices; + +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]; + } + + // + 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, + additionalContents: null, + addFilesToKnowledge: false, + resolveConversation: false, + extractFileContents: false, + cancellationToken: cancellationToken + ); + + // + using var client = Descriptor.GetClient(); + + // + // Handle Provided MCP Servers ... + if (useProvidedMcpServers) + { + // + var availableTools = await mcpServerProvider + .GetAvailableToolsAsync( + userInfo: userInfo, + cancellationToken: cancellationToken + ); + + // + Options.Tools = [.. availableTools.Cast()]; + } + + // + 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, + additionalContents: null, + resolveConversation: false, + addFilesToKnowledge: false, + extractFileContents: false, + cancellationToken: cancellationToken + ); + + // + using var client = Descriptor.GetClient(); + + // + // Handle Provided MCP Servers ... + if (useProvidedMcpServers) + { + // + var availableTools = await mcpServerProvider + .GetAvailableToolsAsync( + userInfo: userInfo, + cancellationToken: cancellationToken + ); + + // + Options.Tools = [.. availableTools.Cast()]; + } + + // + 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, + bool extractFileContents = false, + bool addFilesToKnowledge = true, + IFormFileCollection files = null, + XUserClaimsInfoDto userInfo = null, + CancellationToken cancellationToken = default + ) + { + // + // Validate Args ... + validationProvider + .GroupValidationBuilder() + .AddNotEmpty(prompt) + .AddNotNull(userInfo) + .AddNotEmpty(userInfo.UserId) + .ValidateGroup(); + + // + var prep = await PrepareChatRequirementsAsync( + type: type, + topK: topK, + files: files, + prompt: prompt, + minScore: minScore, + userInfo: userInfo, + persistPrompt: true, + projectId: projectId, + additionalContents: null, + resolveConversation: true, + connectionId: connectionId, + conversationId: conversationId, + cancellationToken: cancellationToken, + extractFileContents: extractFileContents, + addFilesToKnowledge: addFilesToKnowledge + ); + + // + using var client = Descriptor.GetClient(); + + // + // Handle Provided MCP Servers ... + if (useProvidedMcpServers) + { + // + var availableTools = await mcpServerProvider + .GetAvailableToolsAsync( + userInfo: userInfo, + cancellationToken: cancellationToken + ); + + // + Options.Tools = [.. availableTools.Cast()]; + } + + // + 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, + bool extractFileContents = false, + bool addFilesToKnowledge = true, + IFormFileCollection files = null, + XUserClaimsInfoDto userInfo = null, + [EnumeratorCancellation] + CancellationToken cancellationToken = default + ) + { + // + // Validate Args ... + validationProvider + .GroupValidationBuilder() + .AddNotEmpty(prompt) + .AddNotNull(userInfo) + .AddNotEmpty(userInfo.UserId) + .ValidateGroup(); + + // + var prep = await PrepareChatRequirementsAsync( + type: type, + topK: topK, + files: files, + prompt: prompt, + minScore: minScore, + userInfo: userInfo, + persistPrompt: true, + projectId: projectId, + additionalContents: null, + resolveConversation: true, + connectionId: connectionId, + conversationId: conversationId, + cancellationToken: cancellationToken, + extractFileContents: extractFileContents, + addFilesToKnowledge: addFilesToKnowledge + ); + + // + using var client = Descriptor.GetClient(); + + // + // Handle Provided MCP Servers ... + if (useProvidedMcpServers) + { + // + var availableTools = await mcpServerProvider + .GetAvailableToolsAsync( + userInfo: userInfo, + cancellationToken: cancellationToken + ); + + // + Options.Tools = [.. availableTools.Cast()]; + } + + // + 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, + ]; + + // + // Prepare Datetime ... + var datetimeContext = BuildDateTimeContext(); + if (!datetimeContext.IsNullOrEmpty()) + { + // + result.Add(new ChatMessage( + ChatRole.Assistant, + datetimeContext + )); + } + + // + if (forcePrompt && + prompt is not null && + !prompt.IsNullOrEmpty()) + { + result.Add(promptMessage); + } + + // + return result; + } + + /// + /// 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 datetimeContext = BuildDateTimeContext(); + var contextBlock = BuildContextBlock(context); + var systemText = introductionPrompt; + if (context.HasChild() && + !contextBlock.IsNullOrEmpty() + ) + { + // + systemText = + $"{introductionPrompt}{Environment.NewLine}{Environment.NewLine}"; + + // + if (!datetimeContext.IsNullOrEmpty()) + { + // + systemText += $"{datetimeContext}{Environment.NewLine}{Environment.NewLine}"; + } + + // + systemText += + $"{ragPrompt}{Environment.NewLine}{Environment.NewLine}" + + $"Context:{Environment.NewLine}{contextBlock}"; + } + + // + List 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}"; + } + + // + // Prepare Datetime ... + var datetimeContext = BuildDateTimeContext(); + if (!datetimeContext.IsNullOrEmpty()) + { + // + systemText += + $"{datetimeContext}{Environment.NewLine}{Environment.NewLine}"; + } + + // + // Apply Project Prompt as System Text ... + if (!project.IsNullOrDefault() && + !project.Prompt.IsNullOrEmpty()) + { + systemText += $"{project.Prompt}{Environment.NewLine}{Environment.NewLine}"; + } + + // + // Add System Message ... + result.Add(new ChatMessage(ChatRole.System, systemText)); + + // + // Attach Message ... + if (messages.HasChild()) + { + // + // TODO: Here we can Implement Memory Management based on + // Last nth of Messages, or Summarization of Messages, etc ... + result = [..result, ..messages + .OrderBy(m => m.CreatedOn) + .Select(m => m.ToChatMessages())]; + } + + // + return result; + } + + /// + /// 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, + bool extractFileContents = true, + bool addFilesToKnowledge = false, + 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 && + addFilesToKnowledge + ) + { + // + try + { + // + var ingestResult = await ragProvider + .IngestAsync( + files: files, + userInfo: userInfo, + replaceExisting: true, + connectionId: connectionId, + scope: XAiKnowledgeScopeDescriptor + .Conversation( + type: type, + conversationId: conversationId.Value + ), + cancellationToken: cancellationToken + ); + if (ingestResult.SkippedFiles.HasChild()) + { + // + logger.LogWarning( + "Ingest skipped {Count} file(s): {Files}", + ingestResult.SkippedFiles.Count, + string.Join(", ", ingestResult.SkippedFiles)); + } + } + catch (OperationCanceledException) + { + throw; + } + catch (Exception ex) + { + // + logger.LogError(ex, + "Ingest failed for prompt '{Prompt}'. Continuing without attachments.", + prompt + ); + } + } + + // + // If there isn't Files need to add Files to Knowledge ... + if (files.HasChild() && + !addFilesToKnowledge + ) + { + // + // Extract File Content and add them to Additional Contents ... + foreach (var file in files) + { + // + var mimeType = file.ContentType?.ToLowerInvariant() ?? string.Empty; + if (mimeType.IsNullOrEmpty() || + !fileContentExtractor.CanExtract(mimeType)) + { + continue; + } + + // + using var stream = file.OpenReadStream(); + + // + // Extract File Content if necessary ... + if (extractFileContents) + { + // + var content = await fileContentExtractor.ExtractAsync( + fileStream: stream, + mimeType: mimeType, + cancellationToken: cancellationToken + ); + if (!content.IsNullOrEmpty()) + { + // + var fileContent = new TextContent($"File:{Environment.NewLine}{file.FileName}{Environment.NewLine}{content}"); + additionalContents = [.. additionalContents, fileContent]; + } + } + else + { + // + var fileContent = await DataContent.LoadFromAsync(stream, mimeType, cancellationToken); + additionalContents = [.. additionalContents, fileContent]; + } + } + } + + // + // Request Knowledge ... + var knowledgeRequest = new XAiKnowledgeAskRequest + { + TopK = topK, + Type = type, + Prompt = prompt, + IncludeUser = true, + MinScore = minScore, + IncludeGlobal = true, + ProjectId = resolveConversation ? projectId : null, + ConversationId = resolveConversation ? conversationId : null, + }; + var context = await ragProvider + .RetrieveAsync( + userInfo: userInfo, + request: knowledgeRequest, + cancellationToken: cancellationToken + ); + + // + // Prepare History and Persisted Prompt Message ... + IList history; + XAiMessageDto persistedPromptMessage = null; + if (persistPrompt) + { + // + // Retrieve Conversation Message ... + var messages = await dataProvider + .LoadMessages( + conversationId: conversationId.Value, + cancellationToken: cancellationToken + ); + + // + // Prepare History based on Memory Strategies ... + history = await PrepareMemory( + context: context, + project: project, + messages: messages, + cancellationToken: cancellationToken + ); + + // + // Persist Prompt Message ... + persistedPromptMessage = await dataProvider.AddMessage( + item: new XAiMessageDto + { + Content = prompt, + Role = XAiChatRole.User, + OwnerId = userInfo.UserId, + CreatedOn = DateTime.UtcNow, + ConversationId = conversationId.Value, + ConversationTitle = conversation.Title, + }, + connectionId: connectionId, + conversationId: conversationId.Value, + cancellationToken: cancellationToken + ); + + // + history + .Add(persistedPromptMessage + .ToChatMessages(additionalContents: additionalContents)); + } + else + { + // + history = GetHistory(prompt, context); + } + + // + // Prepare Result ... + var result = new XPreparedChatContext + { + Project = project, + Context = context, + History = history, + Conversation = conversation, + PersistedPromptMessage = persistedPromptMessage, + }; + + // + return result; + } + + private string BuildDateTimeContext() + { + // + var cfg = configuration.DateTime; + if (cfg == null || !cfg.InjectIntoSystemPrompt) + { + return string.Empty; + } + + // + try + { + // + var tz = ResolveTimezone(cfg.DefaultTimezone); + var nowUtc = DateTime.UtcNow; + var nowLocal = TimeZoneInfo.ConvertTimeFromUtc(nowUtc, tz); + + // + var sb = new StringBuilder(); + sb.AppendLine("[CURRENT DATETIME — for your reference]"); + sb.AppendLine($"Now (local, {tz.Id}): {nowLocal.ToString(cfg.GregorianFormat)}"); + + // + if (cfg.IncludeDayOfWeek) + { + sb.AppendLine($"Day of week: {nowLocal:dddd}"); + } + + // + if (cfg.IncludePersianCalendar) + { + // + var pc = new PersianCalendar(); + sb.AppendLine($"Now (Persian): {pc.GetYear(nowLocal):D4}/{pc.GetMonth(nowLocal):D2}/{pc.GetDayOfMonth(nowLocal):D2} {nowLocal:HH:mm:ss}"); + } + + // + if (cfg.IncludeUnixTimestamp) + { + sb.AppendLine($"Unix timestamp: {new DateTimeOffset(nowUtc).ToUnixTimeSeconds()}"); + } + + // + sb.AppendLine("Use this information when the user asks about 'today', 'now', 'this week', relative dates, or any time-sensitive calculations."); + return sb.ToString().TrimEnd(); + } + catch + { + return string.Empty; + } + } + + private static TimeZoneInfo ResolveTimezone(string id) + { + // + if (id.IsNullOrEmpty()) + { + return TimeZoneInfo.Utc; + } + + // + try + { + return TZConvert.GetTimeZoneInfo(id); + } + catch + { + return TimeZoneInfo.Utc; + } + } + #endregion + } +} + +### FILE: C:\Users\SaherElm\Documents\Projects\xSaherelmWorkspace\xAiApi\Providers\XDefaultThinkingAiService.cs + +using xAiApi.Constants; +using xAiApi.Interfaces; +using xCommons.Providers; +using xAiModels.Interfaces; +using xAiApi.Configurations; +using Microsoft.Extensions.AI; +using Microsoft.Extensions.Logging; +using xAiApi.Interfaces.Extractors; + +namespace xAiApi.Providers +{ + public class XDefaultThinkingAiService : XAIServiceBase, IXDefaultThinkingAiService + { + public XDefaultThinkingAiService( + IXAiRAGService ragProvider, + IXAiDataProvider dataProvider, + ILogger 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 + } +} + +### FILE: C:\Users\SaherElm\Documents\Projects\xSaherelmWorkspace\xAiApi\wwwroot\Storage\Uploads\Document\xSaherElm_1eae10b8-fd2b-47c7-ac62-5e0e8a818d71.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\SaherElm\Documents\Projects\xSaherelmWorkspace\xAiApi\wwwroot\Storage\Uploads\Document\xSaherElm_3ce5da7a-64c5-4be6-821f-3fe682ca9325.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\SaherElm\Documents\Projects\xSaherelmWorkspace\xAiApi\wwwroot\Storage\Uploads\Document\xSaherElm_3ecc8143-78a9-43e1-9aea-b6e43064d97a.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\SaherElm\Documents\Projects\xSaherelmWorkspace\xAiApi\wwwroot\Storage\Uploads\Document\xSaherElm_49d1c98f-006e-41bf-9ed1-e954f69d13a7.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\SaherElm\Documents\Projects\xSaherelmWorkspace\xAiApi\wwwroot\Storage\Uploads\Document\xSaherElm_690cab6f-a6f3-4605-b5fc-86912f27e95a.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\SaherElm\Documents\Projects\xSaherelmWorkspace\xAiApi\wwwroot\Storage\Uploads\Document\xSaherElm_842b3cfe-806f-4622-a77f-2daafaabd7c0.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\SaherElm\Documents\Projects\xSaherelmWorkspace\xAiApi\wwwroot\Storage\Uploads\Document\xSaherElm_902b0fc0-92aa-4c7d-86cc-7344253b198b.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\SaherElm\Documents\Projects\xSaherelmWorkspace\xAiApi\wwwroot\Storage\Uploads\Document\xSaherElm_a58f8782-e77e-4847-90b8-bb589fb956ca.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\SaherElm\Documents\Projects\xSaherelmWorkspace\xAiApi\wwwroot\Storage\Uploads\Document\xSaherElm_b1ff7368-ac62-4b3f-9d42-c1d8f8af638e.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\SaherElm\Documents\Projects\xSaherelmWorkspace\xAiApi\wwwroot\Storage\Uploads\Document\xSaherElm_e5fd1873-0a07-4384-9efb-3d8aa9613254.html + + + + + + +مستند فرآیند انتشار و استقرار نرم‌افزار | رایان پرداز کاوش + + + + + +
    +
    +
    +
    + +
    +
    رایان پرداز کاوش
    +
    Rayan Pardaz Kavosh
    +
    +
    +
    +
    شماره مستند: REL-PROC-1405-002
    +
    نسخه: ۲.۰.۰ بروزرسانی شده
    +
    تاریخ تهیه: ۲۱ مهر ۱۴۰۵
    +
    تهیه‌کننده: هادی خزاعی اصل
    +
    طبقه‌بندی: محرمانه
    +
    +
    +
    +RELEASE MANAGEMENT PROCESS +

    مستند فرآیند انتشار و استقرار نرم‌افزار

    +

    تشریح گام‌به‌گام چرخه استقرار از Develop تا محیط عملیاتی آبی (نسخه بروزرسانی‌شده)

    +
    +
    + +
    +
    +مخاطبان محترم،
    +این مستند به‌عنوان مرجع رسمی فرآیند انتشار نرم‌افزار در شرکت رایان پرداز کاوش تهیه شده است (نسخه ۲.۰.۰ - بروزرسانی‌شده در ۲۱ مهر ۱۴۰۵). هدف از تدوین این سند، ایجاد زبان مشترک میان تمامی ذینفعان (تیم توسعه، PO، QA، DevOps، DBA و مدیر انتشار) و تضمین اجرای یکپارچه، قابل ردیابی و استاندارد فرآیند استقرار در محیط‌های مختلف (Develop، QA، PreRelease، قرمز و آبی) می‌باشد. در این نسخه، مرحله انتقال به محیط آبی با جزئیات دقیق‌تری شامل ریویو اسکریپت‌های پایگاه داده، ثبت تیکت‌های مجوز و منوهای سوپر وب بازنویسی شده است. +
    + + +
    +
    +
    ۱
    +
    +

    تعاریف و اصطلاحات کلیدی

    +
    Definitions & Key Terms
    +
    +
    +
    + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
    عبارتتعریف
    تیم توسعهگروهی از توسعه‌دهندگان که بر طراحی و پیاده‌سازی یک محصول متمرکز هستند.
    تک لید (Tech Lead)فردی که تیم توسعه را رهبری می‌کند و مسئول کد ریویو و تایید فعالیت‌های تیم توسعه است.
    PO (مدیر محصول)مدیر محصول که تیم تحلیل و توسعه را در راستای تولید محصول مدیریت می‌کند.
    DevOpsتیمی که فرآیند توزیع و انتشار محصولات را انجام می‌دهد.
    محصول (Product)مجموعه‌ای از یک یا چند مولفه که در تیم‌های مختلف بر اساس نیازمندی‌های اعلام‌شده توسط PO تولید می‌شود.
    تیم پایگاه داده (DBA)به دلیل Db First بودن محیط‌های استقرار و عملیاتی کارفرما، وظیفه آماده‌سازی پایگاه داده را برعهده دارد.
    مدیر انتشار (Release Manager)فردی که مدیریت کل فرآیند انتشار را برعهده دارد و بر کلیه مراحل نظارت می‌کند.
    محیط عملیاتیفضایی که نرم‌افزار به‌همراه تمام نیازمندی‌های عملیاتی در آن استقرار می‌یابد.
    ریلیز نوت داخلیگزارش نسخه ارائه‌شده مطابق با قالب Internal Release Note.
    ریلیز نوت خارجیگزارش نسخه ارائه‌شده مطابق با قالب External Release Note.
    DOR (Definition of Ready)معیارهای آمادگی که قبل از انتقال به محیط عملیاتی باید برآورده شوند.
    Smoke Testتست سلامت اولیه برای اطمینان از عملکرد صحیح مولفه‌های کلیدی پس از استقرار.
    فرآیند انتشارتوالی مراحلی که در چرخه استقرار نرم‌افزار طی می‌شود تا محصول در یک یا چند محیط عملیاتی استقرار یابد.
    +
    +
    + + +
    +
    +
    ۲
    +
    +

    نمودار BPMN فرآیند انتشار

    +
    BPMN Process Diagram (نسخه ۲.۰.۰)
    +
    +
    +
    +

    نمودار زیر فرآیند کامل انتشار را از ثبت درخواست تا استقرار نهایی در محیط آبی نشان می‌دهد. در این نسخه، مرحله ۶ (انتقال به محیط آبی) با جزئیات دقیق‌تری بازنویسی شده است:

    +
    +
    +flowchart TD + %% ===== POOL: تیم توسعه ===== + subgraph DEV["🏢 تیم توسعه (Development Team)"] + D1["ثبت درخواست استقرار
    توسط Tech Lead"] + D2{"بررسی توسط
    Release Manager"} + D3["ریجکت درخواست
    و بازگشت به Tech Lead"] + D4["پیوست وابستگی‌ها
    و صدور فرمان انتشار"] + end + + %% ===== POOL: خط لوله استقرار ===== + subgraph PIPE["⚙️ Deployment Pipeline"] + P1{"تغییر DB
    وجود دارد؟"} + P2["همگام‌سازی پایگاه داده"] + P3{"وابستگی جدید
    یا نیاز به بروزرسانی؟"} + P4["انتشار وابستگی‌ها"] + P5["بررسی کیفیت کد
    با SonarQube"] + P6["اعلام خطا
    بدون توقف فرآیند"] + P7["بید کردن
    Pull Request ها"] + P8["اجرای پادهای بیلد شده"] + P9["ایجاد فهرست
    آدرس پادها"] + end + + %% ===== POOL: تضمین کیفیت ===== + subgraph QA["🔍 تضمین کیفیت (QA/Security/UAT/DevOps)"] + Q1["اجرای تست‌های
    موازی تیم‌ها"] + Q2{"نتیجه تست‌ها"} + Q3["تایید / ریجکت
    با گزارش خطا"] + Q4{"PO ریسک
    را می‌پذیرد؟"} + Q5["انتقال به PreRelease
    با قبول مخاطرات"] + Q6["بازگشت خطاها
    به مرحله ۱ (HotFix)"] + Q7["تایید نهایی
    Release Manager"] + end + + %% ===== POOL: محیط پیش از انتشار ===== + subgraph PRE["🧊 محیط PreRelease (فریز شده)"] + R1["لیست پادهای منتقل شده"] + R2{"تمام مولفه‌های
    محصول فریز شدند؟"} + R3["فریز محصول
    و آماده‌سازی برای دمو"] + end + + %% ===== POOL: محیط قرمز ===== + subgraph RED["🔴 محیط قرمز (Red Environment)"] + E1["ثبت درخواست انتقال
    توسط PO به Release Manager"] + E2{"بررسی درخواست
    توسط Release Manager"} + E3["ریجکت و بازگشت
    به PreRelease"] + E4["پیوست وابستگی‌ها
    و شروع اکشن پلن"] + E5{"تغییر DB
    در محیط قرمز؟"} + E6["اجرای تغییرات DB
    و اطمینان از صحت"] + E7{"وابستگی نیاز
    به بروزرسانی دارد؟"} + E8["انتشار موازی وابستگی‌ها"] + E9["بیلد و اجرای پادها"] + E10["تست Smoke
    توسط تیم تحلیل"] + E11{"تایید PO
    از تست Smoke؟"} + E12["گردآوری فهرست
    پادهای محصول"] + end + + %% ===== POOL: محیط آبی ===== + subgraph BLUE["🔵 محیط آبی (Blue Environment)"] + B1["ثبت درخواست انتقال
    توسط PO"] + B2{"بررسی درخواست
    توسط Release Manager"} + B3["ریجکت و بازگشت
    به محیط قرمز"] + B4["پیوست وابستگی‌ها
    و شروع اکشن پلن"] + B5{"تغییر DB
    در محیط آبی؟"} + B6["ریویو اسکریپت DB
    توسط تک لید DBA با PO"] + B7{"اسکریپت کامل است؟
    (View, Table, ...)"} + B8["ثبت تیکت اجرای
    اسکریپت DB در محیط هدف"] + B9["اجرای تغییرات DB
    و اطمینان از صحت"] + B10{"وابستگی نیاز
    به بروزرسانی دارد؟"} + B11["انتشار موازی وابستگی‌ها"] + B12{"سرویس فاقد
    مجوز اجرا در محیط هدف؟"} + B13["ثبت تیکت دریافت
    مجوز دسترسی توسط PO"] + B14["انتقال پادها از قرمز به آبی
    + تست سلامت پادها"] + B15{"نیاز به اضافه کردن
    گزینه در منوهای سوپر وب؟"} + B16["ثبت تیکت منوهای
    سوپر وب توسط PO"] + B17["تست Smoke
    توسط تیم تحلیل"] + B18{"تایید PO
    از تست Smoke؟"} + B19["پاکسازی اطلاعات تستی
    و پایگاه داده"] + B20["گردآوری فهرست
    پادهای محصول"] + end + + %% ===== EVENTS ===== + START(("🟢 شروع")) + END(("🏁 پایان")) + + %% ===== FLOWS ===== + START --> D1 + D1 --> D2 + D2 -->|نقص دارد| D3 + D3 --> D1 + D2 -->|کامل است| D4 + D4 --> P1 + + P1 -->|بله| P2 + P1 -->|خیر| P3 + P2 --> P3 + P3 -->|بله| P4 + P3 -->|خیر| P5 + P4 --> P5 + P5 --> P6 + P5 --> P7 + P6 --> P7 + P7 --> P8 + P8 --> P9 + P9 --> Q1 + + Q1 --> Q2 + Q2 -->|تایید| Q7 + Q2 -->|ریجکت| Q6 + Q2 -->|در انتظار| Q4 + Q4 -->|بله| Q5 + Q4 -->|خیر| Q6 + Q5 --> Q7 + Q6 --> D1 + Q7 --> R1 + + R1 --> R2 + R2 -->|بله| R3 + R2 -->|خیر| R1 + R3 --> E1 + + E1 --> E2 + E2 -->|ریجکت| E3 + E3 --> R1 + E2 -->|قبول| E4 + E4 --> E5 + E5 -->|بله| E6 + E5 -->|خیر| E7 + E6 --> E7 + E7 -->|بله| E8 + E7 -->|خیر| E9 + E8 --> E9 + E9 --> E10 + E10 --> E11 + E11 -->|بله| E12 + E11 -->|خیر| E9 + E12 --> B1 + + B1 --> B2 + B2 -->|ریجکت| B3 + B3 --> E12 + B2 -->|قبول| B4 + B4 --> B5 + B5 -->|بله| B6 + B5 -->|خیر| B10 + B6 --> B7 + B7 -->|بله| B8 + B7 -->|خیر| B6 + B8 --> B9 + B9 --> B10 + B10 -->|بله| B11 + B10 -->|خیر| B12 + B11 --> B12 + B12 -->|بله| B13 + B12 -->|خیر| B14 + B13 --> B14 + B14 --> B15 + B15 -->|بله| B16 + B15 -->|خیر| B17 + B16 --> B17 + B17 --> B18 + B18 -->|بله| B19 + B18 -->|خیر| B14 + B19 --> B20 + B20 --> END +
    +
    +
    +💡 راهنمای نمودار: دایره‌ها = رویدادها | مستطیل‌های گرد = فعالیت‌ها | لوزی‌ها = تصمیم‌گیری‌ها (Gateways) | فلش‌ها = جریان توالی | در نسخه ۲.۰.۰، محیط آبی با ۱۰ گیت تصمیم‌گیری و ۱۰ فعالیت جدید بازنویسی شده است. +
    +
    +🔄 تغییرات کلیدی نسخه ۲.۰.۰: +
      +
    • افزوده شدن ریویو اسکریپت‌های پایگاه داده توسط تک لید DBA با PO
    • +
    • ثبت تیکت‌های جداگانه برای اجرای اسکریپت در محیط هدف
    • +
    • فرآیند دریافت مجوز دسترسی برای سرویس‌های فاقد مجوز
    • +
    • تست سلامت پادها پس از انتقال از قرمز به آبی
    • +
    • ثبت تیکت برای منوهای سوپر وب در صورت نیاز
    • +
    +
    +
    +
    + + +
    +
    +
    ۳
    +
    +

    تشریح گام‌به‌گام فرآیند انتشار

    +
    Step-by-Step Release Process
    +
    +
    +
    + + +
    +

    ۱ ثبت درخواست استقرار

    +

    +مجری: Tech Lead  |  مسئول تایید: Release Manager +

    +

    +تک لید پس از اتمام توسعه و تایید کدها، یک ایشو جهت استقرار از محیط Develop به QA برای مدیر انتشار ثبت می‌کند. این ایشو باید شامل موارد زیر باشد: +

    +
    +
    الزامات پیوست ایشو:
    +
      +
    • ریلیز نوت داخلی (Internal Release Note)
    • +
    • آدرس Pull Request های تایید شده توسط تک لید (به ازای هر مولفه وابسته)
    • +
    • تعیین نیاز به تغییر در پایگاه داده (بله/خیر)
    • +
    • نوع استقرار برای هر مولفه (HotFix یا Feature جدید)
    • +
    +
    +

    +بررسی توسط مدیر انتشار: +

    +
      +
    • در صورت وجود نقص → ریجکت و بازگشت به تک لید
    • +
    • در صورت کامل بودن → پیوست فهرست نیازمندی‌ها و وابستگی‌ها با هماهنگی تک لیدهای تیم‌های دیگر + صدور فرمان انتشار
    • +
    +
    + + +
    +

    ۲ خط لوله استقرار (Deployment Pipeline)

    +

    +مجری: DevOps + DBA  |  ناظر: Release Manager +

    +

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

    +
      +
    • ۲.۱ در صورت وجود تغییرات DB → همگام‌سازی پایگاه داده توسط تیم DBA
    • +
    • ۲.۲ بررسی وابستگی‌ها → اگر وابستگی جدیدی وجود دارد یا نیاز به بروزرسانی دارد، فرآیند انتشار برای آن انجام می‌شود
    • +
    • ۲.۳ بررسی کیفیت کد با SonarQube → خطاها فقط اعلام می‌شوند و فرآیند متوقف نمی‌شود
    • +
    • ۲.۴ بید کردن تک‌تک Pull Request ها
    • +
    • ۲.۵ اجرای پادهای بیلد شده
    • +
    • ۲.۶ ایجاد فهرست آدرس پادهای بیلد شده
    • +
    +
    +⚠️ نکته مهم: گزارش SonarQube در این مرحله صرفاً جهت آگاهی‌بخشی است و نباید به‌عنوان گیت توقف فرآیند عمل کند. تصمیم‌گیری در مورد رفع خطاها در مرحله QA انجام می‌شود. +
    +
    + + +
    +

    ۳ تضمین کیفیت (QA Phase)

    +

    +مجریان موازی: QA | Security | Analysis (UAT) | DevOps | DevSecOps +

    +

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

    +
    +
    تست‌های الزامی:
    +
      +
    • تست‌های عملکردی و رگرسیون (QA)
    • +
    • تست‌های امنیتی و آسیب‌پذیری (Security)
    • +
    • تست پذیرش کاربر (UAT) توسط تیم تحلیل
    • +
    • تست زیرساخت و پایداری (DevOps)
    • +
    • تست امنیت در چرخه توسعه (DevSecOps)
    • +
    +
    +
    +💡 اصل استقلال تیم‌ها: وجود گزارش خطا در یک تیم، نباید باعث وقفه در کار سایر تیم‌ها شود. هر تیم به‌صورت مستقل یکی از سه حالت زیر را اعلام می‌کند: +
      +
    • ✅ تایید
    • +
    • ❌ ریجکت + گزارش خطاها
    • +
    • ⏳ هنوز عملیات انجام نشده
    • +
    +
    +

    سناریوی پذیرش ریسک توسط PO:

    +

    +در صورت وجود محدودیت زمانی یا تجاری، PO می‌تواند با قبول مخاطرات، درخواست انتقال نسخه به محیط PreRelease را صادر کند. در این حالت: +

    +
      +
    • گزارش خطاها به مرحله ۱ بازگردانده می‌شوند
    • +
    • از طریق فرآیند HotFix به جریان انتشار بازمی‌گردند
    • +
    • فرآیند با تایید نهایی مدیر انتشار پایان می‌یابد
    • +
    +
    + + +
    +

    ۴ محیط پیش از انتشار (PreRelease)

    +

    +مجری: DevOps  |  بهره‌بردار: PO +

    +

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

    +
    +
    ویژگی‌های محیط PreRelease:
    +
      +
    • لیست پادهای منتقل‌شده از درخواست انتشار در دسترس است
    • +
    • محیط کاملاً ایزوله از تغییرات Develop و QA
    • +
    • امکان دمو و تست منطق تجاری توسط PO
    • +
    • فریز شدن محصول پس از قرارگیری تمام مولفه‌ها
    • +
    • قابلیت درخواست انتقال به محیط قرمز پس از فریز کامل
    • +
    +
    +
    +🎯 شرط انتقال به محیط قرمز: تمام مولفه‌های محصول باید در فهرست پادهای PreRelease قرار گرفته باشند تا محصول فریز شده و قابلیت انتقال به محیط قرمز را پیدا کند. +
    +
    + + +
    +

    ۵ انتقال به محیط قرمز (Red Environment)

    +

    +درخواست‌دهنده: PO  |  تاییدکننده: Release Manager +

    +

    ۵.۱ - ثبت درخواست انتقال توسط PO:

    +
    +
    الزامات درخواست:
    +
      +
    • ریلیز نوت خارجی (External Release Note)
    • +
    • تعیین مقاصد استقرار: سازمان، کانون یا هر دو
    • +
    • متغیرهای محیطی به تفکیک هر مولفه و مقصد استقرار
    • +
    • اعلام وجود یا عدم تغییر در پایگاه داده
    • +
    +
    +

    ۵.۲ - پیش‌نیازهای کیفی:

    +
      +
    • تاییدیه SonarQube، یا
    • +
    • قبول مخاطرات توسط PO + تعهد کتبی عدم ارائه نسخه به ناظر برای کد ریویو
    • +
    +

    ۵.۳ - اکشن پلن استقرار:

    +
      +
    • ۵.۳.۱ اجرای تغییرات DB (در صورت نیاز) + اطمینان از صحت در محیط‌های هدف
    • +
    • ۵.۳.۲ انتشار موازی وابستگی‌های نیازمند بروزرسانی + اطمینان از صحت عملکرد
    • +
    • ۵.۳.۳ بیلد مولفه‌ها و اجرای پادها
    • +
    • ۵.۳.۴ انجام تست Smoke توسط تیم تحلیل + کسب تایید PO
    • +
    • ۵.۳.۵ گردآوری فهرست پادهای محصول
    • +
    +
    +⚠️ در صورت ریجکت درخواست: فرآیند به محیط PreRelease باز می‌گردد و باید مجدداً درخواست اصلاح‌شده ثبت شود. +
    +
    + + +
    +

    ۶ انتقال از محیط قرمز به آبی (Blue Environment) بروزرسانی شده

    +

    +درخواست‌دهنده: PO  |  تاییدکننده: Release Manager  |  ناظر فنی DB: تک لید تیم پایگاه داده +

    +

    ۶.۱ - ثبت درخواست انتقال توسط PO:

    +
    +
    الزامات درخواست:
    +
      +
    • تعیین مقاصد استقرار: سازمان، کانون یا هر دو
    • +
    • متغیرهای محیطی به تفکیک هر مولفه و مقصد استقرار
    • +
    • اعلام وجود یا عدم تغییر در پایگاه داده
    • +
    • ارائه سناریوی تست Smoke + تعیین دقیق DOR (Definition of Ready)
    • +
    +
    +

    ۶.۲ - بررسی توسط مدیر انتشار:

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

    ۶.۳ - اکشن پلن استقرار (۱۰ زیرمرحله):

    +
      +
    • ۶.۳.۱ ریویو و چک‌تیک اسکریپت توسط تک لید تیم پایگاه داده با PO (در صورت وجود تغییرات DB) + اطمینان از کامل بودن اسکریپت شامل View ها، Table ها و سایر اشیاء
    • +
    • ۶.۳.۲ ثبت تیکت‌های لازم برای اجرای اسکریپت پایگاه داده در محیط هدف (در صورت نیاز)
    • +
    • ۶.۳.۳ اجرای تغییرات در پایگاه داده (در صورت نیاز) + کسب اطمینان از صحت پایگاه داده در محیط‌های هدف
    • +
    • ۶.۳.۴ چنانچه هر کدام از وابستگی‌های مشخص در محیط عملیاتی نیاز به بروزرسانی داشته باشد، فرآیند انتشار آنها به‌صورت موازی انجام شود + اطمینان از صحت عملکرد همه نیازمندی‌ها
    • +
    • ۶.۳.۵ چنانچه در وابستگی‌های مولفه‌های محصول، سرویسی وجود داشته باشد که فاقد مجوز اجرا در محیط هدف است، PO باید برای دریافت مجوز دسترسی ثبت تیکت نماید
    • +
    • ۶.۳.۶ انتقال پادها از قرمز به آبی + تست سلامت آن‌ها
    • +
    • ۶.۳.۷ چنانچه لازم است در منوهای سوپر وب گزینه‌ای اضافه شود، باید تیکت آن توسط PO ثبت شود
    • +
    • ۶.۳.۸ انجام تست Smoke توسط تیم تحلیل + کسب تایید PO
    • +
    • ۶.۳.۹ پاکسازی اطلاعات تستی و پایگاه داده در محیط هدف
    • +
    • ۶.۳.۱۰ گردآوری نهایی فهرست پادهای محصول
    • +
    +
    +💡 تغییرات کلیدی در مرحله ۶: +
      +
    • افزوده شدن ریویو دقیق اسکریپت‌های DB توسط تک لید DBA قبل از اجرا
    • +
    • ثبت تیکت رسمی برای اجرای اسکریپت‌ها در محیط عملیاتی
    • +
    • فرآیند شفاف برای دریافت مجوز سرویس‌های جدید
    • +
    • تست سلامت پادها بلافاصله پس از انتقال
    • +
    • مدیریت منوهای سوپر وب به‌عنوان یک فعالیت مستقل
    • +
    +
    +
    +✅ پایان فرآیند: پس از تکمیل مرحله ۶.۳.۱۰، محصول در محیط عملیاتی آبی به‌صورت پایدار مستقر شده و فرآیند انتشار با موفقیت پایان می‌یابد. +
    +
    + + +
    +

    ۷ پایان فرآیند انتشار

    +

    +پس از استقرار موفق در محیط آبی، مدیر انتشار مستندات زیر را بایگانی می‌کند: +

    +
      +
    • ایشوی اصلی درخواست انتشار
    • +
    • ریلیز نوت داخلی و خارجی
    • +
    • گزارش‌های تست تیم‌های مختلف
    • +
    • فهرست نهایی پادهای مستقر شده
    • +
    • گزارش تغییرات پایگاه داده + تیکت‌های اجرا شده
    • +
    • تیکت‌های مجوز دسترسی و منوهای سوپر وب
    • +
    +
    + +
    +
    + + +
    +
    +
    ۴
    +
    +

    ماتریس مسئولیت‌ها (RACI)

    +
    Responsibility Assignment Matrix
    +
    +
    +
    + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
    مرحلهTech LeadPORelease MgrDevOpsQADBA
    ۱. ثبت درخواستRIAIII
    ۲. Deployment PipelineCIARIR
    ۳. تضمین کیفیتCAARRI
    ۴. PreReleaseIRARII
    ۵. محیط قرمزIRARRR
    ۶. محیط آبی (بروزرسانی شده)IRARRR (ریویو اسکریپت)
    +
    +راهنما: R = Responsible (مجری) | A = Accountable (مسئول نهایی) | C = Consulted (مشورت) | I = Informed (مطلع) +
    +
    +
    + + +
    +
    +
    ۵
    +
    +

    گیت‌های تصمیم‌گیری و معیارهای پذیرش

    +
    Decision Gates & Acceptance Criteria
    +
    +
    +
    + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
    گیتتصمیم‌گیرندهمعیار پذیرشدر صورت رد
    G1: بررسی ایشو اولیهRelease Managerکامل بودن مستندات پیوستبازگشت به Tech Lead
    G2: پایان QAتیم‌های QA/Security/UATتاییدیه تمام تیم‌ها یا پذیرش ریسک POبازگشت به مرحله ۱ (HotFix)
    G3: فریز PreReleaseRelease Managerقرارگیری تمام مولفه‌های محصولادامه استقرار مولفه‌های باقیمانده
    G4: ورود به محیط قرمزRelease Managerریلیز نوت خارجی + تایید SonarQube یا پذیرش ریسکبازگشت به PreRelease
    G5: تست Smoke قرمزPOتایید عملکرد صحیح سناریوهای کلیدیتکرار بیلد و اجرا
    G6: ورود به محیط آبیRelease Managerسناریوی Smoke + DOR مشخصبازگشت به محیط قرمز
    G7: ریویو اسکریپت DB (جدید)تک لید DBA + POکامل بودن اسکریپت (View، Table، ...)بازگشت به تیم توسعه برای اصلاح
    G8: مجوز سرویس‌ها (جدید)POدریافت مجوز برای سرویس‌های فاقد دسترسیتوقف تا دریافت مجوز
    G9: تست سلامت پادها (جدید)DevOpsسلامت تمام پادهای منتقل‌شدهتکرار انتقال یا Rollback
    G10: تایید نهایی آبی (جدید)POتایید Smoke + پاکسازی داده‌هاتکرار انتقال پادها
    +
    +🆕 گیت‌های جدید نسخه ۲.۰.۰: چهار گیت جدید (G7 تا G10) برای کنترل دقیق‌تر فرآیند انتقال به محیط آبی اضافه شده‌اند. +
    +
    +
    + + +
    +
    +
    ۶
    +
    +

    الزامات و بهترین روش‌ها

    +
    Best Practices & Requirements
    +
    +
    +
    +
    +✅ الزامات کلیدی: +
      +
    • تمامی Pull Request ها باید قبل از ثبت ایشو، توسط تک لید تایید شده باشند
    • +
    • ریلیز نوت داخلی و خارجی باید مطابق با قالب استاندارد شرکت باشند
    • +
    • هیچ تغییری در محیط عملیاتی بدون تایید Release Manager انجام نمی‌شود
    • +
    • تست‌های تیم‌های مختلف باید به‌صورت موازی و مستقل اجرا شوند
    • +
    • محیط PreRelease باید کاملاً ایزوله و فریز شده باشد
    • +
    • سناریوی تست Smoke و DOR باید قبل از انتقال به محیط آبی مشخص شوند
    • +
    • پاکسازی داده‌های تستی در محیط آبی الزامی است
    • +
    • (جدید) تمام اسکریپت‌های پایگاه داده باید قبل از اجرا توسط تک لید DBA ریویو شوند
    • +
    • (جدید) برای هر تغییر DB در محیط عملیاتی، تیکت رسمی ثبت شود
    • +
    • (جدید) مجوز دسترسی سرویس‌ها قبل از انتقال پادها دریافت شود
    • +
    • (جدید) سلامت پادها بلافاصله پس از انتقال تست شود
    • +
    +
    +
    +❌ ممنوعیت‌ها: +
      +
    • انتقال مستقیم از Develop به محیط‌های عملیاتی ممنوع است
    • +
    • استقرار بدون ریلیز نوت ممنوع است
    • +
    • تغییر در پایگاه داده عملیاتی بدون هماهنگی DBA و ریویو تک لید ممنوع است
    • +
    • اجرای اسکریپت DB بدون ثبت تیکت رسمی ممنوع است
    • +
    • پذیرش ریسک توسط PO بدون تعهد کتبی ممنوع است
    • +
    • انتقال پادها بدون تست سلامت ممنوع است
    • +
    +
    +
    +
    + + +
    +
    +
    ۷
    +
    +

    جمع‌بندی و نتیجه‌گیری

    +
    Conclusion
    +
    +
    +
    +
    +

    🎯 خلاصه فرآیند (نسخه ۲.۰.۰)

    +

    فرآیند انتشار نرم‌افزار در شرکت رایان پرداز کاوش، یک چرخه ۷ مرحله‌ای استاندارد است که از محیط توسعه آغاز و در محیط عملیاتی آبی پایان می‌یابد. این فرآیند با رعایت اصول BPMN، تفکیک واضح مسئولیت‌ها و ۱۰ گیت تصمیم‌گیری (که ۴ گیت در نسخه جدید اضافه شده‌اند)، کیفیت، امنیت و پایداری استقرار را تضمین می‌کند.

    +
    +💎 ارزش‌های کلیدی:
    +شفافیت در مسئولیت‌ها + ردیابی کامل تغییرات + کاهش ریسک عملیاتی + امکان Rollback سریع + انطباق با استانداردهای صنعتی + کنترل دقیق تغییرات پایگاه داده +
    +
    +
    +📞 گام بعدی: این مستند (نسخه ۲.۰.۰) پس از تایید نهایی، به‌عنوان مرجع رسمی فرآیند انتشار در شرکت رایان پرداز کاوش اجرا خواهد شد. کلیه تیم‌های ذینفع موظف به رعایت مفاد این سند می‌باشند. +
    +
    +
    + +
    +این مستند محرمانه بوده و صرفاً جهت استفاده داخلی شرکت رایان پرداز کاوش تهیه شده است. هرگونه کپی‌برداری یا افشا بدون اجازه کتبی ممنوع است. +
    +
    + +
    + + +
    شرکت رایان پرداز کاوش  |  تاریخ تهیه: ۲۱ مهر ۱۴۰۵  |  نسخه: ۲.۰.۰ (بروزرسانی شده)  |  طبقه‌بندی: محرمانه
    +
    +
    + + + + diff --git a/Documents/GeneratedContext/xDashboard-xAiMcpServer-20261108_143749.txt b/Documents/GeneratedContext/xDashboard-xAiMcpServer-20261108_223851.txt similarity index 96% rename from Documents/GeneratedContext/xDashboard-xAiMcpServer-20261108_143749.txt rename to Documents/GeneratedContext/xDashboard-xAiMcpServer-20261108_223851.txt index b256ea8..4037edd 100644 --- a/Documents/GeneratedContext/xDashboard-xAiMcpServer-20261108_143749.txt +++ b/Documents/GeneratedContext/xDashboard-xAiMcpServer-20261108_223851.txt @@ -1,5 +1,5 @@ -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\xAiMcpServer\Program.cs +### FILE: C:\Users\SaherElm\Documents\Projects\xSaherelmWorkspace\xAiMcpServer\Program.cs using System.Text; using Microsoft.AspNetCore.Hosting; @@ -33,7 +33,7 @@ namespace xAiMcpServer } } -### 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; @@ -41,6 +41,7 @@ using System.Net.Http; using xAiMcpServer.DI; using Newtonsoft.Json; using System.Reflection; +using xLoggingService.DI; using xIdentityService.DI; using xCommons.Extensions; using xAiService.Extensions; @@ -79,6 +80,10 @@ namespace xAiMcpServer services.AddXAppConfiguration(Configuration); var appConfiguration = services.GetRegisteredService(); + // + // Register Logging Service ... + services.AddXLoggingService(Configuration); + // // Register Allowed Origins ... services.AddXCors(appConfiguration.AllowedOrigins); @@ -149,6 +154,10 @@ namespace xAiMcpServer app.UseHsts(); } + // + // Setting Environment in App Confiuration ... + app.AddEnvironmentToXAppConfiguration(env.EnvironmentName); + // // Force Https Redirection ... app.UseHttpsRedirection(); @@ -185,7 +194,7 @@ namespace xAiMcpServer } } -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\xAiMcpServer\Configurations\XAiMcpLinkExtractionToolConfiguration.cs +### FILE: C:\Users\SaherElm\Documents\Projects\xSaherelmWorkspace\xAiMcpServer\Configurations\XAiMcpLinkExtractionToolConfiguration.cs namespace xAiMcpServer.Configurations { @@ -196,7 +205,7 @@ namespace xAiMcpServer.Configurations } } -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\xAiMcpServer\Configurations\XAiMcpWebSearchToolConfiguration.cs +### FILE: C:\Users\SaherElm\Documents\Projects\xSaherelmWorkspace\xAiMcpServer\Configurations\XAiMcpWebSearchToolConfiguration.cs namespace xAiMcpServer.Configurations { @@ -247,7 +256,7 @@ namespace xAiMcpServer.Configurations } } -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\xAiMcpServer\Constants\ConfigurationNodeNames.cs +### FILE: C:\Users\SaherElm\Documents\Projects\xSaherelmWorkspace\xAiMcpServer\Constants\ConfigurationNodeNames.cs namespace xAiMcpServer.Constants { @@ -258,7 +267,7 @@ namespace xAiMcpServer.Constants } } -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\xAiMcpServer\Controllers\McpController.cs +### FILE: C:\Users\SaherElm\Documents\Projects\xSaherelmWorkspace\xAiMcpServer\Controllers\McpController.cs using xIdentityHelper; using System.Threading; @@ -336,7 +345,7 @@ namespace xAiMcpServer.Controllers } } -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\xAiMcpServer\Controllers\StartupController.cs +### FILE: C:\Users\SaherElm\Documents\Projects\xSaherelmWorkspace\xAiMcpServer\Controllers\StartupController.cs using xCommons.Providers; using xCommons.Controllers; @@ -384,7 +393,7 @@ namespace xAiApi.Controllers } } -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\xAiMcpServer\Controllers\TestIdentity.cs +### FILE: C:\Users\SaherElm\Documents\Projects\xSaherelmWorkspace\xAiMcpServer\Controllers\TestIdentity.cs using xCommons.Providers; using xCommons.Configurations; @@ -412,7 +421,7 @@ namespace xAiMcpServer.Controllers } } -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\xAiMcpServer\DI\DiExtensions.cs +### FILE: C:\Users\SaherElm\Documents\Projects\xSaherelmWorkspace\xAiMcpServer\DI\DiExtensions.cs using System.Linq; using xIdentityHelper; @@ -718,7 +727,7 @@ namespace xAiMcpServer.DI } } -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\xAiMcpServer\Interfaces\IXAiMcpWebSearchService.cs +### FILE: C:\Users\SaherElm\Documents\Projects\xSaherelmWorkspace\xAiMcpServer\Interfaces\IXAiMcpWebSearchService.cs using System.Threading; using xAiMcpServer.Models; @@ -746,7 +755,7 @@ namespace xAiMcpServer.Interfaces } } -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\xAiMcpServer\Models\XExtractedLink.cs +### FILE: C:\Users\SaherElm\Documents\Projects\xSaherelmWorkspace\xAiMcpServer\Models\XExtractedLink.cs namespace xAiMcpServer.Models { @@ -758,7 +767,7 @@ namespace xAiMcpServer.Models } } -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\xAiMcpServer\Models\XLinkBundle.cs +### FILE: C:\Users\SaherElm\Documents\Projects\xSaherelmWorkspace\xAiMcpServer\Models\XLinkBundle.cs using System.Collections.Generic; @@ -771,7 +780,7 @@ namespace xAiMcpServer.Models } } -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\xAiMcpServer\Models\XLinkContentResult.cs +### FILE: C:\Users\SaherElm\Documents\Projects\xSaherelmWorkspace\xAiMcpServer\Models\XLinkContentResult.cs namespace xAiMcpServer.Models { @@ -787,7 +796,7 @@ namespace xAiMcpServer.Models } } -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\xAiMcpServer\Models\XWebSearchToolResult.cs +### FILE: C:\Users\SaherElm\Documents\Projects\xSaherelmWorkspace\xAiMcpServer\Models\XWebSearchToolResult.cs namespace xAiMcpServer.Models { @@ -800,7 +809,7 @@ namespace xAiMcpServer.Models } } -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\xAiMcpServer\Providers\XAiMcpWebSearchService.cs +### FILE: C:\Users\SaherElm\Documents\Projects\xSaherelmWorkspace\xAiMcpServer\Providers\XAiMcpWebSearchService.cs using System; using System.Net; @@ -1103,7 +1112,7 @@ namespace xAiMcpServer.Providers } } -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\xAiMcpServer\Tools\XDateTools.cs +### FILE: C:\Users\SaherElm\Documents\Projects\xSaherelmWorkspace\xAiMcpServer\Tools\XDateTools.cs using System; using System.Text; @@ -1445,7 +1454,7 @@ namespace xAiMcpServer.Tools } } -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\xAiMcpServer\Tools\XEchoTools.cs +### FILE: C:\Users\SaherElm\Documents\Projects\xSaherelmWorkspace\xAiMcpServer\Tools\XEchoTools.cs using xAiModels.Attributes; @@ -1468,7 +1477,7 @@ namespace xAiMcpServer.Tools } } -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\xAiMcpServer\Tools\XLinkExtractionTool.cs +### FILE: C:\Users\SaherElm\Documents\Projects\xSaherelmWorkspace\xAiMcpServer\Tools\XLinkExtractionTool.cs using System; using System.Net; @@ -1751,7 +1760,7 @@ namespace xAiMcpServer.Tools } } -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\xAiMcpServer\Tools\XUserTools.cs +### FILE: C:\Users\SaherElm\Documents\Projects\xSaherelmWorkspace\xAiMcpServer\Tools\XUserTools.cs using xIdentityHelper; using xModels.Extensions; @@ -1802,7 +1811,7 @@ namespace xAiMcpServer.Tools } } -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\xAiMcpServer\Tools\XWebSearchTool.cs +### FILE: C:\Users\SaherElm\Documents\Projects\xSaherelmWorkspace\xAiMcpServer\Tools\XWebSearchTool.cs using System; using System.Text; diff --git a/Documents/GeneratedContext/xDashboard-xAiModels-20261108_143749.txt b/Documents/GeneratedContext/xDashboard-xAiModels-20261108_223851.txt similarity index 93% rename from Documents/GeneratedContext/xDashboard-xAiModels-20261108_143749.txt rename to Documents/GeneratedContext/xDashboard-xAiModels-20261108_223851.txt index d10f261..6aee4db 100644 --- a/Documents/GeneratedContext/xDashboard-xAiModels-20261108_143749.txt +++ b/Documents/GeneratedContext/xDashboard-xAiModels-20261108_223851.txt @@ -1,5 +1,5 @@ -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\Modules\xAiModels\Attributes\XAiMcpToolAttribute.cs +### FILE: C:\Users\SaherElm\Documents\Projects\xSaherelmWorkspace\Modules\xAiModels\Attributes\XAiMcpToolAttribute.cs using System; @@ -42,7 +42,7 @@ namespace xAiModels.Attributes } } -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\Modules\xAiModels\Attributes\XAiMcpToolParamAttribute.cs +### FILE: C:\Users\SaherElm\Documents\Projects\xSaherelmWorkspace\Modules\xAiModels\Attributes\XAiMcpToolParamAttribute.cs using System; @@ -79,7 +79,7 @@ namespace xAiModels.Attributes } } -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\Modules\xAiModels\Attributes\XAiMcpToolTypeAttribute.cs +### FILE: C:\Users\SaherElm\Documents\Projects\xSaherelmWorkspace\Modules\xAiModels\Attributes\XAiMcpToolTypeAttribute.cs using System; @@ -92,7 +92,7 @@ namespace xAiModels.Attributes public class XAiMcpToolTypeAttribute : Attribute { } } -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\Modules\xAiModels\Configurations\XAiModelMappersProfile.cs +### FILE: C:\Users\SaherElm\Documents\Projects\xSaherelmWorkspace\Modules\xAiModels\Configurations\XAiModelMappersProfile.cs using AutoMapper; using xAiModels.Models.Dtos; @@ -132,7 +132,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; @@ -152,7 +152,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; @@ -172,7 +172,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; @@ -192,7 +192,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; @@ -212,7 +212,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; @@ -241,7 +241,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 { @@ -251,7 +251,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; @@ -281,7 +281,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; @@ -341,7 +341,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; @@ -379,7 +379,7 @@ namespace xAiModels.Constants } } -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\Modules\xAiModels\Constants\XAiMcpConstants.cs +### FILE: C:\Users\SaherElm\Documents\Projects\xSaherelmWorkspace\Modules\xAiModels\Constants\XAiMcpConstants.cs namespace xAiModels.Constants { @@ -405,7 +405,7 @@ namespace xAiModels.Constants } } -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\Modules\xAiModels\Constants\XAiMcpMethods.cs +### FILE: C:\Users\SaherElm\Documents\Projects\xSaherelmWorkspace\Modules\xAiModels\Constants\XAiMcpMethods.cs using xExceptions.Attributes; @@ -424,7 +424,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; @@ -440,7 +440,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 { @@ -457,7 +457,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 { @@ -560,7 +560,7 @@ namespace xAiModels.Constants } } -### 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; @@ -1086,7 +1086,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; @@ -1116,7 +1116,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; @@ -1296,7 +1296,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; @@ -1857,7 +1857,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; @@ -1914,7 +1914,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; @@ -1991,7 +1991,7 @@ namespace xAiModels.Helpers } } -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\Modules\xAiModels\Helpers\XAiMcpHeaderBuilder.cs +### FILE: C:\Users\SaherElm\Documents\Projects\xSaherelmWorkspace\Modules\xAiModels\Helpers\XAiMcpHeaderBuilder.cs using xCommons.Constants; using xCommons.Extensions; @@ -2068,7 +2068,7 @@ namespace xAiModels.Helpers } } -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\Modules\xAiModels\Helpers\XAiMcpSseReader.cs +### FILE: C:\Users\SaherElm\Documents\Projects\xSaherelmWorkspace\Modules\xAiModels\Helpers\XAiMcpSseReader.cs using System; using System.IO; @@ -2157,7 +2157,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; @@ -3510,7 +3510,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; @@ -3520,7 +3520,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; @@ -3905,7 +3905,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; @@ -3915,7 +3915,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; @@ -3925,7 +3925,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; @@ -3938,7 +3938,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; @@ -4009,7 +4009,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; @@ -4023,7 +4023,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; @@ -4036,7 +4036,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; @@ -4049,7 +4049,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; @@ -4063,7 +4063,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; @@ -4076,7 +4076,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; @@ -4139,7 +4139,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; @@ -4153,7 +4153,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; @@ -4166,7 +4166,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; @@ -4245,7 +4245,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; @@ -4259,7 +4259,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; @@ -4272,7 +4272,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; @@ -4286,7 +4286,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; @@ -4300,7 +4300,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; @@ -4372,7 +4372,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; @@ -4406,7 +4406,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; @@ -4467,7 +4467,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; @@ -4544,7 +4544,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; @@ -4605,7 +4605,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; @@ -4617,7 +4617,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; @@ -4629,7 +4629,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; @@ -4641,7 +4641,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; @@ -4653,7 +4653,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; @@ -4664,7 +4664,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; @@ -4677,7 +4677,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; @@ -4689,7 +4689,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; @@ -4704,7 +4704,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; @@ -4716,7 +4716,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; @@ -4728,7 +4728,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; @@ -4740,7 +4740,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; @@ -4751,7 +4751,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; @@ -4762,7 +4762,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; @@ -4775,7 +4775,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; @@ -4787,7 +4787,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; @@ -4799,7 +4799,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; @@ -4811,7 +4811,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; @@ -4823,7 +4823,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; @@ -4835,7 +4835,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; @@ -4846,7 +4846,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; @@ -4859,7 +4859,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; @@ -4871,7 +4871,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; @@ -4883,7 +4883,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; @@ -4895,7 +4895,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; @@ -4907,7 +4907,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; @@ -4919,7 +4919,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; @@ -4930,7 +4930,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; @@ -4943,7 +4943,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; @@ -4955,7 +4955,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; @@ -4967,7 +4967,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; @@ -4979,7 +4979,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; @@ -4991,7 +4991,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; @@ -5003,7 +5003,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; @@ -5014,7 +5014,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; @@ -5027,7 +5027,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; @@ -5039,7 +5039,7 @@ namespace xAiModels.Interfaces.Entities { } } -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\Modules\xAiModels\Models\XAiMcpJsonRpcError.cs +### FILE: C:\Users\SaherElm\Documents\Projects\xSaherelmWorkspace\Modules\xAiModels\Models\XAiMcpJsonRpcError.cs using System.Text.Json; using System.Text.Json.Serialization; @@ -5059,7 +5059,7 @@ namespace xAiModels.Models } } -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\Modules\xAiModels\Models\XAiMcpJsonRpcRequest.cs +### FILE: C:\Users\SaherElm\Documents\Projects\xSaherelmWorkspace\Modules\xAiModels\Models\XAiMcpJsonRpcRequest.cs using System; using System.Text.Json.Serialization; @@ -5083,7 +5083,7 @@ namespace xAiModels.Models } } -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\Modules\xAiModels\Models\XAiMcpJsonRpcResponse.cs +### FILE: C:\Users\SaherElm\Documents\Projects\xSaherelmWorkspace\Modules\xAiModels\Models\XAiMcpJsonRpcResponse.cs using System.Text.Json; using System.Text.Json.Serialization; @@ -5111,7 +5111,7 @@ namespace xAiModels.Models } } -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\Modules\xAiModels\Models\XAiMcpToolDefinition.cs +### FILE: C:\Users\SaherElm\Documents\Projects\xSaherelmWorkspace\Modules\xAiModels\Models\XAiMcpToolDefinition.cs using System.Text.Json; using System.Text.Json.Serialization; @@ -5131,7 +5131,7 @@ namespace xAiModels.Models } } -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\Modules\xAiModels\Models\XAiMcpToolDescriptor.cs +### FILE: C:\Users\SaherElm\Documents\Projects\xSaherelmWorkspace\Modules\xAiModels\Models\XAiMcpToolDescriptor.cs using System; using System.Threading; @@ -5151,7 +5151,7 @@ namespace xAiModels.Models } } -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\Modules\xAiModels\Models\XAiModelDescriptor.cs +### FILE: C:\Users\SaherElm\Documents\Projects\xSaherelmWorkspace\Modules\xAiModels\Models\XAiModelDescriptor.cs using xAiModels.Constants; @@ -5189,7 +5189,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 { @@ -5241,7 +5241,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; @@ -5260,7 +5260,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; @@ -5304,7 +5304,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; @@ -5378,7 +5378,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; @@ -5455,7 +5455,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; @@ -5517,7 +5517,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; @@ -5609,7 +5609,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; @@ -5676,7 +5676,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; @@ -5716,7 +5716,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; @@ -5734,7 +5734,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; @@ -5780,7 +5780,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; @@ -5850,7 +5850,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; @@ -5938,7 +5938,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; @@ -5989,7 +5989,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; @@ -6027,7 +6027,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; @@ -6065,7 +6065,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; @@ -6089,7 +6089,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; @@ -8542,7 +8542,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; @@ -8580,7 +8580,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; @@ -8618,7 +8618,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; @@ -8642,7 +8642,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; @@ -8680,7 +8680,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; @@ -8704,7 +8704,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; @@ -8742,7 +8742,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; @@ -8762,7 +8762,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; @@ -8972,7 +8972,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; @@ -9002,7 +9002,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; @@ -9022,7 +9022,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; @@ -9051,7 +9051,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; @@ -9076,7 +9076,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; @@ -9096,7 +9096,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; @@ -9264,7 +9264,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; @@ -9294,7 +9294,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; @@ -9314,7 +9314,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; @@ -9639,7 +9639,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; @@ -9669,7 +9669,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; @@ -9689,7 +9689,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; @@ -9716,7 +9716,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; @@ -9746,7 +9746,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; @@ -9947,7 +9947,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; @@ -10029,7 +10029,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; @@ -10179,7 +10179,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; @@ -10486,7 +10486,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; @@ -10603,7 +10603,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; @@ -10633,7 +10633,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; @@ -10652,7 +10652,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; @@ -10677,7 +10677,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; @@ -10689,7 +10689,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; @@ -10718,7 +10718,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; @@ -10730,7 +10730,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; @@ -10759,7 +10759,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; @@ -10786,7 +10786,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; @@ -10811,7 +10811,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; @@ -10830,7 +10830,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; @@ -10851,7 +10851,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; @@ -10863,7 +10863,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; @@ -10889,7 +10889,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; @@ -10901,7 +10901,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; @@ -10925,7 +10925,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; @@ -10952,7 +10952,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; @@ -10982,7 +10982,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; @@ -11001,7 +11001,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; @@ -11026,7 +11026,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; @@ -11038,7 +11038,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; @@ -11067,7 +11067,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; @@ -11079,7 +11079,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; @@ -11108,7 +11108,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; @@ -11135,7 +11135,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; @@ -11165,7 +11165,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; @@ -11184,7 +11184,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; @@ -11209,7 +11209,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; @@ -11221,7 +11221,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; @@ -11250,7 +11250,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; @@ -11262,7 +11262,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; @@ -11291,7 +11291,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; @@ -11318,7 +11318,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; @@ -11348,7 +11348,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; @@ -11367,7 +11367,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; @@ -11392,7 +11392,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; @@ -11404,7 +11404,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; @@ -11433,7 +11433,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; @@ -11445,7 +11445,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; @@ -11474,7 +11474,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; @@ -11501,7 +11501,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; @@ -11525,7 +11525,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; @@ -11551,7 +11551,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; @@ -11567,7 +11567,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; @@ -11588,7 +11588,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; @@ -11612,7 +11612,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; @@ -11638,7 +11638,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; @@ -11654,7 +11654,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; @@ -11680,7 +11680,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; @@ -11704,7 +11704,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; @@ -11730,7 +11730,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; @@ -11746,7 +11746,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; @@ -11769,7 +11769,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; @@ -11793,7 +11793,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; @@ -11819,7 +11819,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; @@ -11835,7 +11835,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; @@ -11857,7 +11857,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; @@ -11881,7 +11881,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; @@ -11907,7 +11907,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; @@ -11923,7 +11923,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; @@ -11942,7 +11942,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-20261108_143750.txt b/Documents/GeneratedContext/xDashboard-xAiService-20261108_223852.txt similarity index 95% rename from Documents/GeneratedContext/xDashboard-xAiService-20261108_143750.txt rename to Documents/GeneratedContext/xDashboard-xAiService-20261108_223852.txt index 24f19b7..2a0b301 100644 --- a/Documents/GeneratedContext/xDashboard-xAiService-20261108_143750.txt +++ b/Documents/GeneratedContext/xDashboard-xAiService-20261108_223852.txt @@ -1,5 +1,5 @@ -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\Modules\xAiService\Constants\ConfigurationNodeNames.cs +### FILE: C:\Users\SaherElm\Documents\Projects\xSaherelmWorkspace\Modules\xAiService\Constants\ConfigurationNodeNames.cs namespace xAiService.Constants { @@ -9,7 +9,7 @@ namespace xAiService.Constants } } -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\Modules\xAiService\Constants\XAiServiceConstants.cs +### FILE: C:\Users\SaherElm\Documents\Projects\xSaherelmWorkspace\Modules\xAiService\Constants\XAiServiceConstants.cs namespace xAiService.Constants { @@ -28,7 +28,7 @@ namespace xAiService.Constants } } -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\Modules\xAiService\Controllers\XAiMcpControllerBase.cs +### FILE: C:\Users\SaherElm\Documents\Projects\xSaherelmWorkspace\Modules\xAiService\Controllers\XAiMcpControllerBase.cs using System.Threading; using xCommons.Providers; @@ -123,7 +123,7 @@ namespace xAiService.Controllers } } -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\Modules\xAiService\DI\XDIHelperExtension.cs +### FILE: C:\Users\SaherElm\Documents\Projects\xSaherelmWorkspace\Modules\xAiService\DI\XDIHelperExtension.cs using System.Net.Http; using System.Threading; @@ -167,7 +167,7 @@ namespace xAiService.DI } } -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\Modules\xAiService\Extensions\DIExtensions.cs +### FILE: C:\Users\SaherElm\Documents\Projects\xSaherelmWorkspace\Modules\xAiService\Extensions\DIExtensions.cs using System; using System.Linq; @@ -217,7 +217,7 @@ namespace xAiService.Extensions } } -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\Modules\xAiService\Extensions\XAiServiceExtensions.cs +### FILE: C:\Users\SaherElm\Documents\Projects\xSaherelmWorkspace\Modules\xAiService\Extensions\XAiServiceExtensions.cs using xAiModels.Models; using xCommons.Extensions; @@ -298,7 +298,7 @@ namespace xAiService.Extensions } } -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\Modules\xAiService\Helpers\XAiMcpArgumentHelper.cs +### FILE: C:\Users\SaherElm\Documents\Projects\xSaherelmWorkspace\Modules\xAiService\Helpers\XAiMcpArgumentHelper.cs using System; using Newtonsoft.Json.Linq; @@ -428,7 +428,7 @@ namespace xAiService.Helpers } } -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\Modules\xAiService\Helpers\XAiMcpResultExtractionHelper.cs +### FILE: C:\Users\SaherElm\Documents\Projects\xSaherelmWorkspace\Modules\xAiService\Helpers\XAiMcpResultExtractionHelper.cs using System; using Newtonsoft.Json; @@ -536,7 +536,7 @@ namespace xAiService.Helpers } } -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\Modules\xAiService\Interfaces\IXAiMcpHandler.cs +### FILE: C:\Users\SaherElm\Documents\Projects\xSaherelmWorkspace\Modules\xAiService\Interfaces\IXAiMcpHandler.cs using System.Threading; using Newtonsoft.Json.Linq; @@ -564,7 +564,7 @@ namespace xAiService.Interfaces } } -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\Modules\xAiService\Interfaces\IXAiMcpUserContext.cs +### FILE: C:\Users\SaherElm\Documents\Projects\xSaherelmWorkspace\Modules\xAiService\Interfaces\IXAiMcpUserContext.cs using xIdentityModels.Models; @@ -610,7 +610,7 @@ namespace xAiService.Interfaces } } -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\Modules\xAiService\Services\XAiMcpAIFunction.cs +### FILE: C:\Users\SaherElm\Documents\Projects\xSaherelmWorkspace\Modules\xAiService\Services\XAiMcpAIFunction.cs using System.Text.Json; using System.Threading; @@ -699,7 +699,7 @@ namespace xAiService.Services } } -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\Modules\xAiService\Services\XAiMcpClient.cs +### FILE: C:\Users\SaherElm\Documents\Projects\xSaherelmWorkspace\Modules\xAiService\Services\XAiMcpClient.cs using System; using System.Text.Json; @@ -970,7 +970,7 @@ namespace xAiService.Services } } -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\Modules\xAiService\Services\XAiMcpHandler.cs +### FILE: C:\Users\SaherElm\Documents\Projects\xSaherelmWorkspace\Modules\xAiService\Services\XAiMcpHandler.cs using System; using System.Threading; @@ -1263,7 +1263,7 @@ namespace xAiService.Services } } -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\Modules\xAiService\Services\XAiMcpHttpTransport.cs +### FILE: C:\Users\SaherElm\Documents\Projects\xSaherelmWorkspace\Modules\xAiService\Services\XAiMcpHttpTransport.cs using System; using System.Text; @@ -1388,7 +1388,7 @@ namespace xAiService.Services } } -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\Modules\xAiService\Services\XAiMcpSessionCleanupService.cs +### FILE: C:\Users\SaherElm\Documents\Projects\xSaherelmWorkspace\Modules\xAiService\Services\XAiMcpSessionCleanupService.cs using System; using System.Threading; @@ -1433,7 +1433,7 @@ namespace xAiService.Services } } -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\Modules\xAiService\Services\XAiMcpSessionStore.cs +### FILE: C:\Users\SaherElm\Documents\Projects\xSaherelmWorkspace\Modules\xAiService\Services\XAiMcpSessionStore.cs using System; using System.Collections.Concurrent; @@ -1519,7 +1519,7 @@ namespace xAiService.Services } } -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\Modules\xAiService\Services\XAiMcpToolBlueprint.cs +### FILE: C:\Users\SaherElm\Documents\Projects\xSaherelmWorkspace\Modules\xAiService\Services\XAiMcpToolBlueprint.cs using System; using xAiModels.Models; @@ -1637,7 +1637,7 @@ namespace xAiService.Services } } -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\Modules\xAiService\Services\XAiMcpToolScanner.cs +### FILE: C:\Users\SaherElm\Documents\Projects\xSaherelmWorkspace\Modules\xAiService\Services\XAiMcpToolScanner.cs using System; using System.Linq; @@ -1877,7 +1877,7 @@ namespace xAiService.Services } } -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\Modules\xAiService\Services\XAiMcpUserContext.cs +### FILE: C:\Users\SaherElm\Documents\Projects\xSaherelmWorkspace\Modules\xAiService\Services\XAiMcpUserContext.cs using System.Threading; using xAiService.Interfaces; diff --git a/Documents/GeneratedContext/xDashboard-xLoggingService-20261108_223911.txt b/Documents/GeneratedContext/xDashboard-xLoggingService-20261108_223911.txt new file mode 100644 index 0000000..b96e56a --- /dev/null +++ b/Documents/GeneratedContext/xDashboard-xLoggingService-20261108_223911.txt @@ -0,0 +1,906 @@ + +### FILE: C:\Users\SaherElm\Documents\Projects\xSaherelmWorkspace\Modules\xLoggingService\Background\XLogDispatcher.cs + +using System; +using System.Threading; +using System.Threading.Tasks; +using xLoggingService.Models; +using xLoggingService.Interfaces; +using System.Collections.Generic; +using System.Collections.Concurrent; + +namespace xLoggingService.Background +{ + public sealed class XLogDispatcher : IDisposable + { + private readonly Task worker; + private readonly BlockingCollection queue; + private readonly IReadOnlyCollection writers; + private readonly CancellationTokenSource cancellation = new CancellationTokenSource(); + + public XLogDispatcher( + int capacity, + IEnumerable writers + ) + { + // + queue = new BlockingCollection(Math.Max(100, capacity)); + this.writers = new List(writers) + .AsReadOnly(); + + // + worker = Task.Run(RunAsync); + } + + public void Enqueue(XLogEntry entry) + { + if (!queue.IsAddingCompleted && !queue.TryAdd(entry)) { } + } + + private async Task RunAsync() + { + // + try + { + // + foreach (var entry in queue.GetConsumingEnumerable(cancellation.Token)) + { + // + foreach (var writer in writers) + { + // + try + { + // + await writer.WriteAsync(entry, cancellation.Token) + .ConfigureAwait(false); + } + catch { } + } + } + } + catch (OperationCanceledException) { } + } + + public void Dispose() + { + // + queue.CompleteAdding(); + + // + try + { + worker.Wait(TimeSpan.FromSeconds(10)); + } + catch { } + + // + cancellation.Cancel(); + queue.Dispose(); + cancellation.Dispose(); + } + } +} + +### FILE: C:\Users\SaherElm\Documents\Projects\xSaherelmWorkspace\Modules\xLoggingService\Configuration\XLoggingServiceConfiguration.cs + +using Microsoft.Extensions.Logging; + +namespace xLoggingService.Configuration +{ + public sealed class XLoggingServiceConfiguration + { + public bool Enabled { get; set; } = false; + public XFileLogConfiguration File { get; set; } = new(); + public XLogQueueConfiguration Queue { get; set; } = new(); + public XEventLogConfiguration Event { get; set; } = new(); + public XDatabaseLogConfiguration Database { get; set; } = new(); + public LogLevel MinimumLevel { get; set; } = LogLevel.Information; + } + + public class XLogQueueConfiguration { + public bool Enabled { get; set; } + public int Capacity { get; set; } = 10000; + public int ShutdownTimeoutSeconds { get; set; } = 10; + } + + public class XFileLogConfiguration { + public bool Enabled { get; set; } + public string Format { get; set; } = "Json"; + public string Directory { get; set; } = "./Logs"; + public int RetainedFileCountLimit { get; set; } = 30; + public string FileName { get; set; } = "x-logging-.log"; + public LogLevel MinimumLevel { get; set; } = LogLevel.Information; + } + + public class XDatabaseLogConfiguration { + public bool Enabled { get; set; } = false; + public string ConnectionString { get; set; } + public string TableName { get; set; } = "XLogs"; + public bool AutoCreateTable { get; set; } = true; + public LogLevel MinimumLevel { get; set; } = LogLevel.Warning; + public string Provider { get; set; } = "Microsoft.Data.Sqlite"; + } + + public class XEventLogConfiguration { + public bool Enabled { get; set; } = false; + public string Sender { get; set; } = "Application"; + public string Action { get; set; } = "XLogCreated"; + public LogLevel MinimumLevel { get; set; } = LogLevel.Error; + public string Topic { get; set; } = "x-logging-service-logs"; + } +} + +### FILE: C:\Users\SaherElm\Documents\Projects\xSaherelmWorkspace\Modules\xLoggingService\Constants\ConfigurationNodeNames.cs + +namespace xLoggingService.Constants +{ + public partial struct ConfigurationNodeNames + { + public const string LOGGING_SERVICE_NODE = "LoggingServiceConfiguration"; + } +} + +### FILE: C:\Users\SaherElm\Documents\Projects\xSaherelmWorkspace\Modules\xLoggingService\Constants\XLoggingServiceConstants.cs + +namespace xLoggingService.Constants +{ + public struct XLoggingServiceConstants + { + // + // Service Extensions Log Tag ... + public const string XLoggingServiceDILogTag = "XLoggingService"; + } +} + +### FILE: C:\Users\SaherElm\Documents\Projects\xSaherelmWorkspace\Modules\xLoggingService\DI\XDIHelperExtension.cs + +using System; +using xCommons.Extensions; +using xExceptions.Constants; +using xLoggingService.Writers; +using xEventService.Interfaces; +using xLoggingService.Providers; +using xLoggingService.Constants; +using xLoggingService.Interfaces; +using Microsoft.Extensions.Logging; +using xLoggingService.Configuration; +using Microsoft.Extensions.Configuration; +using Microsoft.Extensions.DependencyInjection; +using Microsoft.Extensions.DependencyInjection.Extensions; + +namespace xLoggingService.DI +{ + public static class XDIHelperExtension + { + /// + /// Retrieve Logging Service Configuration ... + /// + /// + /// + public static XLoggingServiceConfiguration GetXLoggingServiceConfiguration( + this IConfiguration source + ) + { + // + var section = source + .GetSection(ConfigurationNodeNames.LOGGING_SERVICE_NODE); + + // + var result = section.Get(); + if (result.IsNull()) + { + result = new(); + } + + // + return result; + } + + /// + /// Extract Service Configurations and Register it ... + /// + /// + /// + public static void AddXLoggingServiceConfiguration( + this IServiceCollection source, + IConfiguration configuration + ) + { + // + var config = configuration.GetXLoggingServiceConfiguration(); + source.AddXLoggingServiceConfiguration(config); + } + + /// + /// Register Service Configuration ... + /// + /// + /// + public static void AddXLoggingServiceConfiguration( + this IServiceCollection source, + XLoggingServiceConfiguration configuration + ) + { + // + if (configuration.IsNull()) + { + // + Log($"Invalid Configuration ..."); + XException.InvalidConfiguration.Throw(); + } + + // + source.AddSingleton(configuration); + Log($"Logging Configuration Registered Successfully ..."); + } + + /// + /// Register Logging Service ... + /// + /// + /// + public static void AddXLoggingService( + this IServiceCollection source, + IConfiguration configuration + ) + { + // + var config = configuration.GetXLoggingServiceConfiguration(); + source.AddLoggingService( + configuration: config, + lifeTime: ServiceLifetime.Scoped + ); + } + + // + #region Private + /// + /// a LogTag for Service ... + /// + private static string XLogTag = XLoggingServiceConstants.XLoggingServiceDILogTag; + + /// + /// print a log in Console ... + /// + /// + private static void Log(string message) + { + Console.WriteLine($"{XLogTag} => {message}"); + } + + /// + /// Register Logging Service ... + /// + /// + /// + /// + private static void AddLoggingService( + this IServiceCollection services, + XLoggingServiceConfiguration configuration, + ServiceLifetime lifeTime = ServiceLifetime.Scoped + ) + { + // + // Validate ... + if (lifeTime.IsNull()) + { + // + Log($"Invalid Service Lifetime ..."); + XException.InvalidArgs.Throw(); + } + + // + // Register Service Configuration ... + services.AddXLoggingServiceConfiguration(configuration); + + // + // File Log Provider ... + if (configuration.File.Enabled) + { + // + services.TryAddEnumerable( + ServiceDescriptor.Singleton()); + + // + Log("FileLogWriter registered."); + } + + // + // Database Log Provider ... + if (configuration.Database.Enabled) + { + // + services.TryAddEnumerable( + ServiceDescriptor.Singleton()); + + // + Log("DatabaseLogWriter registered."); + } + + // + // Event Service Provider ... + if (configuration.Event.Enabled) + { + // + var eventService = services.GetRegisteredService(); + if (eventService.IsNull()) + { + // + Log("Event Service not Provided ..."); + XException.InvalidConfiguration.Throw(); + } + + // + services.TryAddEnumerable( + ServiceDescriptor.Singleton()); + + // + Log("EventLogWriter registered."); + } + + // + services.TryAddEnumerable( + ServiceDescriptor.Singleton()); + + // + Log($"Logging Service registered successfully ..."); + } + #endregion + } +} + +### FILE: C:\Users\SaherElm\Documents\Projects\xSaherelmWorkspace\Modules\xLoggingService\Extensions\XLoggingServiceExtensions.cs + +using xCommons.Extensions; +using xLoggingService.Models; +using xCommons.Configurations; + +namespace xLoggingService.Extensions +{ + public static class XLoggingServiceExtensions + { + /// + /// Enrich LogEntry ... + /// + /// + /// + /// + public static XLogEntry Enrich( + this XLogEntry source, + XAppConfiguration configuration + ) + { + // + if (source.IsNull() || configuration.IsNull()) + { + return source; + } + + // + source.Application = configuration.Name; + + // + return source; + } + } +} + +### FILE: C:\Users\SaherElm\Documents\Projects\xSaherelmWorkspace\Modules\xLoggingService\Interfaces\IXLogWriter.cs + +using System.Threading; +using System.Threading.Tasks; +using xLoggingService.Models; + +namespace xLoggingService.Interfaces +{ + public interface IXLogWriter + { + /// + /// Write Log ... + /// + /// + /// + /// + Task WriteAsync( + XLogEntry entry, + CancellationToken cancellationToken + ); + } +} + +### FILE: C:\Users\SaherElm\Documents\Projects\xSaherelmWorkspace\Modules\xLoggingService\Models\XLogEntry.cs + +using System; +using System.Collections.Generic; +using Microsoft.Extensions.Logging; + +namespace xLoggingService.Models +{ + /// + /// a Log which Issued ... + /// + public class XLogEntry + { + public int EventId { get; set; } + public string State { get; set; } + public string SpanId { get; set; } + public LogLevel Level { get; set; } + public string Message { get; set; } + public string TraceId { get; set; } + public string Category { get; set; } + public string Exception { get; set; } + public DateTime Timestamp { get; set; } + public string Application { get; set; } + public string Environment { get; set; } + public string MachineName { get; set; } + public string CorrelationId { get; set; } + public IDictionary Scope { get; set; } = new Dictionary(); + } +} + +### FILE: C:\Users\SaherElm\Documents\Projects\xSaherelmWorkspace\Modules\xLoggingService\Providers\XLoggerProvider.cs + +using System; +using Newtonsoft.Json; +using System.Diagnostics; +using xLoggingService.Models; +using xCommons.Configurations; +using System.Collections.Generic; +using xLoggingService.Background; +using xLoggingService.Interfaces; +using Microsoft.Extensions.Logging; +using xLoggingService.Configuration; + +namespace xLoggingService.Providers +{ + public class XLoggerProvider : ILoggerProvider + { + // + private readonly XLogDispatcher dispatcher; + private readonly XAppConfiguration configuration; + private readonly XLoggingServiceConfiguration config; + private readonly IReadOnlyCollection writers; + + public XLoggerProvider( + XAppConfiguration configuration, + XLoggingServiceConfiguration config, + IEnumerable writers + ) + { + // + this.config = config; + this.configuration = configuration; + this.writers = new List(writers) + .AsReadOnly(); + + // + dispatcher = new XLogDispatcher( + config.Queue.Capacity, this.writers); + } + + public ILogger CreateLogger(string categoryName) + { + // + return new XLogger( + config: config, + category: categoryName, + dispatcher: dispatcher, + configuration: configuration + ); + } + + public void Dispose() + { + dispatcher.Dispose(); + } + } + + public class XLogger : ILogger + { + // + private readonly string category; + private readonly XLogDispatcher dispatcher; + private readonly XAppConfiguration configuration; + private readonly XLoggingServiceConfiguration config; + + public XLogger( + string category, + XLogDispatcher dispatcher, + XAppConfiguration configuration, + XLoggingServiceConfiguration config + ) + { + // + this.config = config; + this.category = category; + this.dispatcher = dispatcher; + this.configuration = configuration; + } + + public IDisposable BeginScope(TState state) + { + return NullScope.Instance; + } + + public bool IsEnabled(LogLevel level) + { + // + var result = + config.Enabled && + level >= config.MinimumLevel && + level != LogLevel.None; + + // + return result; + } + + public void Log( + LogLevel level, + EventId eventId, + TState state, + Exception exception, + Func formatter + ) + { + // + if (!IsEnabled(level)) + { + return; + } + + // + var activity = Activity.Current; + dispatcher.Enqueue(new XLogEntry + { + Level = level, + Category = category, + EventId = eventId.Id, + TraceId = activity?.Id, + SpanId = activity?.RootId, + Timestamp = DateTime.UtcNow, + Message = formatter == null + ? state == null + ? string.Empty + : state.ToString() + : formatter(state, exception), + Exception = exception == null + ? null + : exception.ToString(), + State = state == null + ? null : + JsonConvert.SerializeObject(state), + Application = configuration.Name, + MachineName = Environment.MachineName, + Environment = configuration.Environment, + }); + } + + private sealed class NullScope : IDisposable { + public static readonly NullScope Instance = new(); + public void Dispose() { } + } + } +} + + +### FILE: C:\Users\SaherElm\Documents\Projects\xSaherelmWorkspace\Modules\xLoggingService\Writers\XDatabaseLogWriter.cs + +using System; +using System.Threading; +using System.Data.Common; +using xCommons.Extensions; +using System.Threading.Tasks; +using xLoggingService.Models; +using xCommons.Configurations; +using xLoggingService.Interfaces; +using xLoggingService.Extensions; +using xLoggingService.Configuration; + +namespace xLoggingService.Writers +{ + public sealed class XDatabaseLogWriter : IXLogWriter + { + // + private bool initialized; + private readonly object sync = new(); + private readonly XDatabaseLogConfiguration config; + private readonly XAppConfiguration appConfiguration; + + public XDatabaseLogWriter( + XDatabaseLogConfiguration config, + XAppConfiguration appConfiguration + ) + { + // + this.config = config; + this.appConfiguration = appConfiguration; + } + + public Task WriteAsync( + XLogEntry e, + CancellationToken token + ) + { + // + if (e.IsNull()) + { + return Task.CompletedTask; + } + + // + // Handle Task Enrichment ... + e = e.Enrich(appConfiguration); + + // + if (e.Level < config.MinimumLevel || config.ConnectionString.IsNullOrEmpty()) + { + return Task.CompletedTask; + } + + // + try + { + // + lock (sync) + { + // + using (var c = CreateConnection()) + { + // + c.Open(); + if (!initialized) + { + using (var cmd = c.CreateCommand()) + { + // + cmd.CommandText = $"CREATE TABLE IF NOT EXISTS [{config.TableName}] (Id INTEGER PRIMARY KEY, Timestamp TEXT, Level TEXT, Category TEXT, EventId INTEGER, Message TEXT, Exception TEXT, State TEXT, Application TEXT, Environment TEXT, MachineName TEXT, TraceId TEXT, SpanId TEXT, CorrelationId TEXT)"; + cmd.ExecuteNonQuery(); + } + initialized = true; + } + + // + using (var cmd = c.CreateCommand()) + { + // + cmd.CommandText = $"INSERT INTO [{config.TableName}] (Timestamp,Level,Category,EventId,Message,Exception,State,Application,Environment,MachineName,TraceId,SpanId,CorrelationId) VALUES (@Timestamp,@Level,@Category,@EventId,@Message,@Exception,@State,@Application,@Environment,@MachineName,@TraceId,@SpanId,@CorrelationId)"; + + // + Add(cmd, "@State", e.State); + Add(cmd, "@SpanId", e.SpanId); + Add(cmd, "@EventId", e.EventId); + Add(cmd, "@Message", e.Message); + Add(cmd, "@TraceId", e.TraceId); + Add(cmd, "@Category", e.Category); + Add(cmd, "@Exception", e.Exception); + Add(cmd, "@Level", e.Level.ToString()); + Add(cmd, "@Application", e.Application); + Add(cmd, "@Environment", e.Environment); + Add(cmd, "@MachineName", e.MachineName); + Add(cmd, "@CorrelationId", e.CorrelationId); + Add(cmd, "@Timestamp", e.Timestamp.ToString("O")); + + // + cmd.ExecuteNonQuery(); + } + } + } + } + catch { } + + // + return Task.CompletedTask; + } + + private DbConnection CreateConnection() + { + // + var typeName = + config.Provider == "Microsoft.Data.Sqlite" + ? "Microsoft.Data.Sqlite.SqliteConnection, Microsoft.Data.Sqlite" + : config.Provider == "System.Data.SqlClient" ? + "System.Data.SqlClient.SqlConnection, System.Data.SqlClient" + : config.Provider; + + // + var type = Type.GetType(typeName, false); + if (type.IsNull()) + { + throw new InvalidOperationException("Database provider was not found: " + typeName); + } + + // + var c = (DbConnection)Activator.CreateInstance(type); + c.ConnectionString = config.ConnectionString; + + // + return c; + } + + private static void Add( + DbCommand c, + string name, + object value + ) { + // + var p = c.CreateParameter(); + p.ParameterName = name; + p.Value = (object)value ?? DBNull.Value; + c.Parameters.Add(p); + } + } +} + + + + +### FILE: C:\Users\SaherElm\Documents\Projects\xSaherelmWorkspace\Modules\xLoggingService\Writers\XEventLogWriter.cs + +using System; +using System.Threading; +using xCommons.Extensions; +using xEventService.Models; +using System.Threading.Tasks; +using xLoggingService.Models; +using xCommons.Configurations; +using xEventService.Interfaces; +using System.Collections.Generic; +using xLoggingService.Interfaces; +using xLoggingService.Extensions; +using xLoggingService.Configuration; + +namespace xLoggingService.Writers +{ + public sealed class XEventLogWriter : IXLogWriter + { + + // + private readonly XAppConfiguration appConfiguration; + private readonly XLoggingServiceConfiguration config; + private readonly Func resolver; + + public XEventLogWriter( + XAppConfiguration appConfiguration, + XLoggingServiceConfiguration config, + Func resolver + ) + { + // + this.config = config; + this.resolver = resolver; + this.appConfiguration = appConfiguration; + } + + public async Task WriteAsync( + XLogEntry entry, + CancellationToken token + ) + { + // + if (entry.IsNull()) + { + return; + } + + // + // Handle Task Enrichment ... + entry = entry.Enrich(appConfiguration); + + // + var provider = resolver(); + if (provider.IsNull() || entry.Level < config.Event.MinimumLevel) + { + return; + } + + // + var payload = new Dictionary { + { nameof(XLogEntry.Category), entry.Category }, + { nameof(XLogEntry.Level), entry.Level.ToString() }, + { nameof(XLogEntry.State), entry.State ?? string.Empty }, + { nameof(XLogEntry.TraceId), entry.TraceId ?? string.Empty } , + { nameof(XLogEntry.Exception), entry.Exception ?? string.Empty }, + }; + + // + await provider.SendMessageAsync( + new XEventMessage + { + Payload = payload, + Message = entry.Message, + Offset = entry.Timestamp, + Sender = config.Event.Sender, + Action = config.Event.Action, + }, + config.Event.Topic, + token + ).ConfigureAwait(false); + } + } +} + +### FILE: C:\Users\SaherElm\Documents\Projects\xSaherelmWorkspace\Modules\xLoggingService\Writers\XFileLogWriter.cs + +using System; +using System.IO; +using System.Text; +using Newtonsoft.Json; +using System.Threading; +using xCommons.Extensions; +using xExceptions.Constants; +using System.Threading.Tasks; +using xLoggingService.Models; +using xCommons.Configurations; +using xLoggingService.Interfaces; +using xLoggingService.Extensions; +using xLoggingService.Configuration; + +namespace xLoggingService.Writers +{ + public sealed class XFileLogWriter : IXLogWriter + { + // + private readonly object sync = new(); + private readonly XAppConfiguration appConfiguration; + private readonly XLoggingServiceConfiguration configuration; + + public XFileLogWriter( + XAppConfiguration appConfiguration, + XLoggingServiceConfiguration configuration + ) + { + // + if (configuration.IsNull() || appConfiguration.IsNull()) + { + XException.InvalidConfiguration.Throw(); + } + + // + this.configuration = configuration; + this.appConfiguration = appConfiguration; + + // + Directory.CreateDirectory(configuration.File.Directory); + } + + public Task WriteAsync( + XLogEntry entry, + CancellationToken token + ) + { + // + if (entry.IsNull()) + { + return Task.CompletedTask; + } + + // + // Handle Task Enrichment ... + entry = entry.Enrich(appConfiguration); + + // + if (entry.Level < configuration.File.MinimumLevel) + { + return Task.CompletedTask; + } + + // + var path = Path.Combine(configuration.File.Directory, configuration.File.FileName.Replace("-", "-")); + + // + lock (sync) + { + // + File.AppendAllText(path, configuration.File.Format.Equals( + "Json", + StringComparison.OrdinalIgnoreCase) + ? JsonConvert.SerializeObject(entry) + Environment.NewLine + : $"{entry.Timestamp:O} [{entry.Level}] {entry.Category}: {entry.Message}{Environment.NewLine}", Encoding.UTF8); + } + + // + return Task.CompletedTask; + } + } +} diff --git a/Modules/xLoggingService b/Modules/xLoggingService index 777ceaa..0fe3748 160000 --- a/Modules/xLoggingService +++ b/Modules/xLoggingService @@ -1 +1 @@ -Subproject commit 777ceaa8f084f58d7186744f8ef909e7d0ccaaf5 +Subproject commit 0fe37483bc7da2aa1a6518b08c1630a0029dd2c1 diff --git a/xAiApi b/xAiApi index b58f1dd..c24c14e 160000 --- a/xAiApi +++ b/xAiApi @@ -1 +1 @@ -Subproject commit b58f1dd73615356290654e6600c61365cd068894 +Subproject commit c24c14eb74edd9eb9fa5992348e77a3c05041536 diff --git a/xAiMcpServer b/xAiMcpServer index 63b922f..0bc45bd 160000 --- a/xAiMcpServer +++ b/xAiMcpServer @@ -1 +1 @@ -Subproject commit 63b922f09b538f86609c66b4d3507eaba065a1df +Subproject commit 0bc45bd8b9c83776be83a005a64ff227312c2c7b diff --git a/xApi b/xApi index c711cae..18eb5d9 160000 --- a/xApi +++ b/xApi @@ -1 +1 @@ -Subproject commit c711cae78f7c8d86221460cfa6599bd95278603b +Subproject commit 18eb5d92e1f50c7610aa475fce7039c6c0acad44 diff --git a/xIds b/xIds index df3ed78..b311b1e 160000 --- a/xIds +++ b/xIds @@ -1 +1 @@ -Subproject commit df3ed7868bcb13c16500b0a5370513a7012ce400 +Subproject commit b311b1e391c632da195109e52d208dea714da80e