From b2c4e7c767fb3c0dbbff6700e58c9fcf9fe0ab54 Mon Sep 17 00:00:00 2001 From: Hadi Khazaee Asl Date: Sat, 7 Nov 2026 22:51:41 +0330 Subject: [PATCH] =?UTF-8?q?-=20=D8=AD=D8=B0=D9=81=20=DA=86=D9=87=D8=A7?= =?UTF-8?q?=D8=B1=20context=20=D9=82=D8=AF=DB=8C=D9=85=DB=8C=20=D9=85?= =?UTF-8?q?=D8=B1=D8=A8=D9=88=D8=B7=20=D8=A8=D9=87=202026-11-06.=20-=20?= =?UTF-8?q?=D8=A7=D9=81=D8=B2=D9=88=D8=AF=D9=86=20context=D9=87=D8=A7?= =?UTF-8?q?=DB=8C=20=D8=AC=D8=AF=DB=8C=D8=AF=202026-11-07=20=D8=A8=D8=B1?= =?UTF-8?q?=D8=A7=DB=8C=20xAiApi=D8=8C=20xAiMcpServer=D8=8C=20xAiModels=20?= =?UTF-8?q?=D9=88=20xAiService.?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- Documents/Docs/ChangeLogs/1405-08-16-v01.html | 298 + .../CommitMessage-1405-08-16-v01.txt | 53 + .../Force LLMs to Generate Files.html | 1322 + .../Developer/LLMs Overview 14050817.html | 984 + ...y Strategies and Context Management 1.html | 1455 + .../Docs/Developer/Multi Agentic Roadmap.html | 1825 + .../xDashboard-xAiApi-20261106_205448.txt | 15713 -------- .../xDashboard-xAiApi-20261107_225117.txt | 32419 ++++++++++++++++ ...Dashboard-xAiMcpServer-20261106_205448.txt | 898 - ...Dashboard-xAiMcpServer-20261107_225130.txt | 1905 + ... xDashboard-xAiModels-20261107_225130.txt} | 396 +- .../xDashboard-xAiService-20261106_205449.txt | 1947 - Documents/Resources/Json/Requests.md | 6 +- xAiMcpServer | 2 +- 14 files changed, 40463 insertions(+), 18760 deletions(-) create mode 100644 Documents/Docs/ChangeLogs/1405-08-16-v01.html create mode 100644 Documents/Docs/ChangeLogs/CommitMessage-1405-08-16-v01.txt create mode 100644 Documents/Docs/Developer/Force LLMs to Generate Files.html create mode 100644 Documents/Docs/Developer/LLMs Overview 14050817.html create mode 100644 Documents/Docs/Developer/Memory Strategies and Context Management 1.html create mode 100644 Documents/Docs/Developer/Multi Agentic Roadmap.html delete mode 100644 Documents/GeneratedContext/xDashboard-xAiApi-20261106_205448.txt create mode 100644 Documents/GeneratedContext/xDashboard-xAiApi-20261107_225117.txt delete mode 100644 Documents/GeneratedContext/xDashboard-xAiMcpServer-20261106_205448.txt create mode 100644 Documents/GeneratedContext/xDashboard-xAiMcpServer-20261107_225130.txt rename Documents/GeneratedContext/{xDashboard-xAiModels-20261106_205448.txt => xDashboard-xAiModels-20261107_225130.txt} (96%) delete mode 100644 Documents/GeneratedContext/xDashboard-xAiService-20261106_205449.txt diff --git a/Documents/Docs/ChangeLogs/1405-08-16-v01.html b/Documents/Docs/ChangeLogs/1405-08-16-v01.html new file mode 100644 index 0000000..1913e15 --- /dev/null +++ b/Documents/Docs/ChangeLogs/1405-08-16-v01.html @@ -0,0 +1,298 @@ + + + + + + گزارش تغییرات ۱۴۰۵/۰۸/۱۶ - v01 | xSaherelmWorkspace + + + +
+
+

گزارش بررسی تغییرات کل ساختار پروژه

+

xSaherelmWorkspace — وضعیت کاری Git و زیرماژول xAiMcpServer

+
+
+ تاریخ: ۱۴۰۵/۰۸/۱۶ (2026-11-07)نسخه مستند: v01شاخه: masterوضعیت: commit نشده +
+
+
+

۱. خلاصه اجرایی

+

+ تغییرات فعلی بر تکمیل قابلیت‌های MCP در زیرماژول + xAiMcpServer، به‌روزرسانی contextهای تولیدشده، توسعهٔ + مستندات توسعه و اصلاح نمونه‌های درخواست API متمرکز است. +

+
+ مبنای گزارش: git status و diff ریشه، + وضعیت و diff داخلی زیرماژول xAiMcpServer، و فهرست + فایل‌های جدید. این گزارش وضعیت کاری فعلی است و به‌معنای commit نهایی + نیست. +
+
+
+

۲. تغییرات ریشهٔ Workspace

+ + + + + + + + + + + + + + + + + + + + + +
بخشتغییرات شناسایی‌شده
GeneratedContext + حذف چهار context مربوط به 2026-11-06 و ایجاد چهار context جدید + در Documents/GeneratedContext برای + xAiApi، xAiMcpServer، + xAiModels و xAiService با + timestampهای 2026-11-07. +
مستندات Developer + ایجاد چهار فایل HTML دربارهٔ تولید فایل توسط LLM، مرور مدل‌های + زبانی، مدیریت memory/context و نقشهٔ راه multi-agent. +
Requests.md + به‌روزرسانی مقادیر نمونهٔ پاسخ Authentication شامل access + token، refresh token و زمان انقضا. مقادیر حساس عمداً در این + گزارش تکرار نشده‌اند. +
+
+
+

۳. تغییرات زیرماژول xAiMcpServer

+
    +
  • + افزودن XLinkExtractionTool برای استخراج لینک‌های + HTTP/HTTPS از متن و خواندن محتوای متنی صفحات وب. +
  • +
  • + افزودن مدل‌های XExtractedLink، + XLinkBundle، XLinkContentResult و + XWebSearchToolResult و حذف مدل قدیمی نتیجهٔ جست‌وجو. +
  • +
  • + افزودن XAiMcpLinkExtractionToolConfiguration با + محدودیت تعداد لینک و تعداد کاراکتر. +
  • +
  • + گسترش DI و ConfigurationNodeNames برای ثبت تنظیمات + ابزار استخراج لینک و سرویس‌های مرتبط. +
  • +
  • + اصلاح قرارداد و provider جست‌وجوی وب برای استفاده از نتیجهٔ جدید، + cache، محدودسازی نتایج، fallback و مدیریت anomaly پاسخ DuckDuckGo. +
  • +
  • + افزودن تنظیمات مربوط به ابزار استخراج لینک و تغییرات پیکربندی + اجرایی در appsettings.json. +
  • +
+
+
+

۴. فایل‌های اصلی درگیر

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
مسیرنوع تغییر
xAiMcpServer/Tools/XLinkExtractionTool.csجدید؛ ابزار MCP استخراج و دریافت محتوای لینک
+ xAiMcpServer/Configurations/XAiMcpLinkExtractionToolConfiguration.cs + جدید؛ تنظیمات ابزار
+ xAiMcpServer/Models/XExtractedLink.cs، + XLinkBundle.cs، + XLinkContentResult.cs، + XWebSearchToolResult.cs + جدید؛ مدل‌های خروجی و داده
xAiMcpServer/DI/DiExtensions.csاصلاح؛ ثبت configuration و سرویس‌ها
+ xAiMcpServer/Providers/XAiMcpWebSearchService.cs + اصلاح؛ مدل نتیجه، cache، fallback و parse
+
+ +
+

۵. وضعیت اعتبارسنجی و نکات قبل از commit

+
+ وضعیت ریشه و تغییرات داخلی xAiMcpServer بررسی شد؛ + فایل‌های جدید و حذف‌شده با Git تطبیق داده شدند. +
+
    +
  1. + به‌دلیل وجود credential و API key در Requests.md، پیش + از commit نهایی بررسی کنید این فایل باید در مخزن بماند یا مقادیر + به secret امن منتقل شوند. +
  2. +
  3. + برای submodule، تغییرات داخلی باید در خود مخزن + xAiMcpServer commit و سپس pointer ریشه به‌روزرسانی + شود. +
  4. +
  5. + build، تست‌های واحد و تست endpointهای MCP، استخراج لینک و جست‌وجوی + وب هنوز اجرا نشده‌اند و باید قبل از commit انجام شوند. +
  6. +
  7. + برای مستندسازی نوبت بعدی از 1405-08-16-v02.html و + CommitMessage-1405-08-16-v02.txt استفاده کنید. +
  8. +
+
+
+
+ فایل مرتبط: CommitMessage-1405-08-16-v01.txt | برای تغییرات + بعدی شماره نسخه را افزایش دهید. +
+
+ + diff --git a/Documents/Docs/ChangeLogs/CommitMessage-1405-08-16-v01.txt b/Documents/Docs/ChangeLogs/CommitMessage-1405-08-16-v01.txt new file mode 100644 index 0000000..2a0915a --- /dev/null +++ b/Documents/Docs/ChangeLogs/CommitMessage-1405-08-16-v01.txt @@ -0,0 +1,53 @@ +================================================================================ + Commit Message - xSaherelmWorkspace + تاریخ: ۱۴۰۵/۰۸/۱۶ (2026-11-07) + نسخه مستند: v01 + گزارش کامل: Documents/Docs/ChangeLogs/1405-08-16-v01.html +================================================================================ + +هدف: تکمیل قابلیت‌های MCP در xAiMcpServer، اضافه‌کردن ابزار استخراج و خواندن +محتوای لینک، اصلاح جست‌وجوی وب، تولید contextهای جدید و به‌روزرسانی مستندات. + +وضعیت: این پیام بر اساس وضعیت کاری فعلی تهیه شده است؛ تغییرات هنوز commit نشده‌اند. + +[1] xAiMcpServer / Link Extraction +- افزودن XLinkExtractionTool برای استخراج لینک‌های HTTP/HTTPS از متن و HTML. +- افزودن قابلیت دریافت و استخراج متن قابل‌خواندن از محتوای صفحات وب. +- افزودن تنظیمات XAiMcpLinkExtractionToolConfiguration برای MaxLinks و MaxChars. +- افزودن مدل‌های XExtractedLink، XLinkBundle و XLinkContentResult. +- ثبت ابزار و تنظیمات جدید در DI و ConfigurationNodeNames. + +[2] xAiMcpServer / Web Search +- تغییر قرارداد IXAiMcpWebSearchService برای بازگرداندن XWebSearchToolResult. +- جایگزینی مدل قدیمی XAiMcpWebSearchToolResult با مدل جدید نتیجهٔ جست‌وجو. +- اصلاح provider جست‌وجوی وب برای cache، محدودسازی نتایج، fallback و تشخیص anomaly. +- به‌روزرسانی appsettings.json برای پیکربندی قابلیت‌های جدید. + +[3] Workspace Generated Context +- حذف چهار context قدیمی مربوط به 2026-11-06. +- افزودن contextهای جدید 2026-11-07 برای xAiApi، xAiMcpServer، xAiModels و xAiService. + +[4] Documentation +- افزودن مستندات HTML در Documents/Docs/Developer دربارهٔ تولید فایل توسط LLM، + مدل‌های زبانی، مدیریت memory/context و نقشهٔ راه multi-agent. +- ثبت این گزارش تغییرات و پیام commit در Documents/Docs/ChangeLogs. + +[5] API Request Examples +- به‌روزرسانی نمونهٔ پاسخ Authentication در Documents/Resources/Json/Requests.md. +- مقادیر credential و token در این پیام بازتولید نشده‌اند؛ پیش از commit بررسی امنیتی + انجام شود و در صورت امکان secretها از مستندات نمونه خارج شوند. + +Validation: +- git status و diff ریشه بررسی شد. +- وضعیت و diff داخلی xAiMcpServer بررسی شد. +- build، تست واحد و تست end-to-end هنوز اجرا نشده‌اند. +- تغییرات داخلی submodule باید جداگانه commit شوند و سپس pointer ریشه به‌روزرسانی شود. + +Suggested commit title: +Add Link Extraction Tool and Improve MCP Web Search Integration +(۱۴۰۵/۰۸/۱۶ v01) + +برای مستندسازی تغییرات بعدی، شماره نسخه را افزایش دهید: +1405-08-16-v02.html +CommitMessage-1405-08-16-v02.txt +================================================================================ diff --git a/Documents/Docs/Developer/Force LLMs to Generate Files.html b/Documents/Docs/Developer/Force LLMs to Generate Files.html new file mode 100644 index 0000000..7cced43 --- /dev/null +++ b/Documents/Docs/Developer/Force LLMs to Generate Files.html @@ -0,0 +1,1322 @@ + + + + + +آموزش مدل برای تولید فایل‌های خروجی | راهنمای جامع فنی + + + + +
+ +
+
+
+ +
+
+
شماره مستند: GUIDE-1405-014
+
نسخه: ۱.۰
+
تاریخ تهیه: شهریور ۱۴۰۵
+
طبقه‌بندی: عمومی
+
+
+ +
+ TECHNICAL GUIDE +

آموزش مدل برای تولید فایل‌های خروجی

+

ورد، PDF، اکسل و فراتر از آن — معماری، روش‌ها و نقشه راه پیاده‌سازی

+
+
+ +
+ +
+ پرسش اصلی:
+ «چطور می‌شود یک مدل را آموزش داد تا بتواند فایل‌های مختلفی را به‌عنوان خروجی تولید کند؟ مثلاً فایل Word، PDF یا Excel.»

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

خلاصه اجرایی

+
Executive Summary
+
+
+
+

پیش از هر چیز باید یک تصور غلط رایج را اصلاح کرد: مدل زبانی «فایل» تولید نمی‌کند. فایل Word یا Excel یک ساختار دودویی/فشرده‌شده (ZIP با XML داخلی) است که مدل زبانی به‌طور مستقیم و قابل‌اتکا نمی‌تواند آن را بنویسد. کاری که مدل واقعاً انجام می‌دهد، تولید محتوای ساختاریافته یا کد است؛ سپس یک لایه اجرایی (Runtime) آن را به فایل واقعی تبدیل می‌کند.

+ +
+
+
۳
لایه
+
مدل + ابزار + اعتبارسنجی
+
+
+
۳
رویکرد
+
تولید کد، Tool Calling، قالب‌محور
+
+
+
۵
سطح آموزش
+
از پرامپت تا Fine-tuning
+
+
+ +
+ نتیجه کلیدی: برای تولید فایل، به «آموزش دادن مدل برای نوشتن فایل» نیازی نیست. کافی است مدل را روی تولید داده ساختاریافته (JSON) یا کد کتابخانه‌ای آموزش دهید و یک لایه اجرایی امن در کنار آن قرار دهید. این جداسازی، هم دقت را بالا می‌برد و هم امنیت را تضمین می‌کند. +
+
+
+ +
+
+
۲
+
+

مدل ذهنی درست: معماری سه‌لایه

+
The Three-Layer Architecture
+
+
+
+

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

+ +
+
+
۱
+
لایه تصمیم (مدل)
+

محتوای فایل را می‌فهمد، ساختار می‌دهد و به JSON یا کد تبدیل می‌کند.

+
+
+
۲
+
لایه اجرا (Runtime)
+

با کتابخانه‌های تخصصی، داده را به فایل واقعی تبدیل و ذخیره می‌کند.

+
+
+
۳
+
لایه اعتبارسنجی
+

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

+
+
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
لایهوظیفهابزار نمونهریسک در صورت حذف
تصمیمتولید محتوا و ساختارLLM + JSON Schemaمحتوای بی‌ربط یا ناقص
اجراتبدیل داده به فایلpython-docx، openpyxl، WeasyPrintفایل خراب یا غیرقابل‌باز شدن
اعتبارسنجیکنترل کیفیت و صحتPydantic، بازخوانی فایل، تست بصریخطای خاموش و افت اعتماد کاربر
نتیجهسیستمی پایدار، قابل‌تست و قابل‌توسعه برای هر فرمت خروجی
+ +
+ 💡 قاعده طلایی: هرگز به مدل اجازه ندهید بایت‌های یک فایل را «حدس بزند». مدل باید فقط بگوید چه چیزی در فایل باشد؛ چگونگی ساخت فایل کار کد است. +
+
+
+ +
+
+
۳
+
+

سه رویکرد اصلی تولید فایل

+
Code Generation · Tool Calling · Template-Based
+
+
+
+

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

+ +

الف) تولید کد (Code Generation)

+

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

+ +
+ نمونه: تولید فایل Word با python-docx +from docx import Document +from docx.shared import Pt + +doc = Document() +doc.add_heading('گزارش ماهانه فروش', level=1) +doc.add_paragraph('این گزارش توسط مدل تولید شده است.') + +table = doc.add_table(rows=1, cols=3) +table.style = 'Light Grid Accent 1' +for i, h in enumerate(['محصول', 'تعداد', 'مبلغ']): + table.rows[0].cells[i].text = h + +doc.save('report.docx') +
+ +

ب) فراخوانی ابزار (Tool / Function Calling)

+

بهترین روش برای سیستم‌های تولیدی. ابزار از پیش ساخته شده و تست شده است؛ مدل فقط پارامترهای ساختاریافته (JSON) را پر می‌کند. دقت بالا، امنیت کامل و رفتار قابل پیش‌بینی.

+ +
+ تعریف ابزار برای مدل (JSON Schema) +{ + "name": "create_excel_report", + "description": "ساخت فایل اکسل از جدول داده", + "parameters": { + "type": "object", + "properties": { + "title": { "type": "string" }, + "headers": { "type": "array", "items": { "type": "string" } }, + "rows": { "type": "array", "items": { "type": "array" } }, + "sheet_name": { "type": "string", "default": "Sheet1" } + }, + "required": ["title", "headers", "rows"] + } +} +
+ +

ج) رویکرد قالب‌محور (Template-Based)

+

قالب‌های آماده (docx، html، xlsx) به همراه جایگزین‌کننده متغیر. مدل فقط داده‌ها را پر می‌کند. مناسب اسناد رسمی، فاکتور، قرارداد و گزارش‌هایی با چیدمان ثابت.

+ +
+ نمونه: تزریق داده در قالب Word با docxtpl +from docxtpl import DocxTemplate + +tpl = DocxTemplate('invoice_template.docx') # قالب با {{ name }} و {{ items }} +context = { + 'name': 'شرکت نمونه', + 'items': [{'title': 'خدمات', 'price': '۱۲,۰۰۰,۰۰۰'}], + 'total': '۱۲,۰۰۰,۰۰۰' +} +tpl.render(context) +tpl.save('invoice_out.docx') +
+ +

مقایسه رویکردها:

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
معیارتولید کدTool Callingقالب‌محور
انعطاف‌پذیریبسیار بالامتوسط (در محدوده ابزار)پایین (چیدمان ثابت)
دقت و اتکاپذیریمتغیربالابسیار بالا
امنیتنیازمند سندباکسبالابالا
هزینه پیاده‌سازیکم (اولیه) / زیاد (نگهداری)متوسطکم
کاربرد مناسبخروجی‌های نامحدود و خلاقانهسیستم‌های تولیدی و APIاسناد رسمی و تکرارشونده
+ +
+ ✓ پیشنهاد عملی: معماری ترکیبی بهترین گزینه است — Tool Calling به‌عنوان مسیر اصلی، قالب‌محور برای اسناد استاندارد، و تولید کد صرفاً در سندباکس برای موارد خاص. +
+
+
+ +
+
+
۴
+
+

ابزارها و کتابخانه‌ها به تفکیک فرمت

+
Libraries per Output Format
+
+
+
+

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

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
فرمتکتابخانه / ابزارنقطه قوتملاحظه فارسی / RTL
Word (.docx)python-docxکنترل کامل پاراگراف، جدول، استایلتنظیم دستی RTL و فونت
docxtplقالب‌محور و سادهعالی — قالب را در Word بسازید
Pandocتبدیل Markdown به docxخوب — با قالب مرجع
PDFWeasyPrintHTML/CSS → PDF با پشتیبانی خوب CSSبهترین گزینه برای فارسی و RTL
ReportLabکنترل دقیق و برنامه‌نویسی‌محورنیازمند شکل‌دهی دستی متن فارسی
LaTeX / XePersianکیفیت تایپوگرافی بی‌نظیرعالی برای متون علمی
Excel (.xlsx)openpyxlخواندن و نوشتن، استایل، فرمولپشتیبانی از RTL در تنظیمات شیت
XlsxWriterنمودار، قالب‌بندی پیشرفتهنوشتن سریع، مناسب گزارش‌سازی
pandas + openpyxlاز DataFrame به اکسلسریع‌ترین راه برای جداول داده
PowerPoint (.pptx)python-pptxاسلاید، چارت، تصویرنیازمند قالب RTL آماده
CSV / JSON / Markdownاستاندارد پایتونساده‌ترین و سریع‌ترین خروجیبدون پیچیدگی
+ +
+ ⭐ توصیه ویژه برای فارسی: برای PDF فارسی، مسیر HTML → WeasyPrint را انتخاب کنید. با CSS می‌توانید direction: rtl، فونت وزیرمتن و شکست صحیح خطوط را به‌سادگی کنترل کنید؛ در حالی که ReportLab برای متن فارسی نیاز به پردازش پیچیده دارد. +
+ +
+ نمونه: PDF فارسی از HTML با WeasyPrint +from weasyprint import HTML + +html = """ +<html dir="rtl"><head><meta charset="utf-8"> +<style> + @font-face { font-family: 'Vazir'; src: url('Vazirmatn-Regular.ttf'); } + body { font-family: 'Vazir'; direction: rtl; } + table { width: 100%; border-collapse: collapse; } + th, td { border: 1px solid #ccc; padding: 8px; } +</style></head> +<body><h1>گزارش فروش</h1> +<table><tr><th>محصول</th><th>مبلغ</th></tr> +<tr><td>کرم مرطوب‌کننده</td><td>۱۲۰٬۰۰۰ + +HTML(string=html).write_pdf('report.pdf') +
+
+
+ +
+
+
۵
+
+

پنج سطح «آموزش» مدل

+
From Prompting to Fine-Tuning
+
+
+
+

عبارت «آموزش مدل» می‌تواند به پنج سطح متفاوت اشاره داشته باشد. همیشه از سطح پایین شروع کنید؛ در بیشتر موارد نیازی به آموزش واقعی (Fine-tuning) نیست.

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
سطحروشهزینهچه زمانی؟
۱. پرامپت‌نویسیدستورالعمل + مثال (Few-shot)تقریباً صفرهمیشه — نقطه شروع
۲. خروجی ساختاریافتهJSON Schema / Structured Outputپایینوقتی قالب داده ثابت است
۳. فراخوانی ابزارتعریف توابع و پارامترهامتوسطسیستم‌های تولیدی
۴. RAGبازیابی مستندات کتابخانه‌هامتوسطAPIهای متغیر و نسخه‌های جدید
۵. Fine-tuningآموزش روی زوج‌های (درخواست → کد/JSON)بالافقط پس از اشباع چهار سطح قبل
+ +

چطور داده آموزشی برای Fine-tuning بسازیم؟

+

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

+ +
+ ساختار نمونه آموزشی (JSONL) +{"messages": [ + {"role": "system", "content": "تو یک مولد سند هستی. همیشه JSON معتبر طبق اسکیما برگردان."}, + {"role": "user", "content": "یک فاکتور برای ۳ قلم کالا بساز"}, + {"role": "assistant", "content": + "{\"type\":\"invoice\",\"items\":[{\"title\":\"A\",\"qty\":2,\"price\":100}],\"total\":200}"} +]} +
+ +
+ ⚠️ هشدار: Fine-tuning بدون مجموعه‌داده باکیفیت و ارزیابی دقیق، معمولاً نتیجه را بدتر می‌کند. ابتدا سطح ۱ تا ۴ را کامل کنید؛ در ۸۰٪ موارد پاسخ همین‌جاست. +
+ +
+ 💡 ترفند یادگیری از بازخورد اجرا: یک حلقه بسازید که خروجی مدل را در سندباکس اجرا کند. اگر فایل بدون خطا ساخته شد، آن نمونه به‌عنوان داده مثبت ذخیره شود؛ در غیر این صورت، خطا به مدل بازخورد داده شود. این چرخه به‌مرور کیفیت را بدون آموزش گران‌قیمت بالا می‌برد. +
+
+
+ +
+
+
۶
+
+

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

+
Implementation Roadmap
+
+
+
+

مسیر پیشنهادی از صفر تا سیستم پایدار، در شش گام:

+ +
+
+
+
گام ۱ — تعریف قرارداد داده
+

یک JSON Schema دقیق برای هر نوع سند بنویسید: فیلدهای اجباری، انواع داده و محدودیت‌ها. این قرارداد، مرز بین مدل و کد است.

+
+
+
+ +
+
+
گام ۲ — ساخت ابزار تولید فایل
+

برای هر فرمت یک تابع مستقل بنویسید که ورودی JSON بگیرد و فایل بسازد. این توابع باید کاملاً مستقل از مدل تست شوند.

+
+
+
+ +
+
+
گام ۳ — اتصال مدل به ابزار
+

ابزارها را با Tool Calling یا Structured Output به مدل معرفی کنید. مدل فقط پارامترها را پر می‌کند.

+
+
+
+ +
+
+
گام ۴ — سندباکس و اعتبارسنجی
+

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

+
+
+
+ +
+
+
گام ۵ — مجموعه ارزیابی (Eval Set)
+

۵۰ تا ۱۰۰ نمونه واقعی بسازید و هر تغییر را روی آن بسنجید. بدون این مجموعه، بهبود واقعی قابل تشخیص نیست.

+
+
+
+ +
+
+
گام ۶ — بهینه‌سازی و آموزش
+

فقط اگر کیفیت کافی نبود، به RAG یا Fine-tuning بروید. داده آموزشی را از لاگ‌های موفق بسازید.

+
+
+
+
+ +
+ ✓ معیار موفقیت: سیستمی که در آن، هر فایل تولیدشده بدون دخالت انسان باز شود، ساختارش درست باشد و محتوایش با درخواست کاربر مطابقت داشته باشد. +
+
+
+ +
+
+
۷
+
+

چالش‌ها و دام‌های رایج

+
Pitfalls & Mitigations
+
+
+
+

تجربه نشان می‌دهد بیشتر شکست‌ها ناشی از چند خطای مشخص است:

+ +
+ ⚠️ دام‌های فنی: +
    +
  • توهم API: مدل ممکن است متدهایی بسازد که در کتابخانه وجود ندارند. راه‌حل: RAG روی مستندات و تست اجباری.
  • +
  • نادیده‌گرفتن RTL: فایل ساخته می‌شود اما متن فارسی بی‌جهت و ناخوانا است. راه‌حل: تنظیم صریح جهت و فونت.
  • +
  • فونت ناموجود: در سرور، فونت فارسی نصب نیست و PDF با مربع نمایش داده می‌شود. راه‌حل: embed کردن فونت.
  • +
  • اعداد و ارقام: تفاوت ارقام فارسی و لاتین می‌تواند محاسبات را خراب کند.
  • +
  • حجم و حافظه: فایل‌های اکسل بزرگ می‌توانند حافظه سرور را اشغال کنند. راه‌حل: نوشتن جریانی (streaming).
  • +
  • اجرای کد ناامن: اجرای کد تولیدشده توسط مدل بدون سندباکس، یک آسیب‌پذیری جدی است.
  • +
+
+ +
+
+

روش شکننده ✗

+
    +
  • روش تولید بایت‌های خام فایل
  • +
  • اعتبارسنجی ندارد
  • +
  • اجرای کد بدون سندباکس
  • +
  • تست چشمی و دستی
  • +
+
+ + +
+
+
+ +
+
+
۸
+
+

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

+
Final Summary & Recommendation
+
+
+
+

پاسخ کوتاه به پرسش اصلی این است: برای تولید فایل، مدل را «آموزش» نمی‌دهیم تا فایل بنویسد؛ بلکه مدل را روی تولید داده ساختاریافته تنظیم می‌کنیم و لایه اجرایی را به کد می‌سپاریم.

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
فرمت هدفروش پیشنهادیابزار اصلی
Wordقالب‌محور یا python-docxdocxtpl / python-docx
PDFHTML/CSS → PDFWeasyPrint
ExcelTool Calling + openpyxlopenpyxl / XlsxWriter
PowerPointقالب‌محورpython-pptx
سطح آموزششروع از پرامپت و Schema؛ Fine-tuning فقط در صورت نیاز
+ +
+

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

+

معماری سه‌لایه (مدل + ابزار + اعتبارسنجی) را بپذیرید و با رویکرد Tool Calling شروع کنید.

+

این ترکیب، هم دقیق‌ترین خروجی را می‌دهد، هم امن‌ترین و هم قابل‌توسعه‌ترین — بدون نیاز به آموزش گران‌قیمت مدل.

+
+ 💎 فرمول موفقیت:
+ مدل محتوا را می‌سازد · کد فایل را می‌سازد · اعتبارسنجی کیفیت را تضمین می‌کند +
+
+ +
+ 📞 گام بعدی: اگر بخواهید، می‌توان معماری فوق را برای یک فرمت مشخص (مثلاً فاکتور Word یا گزارش اکسل) به‌صورت کامل و اجرایی پیاده‌سازی کرد — شامل Schema، ابزار تولید فایل، سندباکس و مجموعه ارزیابی. +
+
+
+ +
+ این مستند راهنمای فنی عمومی است و قابل به‌روزرسانی بر اساس نسخه‌های جدید کتابخانه‌ها می‌باشد. +
+ +
+ +
+ + +
تاریخ تهیه: شهریور ۱۴۰۵  |  نسخه: ۱.۰  |  طبقه‌بندی: عمومی
+
+ +
+ + + \ No newline at end of file diff --git a/Documents/Docs/Developer/LLMs Overview 14050817.html b/Documents/Docs/Developer/LLMs Overview 14050817.html new file mode 100644 index 0000000..428c259 --- /dev/null +++ b/Documents/Docs/Developer/LLMs Overview 14050817.html @@ -0,0 +1,984 @@ + + + + + +تحلیل جامع مدل‌های چندوجهی | پیشنهاد بهترین گزینه + + + + +
+ +
+
+
+ +
+
+
شماره مستند: MODEL-1405-002
+
نسخه: ۱.۰
+
تاریخ تهیه: آذر ۱۴۰۵
+
طبقه‌بندی: محرمانه
+
+
+ +
+ MODEL EVALUATION & RECOMMENDATION +

تحلیل جامع مدل‌های چندوجهی

+

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

+
+
+ +
+ +
+ کارفرمای محترم،
+ این مستند به‌عنوان تحلیلی جامع و مبتنی بر داده‌های فنی و مستندات رسمی مدل‌ها، فهرست گسترده‌ای از مدل‌های چندوجهی (Omni-modal) و بینایی-زبانی (Vision-Language) را از نظر چهار معیار کلیدی بررسی می‌کند: پشتیبانی از زبان فارسی، قابلیت OCR، تولید صوت (Speech Generation) و امکان اجرا در محیط‌های محلی (Local / GGUF). هدف، ارائه شفافیت کامل و کمک به انتخاب بهینه‌ترین مدل برای نیازهای پروژه است. +
+ +
+
+
۱
+
+

خلاصه اجرایی

+
Executive Summary
+
+
+
+

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

+ +
+
+
Bina 0.4
Koochik
+
بهترین گزینه برای OCR فارسی
+
+
+
MiniCPM-o
4.5
+
بهترین تعادل بین OCR، صوت و اجرای محلی
+
+
+
Qwen2.5
Omni
+
قوی‌ترین گزینه برای تولید صوت چندزبانه
+
+
+ +
+ نتیجه کلیدی: برای پروژه‌هایی که OCR فارسی اولویت اصلی است، مدل Bina 0.4 Koochik به‌صورت تخصصی طراحی شده و بهترین عملکرد را دارد. برای نیاز هم‌زمان به OCR، درک صوت و اجرای محلی، مدل MiniCPM-o 4.5 گزینه‌ای متعادل و قدرتمند است. اما اگر تولید صوت (TTS) چندزبانه حیاتی باشد، Qwen2.5-Omni (نسخه ۷B) پیشتاز است، هرچند پشتیبانی از فارسی در آن به‌صراحت تأیید نشده است. +
+
+
+ +
+
+
۲
+
+

معیارهای ارزیابی

+
Evaluation Criteria
+
+
+
+

چهار معیار اصلی برای مقایسه مدل‌ها در نظر گرفته شده است:

+
    +
  • پشتیبانی از زبان فارسی (Persian Support): توانایی درک و تولید متن فارسی به‌صورت بومی یا از طریق آموزش تخصصی.
  • +
  • قابلیت OCR (Optical Character Recognition): توانایی استخراج متن از تصاویر، اسناد و صفحات وب، به‌ویژه متون فارسی.
  • +
  • تولید صوت (Speech Generation / TTS): توانایی تبدیل متن به گفتار طبیعی (Text-to-Speech).
  • +
  • اجرای محلی (Local Execution): امکان اجرا روی سخت‌افزارهای محلی (CPU/GPU) با فرمت‌های بهینه مانند GGUF و از طریق ابزارهایی مثل llama.cpp یا Ollama.
  • +
+
+
+ +
+
+
۳
+
+

جدول مقایسه جامع مدل‌ها

+
Comprehensive Model Comparison
+
+
+
+

جدول زیر خلاصه‌ای از وضعیت هر مدل را بر اساس چهار معیار اصلی نشان می‌دهد. (✓ = پشتیبانی کامل، ~ = پشتیبانی محدود یا غیرمستند، ✗ = بدون پشتیبانی)

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
مدلپشتیبانی فارسیOCRتولید صوتاجرای محلینقاط قوت کلیدی
LFM3-Omni-2B~ (غیرمستند)✓✓✓ (GGUF)سبک، Omni واقعی، TTS با کیفیت
MiniCPM-o-4.5~ (چندزبانه)✓ (قوی)✓ (EN/ZH)✓ (GGUF, Ollama)OCR پیشرو، صوت بلادرنگ، اجرای محلی عالی
Qwen2.5-Omni-3B / 7B~ (غیرمستند)✓✓ (چندزبانه)✓ (GGUF)تولید صوت چندزبانه، درک ویدیو
Bina 0.1 / 0.3 / 0.4 Koochik✓ (تخصصی)✓ (فارسی)✗✓ (GGUF, CoreML)بهترین OCR فارسی، سبک و بهینه
SenseNova-U1.5-8B-MoT~ (غیرمستند)~ (تولید تصویر)✗~تمرکز بر تولید تصویر و متن، نه OCR/صوت
Qwen3-Omni-Coder~✓ (32 زبان)✓~OCR چندزبانه گسترده، کدنویسی
Nemotron-3-Nano-Omni-30B✗ (بهینه برای انگلیسی)✓✓ (ASR)✓ (GGUF)درک ویدیو و صوت، OCR قوی
dots3-note-prev~✓✗ (فقط متن)~درک صوت و ویدیو، اما خروجی فقط متنی
Ling-3.0-Flash-VL~~✗~بینایی-زبانی، بدون تولید صوت
Gemma-4-E2B-it (RK182X)~✓~ (ASR)✓ (GGUF)OCR و درک صوت، مناسب لبه
Nemotron-3.5-Bolt-E4B~ (35 زبان)~✗ (فقط متن)✓ (GGUF)سبک، چندزبانه، بدون تولید صوت
+ +
+ توجه: مدل‌های «mythos»، «Lmlm»، «MLQarnonai» و «Mia-v1» در بررسی‌های انجام‌شده، عمدتاً مدل‌های متنی یا فاقد قابلیت‌های چندوجهی مشخص (OCR/صوت) شناسایی شدند و در این مقایسه تخصصی جای نمی‌گیرند. همچنین برخی URLها تکراری بودند و مدل‌های یکسانی را معرفی می‌کردند. +
+
+
+ +
+
+
۴
+
+

تحلیل تفصیلی مدل‌های کلیدی

+
Detailed Analysis of Key Models
+
+
+
+ +

۴.۱. Bina 0.4 Koochik — قهرمان OCR فارسی

+

مدل Bina 0.4 Koochik یک مدل تصویر-به-متن با ۶۳۰ میلیون پارامتر است که به‌طور اختصاصی برای رونویسی اسناد فارسی طراحی شده است. این مدل از معماری Nemotron-3.5-Parse مشتق شده و دارای ستون فقرات بینایی C-RADIOv4-SO400M است. نسخه‌های GGUF و CoreML آن برای اجرای محلی بهینه شده‌اند و حتی در مرورگر با WebGPU قابل اجرا هستند. ارزیابی‌ها نشان می‌دهد که این مدل در بنچمارک PersianOCR-TripleThreat عملکرد قابل‌قبولی دارد. اگر اولویت اصلی پروژه OCR فارسی باشد، Bina بدون شک بهترین انتخاب است.[reference:0][reference:1]

+
+ ✓ مزیت کلیدی: تخصص کامل در OCR فارسی، اجرای محلی بسیار سبک (حتی روی CPU)، و وجود نسخه‌های کوانتیزه متعدد. +
+ +

۴.۲. MiniCPM-o 4.5 — متعادل‌ترین گزینه

+

مدل MiniCPM-o 4.5 یک مدل Omni-modal end-to-end است که هم‌زمان قابلیت پردازش تصویر، ویدیو، صوت و متن را دارد. این مدل در OCR عملکرد بسیار قوی دارد (به‌ویژه برای اسناد انگلیسی) و در بنچمارک OmniDocBench از مدل‌های تجاری پیشی گرفته است. همچنین از تولید صوت بلادرنگ (در زبان‌های انگلیسی و چینی) پشتیبانی می‌کند و قابلیت اجرای محلی عالی با فرمت‌های GGUF و Ollama دارد. هرچند پشتیبانی از فارسی در آن به‌صراحت تأیید نشده، اما قابلیت چندزبانه آن (بیش از ۳۰ زبان) و توانایی OCR قوی، آن را به گزینه‌ای مناسب برای پروژه‌های چندمنظوره تبدیل می‌کند.[reference:2]

+
+ نکته: اگر نیاز به ترکیبی از OCR، درک صوت و اجرای محلی دارید و می‌توانید زبان فارسی را از طریق Fine-tune یا استفاده از مدل‌های مکمل پوشش دهید، MiniCPM-o 4.5 انتخاب هوشمندانه‌ای است. +
+ +

۴.۳. Qwen2.5-Omni (3B / 7B) — پیشتاز تولید صوت چندزبانه

+

مدل Qwen2.5-Omni از معماری Thinker-Talker استفاده می‌کند و توانایی درک هم‌زمان متن، تصویر، صوت و ویدیو را دارد. این مدل در تولید صوت (TTS) و تبدیل گفتار به متن (ASR) چندزبانه بسیار قدرتمند است و در بنچمارک‌های گفتاری رتبه بالایی دارد. نسخه‌های ۳B و ۷B آن با فرمت GGUF برای اجرای محلی در دسترس هستند. با این حال، پشتیبانی از زبان فارسی در مستندات رسمی آن به‌صراحت ذکر نشده و تمرکز اصلی آن بر زبان‌های انگلیسی و چینی است.[reference:3][reference:4]

+
+ ⚠️ محدودیت: در صورت نیاز به تولید صوت فارسی، باید پشتیبانی زبان فارسی در نسخه‌های آینده یا از طریق آموزش اضافی بررسی شود. +
+ +

۴.۴. LFM3-Omni-2B — گزینه سبک و Omni واقعی

+

LFM3-Omni-2B یک مدل ۲.۱۷ میلیارد پارامتری است که به‌صورت end-to-end طراحی شده و ورودی‌های متنی، تصویری، ویدیویی و صوتی را پردازش کرده و خروجی متنی یا صوتی می‌دهد. این مدل برای اجرای روی دستگاه‌های لبه (مانند گوشی و لپ‌تاپ) بهینه شده و از GGUF پشتیبانی می‌کند. در OCR و TTS عملکرد خوبی دارد، اما زبان‌های پشتیبانی‌شده آن شامل فارسی نمی‌شود (حداقل در مستندات رسمی).[reference:5]

+
+ 💡 کاربرد: اگر به دنبال یک مدل سبک با قابلیت Omni و اجرای محلی هستید و می‌توانید فارسی را به‌صورت جداگانه مدیریت کنید، LFM3-Omni-2B گزینه مناسبی است. +
+ +

۴.۵. Nemotron-3-Nano-Omni-30B — قدرت بالا، اما نه برای فارسی

+

این مدل از NVIDIA با ۳۰ میلیارد پارامتر (۳ میلیارد فعال) قابلیت‌های چندوجهی گسترده‌ای شامل OCR، درک ویدیو و رونویسی گفتار دارد. با این حال، بهینه‌سازی اصلی آن برای زبان انگلیسی است و زبان فارسی در فهرست زبان‌های پشتیبانی‌شده آن به‌طور مشخص ذکر نشده است.[reference:6]

+
+ ⚠️ هشدار: برای پروژه‌های فارسی‌محور، استفاده از این مدل بدون Fine-tune توصیه نمی‌شود. +
+ +

۴.۶. سایر مدل‌ها

+
    +
  • SenseNova-U1.5-8B-MoT: تمرکز اصلی آن بر تولید تصویر و متن است و قابلیت OCR یا تولید صوت ندارد.[reference:7]
  • +
  • Qwen3-Omni-Coder: OCR چندزبانه (۳۲ زبان) و قابلیت کدنویسی دارد، اما پشتیبانی از فارسی و تولید صوت آن به‌طور کامل تأیید نشده است.[reference:8]
  • +
  • dots3-note-prev: توانایی درک صوت و ویدیو را دارد، اما خروجی آن فقط متنی است و تولید صوت نمی‌کند.[reference:9]
  • +
  • Ling-3.0-Flash-VL: یک مدل بینایی-زبانی است و تولید صوت ندارد.[reference:10]
  • +
  • Gemma-4-E2B-it (RK182X): از OCR و درک صوت پشتیبانی می‌کند و برای اجرای محلی مناسب است، اما فارسی در آن تأیید نشده است.[reference:11]
  • +
  • Nemotron-3.5-Bolt-E4B: مدلی سبک و چندزبانه (۳۵ زبان) است، اما تولید صوت ندارد و خروجی آن فقط متنی است.[reference:12]
  • +
+ +
+
+ +
+
+
۵
+
+

ماتریس تصمیم‌گیری و پیشنهاد نهایی

+
Decision Matrix & Final Recommendation
+
+
+
+

بر اساس اولویت‌های پروژه، پیشنهاد نهایی به شرح زیر است:

+ +
+ + + +
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
اولویت پروژهپیشنهاد اولپیشنهاد جایگزین
OCR فارسی با کیفیت بالاBina 0.4 KoochikBina 0.3 Koochik (سبک‌تر)
OCR + درک صوت + اجرای محلیMiniCPM-o 4.5LFM3-Omni-2B (سبک‌تر)
تولید صوت چندزبانه (TTS)Qwen2.5-Omni (7B)Qwen2.5-Omni (3B)
OCR چندزبانه + کدنویسیQwen3-Omni-Coder—
سبک‌ترین گزینه با قابلیت OmniLFM3-Omni-2BNemotron-3.5-Bolt-E4B (بدون TTS)
+ +
+

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

+

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

+

برای OCR فارسی از Bina استفاده کنید. برای تولید صوت و درک چندوجهی، MiniCPM-o 4.5 یا Qwen2.5-Omni گزینه‌های برتر هستند. اگر به دنبال یک راه‌حل یکپارچه هستید، MiniCPM-o 4.5 بهترین تعادل را ارائه می‌دهد.

+
+ 💎 توصیه نهایی:
+ Bina 0.4 Koochik برای OCR فارسی + MiniCPM-o 4.5 برای صوت و درک چندوجهی + اجرای محلی +
+
+ +
+ 📞 گام بعدی: در صورت تمایل به شروع همکاری، آماده برگزاری جلسه فنی جهت تشریح جزئیات، تست مدل‌ها روی داده‌های واقعی و انتخاب نهایی معماری هستیم. +
+
+
+ +
+
+
۶
+
+

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

+
References
+
+
+
+
    +
  • + Bina 0.4 Koochik — Hugging Face + مدل تخصصی OCR فارسی +
    منبع: https://huggingface.co/Reza2kn/Bina-0.4-Koochik
    +
  • +
  • + Bina 0.3 Koochik — Hugging Face + نسخه سبک‌تر با عملکرد مشابه +
    منبع: https://huggingface.co/Reza2kn/Bina-0.3-Koochik
    +
  • +
  • + MiniCPM-o 4.5 — GitHub / Hugging Face + مدل Omni-modal با OCR و صوت بلادرنگ +
    منبع: https://huggingface.co/openbmb/MiniCPM-o-4_5
    +
  • +
  • + Qwen2.5-Omni — GitHub + مدل چندوجهی با تولید صوت چندزبانه +
    منبع: https://github.com/QwenLM/Qwen2.5-Omni
    +
  • +
  • + LFM3-Omni-2B — Hugging Face + مدل Omni سبک برای دستگاه‌های لبه +
    منبع: https://huggingface.co/LiquidAI/LFM3-Omni-2B
    +
  • +
  • + Nemotron-3-Nano-Omni-30B — NVIDIA + مدل چندوجهی با OCR و ASR +
    منبع: https://huggingface.co/nvidia/Nemotron-3-Nano-Omni-30B-A3B
    +
  • +
+

سایر مدل‌های بررسی‌شده شامل dots3-note-prev، Ling-3.0-Flash-VL، Gemma-4-E2B-it و Nemotron-3.5-Bolt-E4B نیز بر اساس مستندات رسمی Hugging Face و GitHub ارزیابی شده‌اند.

+
+
+ +
+ این مستند محرمانه بوده و صرفاً جهت ارائه به کارفرمای محترم تهیه شده است. هرگونه کپی‌برداری یا افشا بدون اجازه کتبی ممنوع است. +
+ +
+ +
+ + +
تاریخ تهیه: آذر ۱۴۰۵  |  نسخه: ۱.۰  |  طبقه‌بندی: محرمانه
+
+ +
+ + + \ No newline at end of file diff --git a/Documents/Docs/Developer/Memory Strategies and Context Management 1.html b/Documents/Docs/Developer/Memory Strategies and Context Management 1.html new file mode 100644 index 0000000..24c4737 --- /dev/null +++ b/Documents/Docs/Developer/Memory Strategies and Context Management 1.html @@ -0,0 +1,1455 @@ + + + + + +مدیریت حافظه و کانتکس در پروژه‌های هوش مصنوعی | راهنمای جامع + + + + +
+ +
+
+
+ +
+
+
شماره مستند: AI-ARCH-1405-022
+
نسخه: ۱.۰
+
تاریخ تهیه: شهریور ۱۴۰۵
+
طبقه‌بندی: فنی
+
+
+ +
+ ARCHITECTURE GUIDE +

مدیریت حافظه و کنترل کانتکس در ایجنت‌ها

+

از استراتژی‌های حافظه در پروژه‌های هوش مصنوعی تا غلبه بر محدودیت کانتکس در مدل‌های محلی

+
+
+ +
+ +
+ چکیده:
+ در پروژه‌های هوش مصنوعی، «حافظه» و «کانتکس» دو مفهوم کلیدی و در هم تنیده‌اند. حافظه تعیین می‌کند سیستم چه چیزی را به خاطر می‌سپارد و کانتکس تعیین می‌کند مدل در هر لحظه چه چیزی را می‌بیند. این مستند ابتدا انواع حافظه و استراتژی‌های مدیریت آن را تشریح می‌کند، سپس با تمرکز بر مدل‌های محلی با پنجره کانتکس محدود، روش‌های عملی کنترل کانتکس در ایجنت‌ها را ارائه می‌دهد. +
+ +
+
+
۱
+
+

خلاصه اجرایی

+
Executive Summary
+
+
+
+

مدل‌های زبانی «حافظه» به معنای انسانی ندارند؛ آنچه ما حافظه می‌نامیم، در واقع بازسازی اطلاعات از منابع بیرونی و قرار دادن آن در پنجره کانتکس است. بنابراین مدیریت حافظه یعنی مدیریت اینکه چه چیزی، چه زمانی و به چه مقدار در کانتکس قرار گیرد.

+ +
+
+
۵
نوع حافظه
+
کاری، اپیزودیک، معنایی، رویه‌ای، بلندمدت
+
+
+
۷
استراتژی کانتکس
+
از پنجره لغزان تا فشرده‌سازی
+
+
+
۱
قاعده اصلی
+
کانتکس گران است؛ فقط ضروری‌ها را وارد کن
+
+
+ +
+ نتیجه کلیدی: در مدل‌های محلی با کانتکس محدود (مثلاً ۴K تا ۳۲K توکن)، کیفیت ایجنت مستقیماً به توانایی شما در انتخاب، خلاصه‌سازی و بازسازی اطلاعات بستگی دارد، نه به بزرگی پنجره کانتکس. معماری درست، این محدودیت را به یک مزیتِ سرعت و هزینه تبدیل می‌کند. +
+
+
+ +
+
+
۲
+
+

انواع حافظه در سیستم‌های هوش مصنوعی

+
Memory Taxonomy
+
+
+
+

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

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
نوع حافظهمحتوامحل نگهداریمدت ماندگاری
کاری (Working)پیام‌های جاری، ابزارهای فعال، وضعیت لحظه‌ایپنجره کانتکسیک نوبت مکالمه
اپیزودیک (Episodic)تاریخچه مکالمات و رویدادهای گذشتهپایگاه داده / فایل لاگروز تا ماه
معنایی (Semantic)حقایق، دانش دامنه، مستنداتVector DB / Knowledge Graphبلندمدت
رویه‌ای (Procedural)دستورالعمل‌ها، ابزارها، مهارت‌هاپرامپت سیستم / کد ابزارثابت تا نسخه بعدی
بلندمدت (Long-Term)خلاصه‌های تجمیع‌شده و پروفایل کاربرفایل / DB ساختاریافتهماه تا سال
+ +
+ 💡 نکته معماری: تنها «حافظه کاری» داخل کانتکس مدل است. بقیه حافظه‌ها بیرون از مدل نگهداری می‌شوند و هنگام نیاز، بخشی از آن‌ها به کانتکس «بازیابی» می‌شود. کل هنر مدیریت حافظه، همین بازیابی هوشمندانه است. +
+
+
+ +
+
+
۳
+
+

استراتژی‌های مدیریت حافظه

+
Memory Management Strategies
+
+
+
+

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

+ +
+
+
A
+
ذخیره‌سازی
+

اطلاعات مهم را در منابع پایدار بیرونی نگه دار.

+
+
+
B
+
بازیابی
+

در هر لحظه، مرتبط‌ترین اطلاعات را پیدا و وارد کن.

+
+
+
C
+
تجمیع و فراموشی
+

اطلاعات کهنه را خلاصه یا حذف کن تا فضا آزاد شود.

+
+
+ +

الف) استراتژی‌های ذخیره‌سازی

+
    +
  • حافظه برداری (Vector Store): ذخیره امبدینگ‌ها در پایگاه‌هایی مانند Chroma، FAISS یا Qdrant برای بازیابی معنایی.
  • +
  • پایگاه داده ساختاریافته: ذخیره حقایق و پروفایل کاربر به‌صورت SQL یا Key-Value برای دقت بالا.
  • +
  • گراف دانش (Knowledge Graph): مدل‌سازی روابط بین موجودیت‌ها برای استدلال چندمرحله‌ای.
  • +
  • فایل‌های حافظه (Memory Files): ساده‌ترین و مؤثرترین روش برای ایجنت‌های محلی — ذخیره خلاصه‌ها در memory.md یا JSON.
  • +
+ +

ب) استراتژی‌های بازیابی

+
    +
  • جستجوی برداری (Semantic Search): یافتن نزدیک‌ترین معنایی به پرسش جاری.
  • +
  • بازیابی ترکیبی (Hybrid): ترکیب جستجوی کلیدواژه (BM25) و برداری برای دقت بیشتر.
  • +
  • بازیابی زمان‌محور: اولویت‌دهی به اطلاعات جدیدتر در مکالمات طولانی.
  • +
  • توجه به اهمیت (Importance Scoring): امتیازدهی به هر قطعه حافظه بر اساس اهمیت و تازگی.
  • +
+ +

ج) استراتژی‌های تجمیع و فراموشی

+
    +
  • خلاصه‌سازی تدریجی: هر N پیام، مکالمه قدیمی را با یک خلاصه جایگزین کن.
  • +
  • تجمیع حافظه (Consolidation): حقایق پراکنده را در یک نمای کلی ادغام کن (مثل خواب REM).
  • +
  • منحنی فراموشی: اطلاعات کم‌استفاده به‌تدریج وزن کمتری بگیرند و آرشیو شوند.
  • +
  • حذف مبتنی بر TTL: تعیین تاریخ انقضا برای حافظه‌های موقت.
  • +
+ +
+ نمونه: ساختار ساده یک سیستم حافظه سه‌لایه +from dataclasses import dataclass, field +from typing import List, Dict +import time + +@dataclass +class MemoryItem: + content: str + importance: float = 0.5 + timestamp: float = field(default_factory=time.time) + access_count: int = 0 + +class ThreeTierMemory: + def __init__(self): + self.working: List[MemoryItem] = [] # در کانتکس + self.episodic: List[MemoryItem] = [] # تاریخچه کامل + self.semantic: Dict[str, MemoryItem] = {} # حقایق پایدار + + def add(self, content, importance=0.5, tier='working'): + item = MemoryItem(content, importance) + if tier == 'working': + self.working.append(item) + elif tier == 'episodic': + self.episodic.append(item) + else: + self.semantic[content[:50]] = item + + def consolidate(self): + # انتقال موارد مهم از کاری به اپیزودیک، و ادغام + important = [m for m in self.working if m.importance > 0.7] + self.episodic.extend(important) + self.working = [m for m in self.working if m.importance <= 0.7] + return len(important) + + def decay(self, threshold=0.2): + # فراموشی تدریجی بر اساس اهمیت و زمان + now = time.time() + for m in self.episodic: + age_days = (now - m.timestamp) / 86400 + m.importance *= 0.99 ** age_days + self.episodic = [m for m in self.episodic if m.importance > threshold] +
+ +
+ ✓ قاعده سرانگشتی: هرگز همه‌چیز را در کانتکس نگه ندارید. حافظه خوب، حافظه‌ای است که بتواند فراموش کند — دقیقاً مثل انسان. +
+
+
+ +
+
+
۴
+
+

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

+
Context Window Limits in Local Models
+
+
+
+

مدل‌های محلی (Llama، Mistral، Qwen، Gemma و مشابه) به‌طور معمول پنجره کانتکس ۴K تا ۳۲K توکن دارند — بسیار کمتر از مدل‌های ابری که تا ۲۰۰K می‌رسند. این محدودیت از سه منبع ناشی می‌شود:

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
منبع محدودیتتوضیحپیامد عملی
معماری مدلطول آموزش‌دیده و حافظه KV Cacheفراتر از آن، کیفیت به‌شدت افت می‌کند
حافظه سخت‌افزار (VRAM)KV Cache با طول متن به‌صورت خطی رشد می‌کندکانتکس بزرگ = مصرف حافظه زیاد = کندی
سرعت استنتاجتوجه (Attention) با طول کانتکس کندتر می‌شودپاسخ‌دهی کند در کانتکس‌های بزرگ
نتیجهکانتکس محدود یک واقعیت است؛ باید با معماری درست آن را مدیریت کرد.
+ +
+ ⚠️ پدیده «Lost in the Middle»: حتی اگر محتوا در کانتکس جا شود، مدل‌های محلی معمولاً اطلاعات ابتدا و انتهای کانتکس را بهتر از وسط آن به یاد می‌آورند. پس فقط «جای دادن» اطلاعات کافی نیست؛ جایگاه آن‌ها هم مهم است. +
+
+
+ +
+
+
۵
+
+

روش‌های مدیریت و کنترل کانتکس در ایجنت‌ها

+
Context Management Techniques
+
+
+
+

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

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
تکنیکمکانیزمهزینهمناسب برای
۱. پنجره لغزاننگه‌داشتن N پیام آخرصفرچت ساده
۲. خلاصه‌سازیجمع‌کردن گذشته در یک خلاصهکممکالمات طولانی
۳. RAGبازیابی مرتبط‌ترین تکه‌هامتوسطدانش دامنه بزرگ
۴. کانتکس سلسله‌مراتبیلایه‌بندی: خلاصه کلی + جزئیاتمتوسطپروژه‌های چندفازی
۵. زیرایجنت (Sub-agent)تقسیم کار بین ایجنت‌های تخصصیبالاوظایف پیچیده
۶. فشرده‌سازیحذف کلمات پرتکرار و تکراریکممتن‌های طولانی
۷. Scratchpadنوشتن نتایج میانی در فایل خارجیکمزنجیره‌های استدلالی
+ +

۱. پنجره لغزان (Sliding Window)

+

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

+
+ پیاده‌سازی پنجره لغزان با شمارش توکن +def sliding_window(messages, max_tokens=4000, counter=None): + total, kept = 0, [] + for msg in reversed(messages): + n = counter(msg) + if total + n > max_tokens: + break + kept.insert(0, msg) + total += n + return kept +
+ +

۲. خلاصه‌سازی تدریجی (Incremental Summarization)

+

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

+
+ خلاصه‌سازی هنگام نزدیک شدن به سقف کانتکس +def maybe_summarize(history, llm, threshold=0.8, max_ctx=8000): + used = count_tokens(history) + if used < max_ctx * threshold: + return history + + # نیمی از مکالمه را خلاصه کن + old_part, recent = history[:len(history)//2], history[len(history)//2:] + summary = llm.invoke( + "این مکالمه را در حداکثر ۲۰۰ توکن خلاصه کن و حقایق کلیدی را حفظ کن:\n" + + "\n".join(m['content'] for m in old_part) + ) + return [{'role': 'system', 'content': f'خلاصه مکالمه قبلی: {summary}'}] + recent +
+ +

۳. بازیابی مبتنی بر RAG

+

به جای نگه‌داشتن همه‌چیز در کانتکس، فقط مرتبط‌ترین تکه‌ها را برای پرسش جاری بازیابی می‌کنیم. مناسب زمانی که حجم دانش بیشتر از ظرفیت کانتکس است.

+
+ بازیابی پویا بر اساس پرسش کاربر +def build_context(query, vector_store, k=5, max_tokens=3000): + docs = vector_store.similarity_search(query, k=k) + context, total = [], 0 + for d in docs: + n = count_tokens(d.page_content) + if total + n > max_tokens: + break + context.append(d.page_content) + total += n + return "\n---\n".join(context) +
+ +

۴. کانتکس سلسله‌مراتبی (Hierarchical)

+

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

+ +
+ ساختار سه‌سطحی کانتکس +CONTEXT_STRUCTURE = { + "L0_always": "هدف پروژه: ساخت API فروش. کاربر: توسعه‌دهنده ارشد.", + "L1_current": "در حال رفع باگ احراز هویت در endpoint /login", + "L2_retrieved": [ + # فقط در صورت نیاز و از طریق RAG پر می‌شود + ] +} +
+ +

۵. معماری زیرایجنت (Sub-agent)

+

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

+ +
+

بهترین راه برای حل مسئله کانتکس بزرگ، تقسیم آن به چند کانتکس کوچک است — هر زیرایجنت یک پنجره کانتکس مستقل و تمیز دارد.

+
— الگوی رایج در معماری ایجنت‌های تولیدی
+
+ +

۶. فشرده‌سازی کانتکس (Compression)

+

حذف اطلاعات تکراری، تبدیل متن به بولت‌پوینت، و کوتاه‌سازی عبارات طولانی. یک متن ۲۰۰۰ توکنی می‌تواند به ۴۰۰ توکن با حفظ معنا فشرده شود.

+
+ فشرده‌سازی ساختاری متن ورودی +def compress_history(history): + # ۱. حذف پیام‌های سیستمی تکراری + seen = set() + unique = [] + for m in history: + key = m['role'] + m['content'][:100] + if key not in seen: + unique.append(m) + seen.add(key) + # ۲. تبدیل پیام‌های طولانی به بولت + compressed = [] + for m in unique: + if len(m['content']) > 500: + bullets = extract_bullets(m['content']) + compressed.append({'role': m['role'], 'content': bullets}) + else: + compressed.append(m) + return compressed +
+ +

۷. Scratchpad خارجی

+

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

+
+ Scratchpad فایل‌محور برای ایجنت محلی +import json, pathlib + +class Scratchpad: + def __init__(self, path="agent_scratchpad.json"): + self.path = pathlib.Path(path) + self.data = json.loads(self.path.read_text()) if self.path.exists() else {} + + def write(self, key, value): + self.data[key] = value + self.path.write_text(json.dumps(self.data, ensure_ascii=False)) + + def read(self, key): + return self.data.get(key) + + def summary(self): + return {k: str(v)[:100] for k, v in self.data.items()} +
+ +
+ 💡 نکته ترکیبی: در عمل، بهترین ایجنت‌ها از ترکیب این تکنیک‌ها استفاده می‌کنند: پنجره لغزان برای پیام‌های اخیر + خلاصه‌سازی برای گذشته دور + RAG برای دانش دامنه + Scratchpad برای استدلال‌های میانی. +
+
+
+ +
+
+
۶
+
+

بودجه‌بندی کانتکس: تخصیص هوشمند توکن

+
Context Budgeting
+
+
+
+

یکی از مؤثرترین روش‌ها برای کنترل کانتکس، تعیین سهم مشخص برای هر بخش است. با یک پنجره ۸K توکنی، تخصیص پیشنهادی به‌صورت زیر است:

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
بخش کانتکسسهم توکندرصدتوضیح
پرامپت سیستم و دستورالعمل‌ها۸۰۰۱۰٪نقش، قوانین، ابزارها
خلاصه حافظه بلندمدت۶۰۰۷.۵٪پروفایل کاربر و اهداف
مستندات بازیابی‌شده (RAG)۲۴۰۰۳۰٪مرتبط با پرسش جاری
تاریخچه مکالمه۲۴۰۰۳۰٪اخیر + خلاصه میانی
پاسخ مدل و فضای تنفس۱۸۰۰۲۲.۵٪ذخیره برای خروجی
مجموع۸۰۰۰۱۰۰٪پنجره ۸K توکن
+ +
+ ✓ قاعده طلایی بودجه‌بندی: همیشه حداقل ۲۰٪ از کانتکس را برای خروجی مدل خالی بگذارید. اگر کانتکس را کاملاً پر کنید، مدل جایی برای پاسخ ندارد و یا پاسخ را قطع می‌کند. +
+ +
+ مدیر بودجه کانتکس +class ContextBudget: + def __init__(self, total=8000): + self.total = total + self.allocations = { + 'system': int(total * 0.10), + 'longterm': int(total * 0.075), + 'rag': int(total * 0.30), + 'history': int(total * 0.30), + 'reserve': int(total * 0.225), + } + + def fit(self, section, content, counter): + budget = self.allocations[section] + if counter(content) <= budget: + return content + # برش هوشمند تا سقف بودجه + return truncate_to_tokens(content, budget, counter) +
+
+
+ +
+
+
۷
+
+

مقایسه مدل‌های محلی و ابری از منظر کانتکس

+
Local vs. Cloud Context Trade-offs
+
+
+
+

درک تفاوت‌ها کمک می‌کند استراتژی درست را انتخاب کنید:

+ +
+
+

مدل ابری (API)

+
    +
  • پنجره کانتکس ۱۶K تا ۲۰۰K
  • +
  • هزینه هر توکن پرداخت به ازای مصرف
  • +
  • حریم خصوصی داده به بیرون می‌رود
  • +
  • مدیریت کانتکس کمتر حیاتی
  • +
+
+ + +
+ +
+ ⭐ نتیجه: مدل محلی به‌خاطر حریم خصوصی و هزینه ثابت جذاب است، اما محدودیت کانتکس آن، معماری ایجنت شما را تعیین می‌کند. برای مدل محلی، «مدیریت کانتکس» یک ویژگی لوکس نیست؛ یک نیاز بنیادی است. +
+
+
+ +
+
+
۸
+
+

نقشه راه پیاده‌سازی

+
Implementation Roadmap
+
+
+
+

مسیر پیشنهادی برای ساختن یک ایجنت محلی پایدار با مدیریت حافظه و کانتکس مؤثر:

+ +
+
+
+
گام ۱ — اندازه‌گیری پایه
+

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

+
+
+
+ +
+
+
گام ۲ — بودجه‌بندی کانتکس
+

برای هر بخش (سیستم، RAG، تاریخچه، خروجی) سهم مشخص تعیین کنید و مدیر بودجه پیاده کنید.

+
+
+
+ +
+
+
گام ۳ — حافظه بیرونی
+

پایگاه برداری برای دانش دامنه، فایل حافظه برای خلاصه‌ها و پروفایل کاربر راه‌اندازی کنید.

+
+
+
+ +
+
+
گام ۴ — خلاصه‌سازی و پنجره لغزان
+

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

+
+
+
+ +
+
+
گام ۵ — Scratchpad و زیرایجنت
+

برای وظایف پیچیده، نتایج میانی را خارجی کنید و در صورت نیاز کار را بین زیرایجنت‌ها تقسیم کنید.

+
+
+
+ +
+
+
گام ۶ — ارزیابی و تنظیم
+

با مجموعه‌ای از سناریوهای واقعی، دقت ایجنت را بسنجید و پارامترها (اندازه پنجره، K بازیابی، آستانه خلاصه) را تنظیم کنید.

+
+
+
+
+
+
+ +
+
+
۹
+
+

چالش‌ها و دام‌های رایج

+
Pitfalls & Mitigations
+
+
+
+

تجربه نشان می‌دهد بیشتر مشکلات ایجنت‌های محلی از چند اشتباه مشخص ناشی می‌شود:

+ +
+ ⚠️ دام‌های رایج: +
    +
  • پر کردن کامل کانتکس: اگر فضای خروجی نماند، مدل پاسخ ناقص می‌دهد. همیشه ۲۰٪ رزرو کنید.
  • +
  • نادیده گرفتن Lost in the Middle: اطلاعات مهم را در ابتدا یا انتهای کانتکس قرار دهید، نه وسط.
  • +
  • بازیابی بی‌ربط: RAG با K زیاد، کانتکس را با نویز پر می‌کند. کیفیت بر کمیت اولویت دارد.
  • +
  • خلاصه‌سازی بیش از حد: اگر خلاصه خیلی فشرده باشد، جزئیات حیاتی از بین می‌رود.
  • +
  • حافظه بدون فراموشی: انبار کردن همه‌چیز بدون حذف، سیستم را کند و متناقض می‌کند.
  • +
  • عدم اندازه‌گیری مصرف توکن: بدون لاگ، نمی‌دانید کدام بخش کانتکس را می‌بلعد.
  • +
+
+ +
+

مدیریت کانتکس خوب، مثل مدیریت حافظه انسانی است: نه همه‌چیز را به یاد می‌آوریم، نه همه‌چیز را فراموش می‌کنیم — آنچه را که در لحظه اهمیت دارد، به یاد می‌آوریم.

+
— اصل طراحی ایجنت‌های حافظه‌محور
+
+
+
+ +
+
+
۱۰
+
+

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

+
Final Summary & Recommendation
+
+
+
+

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

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
نیازروش پیشنهادیابزار / الگو
مکالمه طولانیپنجره لغزان + خلاصه‌سازیSliding Window + Summary
دانش دامنه بزرگRAG با بازیابی ترکیبیVector DB + BM25
پروژه چندفازیکانتکس سلسله‌مراتبیL0 + L1 + L2
وظایف پیچیدهزیرایجنت‌هاSub-agent Pattern
استدلال طولانیScratchpad خارجیFile-based Memory
کنترل همیشگیبودجه‌بندی کانتکسContext Budget Manager
حافظه بلندمدتذخیره بیرونی + تجمیع دوره‌ای + فراموشی تدریجی
+ +
+

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

+

محدودیت کانتکس در مدل‌های محلی، یک ضعف نیست — یک محدودیت طراحی است که شما را به ساختن معماری هوشمندتر وادار می‌کند.

+

با ترکیب بودجه‌بندی کانتکس، حافظه بیرونی، خلاصه‌سازی و RAG، می‌توان ایجنتی ساخت که با ۸K توکن، بهتر از ایجنتی با ۱۰۰K توکنِ بی‌ساختار عمل کند.

+
+ 💎 فرمول موفقیت:
+ ذخیره بیرونی هوشمند + بازیابی دقیق + خلاصه‌سازی به‌موقع + بودجه‌بندی سخت‌گیرانه +
+
+ +
+ 📞 گام بعدی: اگر بخواهید، می‌توان معماری فوق را برای یک سناریوی مشخص (مثلاً ایجنت پشتیبانی مشتری یا دستیار کدنویسی) به‌صورت کامل و اجرایی پیاده‌سازی کرد — شامل مدیر بودجه کانتکس، حافظه سه‌لایه، RAG و ارزیابی. +
+
+
+ +
+ این مستند راهنمای فنی عمومی در حوزه معماری حافظه و کانتکس است و قابل به‌روزرسانی بر اساس پیشرفت مدل‌ها و ابزارها می‌باشد. +
+ +
+ +
+ + +
تاریخ تهیه: شهریور ۱۴۰۵  |  نسخه: ۱.۰  |  طبقه‌بندی: فنی
+
+ +
+ + + \ No newline at end of file diff --git a/Documents/Docs/Developer/Multi Agentic Roadmap.html b/Documents/Docs/Developer/Multi Agentic Roadmap.html new file mode 100644 index 0000000..f6ee914 --- /dev/null +++ b/Documents/Docs/Developer/Multi Agentic Roadmap.html @@ -0,0 +1,1825 @@ + + + + + +نقشه راه ابزارهای هوش مصنوعی و معماری ایجنت | پروژه xAiApi + + + + +
+ +
+
+
+ +
+
+
شماره مستند: AGENT-1405-002
+
نسخه: ۱.۰
+
تاریخ تهیه: آبان ۱۴۰۵
+
طبقه‌بندی: محرمانه
+
+
+ +
+ AGENTIC ARCHITECTURE & TOOLING ROADMAP +

نقشه راه ابزارهای هوش مصنوعی و معماری ایجنت

+

بر پایه پروژه xAiApi — از ابزار MCP تا سیستم مولتی‌ایجنت

+
+
+ +
+ +
+ خلاصه مدیریتی،
+ این مستند، نقشه راه فنی و گام‌به‌گام برای توسعه چهار قابلیت کلیدی بر پایه معماری موجود پروژه xAiApi را ارائه می‌دهد: (۱) ابزار MCP استخراج و خواندن لینک‌ها، (۲) پشتیبانی از نتایج جستجوی گوگل، (۳) معماری ایجنت بر پایه لایه‌بندی موجود، (۴) ابزار تولید فایل از محتوا با فرمت استاندارد و (۵) تحلیل Harness و نقشه راه سیستم مولتی‌ایجنت. تمام پیشنهادات، با استفاده از کلاس‌ها و لایه‌های موجود پروژه (مانند IXAiService، XAIServiceBase، IXAiMcpServerProvider، XAiDataProvider، IXFileProvider، IXAiEmbeddingService، Microsoft.Extensions.AI و Microsoft Agent Framework) طراحی شده‌اند تا ادغام آن‌ها با کدبیس، حداقل تغییر و حداکثر همراستایی را داشته باشد. +
+ + +
+
+
۱
+
+

ابزار MCP استخراج و خواندن لینک‌ها

+
MCP Link Extraction & Reader Tool
+
+
+
+ +

هدف: ساخت یک MCP Tool که سه کار انجام دهد: (۱) از محتوای ورودی، لینک‌ها را استخراج کند، (۲) هر لینک را بخواند و HTML را به متن قابل استفاده تبدیل کند، و (۳) متن استخراج‌شده را همراه با متادیتا برگرداند.

+ +
+ 💡 هم‌راستایی با معماری موجود: ابزارهای MCP در پروژه شما از طریق IXAiMcpServerProvider.GetAvailableToolsAsync() بارگذاری می‌شوند و به‌صورت AITool در Options.Tools به مدل ارائه می‌گردند. برای ابزارهای داخلی (Local Tools) بهتر است از AIFunctionFactory.Create() استفاده شود و در IXAiMcpServerProvider به فهرست ابزارهای سراسری اضافه شود. برای ابزارهای خارجی، همان مسیر فعلی MCP Server Provider حفظ می‌شود. +
+ +

۱.۱ طراحی سه Tool مستقل

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
#نام ابزارورودیخروجینقش
۱extract_linkscontent (string)XExtractedLink[]استخراج لینک‌های معتبر از متن با Regex + Normalize
۲read_link_contenturl (string)XLinkContentResultدریافت صفحه، حذف Noise، استخراج متن و عنوان
۳extract_and_readcontent, maxLinks, maxCharsXLinkBundleترکیب دو ابزار بالا به‌صورت Pipeline برای کاهش رفت‌وبرگشت به LLM
+ +
xAiApi / Tools / XLinkExtractionTool.cs
+
using System.ComponentModel; +using Microsoft.Extensions.AI; + +namespace xAiApi.Tools; + +// DTOs +public sealed record XExtractedLink(string Url, string Text, bool IsRelative); + +public sealed record XLinkContentResult( + string Url, + string Title, + string Text, + string ContentType, + int Length, + bool Truncated, + string? Error); + +public sealed record XLinkBundle( + IReadOnlyList<XExtractedLink> Links, + IReadOnlyList<XLinkContentResult> Contents); + +public sealed class XLinkExtractionTool +{ + private static readonly Regex UrlRegex = new( + @"\b(?:https?://|www\.)[^\s<>""'{}|\\^`\[\]]+", + RegexOptions.Compiled | RegexOptions.IgnoreCase); + + private readonly IHttpClientFactory httpClientFactory; + private readonly ILogger<XLinkExtractionTool> logger; + + public XLinkExtractionTool( + IHttpClientFactory httpClientFactory, + ILogger<XLinkExtractionTool> logger) + { + this.httpClientFactory = httpClientFactory; + this.logger = logger; + } + + [Description("Extracts all valid HTTP/HTTPS links from the given content.")] + public IReadOnlyList<XExtractedLink> ExtractLinks( + [Description("Raw text or HTML to scan for links.")] string content) + { + if (string.IsNullOrWhiteSpace(content)) return Array.Empty<XExtractedLink>(); + + return UrlRegex + .Matches(content) + .Select(m => m.Value.TrimEnd('.', ',', ')', ']', ';')) + .Where(IsValidUrl) + .Distinct(StringComparer.OrdinalIgnoreCase) + .Select(u => new XExtractedLink(u, u, u.StartsWith("www."))) + .ToList(); + } + + [Description("Downloads a web page and extracts its readable plain text (noise removed).")] + public async Task<XLinkContentResult> ReadLinkContent( + [Description("Absolute http/https URL.")] string url, + [Description("Optional. Max chars to return (default 8000).")] int maxChars = 8000, + CancellationToken cancellationToken = default) + { + if (!IsValidUrl(url)) + return new XLinkContentResult(url, "", "", "", 0, false, "Invalid URL"); + + try + { + var client = httpClientFactory.CreateClient("XLinkReader"); + using var response = await client.GetAsync(url, HttpCompletionOption.ResponseHeadersRead, cancellationToken); + response.EnsureSuccessStatusCode(); + + var contentType = response.Content.Headers.ContentType?.MediaType ?? "text/html"; + if (!contentType.Contains("html", StringComparison.OrdinalIgnoreCase) && + !contentType.Contains("text", StringComparison.OrdinalIgnoreCase)) + return new XLinkContentResult(url, "", "", contentType, 0, false, $"Unsupported content type: {contentType}"); + + var html = await response.Content.ReadAsStringAsync(cancellationToken); + + var doc = new HtmlDocument(); + doc.LoadHtml(html); + + // Remove noise + foreach (var n in doc.DocumentNode + .SelectNodes("//script|//style|//noscript|//iframe|//svg") ?? Enumerable.Empty<HtmlNode>()) + n.Remove(); + + var title = doc.DocumentNode.SelectSingleNode("//title")?.InnerText?.Trim() ?? ""; + var body = doc.DocumentNode.SelectSingleNode("//body")?.InnerText ?? ""; + + var clean = Regex.Replace(WebUtility.HtmlDecode(body), @"\s{2,}", " ").Trim(); + + var truncated = clean.Length > maxChars; + if (truncated) clean = clean[..maxChars]; + + return new XLinkContentResult(url, title, clean, contentType, clean.Length, truncated, null); + } + catch (Exception ex) + { + logger.LogWarning(ex, "Failed to read link {Url}", url); + return new XLinkContentResult(url, "", "", "", 0, false, ex.Message); + } + } + + [Description("Extracts links from content AND reads the readable text of each one (max N).")] + public async Task<XLinkBundle> ExtractAndRead( + string content, + int maxLinks = 5, + int maxCharsPerLink = 4000, + CancellationToken cancellationToken = default) + { + var links = ExtractLinks(content).Take(maxLinks).ToList(); + var contents = new List<XLinkContentResult>(links.Count); + + foreach (var link in links) + { + cancellationToken.ThrowIfCancellationRequested(); + contents.Add(await ReadLinkContent(link.Url, maxCharsPerLink, cancellationToken)); + } + + return new XLinkBundle(links, contents); + } + + private static bool IsValidUrl(string? raw) + => Uri.TryCreate(raw, UriKind.Absolute, out var u) + && (u.Scheme == Uri.UriSchemeHttp || u.Scheme == Uri.UriSchemeHttps); +}
+ +

۱.۲ ثبت ابزار در Provider

+ +

در متد GetAvailableToolsAsync موجود در XAiMcpServerProvider، فقط کافی است ابزارهای محلی را با MCP Tools ادغام کنید:

+ +
xAiApi / Providers / XAiMcpServerProvider.cs (تنها تغییر لازم)
+
public async Task<IList<AITool>> GetAvailableToolsAsync( + bool forceOwner = false, + XUserClaimsInfoDto userInfo = null, + CancellationToken cancellationToken = default) +{ + // ... (کد فعلی: بارگذاری MCP Servers و ساخت clients) + + var result = tools + .Where(kv => kv.Key.UserId == userInfo.UserId) + .SelectMany(kv => kv.Value) + .ToList(); + + // ← الحاق ابزارهای محلی + var localTools = new[] + { + AIFunctionFactory.Create(linkTool.ExtractLinks), + AIFunctionFactory.Create(linkTool.ReadLinkContent), + AIFunctionFactory.Create(linkTool.ExtractAndRead), + }; + result.AddRange(localTools.Cast<AITool>()); + + return result; +}
+ +

۱.۳ ثبت HttpClient و ملاحظات امنیتی

+ +
    +
  • + ثبت Named HttpClient + در Startup.ConfigureServices: services.AddHttpClient("XLinkReader", c => { c.Timeout = TimeSpan.FromSeconds(20); c.DefaultRequestHeaders.UserAgent.ParseAdd("xAiApi/1.0"); }); +
  • +
  • + محافظت در برابر SSRF + قبل از ارسال درخواست، IP مقصد را با Dns.GetHostAddressesAsync چک کنید و آدرس‌های خصوصی (10.x، 172.16–31.x، 192.168.x، 127.x، 169.254.x) را رد کنید. +
  • +
  • + محدودیت اندازه + حداکثر 2MB برای هر صفحه، حداکثر 5 لینک در هر فراخوانی، حداکثر 8k کاراکتر متن استخراجی. +
  • +
  • + Allow-list اختیاری + در XAiApiConfiguration فیلد جدید AllowedDomains اضافه کنید تا ادمین بتواند دامنه‌های مجاز را محدود کند. +
  • +
+ +
+ ✓ نتیجه: سه ابزار بالا به‌صورت خودکار در فهرست AITool قرار می‌گیرند و مدل می‌تواند در هر درخواست، بدون کد اضافه در XAIServiceBase، از آن‌ها استفاده کند. مسیر فعلی Function Invocation در ChatClientBuilder.UseFunctionInvocation() آن‌ها را فراخوانی می‌کند. +
+
+
+ + +
+
+
۲
+
+

پشتیبانی از نتایج جستجوی گوگل

+
Google Search Integration — Yes, It Is Possible
+
+
+
+ +

پاسخ کوتاه: بله، کاملاً امکان‌پذیر است. ابزار جستجوی فعلی شما (که احتمالاً از xSearchService یا IXSearchProvider استفاده می‌کند) می‌تواند با الگوی Strategy گسترش یابد تا Google را نیز به‌عنوان یک Provider پشتیبانی کند. سه مسیر فنی وجود دارد:

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
روشمزیتمحدودیتتوصیه
Google Custom Search JSON API
(Programmable Search Engine)
رسمی، پایدار، مستند، رایگان تا ۱۰۰ کوئری در روزنیاز به ApiKey + Cx، سهمیه محدودپیشنهاد اول
SerpAPI / Serper.devسادگی، داده کامل‌تر (Snippet + Knowledge Panel)پولی، وابستگی به سرویس ثالثجایگزین
Scraping مستقیم google.comبدون هزینهضد‌اسکرپینگ، CAPTCHA، نقض ToS، شکنندهتوصیه نمی‌شود
+ +

۲.۱ معماری پیشنهادی: Strategy + Provider

+ +
+
+
Contract IXSearchProvider
+
+ Task<IList<XSearchResult>> SearchAsync(query, options, ct) +
+
+
▼
+
+
Implementations
+
+ XInternalSearchProvider + XGoogleCustomSearchProvider + XBingSearchProvider + XDuckDuckGoProvider +
+
+
▼
+
+
Aggregator XSearchAggregator
+
+ Merge + Deduplicate + Re-rank +
+
+
+ +
xAiApi / Search / IXSearchProvider.cs
+
public sealed record XSearchResult( + string Title, + string Url, + string Snippet, + string Source, // "internal" | "google" | "bing" | ... + double? Score = null); + +public sealed class XSearchOptions +{ + public int TopK { get; set; } = 10; + public string? Language { get; set; } + public string? Region { get; set; } + public bool SafeSearch { get; set; } = true; +} + +public interface IXSearchProvider +{ + string Name { get; } + Task<IList<XSearchResult>> SearchAsync( + string query, + XSearchOptions options, + CancellationToken cancellationToken = default); +}
+ +
xAiApi / Search / XGoogleCustomSearchProvider.cs
+
public sealed class XGoogleCustomSearchProvider : IXSearchProvider +{ + private readonly HttpClient http; + private readonly XGoogleSearchConfiguration config; + + public string Name => "google"; + + public async Task<IList<XSearchResult>> SearchAsync( + string query, + XSearchOptions options, + CancellationToken cancellationToken = default) + { + var q = HttpUtility.UrlEncode(query); + var url = $"{config.Endpoint}?key={config.ApiKey}&cx={config.SearchEngineId}&q={q}&num={Math.Min(options.TopK, 10)}"; + if (!string.IsNullOrEmpty(options.Language)) url += $"&hl={options.Language}"; + if (options.SafeSearch) url += "&safe=active"; + + using var resp = await http.GetAsync(url, cancellationToken); + var body = await resp.Content.ReadAsStringAsync(cancellationToken); + + var doc = JsonDocument.Parse(body); + var items = doc.RootElement.GetPropertyOrNull("items"); + if (items is null) return Array.Empty<XSearchResult>(); + + return items.EnumerateArray() + .Select(i => new XSearchResult( + Title: i.GetPropertyOrNull("title")?.GetString() ?? "", + Url: i.GetPropertyOrNull("link")?.GetString() ?? "", + Snippet: i.GetPropertyOrNull("snippet")?.GetString() ?? "", + Source: "google")) + .ToList(); + } +}
+ +

۲.۲ پیکربندی

+ +
appsettings.json — بخش جدید
+
"AiApiConfiguration": { + "Search": { + "Google": { + "Enabled": true, + "ApiKey": "YOUR_GOOGLE_API_KEY", + "SearchEngineId": "YOUR_CX", + "Endpoint": "https://www.googleapis.com/customsearch/v1", + "DailyQuota": 100 + }, + "AggregationStrategy": "ParallelMerge" + } +}
+ +

۲.۳ ادغام در ابزار جستجوی موجود

+ +
    +
  • + افزودن DTO و Interface + IXSearchProvider و XSearchResult را در یک ماژول مشترک (مثلاً xSearchService یا xAiModels) قرار دهید تا هم ابزار جستجوی فعلی و هم ایجنت‌ها بتوانند از آن استفاده کنند. +
  • +
  • + پیاده‌سازی Google Provider + کلاس بالا را اضافه کنید و در DI ثبت نمایید: services.AddSingleton<IXSearchProvider, XGoogleCustomSearchProvider>(); +
  • +
  • + Aggregator + یک XSearchAggregator بسازید که به‌صورت موازی از چند Provider کوئری بگیرد، نتایج را بر اساس URL یکتا کند و امتیاز ترکیبی بدهد. +
  • +
  • + Abstraction برای LLM + ابزار را با AIFunctionFactory.Create(aggregator.Search) به فهرست ابزارهای XAiMcpServerProvider اضافه کنید تا مدل بتواند از آن استفاده کند. +
  • +
  • + مدیریت Quota + یک XQuotaManager ساده (in-memory یا Redis) برای شمارش روزانه فراخوانی‌های Google اضافه کنید. +
  • +
+ +
+ ⚠️ نکته حقوقی: استفاده از Google Custom Search JSON API مشمول Terms of Service است. نمایش نتایج باید همراه با انتساب به Google و بدون تغییر در ترتیب باشد. استفاده از SerpAPI نیز نیازمند بررسی شرایط اشتراک است. +
+ +
+ ✓ نتیجه: با این معماری، ابزار جستجوی فعلی شما به‌طور کامل حفظ می‌شود و Google به‌عنوان یک Provider جدید در کنار آن قرار می‌گیرد. ایجنت می‌تواند بر اساس نوع پرسش، Provider مناسب را انتخاب کند (مثلاً جستجوی داخلی برای اسناد سازمانی و Google برای اطلاعات عمومی). +
+
+
+ + +
+
+
۳
+
+

معماری ایجنت بر پایه پروژه حاضر

+
Agent Architecture — Aligned with xAiApi Layers
+
+
+
+ +

پروژه xAiApi در حال حاضر یک سرویس AI Assistant با قابلیت Function Invocation دارد. برای تبدیل آن به یک ایجنت واقعی (که هدف را به مراحل تبدیل می‌کند، ابزار انتخاب می‌کند، نتیجه را ارزیابی می‌کند و مسیر را اصلاح می‌کند)، نیاز به یک لایه جدید به نام Agent Layer داریم که روی لایه‌های موجود بنشیند.

+ +

۳.۱ نگاشت لایه‌های ایجنت به لایه‌های موجود پروژه

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
لایه ایجنت (پیشنهادی)معادل/زیرساخت موجود در xAiApiنقش
Agent CoreAIAgent از Microsoft Agent Framework + XAIServiceBase موجودحلقه Observe–Think–Act–Reflect
Model GatewayDescriptor.GetClient() + IChatClient + XAiModelProxyMiddlewareانتزاع مدل و پشتیبانی چند Provider
Tool RegistryIXAiMcpServerProvider.GetAvailableToolsAsync() + ابزارهای محلی از طریق AIFunctionFactoryفهرست ابزارهای مجاز (MCP + Local)
Plannerیک IChatClient جدا با Prompt مخصوص Plan-and-Executeتولید برنامه چندمرحله‌ای
Memory / ContextAgentSession (Agent Framework) + IXAiDataProvider (Db) + IXAiRAGServiceحافظه کوتاه‌مدت و بلندمدت
Human-in-the-loopMiddleware سفارشی در Agent Framework + XAiDataProviderHub برای Pushتوقف در نقاط حساس و دریافت تأیید
Guardrails & Observabilityمیان‌افزارهای موجود + Logging/OpenTelemetryممیزی، محدودیت ابزار، Kill Switch
+ +

۳.۲ ساختار پوشه پیشنهادی

+ +
+xAiApi/ +├── Agents/ ← لایه جدید +│ ├── Contracts/ +│ │ ├── IXAiAgent.cs +│ │ ├── IXAiAgentOrchestrator.cs +│ │ └── IXAiToolRegistry.cs +│ ├── Core/ +│ │ ├── XAiAgentBase.cs +│ │ ├── XAiAgentRunContext.cs +│ │ ├── XAiAgentStep.cs +│ │ └── XAiAgentTrace.cs +│ ├── Orchestrator/ +│ │ ├── XAiOrchestratorAgent.cs +│ │ └── XAiWorkflowBuilder.cs +│ ├── Workers/ +│ │ ├── XResearchAgent.cs +│ │ ├── XDocumentAgent.cs +│ │ └── XFileCreationAgent.cs +│ └── Tools/ +│ ├── XLinkExtractionTool.cs +│ ├── XSearchTool.cs +│ └── XFileCreationTool.cs +├── Providers/ ← موجود +├── Controllers/ +│ └── AgentsController.cs ← جدید +└── ... +
+ +

۳.۳ هسته ایجنت — پیاده‌سازی گام‌به‌گام

+ +
    +
  • + تعریف قرارداد + IXAiAgent با متد RunAsync(XAiAgentRequest, CancellationToken) که یک XAiAgentResponse برمی‌گرداند. این پاسخ شامل: برنامه اجراشده، مراحل، خروجی نهایی، منابع مصرفی و هزینه است. +
  • +
  • + ساخت Agent با Agent Framework + در XAIServiceBase موجود، متد AskAsync را می‌توان با یک متد جدید CreateAgent() گسترش داد که chatClient.AsAIAgent(name, instructions) را برمی‌گرداند. +
  • +
  • + تزریق ابزارها + از IXAiMcpServerProvider موجود استفاده کنید. ابزارهای مجاز کاربر را در Options.Tools قرار دهید (همان الگوی فعلی). +
  • +
  • + حلقه اجرا + اجرای agent.RunAsync(messages, session, options, ct) و جمع‌آوری نتایج. در صورت نیاز به چند مرحله، از WorkflowBuilder برای ساخت گراف استفاده کنید. +
  • +
  • + مدیریت نشست + از AgentSession برای حفظ زمینه استفاده کنید و آن را در IMemoryCache یا Redis نگه دارید. حتماً به ازای هر userId + conversationId یک Session بسازید. +
  • +
+ +
xAiApi / Agents / Core / XAiAgentBase.cs (خلاصه)
+
public abstract class XAiAgentBase : IXAiAgent +{ + protected readonly IChatClient chatClient; + protected readonly IXAiMcpServerProvider toolProvider; + protected readonly ILogger logger; + + public virtual async Task<XAiAgentResponse> RunAsync( + XAiAgentRequest request, + CancellationToken cancellationToken = default) + { + // ۱. ساخت AIAgent از Agent Framework + var agent = chatClient.AsAIAgent( + name: GetType().Name, + instructions: BuildSystemPrompt(request), + tools: await ResolveToolsAsync(request.UserInfo, cancellationToken)); + + // ۲. بازیابی یا ساخت Session + var session = request.Session + ?? await agent.CreateSessionAsync(cancellationToken); + + // ۳. حلقه اجرا با ردیابی مراحل + var trace = new XAiAgentTrace(); + var message = new ChatMessage(ChatRole.User, request.Prompt); + + var response = await agent.RunAsync( + messages: new[] { message }, + session: session, + options: new ChatOptions + { + Tools = [.. (await ResolveToolsAsync(request.UserInfo, cancellationToken))] + }, + cancellationToken: cancellationToken); + + trace.AddFromResponse(response); + + return new XAiAgentResponse + { + Text = response.Text, + Session = session, + Trace = trace, + Messages = response.Messages, + }; + } + + protected abstract string BuildSystemPrompt(XAiAgentRequest request); + + protected virtual async Task<IList<AITool>> ResolveToolsAsync( + XUserClaimsInfoDto? userInfo, CancellationToken ct) + => await toolProvider.GetAvailableToolsAsync(forceOwner: true, userInfo: userInfo, cancellationToken: ct); +}
+ +

۳.۴ کنترلر ایجنت

+ +
xAiApi / Controllers / AgentsController.cs
+
[Authorize] +public class AgentsController : XBaseIdentityApiV1Controller +{ + private readonly IXAiAgentOrchestrator orchestrator; + + [HttpPost("Run")] + [Authorize(Policy = XPolicies.EnabledUser)] + public async Task<ActionResult<XAiAgentResponse>> Run( + [FromBody] XAiAgentRequest request, + CancellationToken cancellationToken = default) + { + try + { + if (!request.IsValid()) XException.InvalidArgs.Throw(); + + var userInfo = await GetUserInfo(); + request.UserInfo = userInfo; + + var result = await orchestrator.RunAsync(request, cancellationToken); + return Ok(result); + } + catch (Exception ex) + { + return GetExceptionActionResult(ex); + } + } +}
+ +
+ ✓ نتیجه: با این ساختار، ایجنت شما هم از زیرساخت فعلی (Tool Provider، Model Gateway، Db، RAG) استفاده می‌کند و هم قابلیت‌های جدید Agent Framework (Plan-Execute، Session، Workflow) را در اختیار می‌گیرد. هیچ‌کدام از کدهای فعلی حذف یا بازنویسی نمی‌شوند؛ فقط لایه‌ای روی آن‌ها اضافه می‌شود. +
+
+
+ + +
+
+
۴
+
+

ابزار تولید فایل از محتوا

+
Content-to-File Tool — Two-Stage Design
+
+
+
+ +

برای تولید فایل با فرمت دلخواه کاربر، دو رویکرد وجود دارد. رویکرد ساده (مستقیم) شکننده است چون مدل باید مستقیماً کد فایل را تولید کند. رویکرد حرفه‌ای، دو مرحله‌ای است: مدل محتوا را به یک Schema استاندارد میانی تبدیل می‌کند، سپس یک Renderer قطعی، فایل را تولید می‌کند.

+ +
+
+

رویکرد مستقیم (ناکارآمد)

+
    +
  • مدل مستقیماً HTML/MD می‌نویسد
  • +
  • کیفیت متغیر و غیرقابل پیش‌بینی
  • +
  • سخت برای تست و اعتبارسنجی
  • +
  • خطای ساختاری محتمل
  • +
+
+ +
+ +

۴.۱ Schema استاندارد میانی — XDocumentSpec

+ +
xAiApi / Models / XDocumentSpec.cs
+
public enum XDocumentFormat +{ + Html, Markdown, PlainText, Pdf, Docx, Xlsx +} + +public sealed class XDocumentSpec +{ + public XDocumentFormat Format { get; set; } + public string Title { get; set; } = ""; + public string? Subtitle { get; set; } + public string? Author { get; set; } + public DateTime? GeneratedAtUtc { get; set; } + public string? Language { get; set; } = "fa"; + public bool Rtl { get; set; } = true; + public IList<XDocumentSection> Sections { get; set; } = []; + public XDocumentStyle Style { get; set; } = new(); +} + +public sealed class XDocumentSection +{ + public string Heading { get; set; } = ""; + public int Level { get; set; } = 1; // 1..4 + public IList<XDocumentBlock> Blocks { get; set; } = []; + public IList<XDocumentSection> Children { get; set; } = []; +} + +public abstract class XDocumentBlock { } +public sealed class XParagraphBlock : XDocumentBlock { public string Text { get; set; } = ""; } +public sealed class XListBlock : XDocumentBlock { public bool Ordered { get; set; } public IList<string> Items { get; set; } = []; } +public sealed class XTableBlock : XDocumentBlock { public IList<string> Headers { get; set; } = []; public IList<IList<string>> Rows { get; set; } = []; } +public sealed class XCodeBlock : XDocumentBlock { public string Language { get; set; } = "text"; public string Code { get; set; } = ""; } +public sealed class XQuoteBlock : XDocumentBlock { public string Text { get; set; } = ""; } +public sealed class XImageBlock : XDocumentBlock { public string Url { get; set; } = ""; public string? Alt { get; set; } } + +public sealed class XDocumentStyle +{ + public string PrimaryColor { get; set; } = "#1a365d"; + public string AccentColor { get; set; } = "#c9a961"; + public string FontFamily { get; set; } = "Vazirmatn, Tahoma, sans-serif"; +}
+ +

۴.۲ مرحله اول: مدل به Schema تبدیل می‌کند

+ +

از Structured Output (JSON Mode) یا Prompt مهندسی‌شده استفاده کنید تا مدل، محتوای خام را به XDocumentSpec تبدیل کند:

+ +
xAiApi / Agents / Tools / XFileCreationTool.cs — مرحله اول
+
[Description("Converts raw content into a structured XDocumentSpec JSON for file generation.")] +public async Task<XDocumentSpec> BuildSpecAsync( + [Description("Raw content to structure.")] string content, + [Description("Target format: Html|Markdown|Pdf|Docx|Xlsx.")] string format, + [Description("Optional title.")] string? title = null, + CancellationToken cancellationToken = default) +{ + var systemPrompt = """ + You are a document structuring engine. + Convert the user's raw content into a strict JSON object matching this schema: + { + "format": "Html|Markdown|Pdf|Docx|Xlsx", + "title": "...", + "subtitle": "...", + "author": "...", + "language": "fa|en", + "rtl": true, + "sections": [ + { + "heading": "...", + "level": 1, + "blocks": [ + { "type": "paragraph", "text": "..." }, + { "type": "list", "ordered": false, "items": ["...", "..."] }, + { "type": "table", "headers": ["..."], "rows": [["..."]] }, + { "type": "code", "language": "...", "code": "..." }, + { "type": "quote", "text": "..." } + ], + "children": [] + } + ], + "style": { "primaryColor": "#1a365d", "accentColor": "#c9a961", "fontFamily": "Vazirmatn" } + } + Rules: + - Output ONLY valid JSON. No markdown fences, no explanations. + - If the source is long, prefer more sections over larger sections. + - Preserve Persian text as-is (do not translate). + """; + + var response = await chatClient.GetResponseAsync<XDocumentSpec>( + messages: new[] + { + new ChatMessage(ChatRole.System, systemPrompt), + new ChatMessage(ChatRole.User, $"Format: {format}\nTitle: {title}\n\n{content}") + }, + serializerOptions: new JsonSerializerOptions + { + Converters = { new JsonStringEnumConverter() }, + PropertyNamingPolicy = JsonNamingPolicy.CamelCase, + }, + cancellationToken: cancellationToken); + + return response.Result; +}
+ +

۴.۳ مرحله دوم: Renderer قطعی + ذخیره + لینک دانلود

+ +
xAiApi / Agents / Tools / XFileCreationTool.cs — مرحله دوم
+
[Description("Renders the XDocumentSpec to a real file, stores it, and returns a download URL.")] +public async Task<XFileDownloadResult> CreateFile( + [Description("The structured document spec (JSON).")] XDocumentSpec spec, + XUserClaimsInfoDto userInfo, + CancellationToken cancellationToken = default) +{ + // ۱. رندر + var renderer = rendererFactory.Resolve(spec.Format); + var (bytes, fileName, mimeType) = await renderer.RenderAsync(spec, cancellationToken); + + // ۲. ذخیره از طریق File Provider موجود + using var stream = new MemoryStream(bytes); + var formFile = new FormFile(stream, 0, bytes.Length, fileName, fileName); + var uploaded = await fileProvider.Upload(formFile, userInfo, connectionId: null, cancellationToken); + + // ۳. ساخت لینک دانلود (از Storage Service موجود) + var downloadUrl = $"/api/v1/files/{uploaded.Id}/download"; + + return new XFileDownloadResult( + FileId: uploaded.Id, + FileName: fileName, + Url: downloadUrl, + MimeType: mimeType, + SizeBytes: bytes.Length); +} + +// Factory برای انتخاب Renderer +public sealed class XDocumentRendererFactory +{ + private readonly IReadOnlyDictionary<XDocumentFormat, IXDocumentRenderer> renderers; + + public IXDocumentRenderer Resolve(XDocumentFormat format) + => renderers.TryGetValue(format, out var r) ? r + : throw new NotSupportedException($"Format {format} not supported."); +}
+ +

۴.۴ نگاشت Rendererها به کتابخانه‌های موجود

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
فرمتRendererکتابخانهتوضیح
HtmlXHtmlDocumentRendererRazor / StringBuilderمستقیم از Schema به HTML با CSS استاندارد
MarkdownXMarkdownDocumentRendererStringBuilderتبدیل Schema به MD ساده
PdfXPdfDocumentRendererQuestPDFپشتیبانی کامل RTL؛ QuestPDF در پروژه شما موجود است
DocxXDocxDocumentRendererDocumentFormat.OpenXmlدر پروژه شما برای خواندن DOCX استفاده شده؛ برای نوشتن هم کار می‌کند
XlsxXXlsxDocumentRendererClosedXMLدر پروژه شما برای Excel اشاره شده
+ +
+ 💡 نکته مهم: دو متد BuildSpecAsync و CreateFile به‌عنوان دو Tool جداگانه در فهرست AITool ثبت می‌شوند. این کار به مدل اجازه می‌دهد در صورت خطا در مرحله ۱ (JSON نامعتبر)، دوباره تلاش کند بدون آنکه فایلی ساخته شود. همچنین امکان بازبینی توسط کاربر (Human-in-the-loop) بین دو مرحله وجود دارد. +
+ +
+ ✓ نتیجه: با این طراحی، پشتیبانی از فرمت‌های جدید فقط با افزودن یک Renderer جدید ممکن است. کیفیت خروجی قطعی و قابل تست است. لینک دانلود از همان زیرساخت IXFileProvider و Storage موجود استفاده می‌کند و نیازی به سرویس جدید نیست. +
+
+
+ + +
+
+
۵
+
+

تحلیل Harness و نقشه راه مولتی‌ایجنت

+
Harness Analysis & Multi-Agent Roadmap
+
+
+
+ +

۵.۱ Harness چیست؟

+ +

Harness در سیستم‌های ایجنتی، به «حلقه اجرایی» (Runtime Loop) گفته می‌شود که مسئول موارد زیر است: دریافت ورودی، فراخوانی مدل، تفسیر خروجی، اجرای ابزارها، تزریق نتیجه به مدل، و تکرار تا رسیدن به شرط پایان (پاسخ نهایی، خطا، یا سقف مراحل). در کد فعلی شما، این حلقه به‌صورت ساده در XAIServiceBase.AskAsEnumerable() و AskTextByContextAsEnumerable() پیاده شده است: مدل با GetStreamingResponseAsync فراخوانی می‌شود، ابزارها از طریق ChatClientBuilder.UseFunctionInvocation() اجرا می‌شوند و نتیجه به مدل برمی‌گردد.

+ +
+ 💡 مزیت فعلی: UseFunctionInvocation() در Microsoft.Extensions.AI به‌صورت خودکار حلقه Tool-Calling را اجرا می‌کند. این یعنی Harness پایه شما در سطح کتابخانه وجود دارد و فقط نیاز به لایه‌بندی و مشاهده‌پذیری دارد. +
+ +

۵.۲ اجزای Harness پیشنهادی

+ +
+
+
Layer 0 Input Guard
+
+ Validation · Rate Limit · PII Scan +
+
+
▼
+
+
Layer 1 Planner
+
+ ChatClient.CompleteAsync(PlanPrompt) +
+
+
▼
+
+
Layer 2 Executor (Loop)
+
+ AIAgent.RunAsync · Tool Calls · Retry +
+
+
▼
+
+
Layer 3 Verifier / Critic
+
+ Reflection · Self-Correction +
+
+
▼
+
+
Layer 4 Output Guard + Trace
+
+ Output Sanitization · Cost · OTel +
+
+
+ +

۵.۳ نقشه راه مولتی‌ایجنت — ۶ فاز

+ +
+
+
+
+
فاز ۱ — Harness تک‌ایجنت (تثبیت وضعیت فعلی)
+

تکمیل Harness موجود با Layer 0 (Input Guard)، Trace، و Cost Measurement. تمرکز: مشاهده‌پذیری و قابلیت بازتولید. بدون تغییر در منطق فعلی، فقط افزودن middleware و logging.

+
+
+
+
+
+
فاز ۲ — Harness ابزارمحور (MCP + Local Tools)
+

افزودن ابزارهای محلی (Link Tool، Search Tool، File Tool) و ادغام با MCP Server Provider. تمرکز: گسترش سطح توانایی بدون افزایش پیچیدگی. خروجی: ایجنت ابزارمحور.

+
+
+
+
+
+
فاز ۳ — Planner + Critic (تک‌ایجنت با خودآزمایی)
+

افزودن Plan-and-Execute و Reflexion. مدل ابتدا برنامه می‌سازد، اجرا می‌کند، سپس نتیجه را نقد کرده و اصلاح می‌کند. تمرکز: افزایش کیفیت پاسخ‌های چندمرحله‌ای.

+
+
+
+
+
+
فاز ۴ — Orchestrator + Worker (مولتی‌ایجنت ابتدایی)
+

ساخت XAiOrchestratorAgent با WorkflowBuilder از Agent Framework. ارکستراتور، درخواست را به Workerهای تخصصی (Research، Document، File) توزیع می‌کند. تمرکز: موازی‌سازی و تخصص‌گرایی.

+
+
+
+
+
+
فاز ۵ — Human-in-the-loop (نقاط تأیید انسانی)
+

افزودن Approval Gates در عملیات حساس (تولید فایل، فراخوانی ابزار خارجی، ارسال ایمیل). تمرکز: کنترل و انطباق. خروجی: ایجنت سازمانی قابل استقرار.

+
+
+
+
+
+
فاز ۶ — Evaluation + Production Hardening
+

معیارهای Task Success Rate، Step Efficiency، Error Recovery. یکپارچه‌سازی با OpenTelemetry و Dashboard. تمرکز: پایداری بلندمدت.

+
+
+
+ +

۵.۴ نگاشت فازها به کلاس‌ها و لایه‌های موجود

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
فازمولفه‌های جدیدمولفه‌های موجود درگیر
فاز ۱XAgentHarnessMiddleware، XAgentTraceXAIServiceBase، UseFunctionInvocation، ILogger
فاز ۲XLinkExtractionTool، XSearchTool، XFileCreationToolIXAiMcpServerProvider، AIFunctionFactory، IXFileProvider
فاز ۳XAiPlannerAgent، XAiCriticAgentIChatClient، ChatOptions، AgentSession
فاز ۴XAiOrchestratorAgent، WorkflowBuilder، XAiWorkerAgent<T>Agent Framework، IXAiService، XAiMcpServerProvider
فاز ۵XAiApprovalGate، XAiApprovalHubXAiDataProviderHub، SignalR، IXAiDataProvider
فاز ۶XAgentMetricsExporter، XAgentEvaluationSuiteOpenTelemetry، Serilog، Dashboard
+ +

۵.۵ ملاحظات کلیدی برای Harness در معماری فعلی

+ +
    +
  • + مدیریت Context Window + در PrepareMemory موجود، استراتژی فعلی، کل تاریخچه را ارسال می‌کند. برای ایجنت، لازم است Summarization یا Sliding Window اضافه شود تا از سرریز Context جلوگیری شود. +
  • +
  • + ایزوله‌سازی Session + AgentSession باید بر اساس userId + conversationId ایزوله شود. از IMemoryCache با TTL استفاده کنید. +
  • +
  • + Kill Switch + یک قابلیت توقف فوری برای ایجنت‌های در حال اجرا (با CancellationToken و یک پرچم سراسری) فراهم کنید. +
  • +
  • + سقف مراحل و هزینه + در Harness، محدودیت سخت‌گیرانه‌ای برای maxSteps و maxTokens قرار دهید تا از حلقه‌های بی‌پایان جلوگیری شود. +
  • +
  • + ارزیابی Agent + در کنار Metrics، مجموعه‌ای از Test Scenarios با معیار Task Success Rate بسازید. این مجموعه باید در CI/CD اجرا شود. +
  • +
+ +
+ ⚠️ ریسک اصلی: در سیستم‌های مولتی‌ایجنت، پیچیدگی به‌سرعت زیاد می‌شود. توصیه می‌شود فاز ۴ را تنها پس از تثبیت فازهای ۱ تا ۳ شروع کنید. هر فاز باید حداقل ۲ هفته در محیط واقعی تست شود. +
+ +
+ ✓ نتیجه: این نقشه راه، به‌صورت تدریجی شما را از یک AI Assistant فعلی به یک سیستم مولتی‌ایجنت سازمانی می‌برد، بدون آنکه نیاز به بازنویسی کدبیس باشد. هر فاز روی فاز قبلی سوار می‌شود و ارزش مستقل ارائه می‌دهد. +
+
+
+ + +
+
+
۶
+
+

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

+
Summary & Execution Checklist
+
+
+
+ +

۶.۱ چک‌لیست اجرایی — به ترتیب اولویت

+ +
    +
  • + افزودن ماژول ابزارهای محلی + پوشه xAiApi/Tools را بسازید و XLinkExtractionTool را پیاده کنید. در XAiMcpServerProvider.GetAvailableToolsAsync ابزارهای محلی را به فهرست اضافه کنید. +
  • +
  • + افزودن پشتیبانی Google Search + IXSearchProvider و XGoogleCustomSearchProvider را پیاده کنید. تنظیمات را به XAiApiConfiguration اضافه کنید. ابزار جستجو را در Tool Registry ثبت نمایید. +
  • +
  • + افزودن ابزار تولید فایل + XDocumentSpec و Rendererها را پیاده کنید. دو Tool جداگانه BuildSpecAsync و CreateFile را ثبت نمایید. از IXFileProvider موجود برای ذخیره و لینک دانلود استفاده کنید. +
  • +
  • + ساخت لایه Agents + پوشه xAiApi/Agents را ایجاد کنید. XAiAgentBase و XAiAgentRunContext و XAiAgentTrace را پیاده کنید. یک AgentsController بسازید. +
  • +
  • + Harness پایه (فاز ۱ نقشه راه) + Input Guard، Trace، Cost Measurement، Context Management و Kill Switch را به لایه Agents اضافه کنید. +
  • +
  • + Planner + Critic (فاز ۳ نقشه راه) + XAiPlannerAgent و XAiCriticAgent را بسازید و در XAiOrchestratorAgent به‌عنوان Worker تخصصی استفاده کنید. +
  • +
  • + مولتی‌ایجنت ابتدایی (فاز ۴) + با WorkflowBuilder از Agent Framework، گراف Orchestrator–Worker را بسازید. +
  • +
  • + Human-in-the-loop (فاز ۵) + نقاط تأیید را با XAiDataProviderHub (SignalR) به کلاینت متصل کنید. +
  • +
  • + Evaluation و Production (فاز ۶) + OpenTelemetry، Dashboard و Test Suite را اضافه کنید. +
  • +
+ +

۶.۲ نکات کلیدی

+ +
+ +
+

دام‌های رایج

+
    +
  • افزودن بیش از ۲۰ Tool به مدل
  • +
  • عدم محدودسازی output tool
  • +
  • حلقه بدون سقف مراحل
  • +
  • عدم ایزوله‌سازی Session
  • +
  • ورود بدون Input Guard
  • +
+
+
+ +
+ نکته نهایی: تمام قابلیت‌های مطرح‌شده در این مستند، با استفاده از زیرساخت فعلی پروژه (Microsoft.Extensions.AI، Microsoft Agent Framework، MCP Server Provider، File Provider، RAG Service، Embedding Service) قابل پیاده‌سازی هستند. نیازی به جایگزینی یا بازنویسی کدبیس فعلی نیست؛ فقط لایه‌های جدید روی لایه‌های موجود اضافه می‌شوند. این رویکرد، ریسک پیاده‌سازی را حداقل و سرعت تحویل را حداکثر می‌کند. +
+
+
+ +
+

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

+

این مستند، مسیر فنی گام‌به‌گام از یک AI Assistant فعلی به یک سیستم مولتی‌ایجنت سازمانی را با حفظ کامل معماری موجود ترسیم کرد.

+

پنج قابلیت کلیدی (استخراج و خواندن لینک، جستجوی Google، ابزار تولید فایل، معماری ایجنت، Harness و Multi-Agent) با کمترین تغییر در کدبیس و حداکثر هم‌راستایی با زیرساخت فعلی طراحی شده‌اند.

+
+ 💎 ارزش پیشنهادی:
+ حفظ معماری موجود + افزودن تدریجی لایه‌ها + ابزارهای MCP + پشتیبانی چند Provider + Harness قابل مشاهده + نقشه راه ۶ فازی مولتی‌ایجنت +
+
+ +
+ این مستند محرمانه بوده و صرفاً جهت ارائه به کارفرمای محترم تهیه شده است. هرگونه کپی‌برداری یا افشا بدون اجازه کتبی ممنوع است. +
+ +
+ +
+ + +
تاریخ تهیه: آبان ۱۴۰۵  |  نسخه: ۱.۰  |  طبقه‌بندی: محرمانه
+
+ +
+ + + \ No newline at end of file diff --git a/Documents/GeneratedContext/xDashboard-xAiApi-20261106_205448.txt b/Documents/GeneratedContext/xDashboard-xAiApi-20261106_205448.txt deleted file mode 100644 index c148e70..0000000 --- a/Documents/GeneratedContext/xDashboard-xAiApi-20261106_205448.txt +++ /dev/null @@ -1,15713 +0,0 @@ - -### FILE: C:\Users\saherelm\Documents\Projects\xSaherelmWorkspace\xAiApi\Program.cs - -using System.Text; -using Microsoft.AspNetCore.Hosting; -using Microsoft.Extensions.Hosting; - -namespace xAiApi -{ - public class Program - { - public static void Main(string[] args) - { - // - Encoding.RegisterProvider(CodePagesEncodingProvider.Instance); - - // - CreateHostBuilder(args).Build().Run(); - } - - public static IHostBuilder CreateHostBuilder(string[] args) - { - // - var result = Host.CreateDefaultBuilder(args) - .ConfigureWebHostDefaults(webBuilder => - { - webBuilder.UseStartup(); - }); - - // - return result; - } - } -} - -### FILE: C:\Users\saherelm\Documents\Projects\xSaherelmWorkspace\xAiApi\Startup.cs - -using System; -using System.IO; -using xAiApi.DI; -using System.Linq; -using xAiModels.DI; -using xTagService.DI; -using System.Net.Http; -using xAiApi.Database; -using xHttpService.DI; -using xPushService.DI; -using xFileService.DI; -using xDataService.DI; -using Newtonsoft.Json; -using System.Reflection; -using xAiApi.Extensions; -using xStringService.DI; -using xStorageService.DI; -using xIdentityService.DI; -using xDataService.Models; -using xCommons.Extensions; -using xAiModels.Constants; -using xPushService.Helpers; -using xCommons.Configurations; -using System.Collections.Generic; -using Microsoft.AspNetCore.Builder; -using Microsoft.AspNetCore.Hosting; -using Microsoft.Extensions.Hosting; -using Newtonsoft.Json.Serialization; -using Microsoft.Extensions.Configuration; -using Microsoft.Extensions.DependencyInjection; -using IdentityModel.AspNetCore.OAuth2Introspection; -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\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 = "Gemma"; - public const string XAiEmbeddingModelName = "Embed"; - public const string XAiDefaultVisionModelName = "Qwen"; - public const string XAiDefaultThinkingModelName = "Qwen"; - public const string XAiEmbeddingPromptName = "Embedding"; - } -} - -### FILE: C:\Users\saherelm\Documents\Projects\xSaherelmWorkspace\xAiApi\Controllers\AccountController.cs - -using xCommons.Providers; -using xCommons.Configurations; -using xIdentityHelper.Controllers; -using xIdentityService.Interfaces; -using Microsoft.Extensions.Logging; - -namespace xAiApi.Controllers -{ - public partial class AccountController : XAccountControllerBase - { - // - #region Constructor ... - public AccountController( - ILogger logger, - XAppConfiguration appConfiguration, - IXIdentityProvider identityProvider, - XValidationProvider validationProvider - ) : base( - logger, - appConfiguration, - identityProvider, - validationProvider - ) - { } - #endregion - } -} - -### FILE: C:\Users\saherelm\Documents\Projects\xSaherelmWorkspace\xAiApi\Controllers\ChatWithDocumentsController.cs - -using System; -using System.Linq; -using xAiApi.Models; -using System.Threading; -using xAiApi.Interfaces; -using xAiApi.Extensions; -using xCommons.Providers; -using xCommons.Extensions; -using xAiApi.Configurations; -using xExceptions.Constants; -using xAiModels.Models.Dtos; -using System.Threading.Tasks; -using xHttpService.Extensions; -using xCommons.Configurations; -using Microsoft.AspNetCore.Mvc; -using Microsoft.AspNetCore.Http; -using System.Collections.Generic; -using xIdentityService.Interfaces; -using xIdentityService.Controllers; -using xAiApi.Interfaces.Extractors; -using Microsoft.Extensions.Logging; -using Microsoft.AspNetCore.Authorization; - -namespace xAiApi.Controllers -{ - /// - /// Chat With Documents (In-Memory RAG) Controller ... - /// Flow: Ingest Files -> SessionId -> Ask / AskStream -> Delete Session - /// - [Authorize] - public class ChatWithDocumentsController : XBaseIdentityApiV1Controller - { - /// - /// Default AI Service ... - /// - private readonly IXAiService aiService; - - /// - /// Text Chunker Service ... - /// - private readonly IXTextChunker textChunker; - - /// - /// In Memory Vector Store ... - /// - private readonly IXInMemoryVectorStore vectorStore; - - /// - /// XAiApi Configuration ... - /// - private readonly XAiApiConfiguration apiConfiguration; - - /// - /// Embedding Service ... - /// - private readonly IXAiEmbeddingService embeddingService; - - /// - /// File Context Extractor Service ... - /// - private readonly IXFileContentExtractor fileContentExtractor; - - public ChatWithDocumentsController( - IXAiService aiService, - IXTextChunker textChunker, - IXInMemoryVectorStore vectorStore, - XAppConfiguration appConfiguration, - IXIdentityProvider identityProvider, - XAiApiConfiguration apiConfiguration, - IXAiEmbeddingService embeddingService, - XValidationProvider validationProvider, - ILogger logger, - IXFileContentExtractor fileContentExtractor - ) : base(logger, appConfiguration, identityProvider, validationProvider) - { - // - this.aiService = aiService; - this.textChunker = textChunker; - this.vectorStore = vectorStore; - this.apiConfiguration = apiConfiguration; - this.embeddingService = embeddingService; - this.fileContentExtractor = fileContentExtractor; - } - - // - #region Ingest ... - /// - /// Ingest Files into a (new or existing) In-Memory Session: - /// Extract -> Chunk -> Embed -> Store ... - /// - /// - /// Optional: Add to an Existing Session - /// Optional: Session TTL in Minutes (only for new Session) - /// - /// - [HttpPost("Ingest")] - [Consumes("multipart/form-data")] - public async Task> Ingest( - [FromForm] IFormFileCollection files, - [FromForm] Guid? sessionId = null, - [FromForm] int? ttlMinutes = null, - CancellationToken cancellationToken = default - ) - { - // - try - { - // - // Validate ... - if (!files.HasChild()) - { - XException.InvalidArgs.Throw(); - } - - // - var userInfo = await GetUserInfo(); - var ownerId = userInfo.UserId; - - // - // Resolve Target Session ... - Guid targetSessionId; - if (sessionId.HasValue && sessionId.Value != Guid.Empty) - { - // - if (!vectorStore.TryGet(sessionId.Value, out _, ownerId)) - { - XException.NotFound.Throw(); - } - targetSessionId = sessionId.Value; - } - else - { - // - var ttl = TimeSpan.FromMinutes( - ttlMinutes.HasValue && ttlMinutes.Value > 0 - ? ttlMinutes.Value - : apiConfiguration.RAGDescriptor.DefaultTtlMinutes - ); - targetSessionId = vectorStore.CreateSession(ownerId, ttl); - } - - // - var result = new XAiDocumentIngestResult - { - SessionId = targetSessionId - }; - - // - // Extract -> Chunk -> Embed ... - var vectors = new List(); - foreach (var file in files) - { - // - cancellationToken.ThrowIfCancellationRequested(); - - // - if (file.IsNull() || file.Length == 0) - { - result.SkippedFiles.Add(file?.FileName ?? "(null)"); - continue; - } - - // - var mimeType = file.ContentType?.ToLowerInvariant() ?? string.Empty; - if (!fileContentExtractor.CanExtract(mimeType)) - { - result.SkippedFiles.Add(file.FileName); - continue; - } - - // - var text = await ExtractText(file, mimeType, cancellationToken); - if (string.IsNullOrWhiteSpace(text)) - { - result.SkippedFiles.Add(file.FileName); - continue; - } - - // - var chunks = textChunker.Chunk(text, file.FileName); - if (!chunks.HasChild()) - { - result.SkippedFiles.Add(file.FileName); - continue; - } - - // - // Embed in Batches ... - var fileVectors = await EmbedChunks( - chunks: chunks, - fileName: file.FileName, - mimeType: mimeType, - cancellationToken: cancellationToken - ); - - // - vectors.AddRange(fileVectors); - result.FilesCount++; - } - - // - // Store ... - if (vectors.HasChild() && - !vectorStore.Add(targetSessionId, vectors, ownerId)) - { - XException.ActionFailed.Throw(); - } - - // - // Fill Result ... - result.ChunksCount = vectors.Count; - if (vectorStore.TryGet(targetSessionId, out var session, ownerId)) - { - lock (session.SyncRoot) - { - result.TotalVectorsCount = session.Vectors.Count; - } - result.ExpiresAtUtc = session.LastAccessAtUtc.Add(session.Ttl); - } - - // - return Ok(result); - } - catch (Exception ex) - { - var result = GetExceptionActionResult(ex); - return result; - } - } - #endregion - - // - #region Ask ... - /// - /// Ask a Question over Ingested Documents ... - /// - /// - /// - /// - [HttpPost("Ask")] - public async Task> Ask( - [FromBody] XAiDocumentAskRequest request, - CancellationToken cancellationToken = default - ) - { - // - try - { - // - // Validate ... - if (!request.IsValid()) - { - XException.InvalidArgs.Throw(); - } - - // - var userInfo = await GetUserInfo(); - var ownerId = userInfo.UserId; - - // - // Check Session ... - if (!vectorStore.TryGet(request.SessionId, out _, ownerId)) - { - XException.NotFound.Throw(); - } - - // - // Retrieve ... - var context = await Retrieve(request, ownerId, cancellationToken); - - // - var result = new XAiDocumentAnswer - { - SessionId = request.SessionId, - Sources = ToSources(context) - }; - - // - if (!context.HasChild()) - { - result.NoContextFound = true; - return Ok(result); - } - - // - // Generate ... - result.Answer = await aiService.AskTextByContextAsync( - context: context, - userInfo: userInfo, - prompt: request.Prompt, - cancellationToken: cancellationToken - ); - - // - return Ok(result); - } - catch (Exception ex) - { - var result = GetExceptionActionResult(ex); - return result; - } - } - - /// - /// Ask a Question over Ingested Documents and Stream Response (SSE) ... - /// First Event Carries Sources, Next Events Carry Text Deltas, Last Event has IsFinal = true ... - /// - /// - /// - /// - [HttpPost("AskStream")] - public async Task AskStream( - [FromBody] XAiDocumentAskRequest request, - CancellationToken cancellationToken = default - ) - { - // - // Validate (before Stream Starts -> Proper Http Error) ... - if (!request.IsValid()) - { - // - Response.StatusCode = StatusCodes.Status400BadRequest; - Response.ContentType = "application/json; charset=utf-8"; - await Response.WriteAsync(XException.InvalidArgs.ToXError().ToJSON()); - return; - } - - // - try - { - // - var userInfo = await GetUserInfo(); - var ownerId = userInfo.UserId; - - // - // Check Session ... - if (!vectorStore.TryGet(request.SessionId, out _, ownerId)) - { - XException.NotFound.Throw(); - } - - // - // Retrieve ... - var context = await Retrieve(request, ownerId, cancellationToken); - - // - // Configure SSE Response ... - Response.PrepareSseResponse(); - - // - // First Event: Sources ... - var hasContext = context.HasChild(); - await WriteChunk(new XAiDocumentAnswerChunk - { - Text = string.Empty, - IsFinal = !hasContext, - NoContextFound = !hasContext, - Sources = ToSources(context) - }, cancellationToken); - - // - if (!hasContext) - { - await Response.WriteSseDoneAsync(cancellationToken); - return; - } - - // - // Stream Deltas ... - var enumerable = aiService.AskTextByContextAsEnumerable( - context: context, - userInfo: userInfo, - prompt: request.Prompt, - cancellationToken: cancellationToken - ); - await foreach (var delta in enumerable) - { - // - if (delta.IsNullOrEmpty()) - { - continue; - } - - // - await WriteChunk(new XAiDocumentAnswerChunk - { - Text = delta - }, cancellationToken); - } - - // - // Final Event ... - await WriteChunk(new XAiDocumentAnswerChunk - { - Text = string.Empty, - IsFinal = true - }, cancellationToken); - await Response.WriteSseDoneAsync(cancellationToken); - } - catch (Exception ex) when (ex.IsClientCancellation(cancellationToken)) - { - // Client Disconnected ... - } - catch (Exception ex) - { - // - Logger.LogError(ex, "ChatWithDocuments: AskStream Failed"); - if (!Response.HasStarted) - { - // - var result = GetExceptionActionResult(ex); - await result.ExecuteResultAsync(ControllerContext); - return; - } - - // - await Response.WriteSseErrorAsync(ex.Message); - } - } - #endregion - - // - #region Session ... - /// - /// Retrieve Session Info (without Embeddings) ... - /// - /// - /// - [HttpGet("Session/{id:guid}")] - public async Task> GetSession(Guid id) - { - // - try - { - // - var userInfo = await GetUserInfo(); - if (!vectorStore.TryGet(id, out var session, userInfo.UserId)) - { - XException.NotFound.Throw(); - } - - // - IList vectors; - lock (session.SyncRoot) - { - vectors = session.Vectors.ToList(); - } - - // - var result = new XAiDocumentSessionInfo - { - Id = session.Id, - Ttl = session.Ttl, - VectorsCount = vectors.Count, - CreatedAtUtc = session.CreatedAtUtc, - LastAccessAtUtc = session.LastAccessAtUtc, - ExpiresAtUtc = session.LastAccessAtUtc.Add(session.Ttl), - Files = [.. vectors - .Select(v => v.Metadata.GetMetadata(apiConfiguration.RAGDescriptor.MetadataFileName)) - .Where(f => !f.IsNullOrEmpty()) - .Distinct()] - }; - - // - return Ok(result); - } - catch (Exception ex) - { - var result = GetExceptionActionResult(ex); - return result; - } - } - - /// - /// Remove a Session and Free Memory ... - /// - /// - /// - [HttpDelete("Session/{id:guid}")] - public async Task> DeleteSession(Guid id) - { - // - try - { - // - var userInfo = await GetUserInfo(); - if (!vectorStore.Remove(id, userInfo.UserId)) - { - XException.NotFound.Throw(); - } - - // - return Ok(true); - } - catch (Exception ex) - { - var result = GetExceptionActionResult(ex); - return result; - } - } - #endregion - - // - #region Private ... - /// - /// Extract Plain Text of a File (Text or Audio Transcript) ... - /// - private async Task ExtractText( - IFormFile file, - string mimeType, - CancellationToken cancellationToken - ) - { - // - try - { - // - using var stream = file.OpenReadStream(); - var extraction = await fileContentExtractor.ExtractRichAsync( - fileStream: stream, - mimeType: mimeType, - fileName: file.FileName, - cancellationToken: cancellationToken - ); - - // - var result = extraction?.Text; - if (string.IsNullOrWhiteSpace(result)) - { - result = extraction?.AudioTranscript; - } - - // - return result; - } - catch (OperationCanceledException) - { - throw; - } - catch (Exception ex) - { - Logger.LogWarning(ex, "ChatWithDocuments: Extraction Failed for {FileName}", file.FileName); - return null; - } - } - - /// - /// Embed Chunks in Batches and Build Vectors ... - /// - private async Task> EmbedChunks( - IList chunks, - string fileName, - string mimeType, - CancellationToken cancellationToken - ) - { - // - var result = new List(chunks.Count); - var batchSize = apiConfiguration.RAGDescriptor.EmbeddingBatchSize; - - // - for (var offset = 0; offset < chunks.Count; offset += batchSize) - { - // - cancellationToken.ThrowIfCancellationRequested(); - - // - var batch = chunks.Skip(offset).Take(batchSize).ToList(); - var embeddings = await embeddingService.Embeddings( - batch: batch.Select(c => c.Text).ToArray(), - cancellationToken: cancellationToken - ); - - // - if (embeddings.IsNullOrDefault() || embeddings.Count != batch.Count) - { - XException.ActionFailed.Throw(); - } - - // - for (var i = 0; i < batch.Count; i++) - { - // - var chunk = batch[i]; - result.Add(new XAiVectorDto - { - Id = Guid.NewGuid(), - Text = chunk.Text, - Embedding = embeddings[i], - Identifier = chunk.Identifier, - Metadata = new Dictionary - { - [apiConfiguration.RAGDescriptor.MetadataFileName] = fileName, - [apiConfiguration.RAGDescriptor.MetadataMimeType] = mimeType, - [apiConfiguration.RAGDescriptor.MetadataChunkIndex] = chunk.Index.ToString() - } - }); - } - } - - // - return result; - } - - /// - /// Embed Prompt and Search Session ... - /// - private async Task> Retrieve( - XAiDocumentAskRequest request, - string ownerId, - CancellationToken cancellationToken - ) - { - // - var topK = Math.Clamp( - request.TopK ?? apiConfiguration.RAGDescriptor.DefaultTopK, - 1, - apiConfiguration.RAGDescriptor.MaxTopK - ); - var minScore = request.MinScore ?? apiConfiguration.RAGDescriptor.DefaultMinScore; - - // - var queryEmbedding = await embeddingService.Embedding( - content: request.Prompt, - cancellationToken: cancellationToken - ); - if (queryEmbedding.IsNullOrDefault() || queryEmbedding.Length == 0) - { - XException.ActionFailed.Throw(); - } - - // - var result = vectorStore.Search( - topK: topK, - ownerId: ownerId, - minScore: minScore, - sessionId: request.SessionId, - queryEmbedding: queryEmbedding - ); - - // - return result ?? []; - } - - /// - /// Map Search Results to Public Sources ... - /// - private IList ToSources( - IEnumerable context - ) - { - // - var result = (context ?? []) - .Select(c => - { - // - var chunkIndexText = c.Metadata.GetMetadata(apiConfiguration.RAGDescriptor.MetadataChunkIndex); - var text = c.Text ?? string.Empty; - var snippetLength = Math.Min(text.Length, apiConfiguration.RAGDescriptor.SourceSnippetLength); - - // - return new XAiDocumentSource - { - Score = c.Score, - Identifier = c.Identifier, - Snippet = text.Substring(0, snippetLength), - ChunkIndex = int.TryParse(chunkIndexText, out var idx) ? idx : null, - FileName = c.Metadata.GetMetadata(apiConfiguration.RAGDescriptor.MetadataFileName) - }; - }) - .ToList(); - - // - return result; - } - - /// - /// Write a SSE Event ... - /// - private Task WriteChunk( - XAiDocumentAnswerChunk chunk, - CancellationToken cancellationToken - ) - { - // - return Response.WriteSseEventAsync( - data: chunk, - cancellationToken: cancellationToken - ); - } - #endregion - } -} - -### FILE: C:\Users\saherelm\Documents\Projects\xSaherelmWorkspace\xAiApi\Controllers\KnowledgeController.cs - -using System; -using xAiApi.Models; -using System.Threading; -using xAiApi.Interfaces; -using xCommons.Providers; -using xAiModels.Constants; -using xCommons.Extensions; -using xExceptions.Constants; -using System.Threading.Tasks; -using xHttpService.Extensions; -using xCommons.Configurations; -using Microsoft.AspNetCore.Mvc; -using Microsoft.AspNetCore.Http; -using System.Collections.Generic; -using xIdentityService.Interfaces; -using xIdentityService.Controllers; -using Microsoft.Extensions.Logging; -using Microsoft.AspNetCore.Authorization; -using xIdentityHelper; - -namespace xAiApi.Controllers -{ - /// - /// Knowledge (Persistent RAG over XAiVector Table) Controller ... - /// Flow: Ingest Files -> Ask / AskStream (Retrieve from DB -> Generate) -> Documents / Delete - /// - [Authorize] - public class KnowledgeController : XBaseIdentityApiV1Controller - { - /// - /// Persistent RAG Service ... - /// - private readonly IXAiRAGService ragService; - - public KnowledgeController( - IXAiRAGService ragService, - XAppConfiguration appConfiguration, - IXIdentityProvider identityProvider, - ILogger logger, - XValidationProvider validationProvider - ) : base(logger, appConfiguration, identityProvider, validationProvider) - { - this.ragService = ragService; - } - - // - #region Ingest ... - /// - /// Ingest Files into a Knowledge Scope: - /// Extract -> Chunk -> Embed -> Store in XAiVector Table ... - /// - /// - /// Target Scope: User (default) / Project / Conversation / Global (Admin) - /// ProjectId or ConversationId (Required for Project / Conversation) - /// Optional Knowledge Type / Domain - /// Replace Previously Stored Vectors of Same File (default true) - /// - /// - [HttpPost("Ingest")] - [Consumes("multipart/form-data")] - [Authorize(Policy = XPolicies.EnabledAdmin)] - public async Task> Ingest( - [FromForm] IFormFileCollection files, - [FromForm] XAiKnowledgeScope? scope = XAiKnowledgeScope.Global, - [FromForm] Guid? scopeId = null, - [FromForm] string knowledgeType = null, - [FromForm] bool replaceExisting = true, - CancellationToken cancellationToken = default - ) - { - // - try - { - // - // Validate ... - if (!files.HasChild()) - { - XException.InvalidArgs.Throw(); - } - - // - var userInfo = await GetUserInfo(); - var connectionId = GetConnectionId(); - - // - var result = await ragService.IngestAsync( - files: files, - userInfo: userInfo, - connectionId: connectionId, - replaceExisting: replaceExisting, - cancellationToken: cancellationToken, - scope: BuildScope(scope, scopeId, knowledgeType) - ); - - // - return Ok(result); - } - catch (Exception ex) - { - // - var result = GetExceptionActionResult(ex); - return result; - } - } - #endregion - - // - #region Documents ... - /// - /// List Ingested Documents of a Knowledge Scope ... - /// - /// User (default) / Project / Conversation / Global - /// ProjectId or ConversationId (Required for Project / Conversation) - /// Optional Knowledge Type Filter - /// - /// - [HttpGet("Documents")] - [Authorize(Policy = XPolicies.EnabledAdmin)] - public async Task>> Documents( - [FromQuery] XAiKnowledgeScope? scope = XAiKnowledgeScope.Global, - [FromQuery] Guid? scopeId = null, - [FromQuery] string knowledgeType = null, - CancellationToken cancellationToken = default - ) - { - // - try - { - // - var userInfo = await GetUserInfo(); - var scopeIdentifier = BuildScope(scope, scopeId, knowledgeType); - - // - var result = await ragService.LoadDocumentsAsync( - userInfo: userInfo, - scope: scopeIdentifier, - cancellationToken: cancellationToken - ); - - // - return Ok(result); - } - catch (Exception ex) - { - // - var result = GetExceptionActionResult(ex); - return result; - } - } - - /// - /// Remove All Vectors of a Document in a Knowledge Scope ... - /// - /// - /// User (default) / Project / Conversation / Global (Admin) - /// ProjectId or ConversationId (Required for Project / Conversation) - /// - /// Count of Removed Vectors - [HttpDelete("Documents")] - [Authorize(Policy = XPolicies.EnabledAdmin)] - public async Task> DeleteDocument( - [FromQuery] string fileName, - [FromQuery] XAiKnowledgeScope? scope = XAiKnowledgeScope.Global, - [FromQuery] Guid? scopeId = null, - CancellationToken cancellationToken = default - ) - { - // - try - { - // - // Validate ... - ValidationProvider.NotEmpty(fileName); - - // - var userInfo = await GetUserInfo(); - - // - var result = await ragService.RemoveDocumentAsync( - fileName: fileName, - userInfo: userInfo, - cancellationToken: cancellationToken, - scope: BuildScope(scope, scopeId, null) - ); - - // - return Ok(result); - } - catch (Exception ex) - { - // - var result = GetExceptionActionResult(ex); - return result; - } - } - #endregion - - // - #region Private ... - /// - /// Build Scope Descriptor from Request Params ... - /// - private XAiKnowledgeScopeDescriptor BuildScope( - XAiKnowledgeScope? scope, - Guid? scopeId, - string knowledgeType - ) - { - // - if (!scope.HasValue) - { - scope = XAiKnowledgeScope.Global; - } - - // - var result = new XAiKnowledgeScopeDescriptor - { - Scope = scope.Value, - ScopeId = scopeId, - Type = knowledgeType, - }; - - // - return result; - } - - /// - /// Write a SSE Event ... - /// - private Task WriteChunk( - XAiDocumentAnswerChunk chunk, - CancellationToken cancellationToken - ) - { - // - return Response.WriteSseEventAsync( - data: chunk, - cancellationToken: cancellationToken - ); - } - #endregion - } -} - - -### FILE: C:\Users\saherelm\Documents\Projects\xSaherelmWorkspace\xAiApi\Controllers\McpServersController.cs - -using System; -using xModels.Dtos; -using xIdentityHelper; -using System.Threading; -using xAiApi.Interfaces; -using xCommons.Providers; -using xCommons.Extensions; -using xAiModels.Extensions; -using xAiModels.Models.Dtos; -using xExceptions.Constants; -using System.Threading.Tasks; -using xCommons.Configurations; -using Microsoft.AspNetCore.Mvc; -using System.Collections.Generic; -using xIdentityService.Interfaces; -using Microsoft.Extensions.Logging; -using xIdentityService.Controllers; -using Microsoft.AspNetCore.Authorization; - -namespace xAiApi.Controllers -{ - [Authorize] - public class McpServersController : XBaseIdentityApiV1Controller - { - private readonly IXAiMcpServerProvider mcpServerProvider; - - public McpServersController( - XAppConfiguration appConfiguration, - IXIdentityProvider identityProvider, - ILogger logger, - XValidationProvider validationProvider, - IXAiMcpServerProvider mcpServerProvider - ) : base( - logger, - appConfiguration, - identityProvider, - validationProvider - ) - { - this.mcpServerProvider = mcpServerProvider; - } - - // - #region Provider ... - /// - /// Retrieve Specified MCP Server ... - /// - /// - /// - /// - [HttpGet("{id}")] - [Authorize(Policy = XPolicies.EnabledUser)] - public virtual async Task> GetMcpServer( - [FromRoute] Guid id, - CancellationToken cancellationToken = default - ) - { - // - try - { - // - // Validate ... - if (!ModelState.IsValid || id.IsDefaultGuid()) - { - XException.InvalidArgs.Throw(); - } - - // - var userInfo = await GetUserInfo(); - var connectionId = GetConnectionId(); - - // - var result = await mcpServerProvider.GetMcpServer( - id: id, - userInfo: userInfo, - cancellationToken: cancellationToken - ); - - // - return Ok(result.ToDynamicObject()); - } - catch (Exception ex) - { - // - var result = GetExceptionActionResult(ex); - return result; - } - } - - /// - /// Add MCP Server ... - /// - /// - /// - /// - [HttpPost] - [Authorize(Policy = XPolicies.EnabledUser)] - public virtual async Task> AddMcpServer( - [FromBody] XAiMcpServerDto item, - CancellationToken cancellationToken = default - ) - { - // - try - { - // - // Validate ... - if (!ModelState.IsValid || item.IsNullOrDefault()) - { - XException.InvalidArgs.Throw(); - } - - // - var userInfo = await GetUserInfo(); - var connectionId = GetConnectionId(); - - // - var result = await mcpServerProvider.AddMcpServer( - item: item, - userInfo: userInfo, - connectionId: connectionId, - cancellationToken: cancellationToken - ); - - // - return Ok(result.ToDynamicObject()); - } - catch (Exception ex) - { - // - var result = GetExceptionActionResult(ex); - return result; - } - } - - /// - /// Update Specified MCP Server ... - /// - /// - /// - /// - /// - [HttpPut("{id}")] - [Authorize(Policy = XPolicies.EnabledUser)] - public virtual async Task> UpdateMcpServer( - [FromRoute] Guid id, - [FromBody] XAiMcpServerDto item, - CancellationToken cancellationToken = default - ) - { - // - try - { - // - // Validate ... - if (id.IsDefaultGuid() || - !ModelState.IsValid || - !item.IsValidForAddOrUpdate()) - { - XException.InvalidArgs.Throw(); - } - - // - var userInfo = await GetUserInfo(); - var connectionId = GetConnectionId(); - - // - var result = await mcpServerProvider.UpdateMcpServer( - id: id, - item: item, - userInfo: userInfo, - connectionId: connectionId, - cancellationToken: cancellationToken - ); - - // - return Ok(result.ToDynamicObject()); - } - catch (Exception ex) - { - // - var result = GetExceptionActionResult(ex); - return result; - } - } - - /// - /// Remove Specified MCP Server ... - /// - /// - /// - /// - [HttpDelete("{id}")] - [Authorize(Policy = XPolicies.EnabledUser)] - public virtual async Task> RemoveMcpServer( - [FromRoute] Guid id, - CancellationToken cancellationToken = default - ) - { - // - try - { - // - // Validate ... - if (!ModelState.IsValid || id.IsDefaultGuid()) - { - XException.InvalidArgs.Throw(); - } - - // - var userInfo = await GetUserInfo(); - var connectionId = GetConnectionId(); - - // - var result = await mcpServerProvider.RemoveMcpServer( - id: id, - userInfo: userInfo, - connectionId: connectionId, - cancellationToken: cancellationToken - ); - - // - return Ok(result.ToDynamicObject()); - } - catch (Exception ex) - { - // - var result = GetExceptionActionResult(ex); - return result; - } - } - - /// - /// Enable Specified MCP Server ... - /// - /// - /// - /// - [HttpPost("{id}/Enable")] - [Authorize(Policy = XPolicies.EnabledUser)] - public virtual async Task> EnableMcpServer( - [FromRoute] Guid id, - CancellationToken cancellationToken = default - ) - { - // - try - { - // - // Validate ... - if (!ModelState.IsValid || id.IsDefaultGuid()) - { - XException.InvalidArgs.Throw(); - } - - // - var userInfo = await GetUserInfo(); - var connectionId = GetConnectionId(); - - // - var result = await mcpServerProvider.EnableMcpServer( - id: id, - userInfo: userInfo, - connectionId: connectionId, - cancellationToken: cancellationToken - ); - - // - return Ok(result); - } - catch (Exception ex) - { - // - var result = GetExceptionActionResult(ex); - return result; - } - } - - /// - /// Disable Specified MCP Server ... - /// - /// - /// - /// - [HttpPost("{id}/Disable")] - [Authorize(Policy = XPolicies.EnabledUser)] - public virtual async Task> DisableMcpServer( - [FromRoute] Guid id, - CancellationToken cancellationToken = default - ) - { - // - try - { - // - // Validate ... - if (!ModelState.IsValid || id.IsDefaultGuid()) - { - XException.InvalidArgs.Throw(); - } - - // - var userInfo = await GetUserInfo(); - var connectionId = GetConnectionId(); - - // - var result = await mcpServerProvider.DisableMcpServer( - id: id, - userInfo: userInfo, - connectionId: connectionId, - cancellationToken: cancellationToken - ); - - // - return Ok(result); - } - catch (Exception ex) - { - // - var result = GetExceptionActionResult(ex); - return result; - } - } - - /// - /// Toggle Specified MCP Server ... - /// - /// - /// - /// - [HttpPost("{id}/Toggle")] - [Authorize(Policy = XPolicies.EnabledUser)] - public virtual async Task> ToggleMcpServer( - [FromRoute] Guid id, - CancellationToken cancellationToken = default - ) - { - // - try - { - // - // Validate ... - if (!ModelState.IsValid || id.IsDefaultGuid()) - { - XException.InvalidArgs.Throw(); - } - - // - var userInfo = await GetUserInfo(); - var connectionId = GetConnectionId(); - - // - var result = await mcpServerProvider.ToggleMcpServer( - id: id, - userInfo: userInfo, - connectionId: connectionId, - cancellationToken: cancellationToken - ); - - // - return Ok(result); - } - catch (Exception ex) - { - // - var result = GetExceptionActionResult(ex); - return result; - } - } - - /// - /// Get all Registered MCP Servers by handling Ownership ... - /// - /// - /// - [HttpGet] - [Authorize(Policy = XPolicies.EnabledUser)] - public virtual async Task>> GetMcpServers( - [FromQuery] bool forceOwner = true, - CancellationToken cancellationToken = default - ) - { - // - try - { - // - // Validate ... - if (!ModelState.IsValid) - { - XException.InvalidArgs.Throw(); - } - - // - var userInfo = await GetUserInfo(); - var connectionId = GetConnectionId(); - - // - var result = await mcpServerProvider.GetAll( - userInfo: userInfo, - forceOwner: forceOwner, - cancellationToken: cancellationToken - ); - - // - return Ok(result.ToDynamicObject()); - } - catch (Exception ex) - { - // - var result = GetExceptionActionResult(ex); - return result; - } - } - - /// - /// Query Registered MCP Servers by handling Ownership ... - /// - /// - /// - /// - /// - [HttpGet("Query")] - [Authorize(Policy = XPolicies.EnabledUser)] - public virtual async Task>> QueryMcpServers( - [FromQuery] XQuery query, - [FromQuery] bool forceOwner = true, - CancellationToken cancellationToken = default - ) - { - // - try - { - // - // Validate ... - if (!ModelState.IsValid) - { - XException.InvalidArgs.Throw(); - } - await ValidationProvider - .GroupValidationBuilder() - .AddNotNull(query) - .ValidateGroupAsync(); - - // - var userInfo = await GetUserInfo(); - var connectionId = GetConnectionId(); - - // - var result = await mcpServerProvider.Query( - query: query, - userInfo: userInfo, - forceOwner: forceOwner, - cancellationToken: cancellationToken - ); - - // - return Ok(result.ToDynamicObject()); - } - catch (Exception ex) - { - // - var result = GetExceptionActionResult(ex); - return result; - } - } - #endregion - - /// - /// Refresh MCP Servers ... - /// - /// - /// - [HttpPost("Refresh")] - [Authorize(Policy = XPolicies.EnabledAdmin)] - public async Task RefreshMcpServers( - 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\20261105072614_InitialMigrationAiApi.cs - -using System; -using Microsoft.EntityFrameworkCore.Migrations; - -namespace xAiApi.Migrations -{ - public partial class InitialMigrationAiApi : Migration - { - protected override void Up(MigrationBuilder migrationBuilder) - { - migrationBuilder.CreateTable( - name: "AiConversations", - columns: table => new - { - Id = table.Column(nullable: false), - Deleted = table.Column(nullable: false), - OwnerId = table.Column(maxLength: 255, nullable: false), - Title = table.Column(maxLength: 255, nullable: false), - CreatedOn = table.Column(nullable: false), - UpdatedAt = table.Column(nullable: false), - ProjectId = table.Column(nullable: false) - }, - constraints: table => - { - table.PrimaryKey("PK_AiConversations", x => x.Id); - }); - - migrationBuilder.CreateTable( - name: "AiMcpServers", - columns: table => new - { - Id = table.Column(nullable: false), - Deleted = table.Column(nullable: false), - OwnerId = table.Column(maxLength: 255, nullable: false), - Scope = table.Column(nullable: false), - Name = table.Column(maxLength: 255, nullable: false), - Description = table.Column(maxLength: 1000, nullable: true), - Enabled = table.Column(nullable: false), - EnvironmentVariables = table.Column(nullable: true), - Endpoint = table.Column(maxLength: 1000, nullable: true), - Headers = table.Column(nullable: true), - TimeoutSeconds = table.Column(nullable: false), - CreatedOn = table.Column(nullable: false), - UpdatedAt = table.Column(nullable: false) - }, - constraints: table => - { - table.PrimaryKey("PK_AiMcpServers", x => x.Id); - }); - - migrationBuilder.CreateTable( - name: "AiMessages", - columns: table => new - { - Id = table.Column(nullable: false), - Deleted = table.Column(nullable: false), - OwnerId = table.Column(maxLength: 255, nullable: false), - Content = table.Column(nullable: false), - Role = table.Column(nullable: false), - CreatedOn = table.Column(nullable: false), - UpdatedAt = table.Column(nullable: false), - ConversationId = table.Column(maxLength: 255, nullable: false), - MetaDatas = table.Column(nullable: true) - }, - constraints: table => - { - table.PrimaryKey("PK_AiMessages", x => x.Id); - }); - - migrationBuilder.CreateTable( - name: "AiProjects", - columns: table => new - { - Id = table.Column(nullable: false), - Deleted = table.Column(nullable: false), - OwnerId = table.Column(maxLength: 255, nullable: false), - Title = table.Column(maxLength: 255, nullable: false), - Description = table.Column(maxLength: 1000, nullable: true), - Prompt = table.Column(nullable: true), - CreatedOn = table.Column(nullable: false), - UpdatedAt = table.Column(nullable: false) - }, - constraints: table => - { - table.PrimaryKey("PK_AiProjects", x => x.Id); - }); - - migrationBuilder.CreateTable( - name: "AiVectors", - columns: table => new - { - Id = table.Column(nullable: false), - Deleted = table.Column(nullable: false), - Text = table.Column(nullable: true), - Identifier = table.Column(nullable: true), - Type = table.Column(maxLength: 100, nullable: true), - Embedding = table.Column(nullable: true), - Metadata = table.Column(nullable: true) - }, - constraints: table => - { - table.PrimaryKey("PK_AiVectors", x => x.Id); - }); - - migrationBuilder.CreateTable( - name: "Files", - columns: table => new - { - Id = table.Column(nullable: false), - Deleted = table.Column(nullable: false), - Type = table.Column(nullable: false), - OwnerId = table.Column(maxLength: 255, nullable: false), - Name = table.Column(maxLength: 255, nullable: false), - Path = table.Column(nullable: false), - Thumb = table.Column(nullable: true), - ThumbPath = table.Column(nullable: true), - UploadedOn = table.Column(nullable: false), - FileName = table.Column(nullable: true), - References = table.Column(nullable: true) - }, - constraints: table => - { - table.PrimaryKey("PK_Files", x => x.Id); - }); - - migrationBuilder.CreateTable( - name: "Strings", - columns: table => new - { - Id = table.Column(nullable: false) - .Annotation("Sqlite:Autoincrement", true), - Deleted = table.Column(nullable: false), - Language = table.Column(maxLength: 10, nullable: false), - ResourceTitle = table.Column(maxLength: 255, nullable: false), - TranslatedValue = table.Column(nullable: false) - }, - constraints: table => - { - table.PrimaryKey("PK_Strings", x => x.Id); - }); - - migrationBuilder.CreateTable( - name: "Tags", - columns: table => new - { - Id = table.Column(nullable: false) - .Annotation("Sqlite:Autoincrement", true), - Deleted = table.Column(nullable: false), - Tag = table.Column(maxLength: 255, nullable: false), - References = table.Column(nullable: true) - }, - constraints: table => - { - table.PrimaryKey("PK_Tags", x => x.Id); - }); - - migrationBuilder.CreateIndex( - name: "IX_AiVectors_Identifier", - table: "AiVectors", - column: "Identifier"); - - migrationBuilder.CreateIndex( - name: "IX_AiVectors_Type", - table: "AiVectors", - column: "Type"); - } - - protected override void Down(MigrationBuilder migrationBuilder) - { - migrationBuilder.DropTable( - name: "AiConversations"); - - migrationBuilder.DropTable( - name: "AiMcpServers"); - - migrationBuilder.DropTable( - name: "AiMessages"); - - migrationBuilder.DropTable( - name: "AiProjects"); - - migrationBuilder.DropTable( - name: "AiVectors"); - - migrationBuilder.DropTable( - name: "Files"); - - migrationBuilder.DropTable( - name: "Strings"); - - migrationBuilder.DropTable( - name: "Tags"); - } - } -} - -### FILE: C:\Users\saherelm\Documents\Projects\xSaherelmWorkspace\xAiApi\Migrations\20261105072614_InitialMigrationAiApi.Designer.cs - -// -using System; -using Microsoft.EntityFrameworkCore; -using Microsoft.EntityFrameworkCore.Infrastructure; -using Microsoft.EntityFrameworkCore.Migrations; -using Microsoft.EntityFrameworkCore.Storage.ValueConversion; -using xAiApi.Database; - -namespace xAiApi.Migrations -{ - [DbContext(typeof(XAiApiDbContext))] - [Migration("20261105072614_InitialMigrationAiApi")] - partial class InitialMigrationAiApi - { - protected override void BuildTargetModel(ModelBuilder modelBuilder) - { -#pragma warning disable 612, 618 - modelBuilder - .HasAnnotation("ProductVersion", "3.1.14"); - - modelBuilder.Entity("xAiModels.Models.Entities.XAiConversation", b => - { - b.Property("Id") - .ValueGeneratedOnAdd() - .HasColumnType("TEXT"); - - b.Property("CreatedOn") - .HasColumnType("TEXT"); - - b.Property("Deleted") - .HasColumnType("INTEGER"); - - b.Property("OwnerId") - .IsRequired() - .HasColumnType("TEXT") - .HasMaxLength(255); - - b.Property("ProjectId") - .HasColumnType("TEXT"); - - b.Property("Title") - .IsRequired() - .HasColumnType("TEXT") - .HasMaxLength(255); - - b.Property("UpdatedAt") - .HasColumnType("TEXT"); - - b.HasKey("Id"); - - b.ToTable("AiConversations"); - }); - - modelBuilder.Entity("xAiModels.Models.Entities.XAiMcpServer", b => - { - b.Property("Id") - .ValueGeneratedOnAdd() - .HasColumnType("TEXT"); - - b.Property("CreatedOn") - .HasColumnType("TEXT"); - - b.Property("Deleted") - .HasColumnType("INTEGER"); - - b.Property("Description") - .HasColumnType("TEXT") - .HasMaxLength(1000); - - b.Property("Enabled") - .HasColumnType("INTEGER"); - - b.Property("Endpoint") - .HasColumnType("TEXT") - .HasMaxLength(1000); - - b.Property("EnvironmentVariables") - .HasColumnType("TEXT"); - - b.Property("Headers") - .HasColumnType("TEXT"); - - b.Property("Name") - .IsRequired() - .HasColumnType("TEXT") - .HasMaxLength(255); - - b.Property("OwnerId") - .IsRequired() - .HasColumnType("TEXT") - .HasMaxLength(255); - - b.Property("Scope") - .HasColumnType("INTEGER"); - - b.Property("TimeoutSeconds") - .HasColumnType("INTEGER"); - - b.Property("UpdatedAt") - .HasColumnType("TEXT"); - - b.HasKey("Id"); - - b.ToTable("AiMcpServers"); - }); - - modelBuilder.Entity("xAiModels.Models.Entities.XAiMessage", b => - { - b.Property("Id") - .ValueGeneratedOnAdd() - .HasColumnType("TEXT"); - - b.Property("Content") - .IsRequired() - .HasColumnType("TEXT"); - - b.Property("ConversationId") - .HasColumnType("TEXT") - .HasMaxLength(255); - - b.Property("CreatedOn") - .HasColumnType("TEXT"); - - b.Property("Deleted") - .HasColumnType("INTEGER"); - - b.Property("MetaDatas") - .HasColumnType("TEXT"); - - b.Property("OwnerId") - .IsRequired() - .HasColumnType("TEXT") - .HasMaxLength(255); - - b.Property("Role") - .HasColumnType("INTEGER"); - - b.Property("UpdatedAt") - .HasColumnType("TEXT"); - - b.HasKey("Id"); - - b.ToTable("AiMessages"); - }); - - modelBuilder.Entity("xAiModels.Models.Entities.XAiProject", b => - { - b.Property("Id") - .ValueGeneratedOnAdd() - .HasColumnType("TEXT"); - - b.Property("CreatedOn") - .HasColumnType("TEXT"); - - b.Property("Deleted") - .HasColumnType("INTEGER"); - - b.Property("Description") - .HasColumnType("TEXT") - .HasMaxLength(1000); - - b.Property("OwnerId") - .IsRequired() - .HasColumnType("TEXT") - .HasMaxLength(255); - - b.Property("Prompt") - .HasColumnType("TEXT"); - - b.Property("Title") - .IsRequired() - .HasColumnType("TEXT") - .HasMaxLength(255); - - b.Property("UpdatedAt") - .HasColumnType("TEXT"); - - b.HasKey("Id"); - - b.ToTable("AiProjects"); - }); - - modelBuilder.Entity("xAiModels.Models.Entities.XAiVector", b => - { - b.Property("Id") - .ValueGeneratedOnAdd() - .HasColumnType("TEXT"); - - b.Property("Deleted") - .HasColumnType("INTEGER"); - - b.Property("Embedding") - .HasColumnType("TEXT"); - - b.Property("Identifier") - .HasColumnType("TEXT"); - - b.Property("Metadata") - .HasColumnType("TEXT"); - - b.Property("Text") - .HasColumnType("TEXT"); - - b.Property("Type") - .HasColumnType("TEXT") - .HasMaxLength(100); - - b.HasKey("Id"); - - b.HasIndex("Identifier"); - - b.HasIndex("Type"); - - b.ToTable("AiVectors"); - }); - - modelBuilder.Entity("xFileService.Models.Entities.XFile", b => - { - b.Property("Id") - .ValueGeneratedOnAdd() - .HasColumnType("TEXT"); - - b.Property("Deleted") - .HasColumnType("INTEGER"); - - b.Property("FileName") - .HasColumnType("TEXT"); - - b.Property("Name") - .IsRequired() - .HasColumnType("TEXT") - .HasMaxLength(255); - - b.Property("OwnerId") - .IsRequired() - .HasColumnType("TEXT") - .HasMaxLength(255); - - b.Property("Path") - .IsRequired() - .HasColumnType("TEXT"); - - b.Property("References") - .HasColumnType("TEXT"); - - b.Property("Thumb") - .HasColumnType("TEXT"); - - b.Property("ThumbPath") - .HasColumnType("TEXT"); - - b.Property("Type") - .HasColumnType("INTEGER"); - - b.Property("UploadedOn") - .HasColumnType("TEXT"); - - b.HasKey("Id"); - - b.ToTable("Files"); - }); - - modelBuilder.Entity("xStringService.Models.Entities.XString", b => - { - b.Property("Id") - .ValueGeneratedOnAdd() - .HasColumnType("INTEGER"); - - b.Property("Deleted") - .HasColumnType("INTEGER"); - - b.Property("Language") - .IsRequired() - .HasColumnType("TEXT") - .HasMaxLength(10); - - b.Property("ResourceTitle") - .IsRequired() - .HasColumnType("TEXT") - .HasMaxLength(255); - - b.Property("TranslatedValue") - .IsRequired() - .HasColumnType("TEXT"); - - b.HasKey("Id"); - - b.ToTable("Strings"); - }); - - modelBuilder.Entity("xTagService.Models.Entities.XTag", b => - { - b.Property("Id") - .ValueGeneratedOnAdd() - .HasColumnType("INTEGER"); - - b.Property("Deleted") - .HasColumnType("INTEGER"); - - b.Property("References") - .HasColumnType("TEXT"); - - b.Property("Tag") - .IsRequired() - .HasColumnType("TEXT") - .HasMaxLength(255); - - b.HasKey("Id"); - - b.ToTable("Tags"); - }); -#pragma warning restore 612, 618 - } - } -} - -### FILE: C:\Users\saherelm\Documents\Projects\xSaherelmWorkspace\xAiApi\Migrations\XAiApiDbContextModelSnapshot.cs - -// -using System; -using Microsoft.EntityFrameworkCore; -using Microsoft.EntityFrameworkCore.Infrastructure; -using Microsoft.EntityFrameworkCore.Storage.ValueConversion; -using xAiApi.Database; - -namespace xAiApi.Migrations -{ - [DbContext(typeof(XAiApiDbContext))] - partial class XAiApiDbContextModelSnapshot : ModelSnapshot - { - protected override void BuildModel(ModelBuilder modelBuilder) - { -#pragma warning disable 612, 618 - modelBuilder - .HasAnnotation("ProductVersion", "3.1.14"); - - modelBuilder.Entity("xAiModels.Models.Entities.XAiConversation", b => - { - b.Property("Id") - .ValueGeneratedOnAdd() - .HasColumnType("TEXT"); - - b.Property("CreatedOn") - .HasColumnType("TEXT"); - - b.Property("Deleted") - .HasColumnType("INTEGER"); - - b.Property("OwnerId") - .IsRequired() - .HasColumnType("TEXT") - .HasMaxLength(255); - - b.Property("ProjectId") - .HasColumnType("TEXT"); - - b.Property("Title") - .IsRequired() - .HasColumnType("TEXT") - .HasMaxLength(255); - - b.Property("UpdatedAt") - .HasColumnType("TEXT"); - - b.HasKey("Id"); - - b.ToTable("AiConversations"); - }); - - modelBuilder.Entity("xAiModels.Models.Entities.XAiMcpServer", b => - { - b.Property("Id") - .ValueGeneratedOnAdd() - .HasColumnType("TEXT"); - - b.Property("CreatedOn") - .HasColumnType("TEXT"); - - b.Property("Deleted") - .HasColumnType("INTEGER"); - - b.Property("Description") - .HasColumnType("TEXT") - .HasMaxLength(1000); - - b.Property("Enabled") - .HasColumnType("INTEGER"); - - b.Property("Endpoint") - .HasColumnType("TEXT") - .HasMaxLength(1000); - - b.Property("EnvironmentVariables") - .HasColumnType("TEXT"); - - b.Property("Headers") - .HasColumnType("TEXT"); - - b.Property("Name") - .IsRequired() - .HasColumnType("TEXT") - .HasMaxLength(255); - - b.Property("OwnerId") - .IsRequired() - .HasColumnType("TEXT") - .HasMaxLength(255); - - b.Property("Scope") - .HasColumnType("INTEGER"); - - b.Property("TimeoutSeconds") - .HasColumnType("INTEGER"); - - b.Property("UpdatedAt") - .HasColumnType("TEXT"); - - b.HasKey("Id"); - - b.ToTable("AiMcpServers"); - }); - - modelBuilder.Entity("xAiModels.Models.Entities.XAiMessage", b => - { - b.Property("Id") - .ValueGeneratedOnAdd() - .HasColumnType("TEXT"); - - b.Property("Content") - .IsRequired() - .HasColumnType("TEXT"); - - b.Property("ConversationId") - .HasColumnType("TEXT") - .HasMaxLength(255); - - b.Property("CreatedOn") - .HasColumnType("TEXT"); - - b.Property("Deleted") - .HasColumnType("INTEGER"); - - b.Property("MetaDatas") - .HasColumnType("TEXT"); - - b.Property("OwnerId") - .IsRequired() - .HasColumnType("TEXT") - .HasMaxLength(255); - - b.Property("Role") - .HasColumnType("INTEGER"); - - b.Property("UpdatedAt") - .HasColumnType("TEXT"); - - b.HasKey("Id"); - - b.ToTable("AiMessages"); - }); - - modelBuilder.Entity("xAiModels.Models.Entities.XAiProject", b => - { - b.Property("Id") - .ValueGeneratedOnAdd() - .HasColumnType("TEXT"); - - b.Property("CreatedOn") - .HasColumnType("TEXT"); - - b.Property("Deleted") - .HasColumnType("INTEGER"); - - b.Property("Description") - .HasColumnType("TEXT") - .HasMaxLength(1000); - - b.Property("OwnerId") - .IsRequired() - .HasColumnType("TEXT") - .HasMaxLength(255); - - b.Property("Prompt") - .HasColumnType("TEXT"); - - b.Property("Title") - .IsRequired() - .HasColumnType("TEXT") - .HasMaxLength(255); - - b.Property("UpdatedAt") - .HasColumnType("TEXT"); - - b.HasKey("Id"); - - b.ToTable("AiProjects"); - }); - - modelBuilder.Entity("xAiModels.Models.Entities.XAiVector", b => - { - b.Property("Id") - .ValueGeneratedOnAdd() - .HasColumnType("TEXT"); - - b.Property("Deleted") - .HasColumnType("INTEGER"); - - b.Property("Embedding") - .HasColumnType("TEXT"); - - b.Property("Identifier") - .HasColumnType("TEXT"); - - b.Property("Metadata") - .HasColumnType("TEXT"); - - b.Property("Text") - .HasColumnType("TEXT"); - - b.Property("Type") - .HasColumnType("TEXT") - .HasMaxLength(100); - - b.HasKey("Id"); - - b.HasIndex("Identifier"); - - b.HasIndex("Type"); - - b.ToTable("AiVectors"); - }); - - modelBuilder.Entity("xFileService.Models.Entities.XFile", b => - { - b.Property("Id") - .ValueGeneratedOnAdd() - .HasColumnType("TEXT"); - - b.Property("Deleted") - .HasColumnType("INTEGER"); - - b.Property("FileName") - .HasColumnType("TEXT"); - - b.Property("Name") - .IsRequired() - .HasColumnType("TEXT") - .HasMaxLength(255); - - b.Property("OwnerId") - .IsRequired() - .HasColumnType("TEXT") - .HasMaxLength(255); - - b.Property("Path") - .IsRequired() - .HasColumnType("TEXT"); - - b.Property("References") - .HasColumnType("TEXT"); - - b.Property("Thumb") - .HasColumnType("TEXT"); - - b.Property("ThumbPath") - .HasColumnType("TEXT"); - - b.Property("Type") - .HasColumnType("INTEGER"); - - b.Property("UploadedOn") - .HasColumnType("TEXT"); - - b.HasKey("Id"); - - b.ToTable("Files"); - }); - - modelBuilder.Entity("xStringService.Models.Entities.XString", b => - { - b.Property("Id") - .ValueGeneratedOnAdd() - .HasColumnType("INTEGER"); - - b.Property("Deleted") - .HasColumnType("INTEGER"); - - b.Property("Language") - .IsRequired() - .HasColumnType("TEXT") - .HasMaxLength(10); - - b.Property("ResourceTitle") - .IsRequired() - .HasColumnType("TEXT") - .HasMaxLength(255); - - b.Property("TranslatedValue") - .IsRequired() - .HasColumnType("TEXT"); - - b.HasKey("Id"); - - b.ToTable("Strings"); - }); - - modelBuilder.Entity("xTagService.Models.Entities.XTag", b => - { - b.Property("Id") - .ValueGeneratedOnAdd() - .HasColumnType("INTEGER"); - - b.Property("Deleted") - .HasColumnType("INTEGER"); - - b.Property("References") - .HasColumnType("TEXT"); - - b.Property("Tag") - .IsRequired() - .HasColumnType("TEXT") - .HasMaxLength(255); - - b.HasKey("Id"); - - b.ToTable("Tags"); - }); -#pragma warning restore 612, 618 - } - } -} - -### FILE: C:\Users\saherelm\Documents\Projects\xSaherelmWorkspace\xAiApi\Models\XAiDocumentModels.cs - -using System; -using System.Collections.Generic; - -namespace xAiApi.Models -{ - /// - /// Result of Ingesting Documents into an In-Memory Session ... - /// - public class XAiDocumentIngestResult - { - /// - /// Session Identifier which must be used in Ask Requests ... - /// - public Guid SessionId { get; set; } - - /// - /// Count of Successfully Processed Files ... - /// - public int FilesCount { get; set; } - - /// - /// Count of Chunks (Vectors) Added to Session ... - /// - public int ChunksCount { get; set; } - - /// - /// Total Vectors Count in Session after Ingest ... - /// - public int TotalVectorsCount { get; set; } - - /// - /// Files which Skipped (Unsupported / Empty / Failed) ... - /// - public IList SkippedFiles { get; set; } = new List(); - - /// - /// Session Expiration Time (UTC) based on Last Access ... - /// - public DateTime ExpiresAtUtc { get; set; } - } - - /// - /// Request for Asking a Question over Ingested Documents ... - /// - public class XAiDocumentAskRequest - { - /// - /// Session Identifier ... - /// - public Guid SessionId { get; set; } - - /// - /// User Question ... - /// - public string Prompt { get; set; } - - /// - /// Count of Top Chunks used as Context (Optional) ... - /// - public int? TopK { get; set; } - - /// - /// Minimum Similarity Score of Chunks (Optional) ... - /// - public float? MinScore { get; set; } - } - - /// - /// a Source Chunk which used for Generating Answer ... - /// - public class XAiDocumentSource - { - /// - /// Doc and Chunk Identifier (e.g. "file.pdf#3") ... - /// - public string Identifier { get; set; } - - /// - /// Source File Name ... - /// - public string FileName { get; set; } - - /// - /// Chunk Index in Source File ... - /// - public int? ChunkIndex { get; set; } - - /// - /// Similarity Score ... - /// - public float Score { get; set; } - - /// - /// Short Snippet of Chunk Text ... - /// - public string Snippet { get; set; } - - /// - /// Knowledge Scope the Chunk Retrieved from (Null for Session Based Documents) ... - /// - public string Scope { get; set; } - - /// - /// Knowledge Type of the Chunk ... - /// - public string Type { get; set; } - } - - /// - /// Answer of a Chat With Documents Request ... - /// - public class XAiDocumentAnswer - { - /// - /// Session Identifier ... - /// - public Guid SessionId { get; set; } - - /// - /// Generated Answer ... - /// - public string Answer { get; set; } - - /// - /// True when no Relevant Chunk Found in Session ... - /// - public bool NoContextFound { get; set; } - - /// - /// Sources used for Generating Answer ... - /// - public IList Sources { get; set; } = new List(); - } - - /// - /// Streaming Chunk of a Chat With Documents Answer ... - /// - public class XAiDocumentAnswerChunk - { - /// - /// Text Delta ... - /// - public string Text { get; set; } - - /// - /// True for Last Chunk ... - /// - public bool IsFinal { get; set; } - - /// - /// True when no Relevant Chunk Found in Session ... - /// - public bool NoContextFound { get; set; } - - /// - /// Sources (Only Filled in First Chunk) ... - /// - public IList Sources { get; set; } - } - - /// - /// Public Info of a Document Session (without Embeddings) ... - /// - public class XAiDocumentSessionInfo - { - public Guid Id { get; set; } - public TimeSpan Ttl { get; set; } - public int VectorsCount { get; set; } - public DateTime CreatedAtUtc { get; set; } - public DateTime LastAccessAtUtc { get; set; } - public DateTime ExpiresAtUtc { get; set; } - public IList Files { get; set; } = new List(); - } - - /// - /// Document RAG Configuration ... - /// - public class XAiDocumentRAGDescriptor - { - public int MaxTopK { get; set; } = 20; - public int DefaultTopK { get; set; } = 5; - public int DefaultTtlMinutes { get; set; } = 30; - public int EmbeddingBatchSize { get; set; } = 32; - public int SourceSnippetLength { get; set; } = 200; - public float DefaultMinScore { get; set; } = 0.35f; - public string MetadataFileName { get; set; } = "fileName"; - public string MetadataMimeType { get; set; } = "mimeType"; - public string PromptName { get; set; } = "ChatWithDocuments"; - public string MetadataChunkIndex { get; set; } = "chunkIndex"; - - // - // Knowledge (Persistent RAG) Limits ... - /// - /// Max Files Accepted in a Single Ingest Request (0 = Unlimited) ... - /// - public int MaxFilesPerIngest { get; set; } = 20; - - /// - /// Max Size of a Single File in Bytes (0 = Unlimited) ... - /// - public long MaxFileSizeBytes { get; set; } = 25 * 1024 * 1024; - - /// - /// Max Distinct Documents Allowed in a Non-Global Scope (0 = Unlimited) ... - /// - public int MaxDocumentsPerScope { get; set; } = 50; - } -} - -### FILE: C:\Users\saherelm\Documents\Projects\xSaherelmWorkspace\xAiApi\Models\XAiDocumentSession.cs - -using System; -using xAiModels.Models.Dtos; -using System.Collections.Generic; - -namespace xAiApi.Models -{ - public class XAiDocumentSession - { - public Guid Id { get; set; } - public TimeSpan Ttl { get; set; } - public string OwnerId { get; set; } - public DateTime CreatedAtUtc { get; set; } - public DateTime LastAccessAtUtc { get; set; } - internal object SyncRoot { get; } = new object(); - public IList Vectors { get; set; } = new List(); - public bool IsExpired(DateTime utcNow) { return utcNow - LastAccessAtUtc >= Ttl; } - } -} - -### FILE: C:\Users\saherelm\Documents\Projects\xSaherelmWorkspace\xAiApi\Models\XAiKnowledgeModels.cs - -using System; -using xAiModels.Constants; -using System.Collections.Generic; - -namespace xAiApi.Models -{ - /// - /// Describes Target Knowledge Base Scope of an Operation ... - /// - public class XAiKnowledgeScopeDescriptor - { - /// - /// Scope Kind ... - /// - public XAiKnowledgeScope Scope { get; set; } = XAiKnowledgeScope.User; - - /// - /// Scope Identifier (ProjectId / ConversationId) - Null for Global and User ... - /// - public Guid? ScopeId { get; set; } - - /// - /// Optional Knowledge Type / Domain Filter ... - /// - public string Type { get; set; } - - /// - /// Create User Scope Knowledge Descriptor ... - /// - /// - /// - public static XAiKnowledgeScopeDescriptor User( - string type = null - ) => new() - { - // - Type = type ?? XAiModelsConstants.XAiDefaultKnowledgeType, - ScopeId = null, - Scope = XAiKnowledgeScope.User, - }; - - /// - /// Create Global Scope Knowledge Descriptor ... - /// - /// - /// - public static XAiKnowledgeScopeDescriptor Global( - string type = null - ) => new() - { - Type = type ?? XAiModelsConstants.XAiDefaultKnowledgeType, - ScopeId = null, - Scope = XAiKnowledgeScope.Global, - }; - - /// - /// Create Project Scope Knowledge Descriptor ... - /// - /// - /// - /// - public static XAiKnowledgeScopeDescriptor Project( - Guid projectId, - string type = null - ) => new() - { - Type = type ?? XAiModelsConstants.XAiDefaultKnowledgeType, - ScopeId = projectId, - Scope = XAiKnowledgeScope.Project, - }; - - /// - /// Create Conversational Scope Knowledge Descriptor ... - /// - /// - /// - /// - public static XAiKnowledgeScopeDescriptor Conversation( - Guid conversationId, - string type = null - ) => new() - { - Type = type ?? XAiModelsConstants.XAiDefaultKnowledgeType, - ScopeId = conversationId, - Scope = XAiKnowledgeScope.Conversation, - }; - } - - /// - /// Result of Ingesting Files into Persistent Knowledge Base (XAiVector Table) ... - /// - public class XAiKnowledgeIngestResult - { - /// - /// Target Scope ... - /// - public XAiKnowledgeScope Scope { get; set; } - - /// - /// Target Scope Identifier (Null for Global) ... - /// - public Guid? ScopeId { get; set; } - - /// - /// Knowledge Type of Ingested Vectors ... - /// - public string Type { get; set; } - - /// - /// Count of Successfully Ingested Files ... - /// - public int FilesCount { get; set; } - - /// - /// Count of Stored Chunks (Vectors) in this Request ... - /// - public int ChunksCount { get; set; } - - /// - /// Count of Removed Stale Vectors (Re-Ingest) ... - /// - public int ReplacedCount { get; set; } - - /// - /// Skipped Files (Empty, Unsupported or Extraction Failed) ... - /// - public IList SkippedFiles { get; set; } = new List(); - - /// - /// Ingested Documents Info ... - /// - public IList Documents { get; set; } = new List(); - } - - /// - /// Ask Request over Persistent Knowledge Base ... - /// Retrieval is Tiered: Conversation -> Project -> User -> Global (Each Tier Fills Remaining TopK) ... - /// - public class XAiKnowledgeAskRequest - { - /// - /// Question ... - /// - public string Prompt { get; set; } - - /// - /// Optional: Conversation Scope (Caller must be Conversation Owner) ... - /// When Provided, Conversation's Project is used for Second Tier Automatically ... - /// - public Guid? ConversationId { get; set; } - - /// - /// Optional: Project Scope (Caller must be Project Owner) ... - /// - public Guid? ProjectId { get; set; } - - /// - /// Include Personal (User) Knowledge Tier (default true) ... - /// - public bool IncludeUser { get; set; } = true; - - /// - /// Include Global Knowledge Tier (default true) ... - /// - public bool IncludeGlobal { get; set; } = true; - - /// - /// Optional: Restrict Retrieval to a Knowledge Type / Domain ... - /// - public string Type { get; set; } - - /// - /// Optional: Restrict Retrieval to a Specific File Name ... - /// - public string FileName { get; set; } - - /// - /// Optional: Max Retrieved Chunks ... - /// - public int? TopK { get; set; } - - /// - /// Optional: Minimum Cosine Similarity Score ... - /// - public float? MinScore { get; set; } - } - - /// - /// Ingested Document Info ... - /// - public class XAiKnowledgeDocumentInfo - { - /// - /// Scope ... - /// - public XAiKnowledgeScope Scope { get; set; } - - /// - /// Scope Identifier (Null for Global) ... - /// - public Guid? ScopeId { get; set; } - - /// - /// Knowledge Type ... - /// - public string Type { get; set; } - - /// - /// File Name ... - /// - public string FileName { get; set; } - - /// - /// Mime Type ... - /// - public string MimeType { get; set; } - - /// - /// Ingesting User Identifier ... - /// - public string OwnerId { get; set; } - - /// - /// Count of Stored Chunks ... - /// - public int ChunksCount { get; set; } - - /// - /// Ingestion Time (UTC) ... - /// - public DateTime? IngestedAtUtc { get; set; } - } - - /// - /// Public Vector Info (Export) ... - /// - public class XAiKnowledgeVectorInfo - { - public Guid Id { get; set; } - public string Text { get; set; } - public string Type { get; set; } - public Guid? ScopeId { get; set; } - public string FileName { get; set; } - public int? ChunkIndex { get; set; } - public string Identifier { get; set; } - public XAiKnowledgeScope Scope { get; set; } - public Dictionary Metadata { get; set; } - - /// - /// Embedding (Only Filled when Requested) ... - /// - public float[] Embedding { get; set; } - } -} - - -### FILE: C:\Users\saherelm\Documents\Projects\xSaherelmWorkspace\xAiApi\Models\XAiMcpServerDescriptor.cs - -namespace xAiApi.Models -{ - /// - /// Describe an Mcp Server for Seeding ... - /// - public class XAiMcpServerDescriptor - { - public string Name { get; set; } - public string OwnerId { get; set; } - public string Headers { get; set; } - public string Endpoint { get; set; } - public string Description { get; set; } - public bool Enabled { get; set; } = true; - public int TimeoutSeconds { get; set; } = 30; - public string EnvironmentVariables { get; set; } - } -} - -### FILE: C:\Users\saherelm\Documents\Projects\xSaherelmWorkspace\xAiApi\Models\XAiModelProxyConfiguration.cs - -namespace xAiApi.Models -{ - public class XAiModelProxyConfiguration - { - /// - /// Enable Proxy or not ... - /// - /// - public bool Enabled { get; set; } = false; - - /// - /// Proxy Prefix ... - /// - /// - public string RoutePrefix { get; set; } = "ai-model"; - } -} - -### FILE: C:\Users\saherelm\Documents\Projects\xSaherelmWorkspace\xAiApi\Models\XAiOCRDescriptor.cs - -using Tesseract; - -namespace xAiApi.Models -{ - public class XAiOCRDescriptor - { - /// - /// Provides Trained Data Path ... - /// - public string DataPath { get; set; } - - /// - /// The Engine for Doing OCR ... - /// - public EngineMode EngineMode { get; set; } - - /// - /// Enable OCR Fallback using Model ... - /// - public bool EnableOcrFallback { get; set; } - - /// - /// Default OCR Language ... - /// - public string DefaultLanguage { get; set; } - } -} - -### FILE: C:\Users\saherelm\Documents\Projects\xSaherelmWorkspace\xAiApi\Models\XAiTransciptDescriptor.cs - -namespace xAiApi.Models -{ - public class XAiTransciptDescriptor - { - public string Language { get; set; } - public string ModelsPath { get; set; } - } -} - -### FILE: C:\Users\saherelm\Documents\Projects\xSaherelmWorkspace\xAiApi\Models\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; -using System.IO; - -namespace xAiApi.Providers -{ - /// - /// Base Ai Service ... - /// - public abstract class XAIServiceBase : IXAiServiceBase - { - /// - /// Chat Options ... - /// - public ChatOptions Options { get; } - - /// - /// Descriptor of Models which used in Service ... - /// - public XAiModelDescriptor Descriptor { get; } - - private readonly IXAiRAGService ragProvider; - private readonly IXAiDataProvider dataProvider; - private readonly ILogger logger; - private readonly XAiApiConfiguration configuration; - private readonly XValidationProvider validationProvider; - private readonly IXAiMcpServerProvider mcpServerProvider; - private readonly IXFileContentExtractor fileContentExtractor; - - // - private readonly bool useProvidedMcpServers; - - protected XAIServiceBase( - IXAiRAGService ragProvider, - IXAiDataProvider dataProvider, - ILogger logger, - XAiApiConfiguration configuration, - XValidationProvider validationProvider, - IXAiMcpServerProvider mcpServerProvider, - IXFileContentExtractor fileContentExtractor, - string model = null, - bool useProvidedMcpServers = true - ) - { - // - this.logger = logger; - this.ragProvider = ragProvider; - this.dataProvider = dataProvider; - this.configuration = configuration; - this.mcpServerProvider = mcpServerProvider; - this.validationProvider = validationProvider; - this.fileContentExtractor = fileContentExtractor; - this.useProvidedMcpServers = useProvidedMcpServers; - - // - // Prepare Embedding Model Descriptor ... - Descriptor = configuration.GetModel(model); - if (!Descriptor.IsValid()) - { - XException.InvalidConfiguration.Throw(); - } - - // - // Prepare Chat Options based On Tools ... - Options = new ChatOptions(); - } - - // - #region Actions ... - /// - /// Base Method for Communicate with LLM ... - /// - /// - /// - /// - /// - public virtual async Task AskTextAsync( - string prompt, - XUserClaimsInfoDto userInfo = null, - CancellationToken cancellationToken = default - ) - { - // - // Check Prompt Exists ... - if (prompt.IsNullOrEmpty()) - { - XException.InvalidArgs.Throw(); - } - - // - using var client = Descriptor.GetClient(); - var history = GetHistory(prompt); - - // - // Handle Provided MCP Servers ... - if (useProvidedMcpServers) - { - // - var availableTools = await mcpServerProvider - .GetAvailableToolsAsync( - userInfo: userInfo, - cancellationToken: cancellationToken - ); - - // - Options.Tools = [.. availableTools.Cast()]; - } - - // - var response = await client.GetResponseAsync( - options: Options, - messages: history, - cancellationToken: cancellationToken - ); - - // - // Validate Response ... - if (!response.IsValid()) - { - // - // Dispose Client ... - client.Dispose(); - XException.ActionFailed.Throw(); - } - - // - // Retrieve Response Text ... - var result = response.Text; - - // - return result; - } - - /// - /// Base Method for Communicate with LLM ... - /// - /// - /// - /// - /// - public virtual async IAsyncEnumerable AskTextAsEnumerable( - string prompt, - XUserClaimsInfoDto userInfo = null, - [EnumeratorCancellation] - CancellationToken cancellationToken = default - ) - { - // - // Check Prompt Exists ... - if (prompt.IsNullOrEmpty()) - { - XException.InvalidArgs.Throw(); - } - - // - using var client = Descriptor.GetClient(); - var history = GetHistory(prompt); - - // - // Handle Provided MCP Servers ... - if (useProvidedMcpServers) - { - // - var availableTools = await mcpServerProvider - .GetAvailableToolsAsync( - userInfo: userInfo, - cancellationToken: cancellationToken - ); - - // - Options.Tools = [.. availableTools.Cast()]; - } - - // - var enumerable = client.GetStreamingResponseAsync( - options: Options, - messages: history - ); - - // - await foreach (var res in enumerable) - { - // - // Cancellation Token ... - if (cancellationToken.IsCancellationRequested) - { - yield break; - } - - // - yield return res.Text; - } - } - - /// - /// Ask a Question By Providing Vector Search Result ... - /// - /// - /// - /// - /// - /// - public virtual async Task AskTextByContextAsync( - string prompt, - IList context = null, - XUserClaimsInfoDto userInfo = null, - CancellationToken cancellationToken = default - ) - { - // - // Validate Args ... - validationProvider - .GroupValidationBuilder() - .AddNotEmpty(prompt) - .AddNotNull(userInfo) - .AddNotEmpty(userInfo.UserId) - .ValidateGroup(); - - // - using var client = Descriptor.GetClient(); - var history = GetHistory(prompt, context); - - // - // Handle Provided MCP Servers ... - if (useProvidedMcpServers) - { - // - var availableTools = await mcpServerProvider - .GetAvailableToolsAsync( - userInfo: userInfo, - cancellationToken: cancellationToken - ); - - // - Options.Tools = [.. availableTools.Cast()]; - } - - // - var response = await client.GetResponseAsync( - options: Options, - messages: history, - cancellationToken: cancellationToken - ); - - // - // Validate Response ... - if (!response.IsValid()) - { - client.Dispose(); - XException.ActionFailed.Throw(); - } - - // - var result = response.Text; - - // - return result; - } - - /// - /// Ask a Question By By Providing Vector Search Result and Stream Response ... - /// - /// - /// - /// - /// - /// - public virtual async IAsyncEnumerable AskTextByContextAsEnumerable( - string prompt, - IList context = null, - XUserClaimsInfoDto userInfo = null, - [EnumeratorCancellation] - CancellationToken cancellationToken = default - ) - { - // - // Validate Args ... - validationProvider - .GroupValidationBuilder() - .AddNotEmpty(prompt) - .AddNotNull(userInfo) - .AddNotEmpty(userInfo.UserId) - .ValidateGroup(); - - // - using var client = Descriptor.GetClient(); - var history = GetHistory(prompt, context); - - // - // Handle Provided MCP Servers ... - if (useProvidedMcpServers) - { - // - var availableTools = await mcpServerProvider - .GetAvailableToolsAsync( - userInfo: userInfo, - cancellationToken: cancellationToken - ); - - // - Options.Tools = [.. availableTools.Cast()]; - } - - // - var enumerable = client.GetStreamingResponseAsync( - options: Options, - messages: history, - cancellationToken: cancellationToken - ); - - // - await foreach (var res in enumerable) - { - // - if (cancellationToken.IsCancellationRequested) - { - yield break; - } - - // - yield return res.Text; - } - } - - /// - /// Ask a Question By Rag Retrive From Knowledge ... - /// - /// - /// - /// - /// - /// - /// - /// - public virtual async Task AskTextFromKnowledgeAsync( - string prompt, - string type = null, - int? topK = null, - float? minScore = null, - XUserClaimsInfoDto userInfo = null, - CancellationToken cancellationToken = default - ) - { - // - // Validation ... - validationProvider - .GroupValidationBuilder() - .AddNotEmpty(prompt) - .AddNotNull(userInfo) - .AddNotEmpty(userInfo.UserId) - .ValidateGroup(); - - // - // Prepare Requirements ... - var prep = await PrepareChatRequirementsAsync( - topK: topK, - type: type, - files: null, - prompt: prompt, - projectId: null, - minScore: minScore, - userInfo: userInfo, - connectionId: null, - conversationId: null, - persistPrompt: false, - 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 - } -} diff --git a/Documents/GeneratedContext/xDashboard-xAiApi-20261107_225117.txt b/Documents/GeneratedContext/xDashboard-xAiApi-20261107_225117.txt new file mode 100644 index 0000000..1320ddd --- /dev/null +++ b/Documents/GeneratedContext/xDashboard-xAiApi-20261107_225117.txt @@ -0,0 +1,32419 @@ + +### FILE: C:\Users\SaherElm\Documents\Projects\xSaherelmWorkspace\xAiApi\Program.cs + +using System.Text; +using Microsoft.AspNetCore.Hosting; +using Microsoft.Extensions.Hosting; + +namespace xAiApi +{ + public class Program + { + public static void Main(string[] args) + { + // + Encoding.RegisterProvider(CodePagesEncodingProvider.Instance); + + // + CreateHostBuilder(args).Build().Run(); + } + + public static IHostBuilder CreateHostBuilder(string[] args) + { + // + var result = Host.CreateDefaultBuilder(args) + .ConfigureWebHostDefaults(webBuilder => + { + webBuilder.UseStartup(); + }); + + // + return result; + } + } +} + +### FILE: C:\Users\SaherElm\Documents\Projects\xSaherelmWorkspace\xAiApi\Startup.cs + +using System; +using System.IO; +using xAiApi.DI; +using System.Linq; +using xAiModels.DI; +using xTagService.DI; +using System.Net.Http; +using xAiApi.Database; +using xHttpService.DI; +using xPushService.DI; +using xFileService.DI; +using xDataService.DI; +using Newtonsoft.Json; +using System.Reflection; +using xAiApi.Extensions; +using xStringService.DI; +using xStorageService.DI; +using xIdentityService.DI; +using xDataService.Models; +using xCommons.Extensions; +using xAiModels.Constants; +using xPushService.Helpers; +using xCommons.Configurations; +using System.Collections.Generic; +using Microsoft.AspNetCore.Builder; +using Microsoft.AspNetCore.Hosting; +using Microsoft.Extensions.Hosting; +using Newtonsoft.Json.Serialization; +using Microsoft.Extensions.Configuration; +using Microsoft.Extensions.DependencyInjection; +using IdentityModel.AspNetCore.OAuth2Introspection; +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\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 = "Gemma"; + public const string XAiEmbeddingModelName = "Embed"; + public const string XAiDefaultVisionModelName = "Qwen"; + public const string XAiDefaultThinkingModelName = "Qwen"; + public const string XAiEmbeddingPromptName = "Embedding"; + } +} + +### FILE: C:\Users\SaherElm\Documents\Projects\xSaherelmWorkspace\xAiApi\Controllers\AccountController.cs + +using xCommons.Providers; +using xCommons.Configurations; +using xIdentityHelper.Controllers; +using xIdentityService.Interfaces; +using Microsoft.Extensions.Logging; + +namespace xAiApi.Controllers +{ + public partial class AccountController : XAccountControllerBase + { + // + #region Constructor ... + public AccountController( + ILogger logger, + XAppConfiguration appConfiguration, + IXIdentityProvider identityProvider, + XValidationProvider validationProvider + ) : base( + logger, + appConfiguration, + identityProvider, + validationProvider + ) + { } + #endregion + } +} + +### FILE: C:\Users\SaherElm\Documents\Projects\xSaherelmWorkspace\xAiApi\Controllers\ChatWithDocumentsController.cs + +using System; +using System.Linq; +using xAiApi.Models; +using System.Threading; +using xAiApi.Interfaces; +using xAiApi.Extensions; +using xCommons.Providers; +using xCommons.Extensions; +using xAiApi.Configurations; +using xExceptions.Constants; +using xAiModels.Models.Dtos; +using System.Threading.Tasks; +using xHttpService.Extensions; +using xCommons.Configurations; +using Microsoft.AspNetCore.Mvc; +using Microsoft.AspNetCore.Http; +using System.Collections.Generic; +using xIdentityService.Interfaces; +using xIdentityService.Controllers; +using xAiApi.Interfaces.Extractors; +using Microsoft.Extensions.Logging; +using Microsoft.AspNetCore.Authorization; + +namespace xAiApi.Controllers +{ + /// + /// Chat With Documents (In-Memory RAG) Controller ... + /// Flow: Ingest Files -> SessionId -> Ask / AskStream -> Delete Session + /// + [Authorize] + public class ChatWithDocumentsController : XBaseIdentityApiV1Controller + { + /// + /// Default AI Service ... + /// + private readonly IXAiService aiService; + + /// + /// Text Chunker Service ... + /// + private readonly IXTextChunker textChunker; + + /// + /// In Memory Vector Store ... + /// + private readonly IXInMemoryVectorStore vectorStore; + + /// + /// XAiApi Configuration ... + /// + private readonly XAiApiConfiguration apiConfiguration; + + /// + /// Embedding Service ... + /// + private readonly IXAiEmbeddingService embeddingService; + + /// + /// File Context Extractor Service ... + /// + private readonly IXFileContentExtractor fileContentExtractor; + + public ChatWithDocumentsController( + IXAiService aiService, + IXTextChunker textChunker, + IXInMemoryVectorStore vectorStore, + XAppConfiguration appConfiguration, + IXIdentityProvider identityProvider, + XAiApiConfiguration apiConfiguration, + IXAiEmbeddingService embeddingService, + XValidationProvider validationProvider, + ILogger logger, + IXFileContentExtractor fileContentExtractor + ) : base(logger, appConfiguration, identityProvider, validationProvider) + { + // + this.aiService = aiService; + this.textChunker = textChunker; + this.vectorStore = vectorStore; + this.apiConfiguration = apiConfiguration; + this.embeddingService = embeddingService; + this.fileContentExtractor = fileContentExtractor; + } + + // + #region Ingest ... + /// + /// Ingest Files into a (new or existing) In-Memory Session: + /// Extract -> Chunk -> Embed -> Store ... + /// + /// + /// Optional: Add to an Existing Session + /// Optional: Session TTL in Minutes (only for new Session) + /// + /// + [HttpPost("Ingest")] + [Consumes("multipart/form-data")] + public async Task> Ingest( + [FromForm] IFormFileCollection files, + [FromForm] Guid? sessionId = null, + [FromForm] int? ttlMinutes = null, + CancellationToken cancellationToken = default + ) + { + // + try + { + // + // Validate ... + if (!files.HasChild()) + { + XException.InvalidArgs.Throw(); + } + + // + var userInfo = await GetUserInfo(); + var ownerId = userInfo.UserId; + + // + // Resolve Target Session ... + Guid targetSessionId; + if (sessionId.HasValue && sessionId.Value != Guid.Empty) + { + // + if (!vectorStore.TryGet(sessionId.Value, out _, ownerId)) + { + XException.NotFound.Throw(); + } + targetSessionId = sessionId.Value; + } + else + { + // + var ttl = TimeSpan.FromMinutes( + ttlMinutes.HasValue && ttlMinutes.Value > 0 + ? ttlMinutes.Value + : apiConfiguration.RAGDescriptor.DefaultTtlMinutes + ); + targetSessionId = vectorStore.CreateSession(ownerId, ttl); + } + + // + var result = new XAiDocumentIngestResult + { + SessionId = targetSessionId + }; + + // + // Extract -> Chunk -> Embed ... + var vectors = new List(); + foreach (var file in files) + { + // + cancellationToken.ThrowIfCancellationRequested(); + + // + if (file.IsNull() || file.Length == 0) + { + result.SkippedFiles.Add(file?.FileName ?? "(null)"); + continue; + } + + // + var mimeType = file.ContentType?.ToLowerInvariant() ?? string.Empty; + if (!fileContentExtractor.CanExtract(mimeType)) + { + result.SkippedFiles.Add(file.FileName); + continue; + } + + // + var text = await ExtractText(file, mimeType, cancellationToken); + if (string.IsNullOrWhiteSpace(text)) + { + result.SkippedFiles.Add(file.FileName); + continue; + } + + // + var chunks = textChunker.Chunk(text, file.FileName); + if (!chunks.HasChild()) + { + result.SkippedFiles.Add(file.FileName); + continue; + } + + // + // Embed in Batches ... + var fileVectors = await EmbedChunks( + chunks: chunks, + fileName: file.FileName, + mimeType: mimeType, + cancellationToken: cancellationToken + ); + + // + vectors.AddRange(fileVectors); + result.FilesCount++; + } + + // + // Store ... + if (vectors.HasChild() && + !vectorStore.Add(targetSessionId, vectors, ownerId)) + { + XException.ActionFailed.Throw(); + } + + // + // Fill Result ... + result.ChunksCount = vectors.Count; + if (vectorStore.TryGet(targetSessionId, out var session, ownerId)) + { + lock (session.SyncRoot) + { + result.TotalVectorsCount = session.Vectors.Count; + } + result.ExpiresAtUtc = session.LastAccessAtUtc.Add(session.Ttl); + } + + // + return Ok(result); + } + catch (Exception ex) + { + var result = GetExceptionActionResult(ex); + return result; + } + } + #endregion + + // + #region Ask ... + /// + /// Ask a Question over Ingested Documents ... + /// + /// + /// + /// + [HttpPost("Ask")] + public async Task> Ask( + [FromBody] XAiDocumentAskRequest request, + CancellationToken cancellationToken = default + ) + { + // + try + { + // + // Validate ... + if (!request.IsValid()) + { + XException.InvalidArgs.Throw(); + } + + // + var userInfo = await GetUserInfo(); + var ownerId = userInfo.UserId; + + // + // Check Session ... + if (!vectorStore.TryGet(request.SessionId, out _, ownerId)) + { + XException.NotFound.Throw(); + } + + // + // Retrieve ... + var context = await Retrieve(request, ownerId, cancellationToken); + + // + var result = new XAiDocumentAnswer + { + SessionId = request.SessionId, + Sources = ToSources(context) + }; + + // + if (!context.HasChild()) + { + result.NoContextFound = true; + return Ok(result); + } + + // + // Generate ... + result.Answer = await aiService.AskTextByContextAsync( + context: context, + userInfo: userInfo, + prompt: request.Prompt, + cancellationToken: cancellationToken + ); + + // + return Ok(result); + } + catch (Exception ex) + { + var result = GetExceptionActionResult(ex); + return result; + } + } + + /// + /// Ask a Question over Ingested Documents and Stream Response (SSE) ... + /// First Event Carries Sources, Next Events Carry Text Deltas, Last Event has IsFinal = true ... + /// + /// + /// + /// + [HttpPost("AskStream")] + public async Task AskStream( + [FromBody] XAiDocumentAskRequest request, + CancellationToken cancellationToken = default + ) + { + // + // Validate (before Stream Starts -> Proper Http Error) ... + if (!request.IsValid()) + { + // + Response.StatusCode = StatusCodes.Status400BadRequest; + Response.ContentType = "application/json; charset=utf-8"; + await Response.WriteAsync(XException.InvalidArgs.ToXError().ToJSON()); + return; + } + + // + try + { + // + var userInfo = await GetUserInfo(); + var ownerId = userInfo.UserId; + + // + // Check Session ... + if (!vectorStore.TryGet(request.SessionId, out _, ownerId)) + { + XException.NotFound.Throw(); + } + + // + // Retrieve ... + var context = await Retrieve(request, ownerId, cancellationToken); + + // + // Configure SSE Response ... + Response.PrepareSseResponse(); + + // + // First Event: Sources ... + var hasContext = context.HasChild(); + await WriteChunk(new XAiDocumentAnswerChunk + { + Text = string.Empty, + IsFinal = !hasContext, + NoContextFound = !hasContext, + Sources = ToSources(context) + }, cancellationToken); + + // + if (!hasContext) + { + await Response.WriteSseDoneAsync(cancellationToken); + return; + } + + // + // Stream Deltas ... + var enumerable = aiService.AskTextByContextAsEnumerable( + context: context, + userInfo: userInfo, + prompt: request.Prompt, + cancellationToken: cancellationToken + ); + await foreach (var delta in enumerable) + { + // + if (delta.IsNullOrEmpty()) + { + continue; + } + + // + await WriteChunk(new XAiDocumentAnswerChunk + { + Text = delta + }, cancellationToken); + } + + // + // Final Event ... + await WriteChunk(new XAiDocumentAnswerChunk + { + Text = string.Empty, + IsFinal = true + }, cancellationToken); + await Response.WriteSseDoneAsync(cancellationToken); + } + catch (Exception ex) when (ex.IsClientCancellation(cancellationToken)) + { + // Client Disconnected ... + } + catch (Exception ex) + { + // + Logger.LogError(ex, "ChatWithDocuments: AskStream Failed"); + if (!Response.HasStarted) + { + // + var result = GetExceptionActionResult(ex); + await result.ExecuteResultAsync(ControllerContext); + return; + } + + // + await Response.WriteSseErrorAsync(ex.Message); + } + } + #endregion + + // + #region Session ... + /// + /// Retrieve Session Info (without Embeddings) ... + /// + /// + /// + [HttpGet("Session/{id:guid}")] + public async Task> GetSession(Guid id) + { + // + try + { + // + var userInfo = await GetUserInfo(); + if (!vectorStore.TryGet(id, out var session, userInfo.UserId)) + { + XException.NotFound.Throw(); + } + + // + IList vectors; + lock (session.SyncRoot) + { + vectors = session.Vectors.ToList(); + } + + // + var result = new XAiDocumentSessionInfo + { + Id = session.Id, + Ttl = session.Ttl, + VectorsCount = vectors.Count, + CreatedAtUtc = session.CreatedAtUtc, + LastAccessAtUtc = session.LastAccessAtUtc, + ExpiresAtUtc = session.LastAccessAtUtc.Add(session.Ttl), + Files = [.. vectors + .Select(v => v.Metadata.GetMetadata(apiConfiguration.RAGDescriptor.MetadataFileName)) + .Where(f => !f.IsNullOrEmpty()) + .Distinct()] + }; + + // + return Ok(result); + } + catch (Exception ex) + { + var result = GetExceptionActionResult(ex); + return result; + } + } + + /// + /// Remove a Session and Free Memory ... + /// + /// + /// + [HttpDelete("Session/{id:guid}")] + public async Task> DeleteSession(Guid id) + { + // + try + { + // + var userInfo = await GetUserInfo(); + if (!vectorStore.Remove(id, userInfo.UserId)) + { + XException.NotFound.Throw(); + } + + // + return Ok(true); + } + catch (Exception ex) + { + var result = GetExceptionActionResult(ex); + return result; + } + } + #endregion + + // + #region Private ... + /// + /// Extract Plain Text of a File (Text or Audio Transcript) ... + /// + private async Task ExtractText( + IFormFile file, + string mimeType, + CancellationToken cancellationToken + ) + { + // + try + { + // + using var stream = file.OpenReadStream(); + var extraction = await fileContentExtractor.ExtractRichAsync( + fileStream: stream, + mimeType: mimeType, + fileName: file.FileName, + cancellationToken: cancellationToken + ); + + // + var result = extraction?.Text; + if (string.IsNullOrWhiteSpace(result)) + { + result = extraction?.AudioTranscript; + } + + // + return result; + } + catch (OperationCanceledException) + { + throw; + } + catch (Exception ex) + { + Logger.LogWarning(ex, "ChatWithDocuments: Extraction Failed for {FileName}", file.FileName); + return null; + } + } + + /// + /// Embed Chunks in Batches and Build Vectors ... + /// + private async Task> EmbedChunks( + IList chunks, + string fileName, + string mimeType, + CancellationToken cancellationToken + ) + { + // + var result = new List(chunks.Count); + var batchSize = apiConfiguration.RAGDescriptor.EmbeddingBatchSize; + + // + for (var offset = 0; offset < chunks.Count; offset += batchSize) + { + // + cancellationToken.ThrowIfCancellationRequested(); + + // + var batch = chunks.Skip(offset).Take(batchSize).ToList(); + var embeddings = await embeddingService.Embeddings( + batch: batch.Select(c => c.Text).ToArray(), + cancellationToken: cancellationToken + ); + + // + if (embeddings.IsNullOrDefault() || embeddings.Count != batch.Count) + { + XException.ActionFailed.Throw(); + } + + // + for (var i = 0; i < batch.Count; i++) + { + // + var chunk = batch[i]; + result.Add(new XAiVectorDto + { + Id = Guid.NewGuid(), + Text = chunk.Text, + Embedding = embeddings[i], + Identifier = chunk.Identifier, + Metadata = new Dictionary + { + [apiConfiguration.RAGDescriptor.MetadataFileName] = fileName, + [apiConfiguration.RAGDescriptor.MetadataMimeType] = mimeType, + [apiConfiguration.RAGDescriptor.MetadataChunkIndex] = chunk.Index.ToString() + } + }); + } + } + + // + return result; + } + + /// + /// Embed Prompt and Search Session ... + /// + private async Task> Retrieve( + XAiDocumentAskRequest request, + string ownerId, + CancellationToken cancellationToken + ) + { + // + var topK = Math.Clamp( + request.TopK ?? apiConfiguration.RAGDescriptor.DefaultTopK, + 1, + apiConfiguration.RAGDescriptor.MaxTopK + ); + var minScore = request.MinScore ?? apiConfiguration.RAGDescriptor.DefaultMinScore; + + // + var queryEmbedding = await embeddingService.Embedding( + content: request.Prompt, + cancellationToken: cancellationToken + ); + if (queryEmbedding.IsNullOrDefault() || queryEmbedding.Length == 0) + { + XException.ActionFailed.Throw(); + } + + // + var result = vectorStore.Search( + topK: topK, + ownerId: ownerId, + minScore: minScore, + sessionId: request.SessionId, + queryEmbedding: queryEmbedding + ); + + // + return result ?? []; + } + + /// + /// Map Search Results to Public Sources ... + /// + private IList ToSources( + IEnumerable context + ) + { + // + var result = (context ?? []) + .Select(c => + { + // + var chunkIndexText = c.Metadata.GetMetadata(apiConfiguration.RAGDescriptor.MetadataChunkIndex); + var text = c.Text ?? string.Empty; + var snippetLength = Math.Min(text.Length, apiConfiguration.RAGDescriptor.SourceSnippetLength); + + // + return new XAiDocumentSource + { + Score = c.Score, + Identifier = c.Identifier, + Snippet = text.Substring(0, snippetLength), + ChunkIndex = int.TryParse(chunkIndexText, out var idx) ? idx : null, + FileName = c.Metadata.GetMetadata(apiConfiguration.RAGDescriptor.MetadataFileName) + }; + }) + .ToList(); + + // + return result; + } + + /// + /// Write a SSE Event ... + /// + private Task WriteChunk( + XAiDocumentAnswerChunk chunk, + CancellationToken cancellationToken + ) + { + // + return Response.WriteSseEventAsync( + data: chunk, + cancellationToken: cancellationToken + ); + } + #endregion + } +} + +### FILE: C:\Users\SaherElm\Documents\Projects\xSaherelmWorkspace\xAiApi\Controllers\KnowledgeController.cs + +using System; +using xAiApi.Models; +using System.Threading; +using xAiApi.Interfaces; +using xCommons.Providers; +using xAiModels.Constants; +using xCommons.Extensions; +using xExceptions.Constants; +using System.Threading.Tasks; +using xHttpService.Extensions; +using xCommons.Configurations; +using Microsoft.AspNetCore.Mvc; +using Microsoft.AspNetCore.Http; +using System.Collections.Generic; +using xIdentityService.Interfaces; +using xIdentityService.Controllers; +using Microsoft.Extensions.Logging; +using Microsoft.AspNetCore.Authorization; +using xIdentityHelper; + +namespace xAiApi.Controllers +{ + /// + /// Knowledge (Persistent RAG over XAiVector Table) Controller ... + /// Flow: Ingest Files -> Ask / AskStream (Retrieve from DB -> Generate) -> Documents / Delete + /// + [Authorize] + public class KnowledgeController : XBaseIdentityApiV1Controller + { + /// + /// Persistent RAG Service ... + /// + private readonly IXAiRAGService ragService; + + public KnowledgeController( + IXAiRAGService ragService, + XAppConfiguration appConfiguration, + IXIdentityProvider identityProvider, + ILogger logger, + XValidationProvider validationProvider + ) : base(logger, appConfiguration, identityProvider, validationProvider) + { + this.ragService = ragService; + } + + // + #region Ingest ... + /// + /// Ingest Files into a Knowledge Scope: + /// Extract -> Chunk -> Embed -> Store in XAiVector Table ... + /// + /// + /// Target Scope: User (default) / Project / Conversation / Global (Admin) + /// ProjectId or ConversationId (Required for Project / Conversation) + /// Optional Knowledge Type / Domain + /// Replace Previously Stored Vectors of Same File (default true) + /// + /// + [HttpPost("Ingest")] + [Consumes("multipart/form-data")] + [Authorize(Policy = XPolicies.EnabledAdmin)] + public async Task> Ingest( + [FromForm] IFormFileCollection files, + [FromForm] XAiKnowledgeScope? scope = XAiKnowledgeScope.Global, + [FromForm] Guid? scopeId = null, + [FromForm] string knowledgeType = null, + [FromForm] bool replaceExisting = true, + CancellationToken cancellationToken = default + ) + { + // + try + { + // + // Validate ... + if (!files.HasChild()) + { + XException.InvalidArgs.Throw(); + } + + // + var userInfo = await GetUserInfo(); + var connectionId = GetConnectionId(); + + // + var result = await ragService.IngestAsync( + files: files, + userInfo: userInfo, + connectionId: connectionId, + replaceExisting: replaceExisting, + cancellationToken: cancellationToken, + scope: BuildScope(scope, scopeId, knowledgeType) + ); + + // + return Ok(result); + } + catch (Exception ex) + { + // + var result = GetExceptionActionResult(ex); + return result; + } + } + #endregion + + // + #region Documents ... + /// + /// List Ingested Documents of a Knowledge Scope ... + /// + /// User (default) / Project / Conversation / Global + /// ProjectId or ConversationId (Required for Project / Conversation) + /// Optional Knowledge Type Filter + /// + /// + [HttpGet("Documents")] + [Authorize(Policy = XPolicies.EnabledAdmin)] + public async Task>> Documents( + [FromQuery] XAiKnowledgeScope? scope = XAiKnowledgeScope.Global, + [FromQuery] Guid? scopeId = null, + [FromQuery] string knowledgeType = null, + CancellationToken cancellationToken = default + ) + { + // + try + { + // + var userInfo = await GetUserInfo(); + var scopeIdentifier = BuildScope(scope, scopeId, knowledgeType); + + // + var result = await ragService.LoadDocumentsAsync( + userInfo: userInfo, + scope: scopeIdentifier, + cancellationToken: cancellationToken + ); + + // + return Ok(result); + } + catch (Exception ex) + { + // + var result = GetExceptionActionResult(ex); + return result; + } + } + + /// + /// Remove All Vectors of a Document in a Knowledge Scope ... + /// + /// + /// User (default) / Project / Conversation / Global (Admin) + /// ProjectId or ConversationId (Required for Project / Conversation) + /// + /// Count of Removed Vectors + [HttpDelete("Documents")] + [Authorize(Policy = XPolicies.EnabledAdmin)] + public async Task> DeleteDocument( + [FromQuery] string fileName, + [FromQuery] XAiKnowledgeScope? scope = XAiKnowledgeScope.Global, + [FromQuery] Guid? scopeId = null, + CancellationToken cancellationToken = default + ) + { + // + try + { + // + // Validate ... + ValidationProvider.NotEmpty(fileName); + + // + var userInfo = await GetUserInfo(); + + // + var result = await ragService.RemoveDocumentAsync( + fileName: fileName, + userInfo: userInfo, + cancellationToken: cancellationToken, + scope: BuildScope(scope, scopeId, null) + ); + + // + return Ok(result); + } + catch (Exception ex) + { + // + var result = GetExceptionActionResult(ex); + return result; + } + } + #endregion + + // + #region Private ... + /// + /// Build Scope Descriptor from Request Params ... + /// + private XAiKnowledgeScopeDescriptor BuildScope( + XAiKnowledgeScope? scope, + Guid? scopeId, + string knowledgeType + ) + { + // + if (!scope.HasValue) + { + scope = XAiKnowledgeScope.Global; + } + + // + var result = new XAiKnowledgeScopeDescriptor + { + Scope = scope.Value, + ScopeId = scopeId, + Type = knowledgeType, + }; + + // + return result; + } + + /// + /// Write a SSE Event ... + /// + private Task WriteChunk( + XAiDocumentAnswerChunk chunk, + CancellationToken cancellationToken + ) + { + // + return Response.WriteSseEventAsync( + data: chunk, + cancellationToken: cancellationToken + ); + } + #endregion + } +} + + +### FILE: C:\Users\SaherElm\Documents\Projects\xSaherelmWorkspace\xAiApi\Controllers\McpServersController.cs + +using System; +using xModels.Dtos; +using xIdentityHelper; +using System.Threading; +using xAiApi.Interfaces; +using xCommons.Providers; +using xCommons.Extensions; +using xAiModels.Extensions; +using xAiModels.Models.Dtos; +using xExceptions.Constants; +using System.Threading.Tasks; +using xCommons.Configurations; +using Microsoft.AspNetCore.Mvc; +using System.Collections.Generic; +using xIdentityService.Interfaces; +using Microsoft.Extensions.Logging; +using xIdentityService.Controllers; +using Microsoft.AspNetCore.Authorization; + +namespace xAiApi.Controllers +{ + [Authorize] + public class McpServersController : XBaseIdentityApiV1Controller + { + private readonly IXAiMcpServerProvider mcpServerProvider; + + public McpServersController( + XAppConfiguration appConfiguration, + IXIdentityProvider identityProvider, + ILogger logger, + XValidationProvider validationProvider, + IXAiMcpServerProvider mcpServerProvider + ) : base( + logger, + appConfiguration, + identityProvider, + validationProvider + ) + { + this.mcpServerProvider = mcpServerProvider; + } + + // + #region Provider ... + /// + /// Retrieve Specified MCP Server ... + /// + /// + /// + /// + [HttpGet("{id}")] + [Authorize(Policy = XPolicies.EnabledUser)] + public virtual async Task> GetMcpServer( + [FromRoute] Guid id, + CancellationToken cancellationToken = default + ) + { + // + try + { + // + // Validate ... + if (!ModelState.IsValid || id.IsDefaultGuid()) + { + XException.InvalidArgs.Throw(); + } + + // + var userInfo = await GetUserInfo(); + var connectionId = GetConnectionId(); + + // + var result = await mcpServerProvider.GetMcpServer( + id: id, + userInfo: userInfo, + cancellationToken: cancellationToken + ); + + // + return Ok(result.ToDynamicObject()); + } + catch (Exception ex) + { + // + var result = GetExceptionActionResult(ex); + return result; + } + } + + /// + /// Add MCP Server ... + /// + /// + /// + /// + [HttpPost] + [Authorize(Policy = XPolicies.EnabledUser)] + public virtual async Task> AddMcpServer( + [FromBody] XAiMcpServerDto item, + CancellationToken cancellationToken = default + ) + { + // + try + { + // + // Validate ... + if (!ModelState.IsValid || item.IsNullOrDefault()) + { + XException.InvalidArgs.Throw(); + } + + // + var userInfo = await GetUserInfo(); + var connectionId = GetConnectionId(); + + // + var result = await mcpServerProvider.AddMcpServer( + item: item, + userInfo: userInfo, + connectionId: connectionId, + cancellationToken: cancellationToken + ); + + // + return Ok(result.ToDynamicObject()); + } + catch (Exception ex) + { + // + var result = GetExceptionActionResult(ex); + return result; + } + } + + /// + /// Update Specified MCP Server ... + /// + /// + /// + /// + /// + [HttpPut("{id}")] + [Authorize(Policy = XPolicies.EnabledUser)] + public virtual async Task> UpdateMcpServer( + [FromRoute] Guid id, + [FromBody] XAiMcpServerDto item, + CancellationToken cancellationToken = default + ) + { + // + try + { + // + // Validate ... + if (id.IsDefaultGuid() || + !ModelState.IsValid || + !item.IsValidForAddOrUpdate()) + { + XException.InvalidArgs.Throw(); + } + + // + var userInfo = await GetUserInfo(); + var connectionId = GetConnectionId(); + + // + var result = await mcpServerProvider.UpdateMcpServer( + id: id, + item: item, + userInfo: userInfo, + connectionId: connectionId, + cancellationToken: cancellationToken + ); + + // + return Ok(result.ToDynamicObject()); + } + catch (Exception ex) + { + // + var result = GetExceptionActionResult(ex); + return result; + } + } + + /// + /// Remove Specified MCP Server ... + /// + /// + /// + /// + [HttpDelete("{id}")] + [Authorize(Policy = XPolicies.EnabledUser)] + public virtual async Task> RemoveMcpServer( + [FromRoute] Guid id, + CancellationToken cancellationToken = default + ) + { + // + try + { + // + // Validate ... + if (!ModelState.IsValid || id.IsDefaultGuid()) + { + XException.InvalidArgs.Throw(); + } + + // + var userInfo = await GetUserInfo(); + var connectionId = GetConnectionId(); + + // + var result = await mcpServerProvider.RemoveMcpServer( + id: id, + userInfo: userInfo, + connectionId: connectionId, + cancellationToken: cancellationToken + ); + + // + return Ok(result.ToDynamicObject()); + } + catch (Exception ex) + { + // + var result = GetExceptionActionResult(ex); + return result; + } + } + + /// + /// Enable Specified MCP Server ... + /// + /// + /// + /// + [HttpPost("{id}/Enable")] + [Authorize(Policy = XPolicies.EnabledUser)] + public virtual async Task> EnableMcpServer( + [FromRoute] Guid id, + CancellationToken cancellationToken = default + ) + { + // + try + { + // + // Validate ... + if (!ModelState.IsValid || id.IsDefaultGuid()) + { + XException.InvalidArgs.Throw(); + } + + // + var userInfo = await GetUserInfo(); + var connectionId = GetConnectionId(); + + // + var result = await mcpServerProvider.EnableMcpServer( + id: id, + userInfo: userInfo, + connectionId: connectionId, + cancellationToken: cancellationToken + ); + + // + return Ok(result); + } + catch (Exception ex) + { + // + var result = GetExceptionActionResult(ex); + return result; + } + } + + /// + /// Disable Specified MCP Server ... + /// + /// + /// + /// + [HttpPost("{id}/Disable")] + [Authorize(Policy = XPolicies.EnabledUser)] + public virtual async Task> DisableMcpServer( + [FromRoute] Guid id, + CancellationToken cancellationToken = default + ) + { + // + try + { + // + // Validate ... + if (!ModelState.IsValid || id.IsDefaultGuid()) + { + XException.InvalidArgs.Throw(); + } + + // + var userInfo = await GetUserInfo(); + var connectionId = GetConnectionId(); + + // + var result = await mcpServerProvider.DisableMcpServer( + id: id, + userInfo: userInfo, + connectionId: connectionId, + cancellationToken: cancellationToken + ); + + // + return Ok(result); + } + catch (Exception ex) + { + // + var result = GetExceptionActionResult(ex); + return result; + } + } + + /// + /// Toggle Specified MCP Server ... + /// + /// + /// + /// + [HttpPost("{id}/Toggle")] + [Authorize(Policy = XPolicies.EnabledUser)] + public virtual async Task> ToggleMcpServer( + [FromRoute] Guid id, + CancellationToken cancellationToken = default + ) + { + // + try + { + // + // Validate ... + if (!ModelState.IsValid || id.IsDefaultGuid()) + { + XException.InvalidArgs.Throw(); + } + + // + var userInfo = await GetUserInfo(); + var connectionId = GetConnectionId(); + + // + var result = await mcpServerProvider.ToggleMcpServer( + id: id, + userInfo: userInfo, + connectionId: connectionId, + cancellationToken: cancellationToken + ); + + // + return Ok(result); + } + catch (Exception ex) + { + // + var result = GetExceptionActionResult(ex); + return result; + } + } + + /// + /// Get all Registered MCP Servers by handling Ownership ... + /// + /// + /// + [HttpGet] + [Authorize(Policy = XPolicies.EnabledUser)] + public virtual async Task>> GetMcpServers( + [FromQuery] bool forceOwner = true, + CancellationToken cancellationToken = default + ) + { + // + try + { + // + // Validate ... + if (!ModelState.IsValid) + { + XException.InvalidArgs.Throw(); + } + + // + var userInfo = await GetUserInfo(); + var connectionId = GetConnectionId(); + + // + var result = await mcpServerProvider.GetAll( + userInfo: userInfo, + forceOwner: forceOwner, + cancellationToken: cancellationToken + ); + + // + return Ok(result.ToDynamicObject()); + } + catch (Exception ex) + { + // + var result = GetExceptionActionResult(ex); + return result; + } + } + + /// + /// Query Registered MCP Servers by handling Ownership ... + /// + /// + /// + /// + /// + [HttpGet("Query")] + [Authorize(Policy = XPolicies.EnabledUser)] + public virtual async Task>> QueryMcpServers( + [FromQuery] XQuery query, + [FromQuery] bool forceOwner = true, + CancellationToken cancellationToken = default + ) + { + // + try + { + // + // Validate ... + if (!ModelState.IsValid) + { + XException.InvalidArgs.Throw(); + } + await ValidationProvider + .GroupValidationBuilder() + .AddNotNull(query) + .ValidateGroupAsync(); + + // + var userInfo = await GetUserInfo(); + var connectionId = GetConnectionId(); + + // + var result = await mcpServerProvider.Query( + query: query, + userInfo: userInfo, + forceOwner: forceOwner, + cancellationToken: cancellationToken + ); + + // + return Ok(result.ToDynamicObject()); + } + catch (Exception ex) + { + // + var result = GetExceptionActionResult(ex); + return result; + } + } + #endregion + + /// + /// Refresh MCP Servers ... + /// + /// + /// + [HttpPost("Refresh")] + [Authorize(Policy = XPolicies.EnabledAdmin)] + public async Task RefreshMcpServers( + 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; +using System.IO; + +namespace xAiApi.Providers +{ + /// + /// Base Ai Service ... + /// + public abstract class XAIServiceBase : IXAiServiceBase + { + /// + /// Chat Options ... + /// + public ChatOptions Options { get; } + + /// + /// Descriptor of Models which used in Service ... + /// + public XAiModelDescriptor Descriptor { get; } + + private readonly IXAiRAGService ragProvider; + private readonly IXAiDataProvider dataProvider; + private readonly ILogger logger; + private readonly XAiApiConfiguration configuration; + private readonly XValidationProvider validationProvider; + private readonly IXAiMcpServerProvider mcpServerProvider; + private readonly IXFileContentExtractor fileContentExtractor; + + // + private readonly bool useProvidedMcpServers; + + protected XAIServiceBase( + IXAiRAGService ragProvider, + IXAiDataProvider dataProvider, + ILogger logger, + XAiApiConfiguration configuration, + XValidationProvider validationProvider, + IXAiMcpServerProvider mcpServerProvider, + IXFileContentExtractor fileContentExtractor, + string model = null, + bool useProvidedMcpServers = true + ) + { + // + this.logger = logger; + this.ragProvider = ragProvider; + this.dataProvider = dataProvider; + this.configuration = configuration; + this.mcpServerProvider = mcpServerProvider; + this.validationProvider = validationProvider; + this.fileContentExtractor = fileContentExtractor; + this.useProvidedMcpServers = useProvidedMcpServers; + + // + // Prepare Embedding Model Descriptor ... + Descriptor = configuration.GetModel(model); + if (!Descriptor.IsValid()) + { + XException.InvalidConfiguration.Throw(); + } + + // + // Prepare Chat Options based On Tools ... + Options = new ChatOptions(); + } + + // + #region Actions ... + /// + /// Base Method for Communicate with LLM ... + /// + /// + /// + /// + /// + public virtual async Task AskTextAsync( + string prompt, + XUserClaimsInfoDto userInfo = null, + CancellationToken cancellationToken = default + ) + { + // + // Check Prompt Exists ... + if (prompt.IsNullOrEmpty()) + { + XException.InvalidArgs.Throw(); + } + + // + using var client = Descriptor.GetClient(); + var history = GetHistory(prompt); + + // + // Handle Provided MCP Servers ... + if (useProvidedMcpServers) + { + // + var availableTools = await mcpServerProvider + .GetAvailableToolsAsync( + userInfo: userInfo, + cancellationToken: cancellationToken + ); + + // + Options.Tools = [.. availableTools.Cast()]; + } + + // + var response = await client.GetResponseAsync( + options: Options, + messages: history, + cancellationToken: cancellationToken + ); + + // + // Validate Response ... + if (!response.IsValid()) + { + // + // Dispose Client ... + client.Dispose(); + XException.ActionFailed.Throw(); + } + + // + // Retrieve Response Text ... + var result = response.Text; + + // + return result; + } + + /// + /// Base Method for Communicate with LLM ... + /// + /// + /// + /// + /// + public virtual async IAsyncEnumerable AskTextAsEnumerable( + string prompt, + XUserClaimsInfoDto userInfo = null, + [EnumeratorCancellation] + CancellationToken cancellationToken = default + ) + { + // + // Check Prompt Exists ... + if (prompt.IsNullOrEmpty()) + { + XException.InvalidArgs.Throw(); + } + + // + using var client = Descriptor.GetClient(); + var history = GetHistory(prompt); + + // + // Handle Provided MCP Servers ... + if (useProvidedMcpServers) + { + // + var availableTools = await mcpServerProvider + .GetAvailableToolsAsync( + userInfo: userInfo, + cancellationToken: cancellationToken + ); + + // + Options.Tools = [.. availableTools.Cast()]; + } + + // + var enumerable = client.GetStreamingResponseAsync( + options: Options, + messages: history + ); + + // + await foreach (var res in enumerable) + { + // + // Cancellation Token ... + if (cancellationToken.IsCancellationRequested) + { + yield break; + } + + // + yield return res.Text; + } + } + + /// + /// Ask a Question By Providing Vector Search Result ... + /// + /// + /// + /// + /// + /// + public virtual async Task AskTextByContextAsync( + string prompt, + IList context = null, + XUserClaimsInfoDto userInfo = null, + CancellationToken cancellationToken = default + ) + { + // + // Validate Args ... + validationProvider + .GroupValidationBuilder() + .AddNotEmpty(prompt) + .AddNotNull(userInfo) + .AddNotEmpty(userInfo.UserId) + .ValidateGroup(); + + // + using var client = Descriptor.GetClient(); + var history = GetHistory(prompt, context); + + // + // Handle Provided MCP Servers ... + if (useProvidedMcpServers) + { + // + var availableTools = await mcpServerProvider + .GetAvailableToolsAsync( + userInfo: userInfo, + cancellationToken: cancellationToken + ); + + // + Options.Tools = [.. availableTools.Cast()]; + } + + // + var response = await client.GetResponseAsync( + options: Options, + messages: history, + cancellationToken: cancellationToken + ); + + // + // Validate Response ... + if (!response.IsValid()) + { + client.Dispose(); + XException.ActionFailed.Throw(); + } + + // + var result = response.Text; + + // + return result; + } + + /// + /// Ask a Question By By Providing Vector Search Result and Stream Response ... + /// + /// + /// + /// + /// + /// + public virtual async IAsyncEnumerable AskTextByContextAsEnumerable( + string prompt, + IList context = null, + XUserClaimsInfoDto userInfo = null, + [EnumeratorCancellation] + CancellationToken cancellationToken = default + ) + { + // + // Validate Args ... + validationProvider + .GroupValidationBuilder() + .AddNotEmpty(prompt) + .AddNotNull(userInfo) + .AddNotEmpty(userInfo.UserId) + .ValidateGroup(); + + // + using var client = Descriptor.GetClient(); + var history = GetHistory(prompt, context); + + // + // Handle Provided MCP Servers ... + if (useProvidedMcpServers) + { + // + var availableTools = await mcpServerProvider + .GetAvailableToolsAsync( + userInfo: userInfo, + cancellationToken: cancellationToken + ); + + // + Options.Tools = [.. availableTools.Cast()]; + } + + // + var enumerable = client.GetStreamingResponseAsync( + options: Options, + messages: history, + cancellationToken: cancellationToken + ); + + // + await foreach (var res in enumerable) + { + // + if (cancellationToken.IsCancellationRequested) + { + yield break; + } + + // + yield return res.Text; + } + } + + /// + /// Ask a Question By Rag Retrive From Knowledge ... + /// + /// + /// + /// + /// + /// + /// + /// + public virtual async Task AskTextFromKnowledgeAsync( + string prompt, + string type = null, + int? topK = null, + float? minScore = null, + XUserClaimsInfoDto userInfo = null, + CancellationToken cancellationToken = default + ) + { + // + // Validation ... + validationProvider + .GroupValidationBuilder() + .AddNotEmpty(prompt) + .AddNotNull(userInfo) + .AddNotEmpty(userInfo.UserId) + .ValidateGroup(); + + // + // Prepare Requirements ... + var prep = await PrepareChatRequirementsAsync( + topK: topK, + type: type, + files: null, + prompt: prompt, + projectId: null, + minScore: minScore, + userInfo: userInfo, + connectionId: null, + conversationId: null, + persistPrompt: false, + 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-20261106_205448.txt b/Documents/GeneratedContext/xDashboard-xAiMcpServer-20261106_205448.txt deleted file mode 100644 index b915c81..0000000 --- a/Documents/GeneratedContext/xDashboard-xAiMcpServer-20261106_205448.txt +++ /dev/null @@ -1,898 +0,0 @@ - -### FILE: C:\Users\saherelm\Documents\Projects\xSaherelmWorkspace\xAiMcpServer\Program.cs - -using System.Text; -using Microsoft.AspNetCore.Hosting; -using Microsoft.Extensions.Hosting; - -namespace xAiMcpServer -{ - 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\xAiMcpServer\Startup.cs - -using System; -using System.IO; -using System.Net.Http; -using xAiMcpServer.DI; -using Newtonsoft.Json; -using System.Reflection; -using xIdentityService.DI; -using xCommons.Extensions; -using xAiService.Extensions; -using xCommons.Configurations; -using Microsoft.AspNetCore.Builder; -using Microsoft.AspNetCore.Hosting; -using Microsoft.Extensions.Hosting; -using Newtonsoft.Json.Serialization; -using Microsoft.Extensions.Configuration; -using Microsoft.Extensions.DependencyInjection; -using IdentityModel.AspNetCore.OAuth2Introspection; - -namespace xAiMcpServer -{ - public class Startup - { - public Startup(IConfiguration configuration) - { - Configuration = configuration; - } - - public IConfiguration Configuration { get; } - - public void ConfigureServices(IServiceCollection services) - { - // - // Register MCP Handler ... - services.AddXAiMcpHandler(); - - // - // Register Validation Provider and all XCommons Module Services ... - services.AddXCommons(Configuration); - - // - // Register App Configuration ... - services.AddXAppConfiguration(Configuration); - var appConfiguration = services.GetRegisteredService(); - - // - // Register Allowed Origins ... - services.AddXCors(appConfiguration.AllowedOrigins); - - // - // Register Swagger ... - var xmlFile = $"{Assembly.GetExecutingAssembly().GetName().Name}.xml"; - var xmlPath = Path.Combine(AppContext.BaseDirectory, xmlFile); - services.AddXSwagger(Configuration, xmlFilePath: xmlPath); - - // - // Add Api V1 Versioning ... - services.AddXApiV1Versioning(); - - // - // OAuthIntrospectin Http Client Handler ... - // this is for handling SSLErrors ... - services.AddHttpClient(OAuth2IntrospectionDefaults.BackChannelHttpClientName) - .ConfigurePrimaryHttpMessageHandler(() => - { - return new HttpClientHandler - { - ServerCertificateCustomValidationCallback = (sender, certificate, chain, sslPolicyErrors) => true - }; - }); - - // - services.AddControllers() - .AddNewtonsoftJson(x => - { - x.SerializerSettings.ReferenceLoopHandling = ReferenceLoopHandling.Ignore; - x.SerializerSettings.ContractResolver = new CamelCasePropertyNamesContractResolver(); - }); - - // - var lifeTime = ServiceLifetime.Scoped; - - // - // Register XIdentity Service ... - services.AddXIdentityService( - lifeTime: lifeTime, - configuration: Configuration - ); - - // - // Register Authorizations ... - services.AddXAuthorization(); - - // - // Register MCP Tools in DI ... - services.AddXAiMcpTools(); - } - - public void Configure( - IApplicationBuilder app, - IWebHostEnvironment env - ) - { - // - // Configure the HTTP request pipeline ... - var isDevelopmentEnvironment = env.IsDevelopment(); - if (isDevelopmentEnvironment) - { - app.UseDeveloperExceptionPage(); - } - else - { - app.UseHsts(); - } - - // - // Force Https Redirection ... - app.UseHttpsRedirection(); - - // - // Use Swagger Middleware (Only in Development) ... - if (isDevelopmentEnvironment) - { - app.UseXSwagger(); - } - - // - // Using Cors (before Proxy so Browser Requests get CORS Headers) ... - app.UseXCors(); - - // - // Using Routing ... - app.UseRouting(); - - // - // Use xIdentityService (Authentication) ... - app.UseXIdentityService(); - - // - // Use Authorization ... - app.UseAuthorization(); - - // - app.UseEndpoints(endpoints => - { - endpoints.MapControllers(); - }); - } - } -} - -### FILE: C:\Users\saherelm\Documents\Projects\xSaherelmWorkspace\xAiMcpServer\Controllers\McpController.cs - -using xIdentityHelper; -using System.Threading; -using xCommons.Providers; -using Newtonsoft.Json.Linq; -using xAiService.Interfaces; -using System.Threading.Tasks; -using xAiService.Controllers; -using xCommons.Configurations; -using Microsoft.AspNetCore.Mvc; -using xIdentityService.Interfaces; -using Microsoft.Extensions.Logging; -using Microsoft.AspNetCore.Authorization; - -namespace xAiMcpServer.Controllers -{ - [Authorize] - public class McpController : XAiMcpControllerBase - { - public McpController( - IXAiMcpHandler mcpHandler, - ILogger logger, - XAppConfiguration appConfiguration, - IXIdentityProvider identityProvider, - XValidationProvider validationProvider - ) : base(mcpHandler, appConfiguration, identityProvider, logger, validationProvider) - { } - - // - #region Override ... - /// - /// Handle MCP ... - /// - /// - /// - /// - [HttpPost] - [Authorize(Policy = XPolicies.EnabledUser)] - public override async Task HandleMcp( - [FromBody] JObject request, - CancellationToken cancellationToken = default - ) - { - // - var userInfo = await GetUserInfo(); - var connectionId = GetConnectionId(); - - // - var result = await base - .HandleMcp( - request: request, - cancellationToken: cancellationToken - ); - - // - return result; - } - - /// - /// Handle SSE EndPoint ... - /// - /// - /// - [HttpGet("sse")] - [AllowAnonymous] - public override async Task SseEndpoint( - CancellationToken cancellationToken = default - ) - { - // - await base - .SseEndpoint(cancellationToken); - } - #endregion - } -} - -### FILE: C:\Users\saherelm\Documents\Projects\xSaherelmWorkspace\xAiMcpServer\Controllers\StartupController.cs - -using xCommons.Providers; -using xCommons.Controllers; -using xCommons.Configurations; -using Microsoft.AspNetCore.Mvc; -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); - } - } -} - -### FILE: C:\Users\saherelm\Documents\Projects\xSaherelmWorkspace\xAiMcpServer\Controllers\TestIdentity.cs - -using xCommons.Providers; -using xCommons.Configurations; -using xIdentityHelper.Controllers; -using xIdentityService.Interfaces; -using Microsoft.Extensions.Logging; - -namespace xAiMcpServer.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\xAiMcpServer\DI\DiExtensions.cs - -using System.Linq; -using xIdentityHelper; -using xAiMcpServer.Tools; -using xCommons.Extensions; -using xCommons.Authorization; -using System.Collections.Generic; -using xIdentityService.Interfaces; -using Microsoft.AspNetCore.Builder; -using Microsoft.AspNetCore.HttpOverrides; -using Microsoft.AspNetCore.Authorization; -using Microsoft.Extensions.DependencyInjection; - -namespace xAiMcpServer.DI -{ - public static class DiExtensions - { - 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); - } - - /// - /// Register Tools which required Dependency Injection Services ... - /// - /// - public static void AddXAiMcpTools(this IServiceCollection source) - { - // - source.AddScoped(); - } - } -} - -### FILE: C:\Users\saherelm\Documents\Projects\xSaherelmWorkspace\xAiMcpServer\Tools\XDateTools.cs - -using System; -using System.Text; -using TimeZoneConverter; -using xCommons.Extensions; -using System.Globalization; -using xAiModels.Attributes; -using System.Collections.Generic; -using System.Text.RegularExpressions; - -namespace xAiMcpServer.Tools -{ - [XAiMcpToolType] - public class XDateTools - { - [XAiMcpTool(Description = "Get the CURRENT date and time right now. Use this tool whenever the user asks about 'today', 'now', 'current date', 'current time', or when you need the current date/time for any relative calculation (like 'three days ago', 'next week', 'how many days until...'). Returns Gregorian, Persian (Jalali), day-of-week, and Unix timestamp.")] - public static string GetCurrentDateTime( - [XAiMcpToolParam(Description = "Optional IANA timezone (e.g. 'Asia/Tehran', 'UTC', 'Europe/London'). Defaults to 'Asia/Tehran'.", Required = false)] - string timezone = null - ) - { - try - { - var tz = ResolveTimezone(timezone ?? "Asia/Tehran"); - var nowUtc = DateTime.UtcNow; - var nowLocal = TimeZoneInfo.ConvertTimeFromUtc(nowUtc, tz); - - var pc = new PersianCalendar(); - var sb = new StringBuilder(); - sb.AppendLine($"Timezone: {tz.Id}"); - sb.AppendLine($"Local: {nowLocal:yyyy-MM-dd HH:mm:ss} {nowLocal:dddd}"); - sb.AppendLine($"UTC: {nowUtc:yyyy-MM-dd HH:mm:ss} UTC"); - sb.AppendLine($"Persian: {pc.GetYear(nowLocal):D4}/{pc.GetMonth(nowLocal):D2}/{pc.GetDayOfMonth(nowLocal):D2} {nowLocal:HH:mm:ss}"); - sb.AppendLine($"ISO 8601: {nowLocal:yyyy-MM-ddTHH:mm:ss.fffzzz}"); - sb.AppendLine($"Unix: {new DateTimeOffset(nowUtc).ToUnixTimeSeconds()}"); - sb.AppendLine($"Week: {ISOWeek.GetWeekOfYear(nowLocal)} (of {nowLocal.Year})"); - return sb.ToString().TrimEnd(); - } - catch (Exception ex) - { - return $"Error: {ex.Message}"; - } - } - - [XAiMcpTool(Description = "Detect and extract all date-like patterns from a free text. Supports Gregorian (2024-11-05), Persian (1403/08/15), Hijri (1446/05/03), ISO 8601, and month-name forms.")] - public static string DetectDates( - [XAiMcpToolParam(Description = "Free text that may contain dates.")] - string text, - [XAiMcpToolParam(Description = "Optional: hint for the primary calendar (Gregorian, Persian, Hijri). Leave empty for auto-detection.", Required = false)] - string calendarHint = null - ) - { - // - if (string.IsNullOrWhiteSpace(text)) - { - return "No text provided."; - } - - // - var patterns = new (string Name, Regex Pattern)[] - { - ("ISO8601", new Regex(@"\b\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}(?:\.\d+)?(?:Z|[+-]\d{2}:?\d{2})?\b")), - ("NumericYMD", new Regex(@"\b\d{4}[/\-\.]\d{1,2}[/\-\.]\d{1,2}\b")), - ("NumericDMY", new Regex(@"\b\d{1,2}[/\-\.]\d{1,2}[/\-\.]\d{2,4}\b")), - ("PersianMonth", new Regex(@"\b\d{1,2}\s+(فروردین|اردیبهشت|خرداد|تیر|مرداد|شهریور|مهر|آبان|آذر|دی|بهمن|اسفند)\s+\d{4}\b")), - ("EnglishMonth", new Regex(@"\b\d{1,2}\s+(January|February|March|April|May|June|July|August|September|October|November|December)\s+\d{4}\b", RegexOptions.IgnoreCase)), - }; - - // - var found = new List(); - var sb = new StringBuilder(); - foreach (var (name, pattern) in patterns) - { - // - foreach (Match m in pattern.Matches(text)) - { - // - if (!found.Contains(m.Value)) - { - // - found.Add(m.Value); - sb.AppendLine($"• {m.Value} [{name}]"); - } - } - } - - // - return found.Count == 0 - ? "No date pattern detected." - : $"Detected {found.Count} date(s):\n{sb.ToString().TrimEnd()}"; - } - - [XAiMcpTool(Description = "Parse a single date string. Returns the detected calendar, plus normalized Gregorian (ISO 8601), Persian, Hijri representations, and Unix timestamp.")] - public static string ParseDate( - [XAiMcpToolParam(Description = "Date string like '1403/08/15' or '2024-11-05'.")] - string date, - [XAiMcpToolParam(Description = "Optional: calendar hint (Gregorian, Persian, Hijri). Leave empty for auto-detect.", Required = false)] - string calendarHint = null - ) - { - // - try - { - // - var dt = ParseDateToGregorian(date, calendarHint); - return BuildReport(dt); - } - catch (Exception ex) - { - return $"Error: {ex.Message}"; - } - } - - [XAiMcpTool(Description = "Convert a date from one calendar to another. Supported calendars: Gregorian, Persian (Jalali/Shamsi), Hijri (Islamic).")] - public static string ConvertDate( - [XAiMcpToolParam(Description = "Date string in the source calendar.")] - string date, - [XAiMcpToolParam(Description = "Source calendar: Gregorian, Persian, or Hijri.")] - string fromCalendar, - [XAiMcpToolParam(Description = "Target calendar: Gregorian, Persian, or Hijri.")] - string toCalendar - ) - { - // - try - { - // - var greg = ParseDateToGregorian(date, fromCalendar); - var target = NormalizeCalendarName(toCalendar); - var cal = GetCalendar(target); - - // - return $"{cal.GetYear(greg):D4}/{cal.GetMonth(greg):D2}/{cal.GetDayOfMonth(greg):D2}"; - } - catch (Exception ex) - { - return $"Error: {ex.Message}"; - } - } - - [XAiMcpTool(Description = "Calculate the difference between two dates. Returns total days, and a breakdown into years/months/days.")] - public static string DateDifference( - [XAiMcpToolParam(Description = "First date string.")] - string date1, - [XAiMcpToolParam(Description = "Second date string.")] - string date2, - [XAiMcpToolParam(Description = "Optional: calendar hint for both dates.", Required = false)] - string calendarHint = null - ) - { - // - try - { - // - var d1 = ParseDateToGregorian(date1, calendarHint); - var d2 = ParseDateToGregorian(date2, calendarHint); - var span = d2 - d1; - - // - return $"Difference: {span.Days} days (= {span.Days / 365} years + {(span.Days % 365) / 30} months + {(span.Days % 365) % 30} days)"; - } - catch (Exception ex) - { - return $"Error: {ex.Message}"; - } - } - - [XAiMcpTool(Description = "Convert a date string to Unix timestamp (seconds since 1970-01-01 UTC).")] - public static string ToUnixTimestamp( - [XAiMcpToolParam(Description = "Date string.")] - string date, - [XAiMcpToolParam(Description = "Optional: calendar hint (Gregorian, Persian, Hijri).", Required = false)] - string calendarHint = null - ) - { - // - try - { - // - var dt = ParseDateToGregorian(date, calendarHint); - var ts = new DateTimeOffset(dt, TimeSpan.Zero).ToUnixTimeSeconds(); - - // - return ts.ToString(); - } - catch (Exception ex) - { - return $"Error: {ex.Message}"; - } - } - - [XAiMcpTool(Description = "Convert a Unix timestamp (seconds since 1970-01-01 UTC) back to a date string in the specified calendar.")] - public static string FromUnixTimestamp( - [XAiMcpToolParam(Description = "Unix timestamp in seconds.")] - long timestamp, - [XAiMcpToolParam(Description = "Optional: target calendar (Gregorian, Persian, Hijri). Defaults to Gregorian.", Required = false)] - string targetCalendar = null - ) - { - // - try - { - // - var dt = DateTimeOffset.FromUnixTimeSeconds(timestamp).UtcDateTime; - var calName = NormalizeCalendarName(targetCalendar) ?? "Gregorian"; - if (calName == "Gregorian") - { - return dt.ToString("yyyy-MM-dd HH:mm:ss 'UTC'"); - } - - // - var c = GetCalendar(calName); - return $"{c.GetYear(dt):D4}/{c.GetMonth(dt):D2}/{c.GetDayOfMonth(dt):D2}"; - } - catch (Exception ex) - { - return $"Error: {ex.Message}"; - } - } - - // - #region Private ... - private static string BuildReport(DateTime greg) - { - // - var pc = new PersianCalendar(); - var hc = new UmAlQuraCalendar(); - var sb = new StringBuilder(); - - // - sb.AppendLine($"Gregorian: {greg:yyyy-MM-dd}"); - sb.AppendLine($"Persian: {pc.GetYear(greg):D4}/{pc.GetMonth(greg):D2}/{pc.GetDayOfMonth(greg):D2}"); - sb.AppendLine($"Hijri: {hc.GetYear(greg):D4}/{hc.GetMonth(greg):D2}/{hc.GetDayOfMonth(greg):D2}"); - sb.AppendLine($"ISO 8601: {greg:yyyy-MM-ddTHH:mm:ss.fffZ}"); - sb.AppendLine($"Unix: {new DateTimeOffset(greg, TimeSpan.Zero).ToUnixTimeSeconds()}"); - - // - return sb.ToString().TrimEnd(); - } - - private static DateTime ParseDateToGregorian(string date, string calendarHint) - { - // - if (string.IsNullOrWhiteSpace(date)) - { - throw new ArgumentException("date is empty"); - } - - // - var m = Regex.Match(date.Trim(), @"^(?\d{4})[/\-\.](?\d{1,2})[/\-\.](?\d{1,2})$"); - if (!m.Success) - { - throw new FormatException($"Unrecognized date format: '{date}'. Expected yyyy/MM/dd."); - } - - // - var y = int.Parse(m.Groups["y"].Value); - var mo = int.Parse(m.Groups["m"].Value); - var d = int.Parse(m.Groups["d"].Value); - - // - var calName = NormalizeCalendarName(calendarHint) ?? AutoDetectCalendar(y); - return calName switch - { - // - "Gregorian" => new DateTime(y, mo, d), - "Persian" => new PersianCalendar().ToDateTime(y, mo, d, 0, 0, 0, 0), - "Hijri" => new UmAlQuraCalendar().ToDateTime(y, mo, d, 0, 0, 0, 0), - _ => throw new ArgumentException($"Unknown calendar: {calendarHint}") - }; - } - - private static string NormalizeCalendarName(string name) - { - // - if (string.IsNullOrWhiteSpace(name)) - { - return null; - } - - // - var n = name.Trim().ToLowerInvariant(); - return n switch - { - // - "gregorian" or "میلادی" or "g" => "Gregorian", - "persian" or "jalali" or "shamsi" or "شمسی" or "جلالی" or "p" => "Persian", - "hijri" or "islamic" or "قمری" or "هجری" or "h" => "Hijri", - _ => throw new ArgumentException($"Unknown calendar: {name}. Use Gregorian, Persian, or Hijri.") - }; - } - - private static string AutoDetectCalendar(int year) - { - // - if (year >= 1900 && year <= 2100) - { - return "Gregorian"; - } - - // - if (year >= 1300 && year <= 1499) - { - return "Persian"; - } - - // - return "Gregorian"; - } - - private static TimeZoneInfo ResolveTimezone(string timezoneId) - { - // - if (timezoneId.IsNullOrEmpty()) - { - timezoneId = "UTC"; - } - - // - try - { - return TZConvert.GetTimeZoneInfo(timezoneId); - } - catch - { - return TimeZoneInfo.Utc; - } - } - - private static Calendar GetCalendar(string name) => name switch - { - // - "Gregorian" => new GregorianCalendar(), - "Persian" => new PersianCalendar(), - "Hijri" => new UmAlQuraCalendar(), - _ => throw new ArgumentException($"Unknown calendar: {name}") - }; - #endregion - } -} - -### FILE: C:\Users\saherelm\Documents\Projects\xSaherelmWorkspace\xAiMcpServer\Tools\XEchoTools.cs - - -using xAiModels.Attributes; - -namespace xAiMcpServer.Tools -{ - [XAiMcpToolType] - public static class XEchoTools - { - [XAiMcpTool(Description = "Echoes the string back to the client give message in string")] - public static string Echo( - [XAiMcpToolParam(Description = "string value which specified message")] - string message - ) - { - // - var result = $"hello {message}"; - return result; - } - } -} - -### FILE: C:\Users\saherelm\Documents\Projects\xSaherelmWorkspace\xAiMcpServer\Tools\XUserTools.cs - -using xIdentityHelper; -using xModels.Extensions; -using xCommons.Extensions; -using xAiModels.Attributes; -using xAiService.Interfaces; -using System.Threading.Tasks; -using xIdentityService.Interfaces; - -namespace xAiMcpServer.Tools -{ - [XAiMcpToolType] - public class XUserTools - { - // - private readonly IXPersonService personService; - private readonly IXAiMcpUserContext userContext; - - public XUserTools( - IXAiMcpUserContext userContext, - IXPersonService personService - ) - { - // - this.userContext = userContext; - this.personService = personService; - } - - [XAiMcpTool( - RequiresAuthentication = true, - RequiredPolicy = XPolicies.EnabledUser, - Description = "Get information about the currently logged-in user.")] - public async Task WhoAmI() - { - // - var user = userContext.UserInfo; - if (user.IsNullOrDefault()) - { - return "Anonymous"; - } - - // - var person = await personService.GetPerson(user.UserId); - - // - return person?.GetFullname() ?? user.UserId; - } - } -} diff --git a/Documents/GeneratedContext/xDashboard-xAiMcpServer-20261107_225130.txt b/Documents/GeneratedContext/xDashboard-xAiMcpServer-20261107_225130.txt new file mode 100644 index 0000000..7eba5a8 --- /dev/null +++ b/Documents/GeneratedContext/xDashboard-xAiMcpServer-20261107_225130.txt @@ -0,0 +1,1905 @@ + +### FILE: C:\Users\SaherElm\Documents\Projects\xSaherelmWorkspace\xAiMcpServer\Program.cs + +using System.Text; +using Microsoft.AspNetCore.Hosting; +using Microsoft.Extensions.Hosting; + +namespace xAiMcpServer +{ + 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\xAiMcpServer\Startup.cs + +using System; +using System.IO; +using System.Net.Http; +using xAiMcpServer.DI; +using Newtonsoft.Json; +using System.Reflection; +using xIdentityService.DI; +using xCommons.Extensions; +using xAiService.Extensions; +using xCommons.Configurations; +using Microsoft.AspNetCore.Builder; +using Microsoft.AspNetCore.Hosting; +using Microsoft.Extensions.Hosting; +using Newtonsoft.Json.Serialization; +using Microsoft.Extensions.Configuration; +using Microsoft.Extensions.DependencyInjection; +using IdentityModel.AspNetCore.OAuth2Introspection; + +namespace xAiMcpServer +{ + public class Startup + { + public Startup(IConfiguration configuration) + { + Configuration = configuration; + } + + public IConfiguration Configuration { get; } + + public void ConfigureServices(IServiceCollection services) + { + // + // Register MCP Handler ... + services.AddXAiMcpHandler(); + + // + // Register Validation Provider and all XCommons Module Services ... + services.AddXCommons(Configuration); + + // + // Register App Configuration ... + services.AddXAppConfiguration(Configuration); + var appConfiguration = services.GetRegisteredService(); + + // + // Register Allowed Origins ... + services.AddXCors(appConfiguration.AllowedOrigins); + + // + // Register Swagger ... + var xmlFile = $"{Assembly.GetExecutingAssembly().GetName().Name}.xml"; + var xmlPath = Path.Combine(AppContext.BaseDirectory, xmlFile); + services.AddXSwagger(Configuration, xmlFilePath: xmlPath); + + // + // Add Api V1 Versioning ... + services.AddXApiV1Versioning(); + + // + // OAuthIntrospectin Http Client Handler ... + // this is for handling SSLErrors ... + services.AddHttpClient(OAuth2IntrospectionDefaults.BackChannelHttpClientName) + .ConfigurePrimaryHttpMessageHandler(() => + { + return new HttpClientHandler + { + ServerCertificateCustomValidationCallback = (sender, certificate, chain, sslPolicyErrors) => true + }; + }); + + // + services.AddControllers() + .AddNewtonsoftJson(x => + { + x.SerializerSettings.ReferenceLoopHandling = ReferenceLoopHandling.Ignore; + x.SerializerSettings.ContractResolver = new CamelCasePropertyNamesContractResolver(); + }); + + // + var lifeTime = ServiceLifetime.Scoped; + + // + // Register XIdentity Service ... + services.AddXIdentityService( + lifeTime: lifeTime, + configuration: Configuration + ); + + // + // Register Authorizations ... + services.AddXAuthorization(); + + // + // Register MCP Tools in DI ... + services.AddXAiMcpTools(Configuration); + } + + public void Configure( + IApplicationBuilder app, + IWebHostEnvironment env + ) + { + // + // Configure the HTTP request pipeline ... + var isDevelopmentEnvironment = env.IsDevelopment(); + if (isDevelopmentEnvironment) + { + app.UseDeveloperExceptionPage(); + } + else + { + app.UseHsts(); + } + + // + // Force Https Redirection ... + app.UseHttpsRedirection(); + + // + // Use Swagger Middleware (Only in Development) ... + if (isDevelopmentEnvironment) + { + app.UseXSwagger(); + } + + // + // Using Cors (before Proxy so Browser Requests get CORS Headers) ... + app.UseXCors(); + + // + // Using Routing ... + app.UseRouting(); + + // + // Use xIdentityService (Authentication) ... + app.UseXIdentityService(); + + // + // Use Authorization ... + app.UseAuthorization(); + + // + app.UseEndpoints(endpoints => + { + endpoints.MapControllers(); + }); + } + } +} + +### FILE: C:\Users\SaherElm\Documents\Projects\xSaherelmWorkspace\xAiMcpServer\Configurations\XAiMcpLinkExtractionToolConfiguration.cs + +namespace xAiMcpServer.Configurations +{ + public class XAiMcpLinkExtractionToolConfiguration + { + public int MaxLinks { get; set; } + public int MaxChars { get; set; } + } +} + +### FILE: C:\Users\SaherElm\Documents\Projects\xSaherelmWorkspace\xAiMcpServer\Configurations\XAiMcpWebSearchToolConfiguration.cs + +namespace xAiMcpServer.Configurations +{ + /// + /// Web Search Tool Configuration ... + /// + public class XAiMcpWebSearchToolConfiguration + { + /// + /// Region for Search ... + /// + public string Region {get; set;} + + /// + /// Timeout ... + /// + public int TimeoutSeconds {get; set;} + + /// + /// Cache TTL ... + /// + public int CacheTtlSeconds {get; set;} + + /// + /// Main Endpoint Url for Search ... + /// + public string HtmlEndpoint {get; set;} + + /// + /// Fallback Endpoint Url ... + /// + public string LiteEndpoint {get; set;} + + /// + /// Selected Result items ... + /// + public int DefaultMaxResults {get; set;} + + /// + /// Enable Falling Back ... + /// + public bool EnableLiteFallback {get; set;} + + /// + /// Min Delay betwen two Requests ... + /// + public int MinDelayMilliseconds {get; set;} + } +} + +### FILE: C:\Users\SaherElm\Documents\Projects\xSaherelmWorkspace\xAiMcpServer\Constants\ConfigurationNodeNames.cs + +namespace xAiMcpServer.Constants +{ + public partial struct ConfigurationNodeNames + { + public const string WEB_SEARCH_TOOL_NODE = "WebSearchToolConfiguration"; + public const string LINK_EXTRACTION_TOOL_NODE = "LinkExtractionToolConfiguration"; + } +} + +### FILE: C:\Users\SaherElm\Documents\Projects\xSaherelmWorkspace\xAiMcpServer\Controllers\McpController.cs + +using xIdentityHelper; +using System.Threading; +using xCommons.Providers; +using Newtonsoft.Json.Linq; +using xAiService.Interfaces; +using System.Threading.Tasks; +using xAiService.Controllers; +using xCommons.Configurations; +using Microsoft.AspNetCore.Mvc; +using xIdentityService.Interfaces; +using Microsoft.Extensions.Logging; +using Microsoft.AspNetCore.Authorization; + +namespace xAiMcpServer.Controllers +{ + [Authorize] + public class McpController : XAiMcpControllerBase + { + public McpController( + IXAiMcpHandler mcpHandler, + ILogger logger, + XAppConfiguration appConfiguration, + IXIdentityProvider identityProvider, + XValidationProvider validationProvider + ) : base(mcpHandler, appConfiguration, identityProvider, logger, validationProvider) + { } + + // + #region Override ... + /// + /// Handle MCP ... + /// + /// + /// + /// + [HttpPost] + [Authorize(Policy = XPolicies.EnabledUser)] + public override async Task HandleMcp( + [FromBody] JObject request, + CancellationToken cancellationToken = default + ) + { + // + var userInfo = await GetUserInfo(); + var connectionId = GetConnectionId(); + + // + var result = await base + .HandleMcp( + request: request, + cancellationToken: cancellationToken + ); + + // + return result; + } + + /// + /// Handle SSE EndPoint ... + /// + /// + /// + [HttpGet("sse")] + [AllowAnonymous] + public override async Task SseEndpoint( + CancellationToken cancellationToken = default + ) + { + // + await base + .SseEndpoint(cancellationToken); + } + #endregion + } +} + +### FILE: C:\Users\SaherElm\Documents\Projects\xSaherelmWorkspace\xAiMcpServer\Controllers\StartupController.cs + +using xCommons.Providers; +using xCommons.Controllers; +using xCommons.Configurations; +using Microsoft.AspNetCore.Mvc; +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); + } + } +} + +### FILE: C:\Users\SaherElm\Documents\Projects\xSaherelmWorkspace\xAiMcpServer\Controllers\TestIdentity.cs + +using xCommons.Providers; +using xCommons.Configurations; +using xIdentityHelper.Controllers; +using xIdentityService.Interfaces; +using Microsoft.Extensions.Logging; + +namespace xAiMcpServer.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\xAiMcpServer\DI\DiExtensions.cs + +using System.Linq; +using xIdentityHelper; +using xAiMcpServer.Tools; +using xCommons.Extensions; +using xExceptions.Constants; +using xCommons.Authorization; +using xAiMcpServer.Constants; +using xAiMcpServer.Providers; +using xAiMcpServer.Interfaces; +using System.Collections.Generic; +using xIdentityService.Interfaces; +using xAiMcpServer.Configurations; +using Microsoft.AspNetCore.Builder; +using Microsoft.AspNetCore.HttpOverrides; +using Microsoft.AspNetCore.Authorization; +using Microsoft.Extensions.Configuration; +using Microsoft.Extensions.DependencyInjection; + +namespace xAiMcpServer.DI +{ + public static class DiExtensions + { + 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); + } + + // + #region WebSearchTool ... + /// + /// Extract Web Search Tool Configuration ... + /// + /// + /// + public static XAiMcpWebSearchToolConfiguration GetXAiMcpWebSearchToolConfiguration( + this IConfiguration source + ) + { + // + XAiMcpWebSearchToolConfiguration result = null; + + // + var section = source.GetSection(ConfigurationNodeNames.WEB_SEARCH_TOOL_NODE); + if (!section.IsNull()) + { + result = section.Get(); + } + + // + return result; + } + + /// + /// Inject Web Search MCP Tool Configuration and Register it ... + /// + /// + /// + public static void AddXAiMcpWebSearchToolConfiguration( + this IServiceCollection source, + IConfiguration configuration + ) + { + // + var config = configuration.GetXAiMcpWebSearchToolConfiguration(); + source.AddXAiMcpWebSearchToolConfiguration(config); + } + + /// + /// Register Web Search MCP Tool Configuration ... + /// + /// + /// + public static void AddXAiMcpWebSearchToolConfiguration( + this IServiceCollection source, + XAiMcpWebSearchToolConfiguration configuration + ) + { + // + if (configuration.IsNull()) + { + XException.InvalidConfiguration.Throw(); + } + + // + source.AddSingleton(configuration); + } + #endregion + + // + #region LinkExtractionTool ... + /// + /// Extract Link Extraction Tool Configuration ... + /// + /// + /// + public static XAiMcpLinkExtractionToolConfiguration GetXAiMcpLinkExtractionToolConfiguration( + this IConfiguration source + ) + { + // + XAiMcpLinkExtractionToolConfiguration result = null; + + // + var section = source.GetSection(ConfigurationNodeNames.LINK_EXTRACTION_TOOL_NODE); + if (!section.IsNull()) + { + result = section.Get(); + } + + // + return result; + } + + /// + /// Inject Link Extraction MCP Tool Configuration and Register it ... + /// + /// + /// + public static void AddXAiMcpLinkExtractionToolConfiguration( + this IServiceCollection source, + IConfiguration configuration + ) + { + // + var config = configuration.GetXAiMcpLinkExtractionToolConfiguration(); + source.AddXAiMcpLinkExtractionToolConfiguration(config); + } + + /// + /// Register Link Extraction MCP Tool Configuration ... + /// + /// + /// + public static void AddXAiMcpLinkExtractionToolConfiguration( + this IServiceCollection source, + XAiMcpLinkExtractionToolConfiguration configuration + ) + { + // + if (configuration.IsNull()) + { + XException.InvalidConfiguration.Throw(); + } + + // + source.AddSingleton(configuration); + } + #endregion + + /// + /// Register Tools which required Dependency Injection Services ... + /// + /// + public static void AddXAiMcpTools( + this IServiceCollection source, + IConfiguration configuration + ) + { + // + // Register Memory Cache Service ... + source.AddMemoryCache(); + + // + // User Tools ... + source.AddScoped(); + + // + #region Web Search Tool ... + // + // Register Search Tool Configuration ... + source.AddXAiMcpWebSearchToolConfiguration(configuration); + + // + // Register HttpClient ... + // Since we Have Falling Back Endpoint, (more than one Endpoint), + // we Doesn't pass Base Url ... + source.AddHttpClient(); + + // + // Register Web Search Tool ... + source.AddScoped(); + #endregion + + // + #region Link Extraction Tool ... + // + // Register Link Extraction Tool Configuration ... + source.AddXAiMcpLinkExtractionToolConfiguration(configuration); + + // + // Register Tool ... + source.AddScoped(); + #endregion + } + } +} + +### FILE: C:\Users\SaherElm\Documents\Projects\xSaherelmWorkspace\xAiMcpServer\Interfaces\IXAiMcpWebSearchService.cs + +using System.Threading; +using xAiMcpServer.Models; +using System.Threading.Tasks; +using System.Collections.Generic; + +namespace xAiMcpServer.Interfaces +{ + public interface IXAiMcpWebSearchService + { + /// + /// Search Web and Retrieve Response ... + /// + /// + /// + /// + /// + /// + Task> SearchAsync( + string query, + int maxResults, + string region = null, + CancellationToken cancellationToken = default + ); + } +} + +### FILE: C:\Users\SaherElm\Documents\Projects\xSaherelmWorkspace\xAiMcpServer\Models\XExtractedLink.cs + +namespace xAiMcpServer.Models +{ + public class XExtractedLink + { + public string Url { get; set; } + public string Text { get; set; } + public bool IsRelative { get; set; } + } +} + +### FILE: C:\Users\SaherElm\Documents\Projects\xSaherelmWorkspace\xAiMcpServer\Models\XLinkBundle.cs + +using System.Collections.Generic; + +namespace xAiMcpServer.Models +{ + public class XLinkBundle + { + public IReadOnlyList Linkes { get; set; } = []; + public IReadOnlyList Contents { get; set; } = []; + } +} + +### FILE: C:\Users\SaherElm\Documents\Projects\xSaherelmWorkspace\xAiMcpServer\Models\XLinkContentResult.cs + +namespace xAiMcpServer.Models +{ + public class XLinkContentResult + { + public int Length { get; set; } = 0; + public bool Truncated { get; set; } = false; + public string Url { get; set; } = string.Empty; + public string Text { get; set; } = string.Empty; + public string Title { get; set; } = string.Empty; + public string Error { get; set; } = string.Empty; + public string ContentType { get; set; } = string.Empty; + } +} + +### FILE: C:\Users\SaherElm\Documents\Projects\xSaherelmWorkspace\xAiMcpServer\Models\XWebSearchToolResult.cs + +namespace xAiMcpServer.Models +{ + public class XWebSearchToolResult + { + public int Rank { get; set; } + public string Url { get; set; } + public string Title { get; set; } + public string Snippet { get; set; } + } +} + +### FILE: C:\Users\SaherElm\Documents\Projects\xSaherelmWorkspace\xAiMcpServer\Providers\XAiMcpWebSearchService.cs + +using System; +using System.Net; +using HtmlAgilityPack; +using System.Net.Http; +using System.Threading; +using xCommons.Extensions; +using xAiMcpServer.Models; +using xExceptions.Constants; +using System.Threading.Tasks; +using xAiMcpServer.Interfaces; +using System.Collections.Generic; +using xIdentityService.Interfaces; +using xAiMcpServer.Configurations; +using Microsoft.Extensions.Logging; +using System.Text.RegularExpressions; +using Microsoft.Extensions.Caching.Memory; + +namespace xAiMcpServer.Providers +{ + public class XAiMcpWebSearchService : IXAiMcpWebSearchService + { + // + private readonly HttpClient http; + private readonly IMemoryCache cache; + private readonly ILogger logger; + private readonly XAiMcpWebSearchToolConfiguration configuration; + + // + private static readonly SemaphoreSlim gate = new(1, 1); + + public XAiMcpWebSearchService( + HttpClient http, + IMemoryCache cache, + IXIdentityProvider identityProvider, + ILogger logger, + XAiMcpWebSearchToolConfiguration configuration + ) + { + // + if (configuration.IsNull()) + { + XException.InvalidConfiguration.Throw(); + } + + // + this.http = http; + this.cache = cache; + this.logger = logger; + this.configuration = configuration; + + // + // Preparing Http Client ... + http.Timeout = TimeSpan.FromSeconds(configuration.TimeoutSeconds); + http.DefaultRequestHeaders.UserAgent.ParseAdd(identityProvider.GetDevice().ToJSON()); + http.DefaultRequestHeaders.Accept + .ParseAdd("text/html,application/xhtml+xml"); + } + + /// + /// Search Web and Retrieve Response ... + /// + /// + /// + /// + /// + /// + public async Task> SearchAsync( + string query, + int maxResults, + string region = null, + CancellationToken cancellationToken = default + ) + { + // + maxResults = Math.Clamp(maxResults, 1, 10); + var key = $"ddg:{region}:{maxResults}:{query.Trim().ToLowerInvariant()}"; + if (cache.TryGetValue(key, out IReadOnlyList cached)) + { + return cached; + } + + // + await gate.WaitAsync(cancellationToken); + try + { + // + // Retrieve Result ... + var results = await InternalSearchAsync( + configuration.HtmlEndpoint, + query, + maxResults, + region, + cancellationToken + ); + + // + // Handle Falling Back ... + if (results.Count == 0 && configuration.EnableLiteFallback) + { + // + logger.LogWarning( + "DDG HTML returned no results for '{Q}', trying Lite...", query); + + // + // Retrieve Fallbacked Result ... + results = await InternalSearchAsync( + configuration.LiteEndpoint, + query, + maxResults, + region, + cancellationToken + ); + } + + // + // Setting Cahce ... + cache.Set( + key, + results, + TimeSpan.FromSeconds(configuration.CacheTtlSeconds) + ); + + // + return results; + } + finally + { + // + // Handle Delay Betwen Requests ... + await Task.Delay(configuration.MinDelayMilliseconds, CancellationToken.None); + gate.Release(); + } + } + + // + #region Private ... + private async Task> InternalSearchAsync( + string baseUrl, + string query, + int max, + string region, + CancellationToken cancellationToken = default + ) + { + // + // Preparing Search Url ... + var url = $"{baseUrl}?q={Uri.EscapeDataString(query)}"; + if (!region.IsNullOrEmpty()) + { + url += $"&kl={Uri.EscapeDataString(region)}"; + } + + // + // Send Request and Get Response ... + using var resp = await http.GetAsync(url, cancellationToken); + + // + // HTTP 202 = Anomaly Page ... + if ((int)resp.StatusCode == 202) + { + // + logger.LogWarning("DDG anomaly page (202) for '{Q}'", query); + return []; + } + + // + resp.EnsureSuccessStatusCode(); + + // + // Reading Response Content ... + var html = await resp.Content.ReadAsStringAsync(); + + // + // Parse Content as List of Items ... + var result = Parse(html, baseUrl, max); + + // + return result; + } + + private List Parse( + string html, + string baseUrl, + int max + ) + { + // + var doc = new HtmlDocument(); + doc.LoadHtml(html); + + // + // Handling Anomaly in HTML ... + if (html.Contains("anomaly-modal") || html.Contains("unusual traffic")) + { + // + logger.LogWarning("DDG anomaly detected in HTML body"); + return []; + } + + // + var results = new List(); + var seen = new HashSet(StringComparer.OrdinalIgnoreCase); + + // + // HTML endpoint: div.result ; Lite endpoint: جدول‌های لینک + var nodes = doc.DocumentNode + .SelectNodes("//div[contains(@class,'result')]"); + foreach (var node in nodes) + { + // + if (results.Count >= max) + { + break; + } + + // + // Remove Ads ... + if (node.GetAttributeValue("class", "").Contains("result--ad")) + { + continue; + } + + // + // Select Search Results ... + var a = node.SelectSingleNode(".//a[contains(@class,'result__a')]") + ?? node.SelectSingleNode(".//a[contains(@class,'result-link')]"); + if (a.IsNull()) + { + continue; + } + + // + var title = WebUtility.HtmlDecode(a.InnerText?.Trim() ?? ""); + var rawUrl = a.GetAttributeValue("href", ""); + var realUrl = UnwrapRedirect(rawUrl, baseUrl); + if (realUrl.IsNullOrEmpty() || !seen.Add(realUrl)) + { + continue; + } + + // + var snippetNode = node.SelectSingleNode( + ".//*[contains(@class,'result__snippet')]"); + var snippet = WebUtility.HtmlDecode( + snippetNode?.InnerText?.Trim() ?? ""); + + // + results.Add(new XWebSearchToolResult + { + Title = title, + Url = realUrl, + Snippet = snippet, + Rank = results.Count + 1, + }); + } + + // + return results; + } + + private static string UnwrapRedirect( + string href, + string baseUrl + ) + { + // + if (href.IsNullOrEmpty()) + { + return null; + } + + // + // Extract Real Url ... + var m = Regex.Match(href, @"[?&]uddg=([^&]+)"); + if (m.Success) + { + return Uri.UnescapeDataString(m.Groups[1].Value); + } + + // + // Relative Links ... + + // + if (href.StartsWith("//")) + { + return "https:" + href; + } + + // + if (href.StartsWith("/")) + { + return new Uri(new Uri(baseUrl), href).ToString(); + } + + // + return href.StartsWith("http") ? href : null; + } + #endregion + } +} + +### FILE: C:\Users\SaherElm\Documents\Projects\xSaherelmWorkspace\xAiMcpServer\Tools\XDateTools.cs + +using System; +using System.Text; +using TimeZoneConverter; +using xCommons.Extensions; +using System.Globalization; +using xAiModels.Attributes; +using System.Collections.Generic; +using System.Text.RegularExpressions; + +namespace xAiMcpServer.Tools +{ + [XAiMcpToolType] + public class XDateTools + { + [XAiMcpTool(Description = "Get the CURRENT date and time right now. Use this tool whenever the user asks about 'today', 'now', 'current date', 'current time', or when you need the current date/time for any relative calculation (like 'three days ago', 'next week', 'how many days until...'). Returns Gregorian, Persian (Jalali), day-of-week, and Unix timestamp.")] + public static string GetCurrentDateTime( + [XAiMcpToolParam(Description = "Optional IANA timezone (e.g. 'Asia/Tehran', 'UTC', 'Europe/London'). Defaults to 'Asia/Tehran'.", Required = false)] + string timezone = null + ) + { + try + { + var tz = ResolveTimezone(timezone ?? "Asia/Tehran"); + var nowUtc = DateTime.UtcNow; + var nowLocal = TimeZoneInfo.ConvertTimeFromUtc(nowUtc, tz); + + var pc = new PersianCalendar(); + var sb = new StringBuilder(); + sb.AppendLine($"Timezone: {tz.Id}"); + sb.AppendLine($"Local: {nowLocal:yyyy-MM-dd HH:mm:ss} {nowLocal:dddd}"); + sb.AppendLine($"UTC: {nowUtc:yyyy-MM-dd HH:mm:ss} UTC"); + sb.AppendLine($"Persian: {pc.GetYear(nowLocal):D4}/{pc.GetMonth(nowLocal):D2}/{pc.GetDayOfMonth(nowLocal):D2} {nowLocal:HH:mm:ss}"); + sb.AppendLine($"ISO 8601: {nowLocal:yyyy-MM-ddTHH:mm:ss.fffzzz}"); + sb.AppendLine($"Unix: {new DateTimeOffset(nowUtc).ToUnixTimeSeconds()}"); + sb.AppendLine($"Week: {ISOWeek.GetWeekOfYear(nowLocal)} (of {nowLocal.Year})"); + return sb.ToString().TrimEnd(); + } + catch (Exception ex) + { + return $"Error: {ex.Message}"; + } + } + + [XAiMcpTool(Description = "Detect and extract all date-like patterns from a free text. Supports Gregorian (2024-11-05), Persian (1403/08/15), Hijri (1446/05/03), ISO 8601, and month-name forms.")] + public static string DetectDates( + [XAiMcpToolParam(Description = "Free text that may contain dates.")] + string text, + [XAiMcpToolParam(Description = "Optional: hint for the primary calendar (Gregorian, Persian, Hijri). Leave empty for auto-detection.", Required = false)] + string calendarHint = null + ) + { + // + if (string.IsNullOrWhiteSpace(text)) + { + return "No text provided."; + } + + // + var patterns = new (string Name, Regex Pattern)[] + { + ("ISO8601", new Regex(@"\b\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}(?:\.\d+)?(?:Z|[+-]\d{2}:?\d{2})?\b")), + ("NumericYMD", new Regex(@"\b\d{4}[/\-\.]\d{1,2}[/\-\.]\d{1,2}\b")), + ("NumericDMY", new Regex(@"\b\d{1,2}[/\-\.]\d{1,2}[/\-\.]\d{2,4}\b")), + ("PersianMonth", new Regex(@"\b\d{1,2}\s+(فروردین|اردیبهشت|خرداد|تیر|مرداد|شهریور|مهر|آبان|آذر|دی|بهمن|اسفند)\s+\d{4}\b")), + ("EnglishMonth", new Regex(@"\b\d{1,2}\s+(January|February|March|April|May|June|July|August|September|October|November|December)\s+\d{4}\b", RegexOptions.IgnoreCase)), + }; + + // + var found = new List(); + var sb = new StringBuilder(); + foreach (var (name, pattern) in patterns) + { + // + foreach (Match m in pattern.Matches(text)) + { + // + if (!found.Contains(m.Value)) + { + // + found.Add(m.Value); + sb.AppendLine($"• {m.Value} [{name}]"); + } + } + } + + // + return found.Count == 0 + ? "No date pattern detected." + : $"Detected {found.Count} date(s):\n{sb.ToString().TrimEnd()}"; + } + + [XAiMcpTool(Description = "Parse a single date string. Returns the detected calendar, plus normalized Gregorian (ISO 8601), Persian, Hijri representations, and Unix timestamp.")] + public static string ParseDate( + [XAiMcpToolParam(Description = "Date string like '1403/08/15' or '2024-11-05'.")] + string date, + [XAiMcpToolParam(Description = "Optional: calendar hint (Gregorian, Persian, Hijri). Leave empty for auto-detect.", Required = false)] + string calendarHint = null + ) + { + // + try + { + // + var dt = ParseDateToGregorian(date, calendarHint); + return BuildReport(dt); + } + catch (Exception ex) + { + return $"Error: {ex.Message}"; + } + } + + [XAiMcpTool(Description = "Convert a date from one calendar to another. Supported calendars: Gregorian, Persian (Jalali/Shamsi), Hijri (Islamic).")] + public static string ConvertDate( + [XAiMcpToolParam(Description = "Date string in the source calendar.")] + string date, + [XAiMcpToolParam(Description = "Source calendar: Gregorian, Persian, or Hijri.")] + string fromCalendar, + [XAiMcpToolParam(Description = "Target calendar: Gregorian, Persian, or Hijri.")] + string toCalendar + ) + { + // + try + { + // + var greg = ParseDateToGregorian(date, fromCalendar); + var target = NormalizeCalendarName(toCalendar); + var cal = GetCalendar(target); + + // + return $"{cal.GetYear(greg):D4}/{cal.GetMonth(greg):D2}/{cal.GetDayOfMonth(greg):D2}"; + } + catch (Exception ex) + { + return $"Error: {ex.Message}"; + } + } + + [XAiMcpTool(Description = "Calculate the difference between two dates. Returns total days, and a breakdown into years/months/days.")] + public static string DateDifference( + [XAiMcpToolParam(Description = "First date string.")] + string date1, + [XAiMcpToolParam(Description = "Second date string.")] + string date2, + [XAiMcpToolParam(Description = "Optional: calendar hint for both dates.", Required = false)] + string calendarHint = null + ) + { + // + try + { + // + var d1 = ParseDateToGregorian(date1, calendarHint); + var d2 = ParseDateToGregorian(date2, calendarHint); + var span = d2 - d1; + + // + return $"Difference: {span.Days} days (= {span.Days / 365} years + {(span.Days % 365) / 30} months + {(span.Days % 365) % 30} days)"; + } + catch (Exception ex) + { + return $"Error: {ex.Message}"; + } + } + + [XAiMcpTool(Description = "Convert a date string to Unix timestamp (seconds since 1970-01-01 UTC).")] + public static string ToUnixTimestamp( + [XAiMcpToolParam(Description = "Date string.")] + string date, + [XAiMcpToolParam(Description = "Optional: calendar hint (Gregorian, Persian, Hijri).", Required = false)] + string calendarHint = null + ) + { + // + try + { + // + var dt = ParseDateToGregorian(date, calendarHint); + var ts = new DateTimeOffset(dt, TimeSpan.Zero).ToUnixTimeSeconds(); + + // + return ts.ToString(); + } + catch (Exception ex) + { + return $"Error: {ex.Message}"; + } + } + + [XAiMcpTool(Description = "Convert a Unix timestamp (seconds since 1970-01-01 UTC) back to a date string in the specified calendar.")] + public static string FromUnixTimestamp( + [XAiMcpToolParam(Description = "Unix timestamp in seconds.")] + long timestamp, + [XAiMcpToolParam(Description = "Optional: target calendar (Gregorian, Persian, Hijri). Defaults to Gregorian.", Required = false)] + string targetCalendar = null + ) + { + // + try + { + // + var dt = DateTimeOffset.FromUnixTimeSeconds(timestamp).UtcDateTime; + var calName = NormalizeCalendarName(targetCalendar) ?? "Gregorian"; + if (calName == "Gregorian") + { + return dt.ToString("yyyy-MM-dd HH:mm:ss 'UTC'"); + } + + // + var c = GetCalendar(calName); + return $"{c.GetYear(dt):D4}/{c.GetMonth(dt):D2}/{c.GetDayOfMonth(dt):D2}"; + } + catch (Exception ex) + { + return $"Error: {ex.Message}"; + } + } + + // + #region Private ... + private static string BuildReport(DateTime greg) + { + // + var pc = new PersianCalendar(); + var hc = new UmAlQuraCalendar(); + var sb = new StringBuilder(); + + // + sb.AppendLine($"Gregorian: {greg:yyyy-MM-dd}"); + sb.AppendLine($"Persian: {pc.GetYear(greg):D4}/{pc.GetMonth(greg):D2}/{pc.GetDayOfMonth(greg):D2}"); + sb.AppendLine($"Hijri: {hc.GetYear(greg):D4}/{hc.GetMonth(greg):D2}/{hc.GetDayOfMonth(greg):D2}"); + sb.AppendLine($"ISO 8601: {greg:yyyy-MM-ddTHH:mm:ss.fffZ}"); + sb.AppendLine($"Unix: {new DateTimeOffset(greg, TimeSpan.Zero).ToUnixTimeSeconds()}"); + + // + return sb.ToString().TrimEnd(); + } + + private static DateTime ParseDateToGregorian(string date, string calendarHint) + { + // + if (string.IsNullOrWhiteSpace(date)) + { + throw new ArgumentException("date is empty"); + } + + // + var m = Regex.Match(date.Trim(), @"^(?\d{4})[/\-\.](?\d{1,2})[/\-\.](?\d{1,2})$"); + if (!m.Success) + { + throw new FormatException($"Unrecognized date format: '{date}'. Expected yyyy/MM/dd."); + } + + // + var y = int.Parse(m.Groups["y"].Value); + var mo = int.Parse(m.Groups["m"].Value); + var d = int.Parse(m.Groups["d"].Value); + + // + var calName = NormalizeCalendarName(calendarHint) ?? AutoDetectCalendar(y); + return calName switch + { + // + "Gregorian" => new DateTime(y, mo, d), + "Persian" => new PersianCalendar().ToDateTime(y, mo, d, 0, 0, 0, 0), + "Hijri" => new UmAlQuraCalendar().ToDateTime(y, mo, d, 0, 0, 0, 0), + _ => throw new ArgumentException($"Unknown calendar: {calendarHint}") + }; + } + + private static string NormalizeCalendarName(string name) + { + // + if (string.IsNullOrWhiteSpace(name)) + { + return null; + } + + // + var n = name.Trim().ToLowerInvariant(); + return n switch + { + // + "gregorian" or "میلادی" or "g" => "Gregorian", + "persian" or "jalali" or "shamsi" or "شمسی" or "جلالی" or "p" => "Persian", + "hijri" or "islamic" or "قمری" or "هجری" or "h" => "Hijri", + _ => throw new ArgumentException($"Unknown calendar: {name}. Use Gregorian, Persian, or Hijri.") + }; + } + + private static string AutoDetectCalendar(int year) + { + // + if (year >= 1900 && year <= 2100) + { + return "Gregorian"; + } + + // + if (year >= 1300 && year <= 1499) + { + return "Persian"; + } + + // + return "Gregorian"; + } + + private static TimeZoneInfo ResolveTimezone(string timezoneId) + { + // + if (timezoneId.IsNullOrEmpty()) + { + timezoneId = "UTC"; + } + + // + try + { + return TZConvert.GetTimeZoneInfo(timezoneId); + } + catch + { + return TimeZoneInfo.Utc; + } + } + + private static Calendar GetCalendar(string name) => name switch + { + // + "Gregorian" => new GregorianCalendar(), + "Persian" => new PersianCalendar(), + "Hijri" => new UmAlQuraCalendar(), + _ => throw new ArgumentException($"Unknown calendar: {name}") + }; + #endregion + } +} + +### FILE: C:\Users\SaherElm\Documents\Projects\xSaherelmWorkspace\xAiMcpServer\Tools\XEchoTools.cs + + +using xAiModels.Attributes; + +namespace xAiMcpServer.Tools +{ + [XAiMcpToolType] + public static class XEchoTools + { + [XAiMcpTool(Description = "Echoes the string back to the client give message in string")] + public static string Echo( + [XAiMcpToolParam(Description = "string value which specified message")] + string message + ) + { + // + var result = $"hello {message}"; + return result; + } + } +} + +### FILE: C:\Users\SaherElm\Documents\Projects\xSaherelmWorkspace\xAiMcpServer\Tools\XLinkExtractionTool.cs + +using System; +using System.Net; +using System.Linq; +using System.Net.Http; +using xIdentityHelper; +using HtmlAgilityPack; +using System.Threading; +using xCommons.Extensions; +using xAiMcpServer.Models; +using xAiModels.Attributes; +using xExceptions.Constants; +using System.Threading.Tasks; +using System.Collections.Generic; +using xAiMcpServer.Configurations; +using Microsoft.Extensions.Logging; +using System.Text.RegularExpressions; + +namespace xAiMcpServer.Tools +{ + [XAiMcpToolType] + public class XLinkExtractionTool + { + // + private static readonly Regex UrlRegex = new( + @"\b(?:https?://|www\.)[^\s<>""'{}|\\^`\[\]]+", + RegexOptions.Compiled | RegexOptions.IgnoreCase); + + // + private readonly ILogger logger; + private readonly IHttpClientFactory httpClientFactory; + private readonly XAiMcpLinkExtractionToolConfiguration configuration; + + public XLinkExtractionTool( + ILogger logger, + IHttpClientFactory httpClientFactory, + XAiMcpLinkExtractionToolConfiguration configuration + ) + { + // + if (configuration.IsNull()) + { + XException.InvalidConfiguration.Throw(); + } + + // + this.logger = logger; + this.configuration = configuration; + this.httpClientFactory = httpClientFactory; + } + + [XAiMcpTool( + RequiresAuthentication = true, + RequiredPolicy = XPolicies.EnabledUser, + Description = "Extracts all valid HTTP/HTTPS links from the given content.")] + public IReadOnlyList ExtractLinks( + [XAiMcpToolParam( + Required = true, + Description = "Raw text or HTML to scan for links.")] + string content + ) + { + // + var result = new List(); + + // + // Validate ... + if (content.IsNullOrEmpty()) + { + return result; + } + + // + result = [.. UrlRegex + .Matches(content) + .Select(m => m.Value.TrimEnd('.', ',', ')', ']', ';')) + .Where(IsValidUrl) + .Distinct(StringComparer.OrdinalIgnoreCase) + .Select(u => new XExtractedLink + { + Url = u, + Text = u, + IsRelative = u.StartsWith("www."), + })]; + + // + return result; + } + + [XAiMcpTool( + RequiresAuthentication = true, + RequiredPolicy = XPolicies.EnabledUser, + Description = "Downloads a web page and extracts its readable plain text (noise removed).")] + public async Task ReadLinkContent( + [XAiMcpToolParam( + Required = true, + Description = "Absolute http/https URL.")] + string url, + [XAiMcpToolParam( + Required = false, + Description = "Optional. Max chars to return.")] + int? maxChars = null, + CancellationToken cancellationToken = default + ) + { + // + // Normalize ... + if (!maxChars.HasValue) + { + maxChars = configuration.MaxChars; + } + + // + var result = new XLinkContentResult(); + + // + // Validate url ... + if (url.IsNullOrEmpty() || !IsValidUrl(url)) + { + // + result = new XLinkContentResult + { + Url = url, + Error = "Invalid URL" + }; + + // + return result; + } + + // + try + { + // + var client = httpClientFactory + .CreateClient(nameof(XLinkExtractionTool)); + + // + using var response = await client + .GetAsync(url, HttpCompletionOption.ResponseHeadersRead, cancellationToken); + response.EnsureSuccessStatusCode(); + + // + var contentType = response.Content.Headers.ContentType?.MediaType ?? "text/html"; + if (!contentType.Contains("html", StringComparison.OrdinalIgnoreCase) && + !contentType.Contains("text", StringComparison.OrdinalIgnoreCase)) + { + // + result = new XLinkContentResult + { + Url = url, + ContentType = contentType, + Error = $"Unsupported content type: {contentType}" + }; + + // + return result; + } + + // + var html = await response.Content.ReadAsStringAsync(); + var doc = new HtmlDocument(); + doc.LoadHtml(html); + + // + // Remove noise ... + foreach (var n in doc.DocumentNode + .SelectNodes("//script|//style|//noscript|//iframe|//svg") ?? Enumerable.Empty()) + { + n.Remove(); + } + + // + var title = doc.DocumentNode.SelectSingleNode("//title")?.InnerText?.Trim() ?? ""; + var body = doc.DocumentNode.SelectSingleNode("//body")?.InnerText ?? ""; + var clean = Regex.Replace(WebUtility.HtmlDecode(body), @"\s{2,}", " ").Trim(); + + // + var truncated = clean.Length > maxChars.Value; + if (truncated) + { + clean = clean[..maxChars.Value]; + } + + // + result = new XLinkContentResult + { + Url = url, + Text = clean, + Error = null, + Title = title, + Length = clean.Length, + Truncated = truncated, + ContentType = contentType + }; + + // + return result; + } + catch (Exception ex) + { + // + logger.LogWarning(ex, "Failed to read link {Url}", url); + var resut = new XLinkContentResult + { + Url = url, + Error = ex.Message + }; + + // + return result; + } + } + + [XAiMcpTool( + RequiresAuthentication = true, + RequiredPolicy = XPolicies.EnabledUser, + Description = "Extracts links from content AND reads the readable text of each one (max N).")] + public async Task ExtractAndRead( + [XAiMcpToolParam( + Required = true, + Description = "Raw text or HTML to scan for links.")] + string content, + [XAiMcpToolParam( + Required = false, + Description = "Optional. Max link to extract content.")] + int? maxLinks = null, + [XAiMcpToolParam( + Required = false, + Description = "Optional. Max chars to extract from each detected link's content.")] + int? maxCharsPerLink = null, + CancellationToken cancellationToken = default + ) + { + // + // Mormalize ... + if (!maxLinks.HasValue) + { + maxLinks = configuration.MaxLinks; + } + if (!maxCharsPerLink.HasValue) + { + maxCharsPerLink = configuration.MaxChars; + } + + // + var links = ExtractLinks(content).Take(maxLinks.Value).ToList(); + var contents = new List(links.Count); + foreach (var link in links) + { + // + cancellationToken.ThrowIfCancellationRequested(); + var linkContent = await ReadLinkContent( + link.Url, + maxCharsPerLink, + cancellationToken + ); + + // + contents.Add(linkContent); + } + + // + var result = new XLinkBundle + { + Linkes = links, + Contents = contents + }; + + // + return result; + } + + // + #region Private ... + private static bool IsValidUrl(string? raw) + => Uri.TryCreate(raw, UriKind.Absolute, out var u) + && (u.Scheme == Uri.UriSchemeHttp || u.Scheme == Uri.UriSchemeHttps); + #endregion + } +} + +### FILE: C:\Users\SaherElm\Documents\Projects\xSaherelmWorkspace\xAiMcpServer\Tools\XUserTools.cs + +using xIdentityHelper; +using xModels.Extensions; +using xCommons.Extensions; +using xAiModels.Attributes; +using xAiService.Interfaces; +using System.Threading.Tasks; +using xIdentityService.Interfaces; + +namespace xAiMcpServer.Tools +{ + [XAiMcpToolType] + public class XUserTools + { + // + private readonly IXPersonService personService; + private readonly IXAiMcpUserContext userContext; + + public XUserTools( + IXAiMcpUserContext userContext, + IXPersonService personService + ) + { + // + this.userContext = userContext; + this.personService = personService; + } + + [XAiMcpTool( + RequiresAuthentication = true, + RequiredPolicy = XPolicies.EnabledUser, + Description = "Get information about the currently logged-in user.")] + public async Task WhoAmI() + { + // + var user = userContext.UserInfo; + if (user.IsNullOrDefault()) + { + return "Anonymous"; + } + + // + var person = await personService.GetPerson(user.UserId); + + // + return person?.GetFullname() ?? user.UserId; + } + } +} + +### FILE: C:\Users\SaherElm\Documents\Projects\xSaherelmWorkspace\xAiMcpServer\Tools\XWebSearchTool.cs + +using System; +using System.Text; +using xIdentityHelper; +using System.Threading; +using xCommons.Extensions; +using xAiModels.Attributes; +using System.Threading.Tasks; +using xAiMcpServer.Interfaces; + +namespace xAiMcpServer.Tools +{ + [XAiMcpToolType] + public class XWebSearchTool + { + private readonly IXAiMcpWebSearchService webSearchService; + + public XWebSearchTool( + IXAiMcpWebSearchService webSearchService + ) + { + this.webSearchService = webSearchService; + } + + /// + /// Search the web via Search Engine for the LATEST info on any topic. + /// No API key required. Use this whenever the user asks about + /// current events, recent releases, or time-sensitive facts. + /// + [XAiMcpTool("web_search", + Description = "Search the web via Search Engine and return the most recent results (title, URL, snippet). ALWAYS use this tool when the user asks about current events, latest releases, new concepts, or anything that may have changed recently. Returns up to 10 results.", + RequiresAuthentication = true, + RequiredPolicy = XPolicies.EnabledUser)] + public async Task SearchWeb( + [XAiMcpToolParam( + Description = "Search query. Be specific; include year or keywords (e.g. 'latest ASP.NET Core 9 features 2025').")] + string query, + [XAiMcpToolParam( + Description = "Max results to return (1-10). Default: 5.", + Required = false)] + int? maxResults = null, + [XAiMcpToolParam( + Description = "Region code for localized results (e.g. 'us-en', 'ir-fa', 'wt-wt' for worldwide). Default: wt-wt.", + Required = false)] + string region = null, + CancellationToken cancellationToken = default + ) + { + // + if (query.IsNullOrEmpty()) + { + return "Error: query is empty."; + } + + // + try + { + // + var results = await webSearchService + .SearchAsync( + query.Trim(), + maxResults.HasValue ? maxResults.Value : 5, + region, + cancellationToken + ); + if (results.Count == 0) + { + return $"No results found for: {query}. " + "Search may be rate-limiting; try again in a few seconds."; + } + + // + var sb = new StringBuilder(); + sb.AppendLine($"## Web Search Results for: {query}"); + sb.AppendLine(); + + // + foreach (var r in results) + { + // + sb.AppendLine($"### [{r.Rank}] {r.Title}"); + sb.AppendLine($"- URL: {r.Url}"); + if (!r.Snippet.IsNullOrEmpty()) + { + sb.AppendLine($"- Snippet: {r.Snippet}"); + } + sb.AppendLine(); + } + + // + var result = sb.ToString(); + return result; + } + catch (OperationCanceledException) { throw; } + catch (Exception ex) + { + return $"Web search failed: {ex.Message}"; + } + } + } +} diff --git a/Documents/GeneratedContext/xDashboard-xAiModels-20261106_205448.txt b/Documents/GeneratedContext/xDashboard-xAiModels-20261107_225130.txt similarity index 96% rename from Documents/GeneratedContext/xDashboard-xAiModels-20261106_205448.txt rename to Documents/GeneratedContext/xDashboard-xAiModels-20261107_225130.txt index 9c70791..65a9283 100644 --- a/Documents/GeneratedContext/xDashboard-xAiModels-20261106_205448.txt +++ b/Documents/GeneratedContext/xDashboard-xAiModels-20261107_225130.txt @@ -1,5 +1,5 @@ -### FILE: C:\Users\saherelm\Documents\Projects\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\saherelm\Documents\Projects\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\saherelm\Documents\Projects\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\saherelm\Documents\Projects\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\saherelm\Documents\Projects\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\saherelm\Documents\Projects\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\saherelm\Documents\Projects\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\saherelm\Documents\Projects\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\saherelm\Documents\Projects\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\saherelm\Documents\Projects\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\saherelm\Documents\Projects\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\saherelm\Documents\Projects\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\saherelm\Documents\Projects\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\saherelm\Documents\Projects\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\saherelm\Documents\Projects\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\saherelm\Documents\Projects\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\saherelm\Documents\Projects\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\saherelm\Documents\Projects\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\saherelm\Documents\Projects\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\saherelm\Documents\Projects\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; @@ -1115,7 +1115,7 @@ namespace xAiModels.Extensions } } -### FILE: C:\Users\saherelm\Documents\Projects\xSaherelmWorkspace\Modules\xAiModels\Extensions\ChatRoleExtensions.cs +### FILE: C:\Users\SaherElm\Documents\Projects\xSaherelmWorkspace\Modules\xAiModels\Extensions\ChatRoleExtensions.cs using xAiModels.Constants; using xCommons.Extensions; @@ -1295,7 +1295,7 @@ namespace xAiModels.Extensions } } -### FILE: C:\Users\saherelm\Documents\Projects\xSaherelmWorkspace\Modules\xAiModels\Extensions\XAiModelsExtensions.cs +### FILE: C:\Users\SaherElm\Documents\Projects\xSaherelmWorkspace\Modules\xAiModels\Extensions\XAiModelsExtensions.cs using System; using System.Linq; @@ -1856,7 +1856,7 @@ namespace xAiModels.Extensions } } -### FILE: C:\Users\saherelm\Documents\Projects\xSaherelmWorkspace\Modules\xAiModels\Extensions\XEmbeddingExtensions.cs +### FILE: C:\Users\SaherElm\Documents\Projects\xSaherelmWorkspace\Modules\xAiModels\Extensions\XEmbeddingExtensions.cs using System; using xCommons.Extensions; @@ -1913,7 +1913,7 @@ namespace xAiModels.Extensions } } -### FILE: C:\Users\saherelm\Documents\Projects\xSaherelmWorkspace\Modules\xAiModels\Helpers\VectorHelper.cs +### FILE: C:\Users\SaherElm\Documents\Projects\xSaherelmWorkspace\Modules\xAiModels\Helpers\VectorHelper.cs using System; using xCommons.Extensions; @@ -1990,7 +1990,7 @@ namespace xAiModels.Helpers } } -### FILE: C:\Users\saherelm\Documents\Projects\xSaherelmWorkspace\Modules\xAiModels\Helpers\XAiMcpHeaderBuilder.cs +### FILE: C:\Users\SaherElm\Documents\Projects\xSaherelmWorkspace\Modules\xAiModels\Helpers\XAiMcpHeaderBuilder.cs using xCommons.Constants; using xCommons.Extensions; @@ -2067,7 +2067,7 @@ namespace xAiModels.Helpers } } -### FILE: C:\Users\saherelm\Documents\Projects\xSaherelmWorkspace\Modules\xAiModels\Helpers\XAiMcpSseReader.cs +### FILE: C:\Users\SaherElm\Documents\Projects\xSaherelmWorkspace\Modules\xAiModels\Helpers\XAiMcpSseReader.cs using System; using System.IO; @@ -2156,7 +2156,7 @@ namespace xAiModels.Helpers } } -### FILE: C:\Users\saherelm\Documents\Projects\xSaherelmWorkspace\Modules\xAiModels\Helpers\XAiModelsHelper.cs +### FILE: C:\Users\SaherElm\Documents\Projects\xSaherelmWorkspace\Modules\xAiModels\Helpers\XAiModelsHelper.cs using System; using GraphQL.Types; @@ -3509,7 +3509,7 @@ namespace xAiModels.Helpers } } -### FILE: C:\Users\saherelm\Documents\Projects\xSaherelmWorkspace\Modules\xAiModels\Interfaces\IXAiConversationTitleResourceProvider.cs +### FILE: C:\Users\SaherElm\Documents\Projects\xSaherelmWorkspace\Modules\xAiModels\Interfaces\IXAiConversationTitleResourceProvider.cs using xStringService.Interfaces; @@ -3519,7 +3519,7 @@ namespace xAiModels.Interfaces { } } -### FILE: C:\Users\saherelm\Documents\Projects\xSaherelmWorkspace\Modules\xAiModels\Interfaces\IXAiDataProvider.cs +### FILE: C:\Users\SaherElm\Documents\Projects\xSaherelmWorkspace\Modules\xAiModels\Interfaces\IXAiDataProvider.cs using System; using xModels.Dtos; @@ -3904,7 +3904,7 @@ namespace xAiModels.Interfaces } } -### FILE: C:\Users\saherelm\Documents\Projects\xSaherelmWorkspace\Modules\xAiModels\Interfaces\IXAiProjectDescriptionResourceProvider.cs +### FILE: C:\Users\SaherElm\Documents\Projects\xSaherelmWorkspace\Modules\xAiModels\Interfaces\IXAiProjectDescriptionResourceProvider.cs using xStringService.Interfaces; @@ -3914,7 +3914,7 @@ namespace xAiModels.Interfaces { } } -### FILE: C:\Users\saherelm\Documents\Projects\xSaherelmWorkspace\Modules\xAiModels\Interfaces\IXAiProjectTitleResourceProvider.cs +### FILE: C:\Users\SaherElm\Documents\Projects\xSaherelmWorkspace\Modules\xAiModels\Interfaces\IXAiProjectTitleResourceProvider.cs using xStringService.Interfaces; @@ -3924,7 +3924,7 @@ namespace xAiModels.Interfaces { } } -### FILE: C:\Users\saherelm\Documents\Projects\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; @@ -3937,7 +3937,7 @@ namespace xAiModels.Interfaces.Dtos { } } -### FILE: C:\Users\saherelm\Documents\Projects\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; @@ -4008,7 +4008,7 @@ namespace xAiModels.Interfaces.Dtos } } -### FILE: C:\Users\saherelm\Documents\Projects\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; @@ -4022,7 +4022,7 @@ namespace xAiModels.Interfaces.Dtos { } } -### FILE: C:\Users\saherelm\Documents\Projects\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; @@ -4035,7 +4035,7 @@ namespace xAiModels.Interfaces.Dtos { } } -### FILE: C:\Users\saherelm\Documents\Projects\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; @@ -4048,7 +4048,7 @@ namespace xAiModels.Interfaces.Dtos { } } -### FILE: C:\Users\saherelm\Documents\Projects\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; @@ -4062,7 +4062,7 @@ namespace xAiModels.Interfaces.Dtos { } } -### FILE: C:\Users\saherelm\Documents\Projects\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; @@ -4075,7 +4075,7 @@ namespace xAiModels.Interfaces.Dtos { } } -### FILE: C:\Users\saherelm\Documents\Projects\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; @@ -4138,7 +4138,7 @@ namespace xAiModels.Interfaces.Dtos } } -### FILE: C:\Users\saherelm\Documents\Projects\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; @@ -4152,7 +4152,7 @@ namespace xAiModels.Interfaces.Dtos { } } -### FILE: C:\Users\saherelm\Documents\Projects\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; @@ -4165,7 +4165,7 @@ namespace xAiModels.Interfaces.Dtos { } } -### FILE: C:\Users\saherelm\Documents\Projects\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; @@ -4244,7 +4244,7 @@ namespace xAiModels.Interfaces.Dtos } } -### FILE: C:\Users\saherelm\Documents\Projects\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; @@ -4258,7 +4258,7 @@ namespace xAiModels.Interfaces.Dtos { } } -### FILE: C:\Users\saherelm\Documents\Projects\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; @@ -4271,7 +4271,7 @@ namespace xAiModels.Interfaces.Dtos { } } -### FILE: C:\Users\saherelm\Documents\Projects\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; @@ -4285,7 +4285,7 @@ namespace xAiModels.Interfaces.Dtos } } -### FILE: C:\Users\saherelm\Documents\Projects\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; @@ -4299,7 +4299,7 @@ namespace xAiModels.Interfaces.Dtos { } } -### FILE: C:\Users\saherelm\Documents\Projects\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; @@ -4371,7 +4371,7 @@ namespace xAiModels.Interfaces.Enrichers } } -### FILE: C:\Users\saherelm\Documents\Projects\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; @@ -4405,7 +4405,7 @@ namespace xAiModels.Interfaces.Enrichers } } -### FILE: C:\Users\saherelm\Documents\Projects\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; @@ -4466,7 +4466,7 @@ namespace xAiModels.Interfaces.Enrichers } } -### FILE: C:\Users\saherelm\Documents\Projects\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; @@ -4543,7 +4543,7 @@ namespace xAiModels.Interfaces.Enrichers } } -### FILE: C:\Users\saherelm\Documents\Projects\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; @@ -4604,7 +4604,7 @@ namespace xAiModels.Interfaces.Enrichers } } -### FILE: C:\Users\saherelm\Documents\Projects\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; @@ -4616,7 +4616,7 @@ namespace xAiModels.Interfaces.Entities { } } -### FILE: C:\Users\saherelm\Documents\Projects\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; @@ -4628,7 +4628,7 @@ namespace xAiModels.Interfaces.Entities { } } -### FILE: C:\Users\saherelm\Documents\Projects\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; @@ -4640,7 +4640,7 @@ namespace xAiModels.Interfaces.Entities { } } -### FILE: C:\Users\saherelm\Documents\Projects\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; @@ -4652,7 +4652,7 @@ namespace xAiModels.Interfaces.Entities { } } -### FILE: C:\Users\saherelm\Documents\Projects\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; @@ -4663,7 +4663,7 @@ namespace xAiModels.Interfaces.Entities { } } -### FILE: C:\Users\saherelm\Documents\Projects\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; @@ -4676,7 +4676,7 @@ namespace xAiModels.Interfaces.Entities { } } -### FILE: C:\Users\saherelm\Documents\Projects\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; @@ -4688,7 +4688,7 @@ namespace xAiModels.Interfaces.Entities { } } -### FILE: C:\Users\saherelm\Documents\Projects\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; @@ -4703,7 +4703,7 @@ namespace xAiModels.Interfaces.Entities } } -### FILE: C:\Users\saherelm\Documents\Projects\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; @@ -4715,7 +4715,7 @@ namespace xAiModels.Interfaces.Entities { } } -### FILE: C:\Users\saherelm\Documents\Projects\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; @@ -4727,7 +4727,7 @@ namespace xAiModels.Interfaces.Entities { } } -### FILE: C:\Users\saherelm\Documents\Projects\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; @@ -4739,7 +4739,7 @@ namespace xAiModels.Interfaces.Entities { } } -### FILE: C:\Users\saherelm\Documents\Projects\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; @@ -4750,7 +4750,7 @@ namespace xAiModels.Interfaces.Entities public interface IXAiMcpServerRepository : IXBaseRepository { } } -### FILE: C:\Users\saherelm\Documents\Projects\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; @@ -4761,7 +4761,7 @@ namespace xAiModels.Interfaces.Entities { } } -### FILE: C:\Users\saherelm\Documents\Projects\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; @@ -4774,7 +4774,7 @@ namespace xAiModels.Interfaces.Entities { } } -### FILE: C:\Users\saherelm\Documents\Projects\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; @@ -4786,7 +4786,7 @@ namespace xAiModels.Interfaces.Entities { } } -### FILE: C:\Users\saherelm\Documents\Projects\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; @@ -4798,7 +4798,7 @@ namespace xAiModels.Interfaces.Entities { } } -### FILE: C:\Users\saherelm\Documents\Projects\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; @@ -4810,7 +4810,7 @@ namespace xAiModels.Interfaces.Entities { } } -### FILE: C:\Users\saherelm\Documents\Projects\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; @@ -4822,7 +4822,7 @@ namespace xAiModels.Interfaces.Entities { } } -### FILE: C:\Users\saherelm\Documents\Projects\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; @@ -4834,7 +4834,7 @@ namespace xAiModels.Interfaces.Entities { } } -### FILE: C:\Users\saherelm\Documents\Projects\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; @@ -4845,7 +4845,7 @@ namespace xAiModels.Interfaces.Entities { } } -### FILE: C:\Users\saherelm\Documents\Projects\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; @@ -4858,7 +4858,7 @@ namespace xAiModels.Interfaces.Entities { } } -### FILE: C:\Users\saherelm\Documents\Projects\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; @@ -4870,7 +4870,7 @@ namespace xAiModels.Interfaces.Entities { } } -### FILE: C:\Users\saherelm\Documents\Projects\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; @@ -4882,7 +4882,7 @@ namespace xAiModels.Interfaces.Entities { } } -### FILE: C:\Users\saherelm\Documents\Projects\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; @@ -4894,7 +4894,7 @@ namespace xAiModels.Interfaces.Entities { } } -### FILE: C:\Users\saherelm\Documents\Projects\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; @@ -4906,7 +4906,7 @@ namespace xAiModels.Interfaces.Entities { } } -### FILE: C:\Users\saherelm\Documents\Projects\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; @@ -4918,7 +4918,7 @@ namespace xAiModels.Interfaces.Entities { } } -### FILE: C:\Users\saherelm\Documents\Projects\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; @@ -4929,7 +4929,7 @@ namespace xAiModels.Interfaces.Entities { } } -### FILE: C:\Users\saherelm\Documents\Projects\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; @@ -4942,7 +4942,7 @@ namespace xAiModels.Interfaces.Entities { } } -### FILE: C:\Users\saherelm\Documents\Projects\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; @@ -4954,7 +4954,7 @@ namespace xAiModels.Interfaces.Entities { } } -### FILE: C:\Users\saherelm\Documents\Projects\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; @@ -4966,7 +4966,7 @@ namespace xAiModels.Interfaces.Entities { } } -### FILE: C:\Users\saherelm\Documents\Projects\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; @@ -4978,7 +4978,7 @@ namespace xAiModels.Interfaces.Entities { } } -### FILE: C:\Users\saherelm\Documents\Projects\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; @@ -4990,7 +4990,7 @@ namespace xAiModels.Interfaces.Entities { } } -### FILE: C:\Users\saherelm\Documents\Projects\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; @@ -5002,7 +5002,7 @@ namespace xAiModels.Interfaces.Entities { } } -### FILE: C:\Users\saherelm\Documents\Projects\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; @@ -5013,7 +5013,7 @@ namespace xAiModels.Interfaces.Entities { } } -### FILE: C:\Users\saherelm\Documents\Projects\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; @@ -5026,7 +5026,7 @@ namespace xAiModels.Interfaces.Entities { } } -### FILE: C:\Users\saherelm\Documents\Projects\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; @@ -5038,7 +5038,7 @@ namespace xAiModels.Interfaces.Entities { } } -### FILE: C:\Users\saherelm\Documents\Projects\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; @@ -5058,7 +5058,7 @@ namespace xAiModels.Models } } -### FILE: C:\Users\saherelm\Documents\Projects\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; @@ -5082,7 +5082,7 @@ namespace xAiModels.Models } } -### FILE: C:\Users\saherelm\Documents\Projects\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; @@ -5110,7 +5110,7 @@ namespace xAiModels.Models } } -### FILE: C:\Users\saherelm\Documents\Projects\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; @@ -5130,7 +5130,7 @@ namespace xAiModels.Models } } -### FILE: C:\Users\saherelm\Documents\Projects\xSaherelmWorkspace\Modules\xAiModels\Models\XAiMcpToolDescriptor.cs +### FILE: C:\Users\SaherElm\Documents\Projects\xSaherelmWorkspace\Modules\xAiModels\Models\XAiMcpToolDescriptor.cs using System; using System.Threading; @@ -5150,7 +5150,7 @@ namespace xAiModels.Models } } -### FILE: C:\Users\saherelm\Documents\Projects\xSaherelmWorkspace\Modules\xAiModels\Models\XAiModelDescriptor.cs +### FILE: C:\Users\SaherElm\Documents\Projects\xSaherelmWorkspace\Modules\xAiModels\Models\XAiModelDescriptor.cs using xAiModels.Constants; @@ -5188,7 +5188,7 @@ namespace xAiModels.Models } } -### FILE: C:\Users\saherelm\Documents\Projects\xSaherelmWorkspace\Modules\xAiModels\Models\XAiPromptDescriptor.cs +### FILE: C:\Users\SaherElm\Documents\Projects\xSaherelmWorkspace\Modules\xAiModels\Models\XAiPromptDescriptor.cs namespace xAiModels.Models { @@ -5240,7 +5240,7 @@ namespace xAiModels.Models } } -### FILE: C:\Users\saherelm\Documents\Projects\xSaherelmWorkspace\Modules\xAiModels\Models\XAiResonseMessage.cs +### FILE: C:\Users\SaherElm\Documents\Projects\xSaherelmWorkspace\Modules\xAiModels\Models\XAiResonseMessage.cs using System; using xModels.Base; @@ -5259,7 +5259,7 @@ namespace xAiModels.Models } } -### FILE: C:\Users\saherelm\Documents\Projects\xSaherelmWorkspace\Modules\xAiModels\Models\XAiResponseRequest.cs +### FILE: C:\Users\SaherElm\Documents\Projects\xSaherelmWorkspace\Modules\xAiModels\Models\XAiResponseRequest.cs using System; using xAiModels.Constants; @@ -5303,7 +5303,7 @@ namespace xAiModels.Models } } -### FILE: C:\Users\saherelm\Documents\Projects\xSaherelmWorkspace\Modules\xAiModels\Models\XFileExtractionResult.cs +### FILE: C:\Users\SaherElm\Documents\Projects\xSaherelmWorkspace\Modules\xAiModels\Models\XFileExtractionResult.cs using System.Collections.Generic; @@ -5377,7 +5377,7 @@ namespace xAiModels.Models } } -### FILE: C:\Users\saherelm\Documents\Projects\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; @@ -5454,7 +5454,7 @@ namespace xAiModels.Models.Dtos } } -### FILE: C:\Users\saherelm\Documents\Projects\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; @@ -5516,7 +5516,7 @@ namespace xAiModels.Models.Dtos } } -### FILE: C:\Users\saherelm\Documents\Projects\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; @@ -5608,7 +5608,7 @@ namespace xAiModels.Models.Dtos } } -### FILE: C:\Users\saherelm\Documents\Projects\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; @@ -5675,7 +5675,7 @@ namespace xAiModels.Models.Dtos } } -### FILE: C:\Users\saherelm\Documents\Projects\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; @@ -5715,7 +5715,7 @@ namespace xAiModels.Models.Dtos } } -### FILE: C:\Users\saherelm\Documents\Projects\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; @@ -5733,7 +5733,7 @@ namespace xAiModels.Models.Dtos } } -### FILE: C:\Users\saherelm\Documents\Projects\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; @@ -5779,7 +5779,7 @@ namespace xAiModels.Models.Entities } } -### FILE: C:\Users\saherelm\Documents\Projects\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; @@ -5849,7 +5849,7 @@ namespace xAiModels.Models.Entities } } -### FILE: C:\Users\saherelm\Documents\Projects\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; @@ -5937,7 +5937,7 @@ namespace xAiModels.Models.Entities } } -### FILE: C:\Users\saherelm\Documents\Projects\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; @@ -5988,7 +5988,7 @@ namespace xAiModels.Models.Entities } } -### FILE: C:\Users\saherelm\Documents\Projects\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; @@ -6026,7 +6026,7 @@ namespace xAiModels.Models.Entities } } -### FILE: C:\Users\saherelm\Documents\Projects\xSaherelmWorkspace\Modules\xAiModels\Providers\XAiConversationEntityRegisterar.cs +### FILE: C:\Users\SaherElm\Documents\Projects\xSaherelmWorkspace\Modules\xAiModels\Providers\XAiConversationEntityRegisterar.cs using System; using xDataService.Providers; @@ -6064,7 +6064,7 @@ namespace xAiModels.Providers } } -### FILE: C:\Users\saherelm\Documents\Projects\xSaherelmWorkspace\Modules\xAiModels\Providers\XAiConversationTitleResourceProvider.cs +### FILE: C:\Users\SaherElm\Documents\Projects\xSaherelmWorkspace\Modules\xAiModels\Providers\XAiConversationTitleResourceProvider.cs using xAiModels.Constants; using xAiModels.Interfaces; @@ -6088,7 +6088,7 @@ namespace xAiModels.Providers } } -### FILE: C:\Users\saherelm\Documents\Projects\xSaherelmWorkspace\Modules\xAiModels\Providers\XAiDataProvider.cs +### FILE: C:\Users\SaherElm\Documents\Projects\xSaherelmWorkspace\Modules\xAiModels\Providers\XAiDataProvider.cs using System; using System.Linq; @@ -8541,7 +8541,7 @@ namespace xAiModels.Providers } } -### FILE: C:\Users\saherelm\Documents\Projects\xSaherelmWorkspace\Modules\xAiModels\Providers\XAiMcpServerEntityRegisterar .cs +### FILE: C:\Users\SaherElm\Documents\Projects\xSaherelmWorkspace\Modules\xAiModels\Providers\XAiMcpServerEntityRegisterar .cs using System; using xDataService.Providers; @@ -8579,7 +8579,7 @@ namespace xAiModels.Providers } } -### FILE: C:\Users\saherelm\Documents\Projects\xSaherelmWorkspace\Modules\xAiModels\Providers\XAiMessageEntityRegisterar.cs +### FILE: C:\Users\SaherElm\Documents\Projects\xSaherelmWorkspace\Modules\xAiModels\Providers\XAiMessageEntityRegisterar.cs using System; using xDataService.Providers; @@ -8617,7 +8617,7 @@ namespace xAiModels.Providers } } -### FILE: C:\Users\saherelm\Documents\Projects\xSaherelmWorkspace\Modules\xAiModels\Providers\XAiProjectDescriptionResourceProvider.cs +### FILE: C:\Users\SaherElm\Documents\Projects\xSaherelmWorkspace\Modules\xAiModels\Providers\XAiProjectDescriptionResourceProvider.cs using xAiModels.Constants; using xAiModels.Interfaces; @@ -8641,7 +8641,7 @@ namespace xAiModels.Providers } } -### FILE: C:\Users\saherelm\Documents\Projects\xSaherelmWorkspace\Modules\xAiModels\Providers\XAiProjectEntityRegisterar.cs +### FILE: C:\Users\SaherElm\Documents\Projects\xSaherelmWorkspace\Modules\xAiModels\Providers\XAiProjectEntityRegisterar.cs using System; using xDataService.Providers; @@ -8679,7 +8679,7 @@ namespace xAiModels.Providers } } -### FILE: C:\Users\saherelm\Documents\Projects\xSaherelmWorkspace\Modules\xAiModels\Providers\XAiProjectTitleResourceProvider.cs +### FILE: C:\Users\SaherElm\Documents\Projects\xSaherelmWorkspace\Modules\xAiModels\Providers\XAiProjectTitleResourceProvider.cs using xAiModels.Constants; using xAiModels.Interfaces; @@ -8703,7 +8703,7 @@ namespace xAiModels.Providers } } -### FILE: C:\Users\saherelm\Documents\Projects\xSaherelmWorkspace\Modules\xAiModels\Providers\XAiVectorEntityRegisterar.cs +### FILE: C:\Users\SaherElm\Documents\Projects\xSaherelmWorkspace\Modules\xAiModels\Providers\XAiVectorEntityRegisterar.cs using System; using xDataService.Providers; @@ -8741,7 +8741,7 @@ namespace xAiModels.Providers } } -### FILE: C:\Users\saherelm\Documents\Projects\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; @@ -8761,7 +8761,7 @@ namespace xAiModels.Providers.Dtos } } -### FILE: C:\Users\saherelm\Documents\Projects\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; @@ -8971,7 +8971,7 @@ namespace xAiModels.Providers.Dtos } } -### FILE: C:\Users\saherelm\Documents\Projects\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; @@ -9001,7 +9001,7 @@ namespace xAiModels.Providers.Dtos } } -### FILE: C:\Users\saherelm\Documents\Projects\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; @@ -9021,7 +9021,7 @@ namespace xAiModels.Providers.Dtos } } -### FILE: C:\Users\saherelm\Documents\Projects\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; @@ -9050,7 +9050,7 @@ namespace xAiModels.Providers.Dtos } } -### FILE: C:\Users\saherelm\Documents\Projects\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; @@ -9075,7 +9075,7 @@ namespace xAiModels.Providers.Dtos } } -### FILE: C:\Users\saherelm\Documents\Projects\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; @@ -9095,7 +9095,7 @@ namespace xAiModels.Providers.Dtos } } -### FILE: C:\Users\saherelm\Documents\Projects\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; @@ -9263,7 +9263,7 @@ namespace xAiModels.Providers.Dtos } } -### FILE: C:\Users\saherelm\Documents\Projects\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; @@ -9293,7 +9293,7 @@ namespace xAiModels.Providers.Dtos } } -### FILE: C:\Users\saherelm\Documents\Projects\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; @@ -9313,7 +9313,7 @@ namespace xAiModels.Providers.Dtos } } -### FILE: C:\Users\saherelm\Documents\Projects\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; @@ -9638,7 +9638,7 @@ namespace xAiModels.Providers.Dtos } } -### FILE: C:\Users\saherelm\Documents\Projects\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; @@ -9668,7 +9668,7 @@ namespace xAiModels.Providers.Dtos } } -### FILE: C:\Users\saherelm\Documents\Projects\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; @@ -9688,7 +9688,7 @@ namespace xAiModels.Providers.Dtos } } -### FILE: C:\Users\saherelm\Documents\Projects\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; @@ -9715,7 +9715,7 @@ namespace xAiModels.Providers.Dtos } } -### FILE: C:\Users\saherelm\Documents\Projects\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; @@ -9745,7 +9745,7 @@ namespace xAiModels.Providers.Dtos } } -### FILE: C:\Users\saherelm\Documents\Projects\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; @@ -9946,7 +9946,7 @@ namespace xAiModels.Providers.Enrichers } } -### FILE: C:\Users\saherelm\Documents\Projects\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; @@ -10028,7 +10028,7 @@ namespace xAiModels.Providers.Enrichers } } -### FILE: C:\Users\saherelm\Documents\Projects\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; @@ -10178,7 +10178,7 @@ namespace xAiModels.Providers.Enrichers } } -### FILE: C:\Users\saherelm\Documents\Projects\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; @@ -10485,7 +10485,7 @@ namespace xAiModels.Providers.Enrichers } } -### FILE: C:\Users\saherelm\Documents\Projects\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; @@ -10602,7 +10602,7 @@ namespace xAiModels.Providers.Enrichers } } -### FILE: C:\Users\saherelm\Documents\Projects\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; @@ -10632,7 +10632,7 @@ namespace xAiModels.Providers.Entities } } -### FILE: C:\Users\saherelm\Documents\Projects\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; @@ -10651,7 +10651,7 @@ namespace xAiModels.Providers.Entities } } -### FILE: C:\Users\saherelm\Documents\Projects\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; @@ -10676,7 +10676,7 @@ namespace xAiModels.Providers.Entities } } -### FILE: C:\Users\saherelm\Documents\Projects\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; @@ -10688,7 +10688,7 @@ namespace xAiModels.Providers.Entities { } } -### FILE: C:\Users\saherelm\Documents\Projects\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; @@ -10717,7 +10717,7 @@ namespace xAiModels.Providers.Entities } } -### FILE: C:\Users\saherelm\Documents\Projects\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; @@ -10729,7 +10729,7 @@ namespace xAiModels.Providers.Entities { } } -### FILE: C:\Users\saherelm\Documents\Projects\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; @@ -10758,7 +10758,7 @@ namespace xAiModels.Providers.Entities } } -### FILE: C:\Users\saherelm\Documents\Projects\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; @@ -10785,7 +10785,7 @@ namespace xAiModels.Providers.Entities } } -### FILE: C:\Users\saherelm\Documents\Projects\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; @@ -10810,7 +10810,7 @@ namespace xAiModels.Providers.Entities } } -### FILE: C:\Users\saherelm\Documents\Projects\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; @@ -10829,7 +10829,7 @@ namespace xAiModels.Providers.Entities } } -### FILE: C:\Users\saherelm\Documents\Projects\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; @@ -10850,7 +10850,7 @@ namespace xAiModels.Providers.Entities } } -### FILE: C:\Users\saherelm\Documents\Projects\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; @@ -10862,7 +10862,7 @@ namespace xAiModels.Providers.Entities { } } -### FILE: C:\Users\saherelm\Documents\Projects\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; @@ -10888,7 +10888,7 @@ namespace xAiModels.Providers.Entities } } -### FILE: C:\Users\saherelm\Documents\Projects\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; @@ -10900,7 +10900,7 @@ namespace xAiModels.Providers.Entities { } } -### FILE: C:\Users\saherelm\Documents\Projects\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; @@ -10924,7 +10924,7 @@ namespace xAiModels.Providers.Entities } } -### FILE: C:\Users\saherelm\Documents\Projects\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; @@ -10951,7 +10951,7 @@ namespace xAiModels.Providers.Entities } } -### FILE: C:\Users\saherelm\Documents\Projects\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; @@ -10981,7 +10981,7 @@ namespace xAiModels.Providers.Entities } } -### FILE: C:\Users\saherelm\Documents\Projects\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; @@ -11000,7 +11000,7 @@ namespace xAiModels.Providers.Entities } } -### FILE: C:\Users\saherelm\Documents\Projects\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; @@ -11025,7 +11025,7 @@ namespace xAiModels.Providers.Entities } } -### FILE: C:\Users\saherelm\Documents\Projects\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; @@ -11037,7 +11037,7 @@ namespace xAiModels.Providers.Entities { } } -### FILE: C:\Users\saherelm\Documents\Projects\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; @@ -11066,7 +11066,7 @@ namespace xAiModels.Providers.Entities } } -### FILE: C:\Users\saherelm\Documents\Projects\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; @@ -11078,7 +11078,7 @@ namespace xAiModels.Providers.Entities { } } -### FILE: C:\Users\saherelm\Documents\Projects\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; @@ -11107,7 +11107,7 @@ namespace xAiModels.Providers.Entities } } -### FILE: C:\Users\saherelm\Documents\Projects\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; @@ -11134,7 +11134,7 @@ namespace xAiModels.Providers.Entities } } -### FILE: C:\Users\saherelm\Documents\Projects\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; @@ -11164,7 +11164,7 @@ namespace xAiModels.Providers.Entities } } -### FILE: C:\Users\saherelm\Documents\Projects\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; @@ -11183,7 +11183,7 @@ namespace xAiModels.Providers.Entities } } -### FILE: C:\Users\saherelm\Documents\Projects\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; @@ -11208,7 +11208,7 @@ namespace xAiModels.Providers.Entities } } -### FILE: C:\Users\saherelm\Documents\Projects\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; @@ -11220,7 +11220,7 @@ namespace xAiModels.Providers.Entities { } } -### FILE: C:\Users\saherelm\Documents\Projects\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; @@ -11249,7 +11249,7 @@ namespace xAiModels.Providers.Entities } } -### FILE: C:\Users\saherelm\Documents\Projects\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; @@ -11261,7 +11261,7 @@ namespace xAiModels.Providers.Entities { } } -### FILE: C:\Users\saherelm\Documents\Projects\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; @@ -11290,7 +11290,7 @@ namespace xAiModels.Providers.Entities } } -### FILE: C:\Users\saherelm\Documents\Projects\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; @@ -11317,7 +11317,7 @@ namespace xAiModels.Providers.Entities } } -### FILE: C:\Users\saherelm\Documents\Projects\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; @@ -11347,7 +11347,7 @@ namespace xAiModels.Providers.Entities } } -### FILE: C:\Users\saherelm\Documents\Projects\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; @@ -11366,7 +11366,7 @@ namespace xAiModels.Providers.Entities } } -### FILE: C:\Users\saherelm\Documents\Projects\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; @@ -11391,7 +11391,7 @@ namespace xAiModels.Providers.Entities } } -### FILE: C:\Users\saherelm\Documents\Projects\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; @@ -11403,7 +11403,7 @@ namespace xAiModels.Providers.Entities { } } -### FILE: C:\Users\saherelm\Documents\Projects\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; @@ -11432,7 +11432,7 @@ namespace xAiModels.Providers.Entities } } -### FILE: C:\Users\saherelm\Documents\Projects\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; @@ -11444,7 +11444,7 @@ namespace xAiModels.Providers.Entities { } } -### FILE: C:\Users\saherelm\Documents\Projects\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; @@ -11473,7 +11473,7 @@ namespace xAiModels.Providers.Entities } } -### FILE: C:\Users\saherelm\Documents\Projects\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; @@ -11500,7 +11500,7 @@ namespace xAiModels.Providers.Entities } } -### FILE: C:\Users\saherelm\Documents\Projects\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; @@ -11524,7 +11524,7 @@ namespace xAiModels.Providers.GraphQL } } -### FILE: C:\Users\saherelm\Documents\Projects\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; @@ -11550,7 +11550,7 @@ namespace xAiModels.Providers.GraphQL } } -### FILE: C:\Users\saherelm\Documents\Projects\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; @@ -11566,7 +11566,7 @@ namespace xAiModels.Providers.GraphQL } } -### FILE: C:\Users\saherelm\Documents\Projects\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; @@ -11587,7 +11587,7 @@ namespace xAiModels.Providers.GraphQL } } -### FILE: C:\Users\saherelm\Documents\Projects\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; @@ -11611,7 +11611,7 @@ namespace xAiModels.Providers.GraphQL } } -### FILE: C:\Users\saherelm\Documents\Projects\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; @@ -11637,7 +11637,7 @@ namespace xAiModels.Providers.GraphQL } } -### FILE: C:\Users\saherelm\Documents\Projects\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; @@ -11653,7 +11653,7 @@ namespace xAiModels.Providers.GraphQL } } -### FILE: C:\Users\saherelm\Documents\Projects\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; @@ -11679,7 +11679,7 @@ namespace xAiModels.Providers.GraphQL } } -### FILE: C:\Users\saherelm\Documents\Projects\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; @@ -11703,7 +11703,7 @@ namespace xAiModels.Providers.GraphQL } } -### FILE: C:\Users\saherelm\Documents\Projects\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; @@ -11729,7 +11729,7 @@ namespace xAiModels.Providers.GraphQL } } -### FILE: C:\Users\saherelm\Documents\Projects\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; @@ -11745,7 +11745,7 @@ namespace xAiModels.Providers.GraphQL } } -### FILE: C:\Users\saherelm\Documents\Projects\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; @@ -11768,7 +11768,7 @@ namespace xAiModels.Providers.GraphQL } } -### FILE: C:\Users\saherelm\Documents\Projects\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; @@ -11792,7 +11792,7 @@ namespace xAiModels.Providers.GraphQL } } -### FILE: C:\Users\saherelm\Documents\Projects\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; @@ -11818,7 +11818,7 @@ namespace xAiModels.Providers.GraphQL } } -### FILE: C:\Users\saherelm\Documents\Projects\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; @@ -11834,7 +11834,7 @@ namespace xAiModels.Providers.GraphQL } } -### FILE: C:\Users\saherelm\Documents\Projects\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; @@ -11856,7 +11856,7 @@ namespace xAiModels.Providers.GraphQL } } -### FILE: C:\Users\saherelm\Documents\Projects\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; @@ -11880,7 +11880,7 @@ namespace xAiModels.Providers.GraphQL } } -### FILE: C:\Users\saherelm\Documents\Projects\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; @@ -11906,7 +11906,7 @@ namespace xAiModels.Providers.GraphQL } } -### FILE: C:\Users\saherelm\Documents\Projects\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; @@ -11922,7 +11922,7 @@ namespace xAiModels.Providers.GraphQL } } -### FILE: C:\Users\saherelm\Documents\Projects\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; @@ -11941,7 +11941,7 @@ namespace xAiModels.Providers.GraphQL } } -### FILE: C:\Users\saherelm\Documents\Projects\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-20261106_205449.txt b/Documents/GeneratedContext/xDashboard-xAiService-20261106_205449.txt deleted file mode 100644 index 322d892..0000000 --- a/Documents/GeneratedContext/xDashboard-xAiService-20261106_205449.txt +++ /dev/null @@ -1,1947 +0,0 @@ - -### FILE: C:\Users\saherelm\Documents\Projects\xSaherelmWorkspace\Modules\xAiService\Constants\ConfigurationNodeNames.cs - -namespace xAiService.Constants -{ - public partial struct ConfigurationNodeNames - { - public const string AI_SERVICE_NODE = "AIServiceConfiguration"; - } -} - -### FILE: C:\Users\saherelm\Documents\Projects\xSaherelmWorkspace\Modules\xAiService\Constants\XAiServiceConstants.cs - -namespace xAiService.Constants -{ - public struct XAiServiceConstants - { - // - // Service Extensions Log Tag ... - public const string XAiServiceDILogTag = "XAiService"; - - // - // File Provider Identifiers ... - public const string XAiProjectFilesIdentifier = "AiPrjF"; - public const string XAiMessageFilesIdentifier = "AiMsgF"; - public const string XMetaDataFileIdsIdentifier = "FileIds"; - public const string XAiConversationFilesIdentifier = "AiCnvrF"; - } -} - -### FILE: C:\Users\saherelm\Documents\Projects\xSaherelmWorkspace\Modules\xAiService\Controllers\XAiMcpControllerBase.cs - -using System.Threading; -using xCommons.Providers; -using Newtonsoft.Json.Linq; -using xAiService.Interfaces; -using System.Threading.Tasks; -using xCommons.Configurations; -using Microsoft.AspNetCore.Mvc; -using Microsoft.AspNetCore.Http; -using xIdentityService.Interfaces; -using Microsoft.Extensions.Logging; -using xIdentityService.Controllers; -using Microsoft.AspNetCore.Authorization; - -namespace xAiService.Controllers -{ - [Route("mcp")] - [AllowAnonymous] - public abstract class XAiMcpControllerBase : XBaseIdentityApiV1Controller - { - private readonly IXAiMcpHandler mcpHandler; - - protected XAiMcpControllerBase( - IXAiMcpHandler mcpHandler, - XAppConfiguration appConfiguration, - IXIdentityProvider identityProvider, - ILogger logger, - XValidationProvider validationProvider - ) : base(logger, appConfiguration, identityProvider, validationProvider) - { - this.mcpHandler = mcpHandler; - } - - /// - /// Handle MCP ... - /// - /// - /// - /// - [HttpPost] - public virtual async Task HandleMcp( - [FromBody] JObject request, - CancellationToken cancellationToken = default - ) - { - // - var userInfo = await GetUserInfo(); - var connectionId = GetConnectionId(); - - // - var response = await mcpHandler.ProcessAsync( - request: request, - userInfo: userInfo, - connectionId: connectionId, - cancellationToken: cancellationToken - ); - - // - return Ok(response); - } - - /// - /// Handle SSE EndPoint ... - /// - /// - /// - [HttpGet("sse")] - public virtual async Task SseEndpoint( - CancellationToken cancellationToken = default - ) - { - // - Response.Headers.Add("Content-Type", "text/event-stream"); - Response.Headers.Add("Cache-Control", "no-cache"); - - // - await Response - .WriteAsync( - "event: endpoint\ndata: /mcp\n\n", - cancellationToken - ); - - // - await Response.Body.FlushAsync(cancellationToken); - - // - while (!cancellationToken.IsCancellationRequested) - { - await Task.Delay(1000, cancellationToken); - } - } - } -} - -### FILE: C:\Users\saherelm\Documents\Projects\xSaherelmWorkspace\Modules\xAiService\DI\XDIHelperExtension.cs - -using System.Net.Http; -using System.Threading; -using xAiModels.Constants; -using xAiService.Services; -using Microsoft.Extensions.DependencyInjection; - -namespace xAiService.DI -{ - public static partial class XDIHelperExtension - { - /// - /// Register XAiMcpClient in DI ... - /// - /// - public static void AddXAiMcpClient( - this IServiceCollection source - ) - { - // - // Register Http Client ... - source.AddHttpClient( - XAiMcpConstants.XAiMcpClientName, - client => - { - client.Timeout = Timeout.InfiniteTimeSpan; - } - ) - .ConfigurePrimaryHttpMessageHandler(() => new HttpClientHandler - { - ServerCertificateCustomValidationCallback = (message, cert, chain, errors) => true - }); - - // - source.AddScoped(); - source.AddSingleton(); - - // - source.AddHostedService(); - } - } -} - -### FILE: C:\Users\saherelm\Documents\Projects\xSaherelmWorkspace\Modules\xAiService\Extensions\DIExtensions.cs - -using System; -using System.Linq; -using System.Reflection; -using xAiService.Services; -using xAiService.Interfaces; -using Microsoft.Extensions.DependencyInjection; - -namespace xAiService.Extensions -{ - public static class DIExtensions - { - /// - /// Register XAiMcpHandler Service ... - /// - /// - public static void AddXAiMcpHandler( - this IServiceCollection source - ) - { - // - // Register MCP User Context ... - source.AddScoped(); - - // - // Register MCP Tool Scanner ... - source.AddSingleton(sp => - { - // - // Scan All Exists Assemblies ... - var asms = AppDomain.CurrentDomain - .GetAssemblies() - .Where(a => !a.IsDynamic && - a.GetName().Name != null && - a.GetName().Name!.StartsWith("xAi", StringComparison.OrdinalIgnoreCase)) - .Append(Assembly.GetEntryAssembly()!) - .ToArray(); - - // - return new XAiMcpToolScanner(asms); - }); - - // - // 2) Register MCP Handler ... - source.AddScoped(); - } - } -} - -### FILE: C:\Users\saherelm\Documents\Projects\xSaherelmWorkspace\Modules\xAiService\Extensions\XAiServiceExtensions.cs - -using xAiModels.Models; -using xCommons.Extensions; -using xAiService.Services; -using xExceptions.Constants; -using xIdentityModels.Models; -using Microsoft.Extensions.AI; -using System.Collections.Generic; - -namespace xAiService.Extensions -{ - public static class XAiServiceExtensions - { - /// - /// Validate User Info ... - /// - /// - /// - public static bool IsValid(this XUserClaimsInfoDto source) - { - // - var result = - !source.IsNullOrDefault() && - !source.UserId.IsNullOrEmpty() && - !source.AccessToken.IsNullOrEmpty(); - - // - return result; - } - - /// - /// Validate User Info ... - /// - /// - /// - public static void Validate( - this XUserClaimsInfoDto source, - XException invalidException = XException.InvalidArgs - ) - { - // - var isValid = source.IsValid(); - if (!isValid) - { - invalidException.Throw(); - } - } - - /// - /// Converts To AITools ... - /// - /// - /// - /// - public static IList ToAITools( - this IList source, - XAiMcpClient client - ) - { - // - if (client.IsNullOrDefault()) - { - XException.InvalidArgs.Throw(); - } - - // - var result = new List(); - - // - foreach (var tool in source) - { - result.Add(new XAiMcpAIFunction(client, tool)); - } - - // - return result; - } - } -} - -### FILE: C:\Users\saherelm\Documents\Projects\xSaherelmWorkspace\Modules\xAiService\Helpers\XAiMcpArgumentHelper.cs - -using System; -using Newtonsoft.Json.Linq; - -namespace xAiService.Helpers -{ - public static class XAiMcpArgumentHelper - { - /// - /// Bind Parameters ... - /// - /// - /// - /// - public static object Bind( - JToken token, - Type targetType - ) - { - // - var underlying = Nullable.GetUnderlyingType(targetType) ?? targetType; - - // - // Null Handling ... - if (token == null || token.Type == JTokenType.Null || token.Type == JTokenType.Undefined) - { - // - if (!targetType.IsValueType || Nullable.GetUnderlyingType(targetType) != null) - { - return null; - } - - // - return Activator.CreateInstance(targetType); - } - - // - // Primitive Types ... - - // - if (underlying == typeof(string)) - { - return token.ToString(); - } - - // - if (underlying == typeof(int)) - { - return token.Value(); - } - - // - if (underlying == typeof(long)) - { - return token.Value(); - } - - // - if (underlying == typeof(short)) - { - return token.Value(); - } - - // - if (underlying == typeof(float)) - { - return token.Value(); - } - - // - if (underlying == typeof(double)) - { - return token.Value(); - } - - // - if (underlying == typeof(decimal)) - { - return token.Value(); - } - - // - if (underlying == typeof(bool)) - { - return token.Value(); - } - - // - if (underlying == typeof(Guid)) - { - return token.Value(); - } - - // - if (underlying == typeof(DateTime)) - { - return token.Value(); - } - - // - // Enum ... - if (underlying.IsEnum) - { - return Enum.Parse(underlying, token.ToString(), ignoreCase: true); - } - - // - // Arrays ... - if (underlying.IsArray && token is JArray jarr) - { - // - var elementType = underlying.GetElementType(); - var arr = Array.CreateInstance(elementType, jarr.Count); - for (var i = 0; i < jarr.Count; i++) - { - arr.SetValue(Bind(jarr[i], elementType), i); - } - - // - return arr; - } - - // - // Fallback: JSON Deserialize - return token.ToObject(underlying); - } - } -} - -### FILE: C:\Users\saherelm\Documents\Projects\xSaherelmWorkspace\Modules\xAiService\Helpers\XAiMcpResultExtractionHelper.cs - -using System; -using Newtonsoft.Json; -using Newtonsoft.Json.Linq; -using System.Threading.Tasks; - -namespace xAiService.Helpers -{ - public static class XAiMcpResultExtractionHelper - { - /// - /// Extract Specified Object Result of Method Invoking ... - /// - /// - /// - /// - public static async Task ExtractAsync( - object raw, - Type returnType - ) - { - // - // Task / Task - if (raw is Task task) - { - // - await task.ConfigureAwait(false); - if (returnType.IsGenericType && - returnType.GetGenericTypeDefinition() == typeof(Task<>)) - { - // - var value = returnType.GetProperty("Result").GetValue(task); - return Format(value); - } - - // - return string.Empty; - } - - // - // ValueTask (non-generic) - if (returnType == typeof(ValueTask)) - { - // - await ((ValueTask)raw).ConfigureAwait(false); - return string.Empty; - } - - // - // ValueTask ... - if (returnType.IsGenericType && - returnType.GetGenericTypeDefinition() == typeof(ValueTask<>)) - { - // - var asTask = (Task)returnType.GetMethod("AsTask").Invoke(raw, null); - await asTask.ConfigureAwait(false); - var value = asTask.GetType().GetProperty("Result").GetValue(asTask); - - // - return Format(value); - } - - // - // void / T Syncron ... - return Format(raw); - } - - // - #region Private ... - /// - /// Format Extracted Response ... - /// /// - /// - /// - private static string Format(object value) - { - // - if (value == null) - { - return string.Empty; - } - - // - if (value is string s) - { - return s; - } - - // - if (value is JToken jt) - { - return jt.ToString(Formatting.None); - } - - // - if (value.GetType().IsPrimitive || value is decimal) - { - return value.ToString(); - } - - // - return JToken.FromObject(value).ToString(Formatting.None); - } - #endregion - } -} - -### FILE: C:\Users\saherelm\Documents\Projects\xSaherelmWorkspace\Modules\xAiService\Interfaces\IXAiMcpHandler.cs - -using System.Threading; -using Newtonsoft.Json.Linq; -using System.Threading.Tasks; -using xIdentityModels.Models; - -namespace xAiService.Interfaces -{ - public interface IXAiMcpHandler - { - /// - /// Process Specified JSON-RPC Request ... - /// - /// - /// - /// - /// - /// - Task ProcessAsync( - JObject request, - string connectionId = null, - XUserClaimsInfoDto userInfo = null, - CancellationToken cancellationToken = default - ); - } -} - -### FILE: C:\Users\saherelm\Documents\Projects\xSaherelmWorkspace\Modules\xAiService\Interfaces\IXAiMcpUserContext.cs - -using xIdentityModels.Models; - -namespace xAiService.Interfaces -{ - /// - /// User Context for MCP Servers ... - /// - /// Automatic Filled in HTTP Request Execution Time ... - /// When Request Execution Ended, Disposed ... - /// - /// - for Instanced Tools: Accessible using Dependency Injection ... - /// - for Static Tools: Accessible using Static Properties Current* ... - /// - public interface IXAiMcpUserContext - { - /// - /// Connection Id ... - /// - /// - string ConnectionId { get; } - - /// - /// User Claims ... - /// - /// - XUserClaimsInfoDto UserInfo { get; } - - /// - /// Fill Context ... - /// - /// - /// - void Set( - XUserClaimsInfoDto userInfo, - string connectionId = null - ); - - /// - /// Clear Context ... - /// - void Clear(); - } -} - -### FILE: C:\Users\saherelm\Documents\Projects\xSaherelmWorkspace\Modules\xAiService\Services\XAiMcpAIFunction.cs - -using System.Text.Json; -using System.Threading; -using xAiModels.Models; -using xCommons.Extensions; -using xExceptions.Constants; -using System.Text.Json.Nodes; -using System.Threading.Tasks; -using Microsoft.Extensions.AI; - -namespace xAiService.Services -{ - /// - /// a Customized AIFunction Implementation ... - /// - public class XAiMcpAIFunction : AIFunction - { - // - private readonly XAiMcpClient client; - private readonly JsonElement jsonSchema; - private readonly XAiMcpToolDefinition definition; - - public XAiMcpAIFunction( - XAiMcpClient client, - XAiMcpToolDefinition definition - ) - { - // - if (client.IsNull() || definition.IsNull()) - { - XException.InvalidArgs.Throw(); - } - - // - this.client = client; - this.definition = definition; - - // - jsonSchema = definition.InputSchema.Clone(); - } - - // - public override string Name => definition.Name; - public override JsonElement JsonSchema => jsonSchema; - public override string Description => definition.Description; - - /// - /// Invoke Tool ... - /// - /// - /// - /// - protected override async ValueTask InvokeCoreAsync( - AIFunctionArguments arguments, - CancellationToken cancellationToken = default - ) - { - // - var jsonArgs = ToJsonObject(arguments); - return await client.CallToolAsync( - definition.Name, - jsonArgs, - cancellationToken - ); - } - - private JsonObject ToJsonObject(AIFunctionArguments arguments) - { - // - var result = new JsonObject(); - if (arguments.IsNull() || - arguments is null) - { - return result; - } - - // - foreach (var kvp in arguments) - { - result[kvp.Key] = JsonSerializer.SerializeToNode(kvp.Value); - } - - // - return result; - } - } -} - -### FILE: C:\Users\saherelm\Documents\Projects\xSaherelmWorkspace\Modules\xAiService\Services\XAiMcpClient.cs - -using System; -using System.Text.Json; -using System.Threading; -using xAiModels.Models; -using xAiModels.Helpers; -using xAiModels.Constants; -using xCommons.Extensions; -using System.Text.Json.Nodes; -using System.Threading.Tasks; -using xIdentityModels.Models; -using xCommons.Configurations; -using System.Collections.Generic; -using Microsoft.Extensions.Logging; - -namespace xAiService.Services -{ - public class XAiMcpClient : IAsyncDisposable - { - // - private readonly Uri endpoint; - private readonly Guid serverId; - private readonly ILogger logger; - private readonly string connectionId; - private readonly XUserClaimsInfoDto userInfo; - private readonly XAiMcpHttpTransport transport; - private readonly XAiMcpSessionStore sessionStore; - private readonly XAppConfiguration appConfiguration; - - // - public string ServerName { get; private set; } - public bool IsInitialized { get; private set; } - public string ServerVersion { get; private set; } - public string ProtocolVersion { get; private set; } = XAiMcpConstants.XAiMcpProtocol; - - public XAiMcpClient( - Uri endpoint, - Guid serverId, - ILogger logger, - XAiMcpHttpTransport transport, - XAiMcpSessionStore sessionStore, - XAppConfiguration appConfiguration, - string connectionId = null, - XUserClaimsInfoDto userInfo = null - ) - { - // - this.logger = logger; - this.serverId = serverId; - this.endpoint = endpoint; - this.userInfo = userInfo; - this.transport = transport; - this.sessionStore = sessionStore; - this.connectionId = connectionId; - this.appConfiguration = appConfiguration; - } - - /// - /// Initialize MCP Server ... - /// - /// - /// - public async Task InitializeAsync(CancellationToken cancellationToken = default) - { - // - if (IsInitialized) - { - return; - } - - // - var request = new XAiMcpJsonRpcRequest - { - Method = XAiMcpMethods.Initialize.GetStringValue(), - Params = new - { - capabilities = new { tools = new { } }, - protocolVersion = XAiMcpConstants.XAiMcpProtocol, - clientInfo = new { - name = XAiMcpConstants.serverInfoNameValue, - version = XAiMcpConstants.serverInfoVersionValue - } - } - }; - - // - var headers = XAiMcpHeaderBuilder.Build( - userInfo: userInfo, - connectionId: connectionId, - appConfiguration: appConfiguration - ); - - // - var response = await transport - .SendAsync( - endpoint, - headers, - request, - cancellationToken - ); - if (!response.IsSuccess) - { - throw new InvalidOperationException($"Initialize failed: {response.Error?.Message}"); - } - - // - var result = response.Result?.Deserialize(); - if (result?.TryGetProperty(XAiMcpConstants.ProtocolVersionKey, out var pv) == true) - { - ProtocolVersion = pv.GetString() ?? ProtocolVersion; - } - if (result?.TryGetProperty(XAiMcpConstants.ServerInfoKey, out var si) == true) - { - // - ServerName = si.TryGetProperty(XAiMcpConstants.ServerInfoNameKey, out var n) ? n.GetString() : null; - ServerVersion = si.TryGetProperty(XAiMcpConstants.ServerInfoVersionKey, out var v) ? v.GetString() : null; - } - - // - IsInitialized = true; - logger.LogInformation( - "MCP initialized: {Name} v{Version} (protocol {PV})", - ServerName, - ServerVersion, - ProtocolVersion - ); - } - - /// - /// Get a List of Available Tools on Initialize MCP Server ... - /// - /// - /// - public async Task> ListToolsAsync(CancellationToken cancellationToken = default) - { - // - await EnsureInitializedAsync(cancellationToken); - - // - var request = new XAiMcpJsonRpcRequest - { - Method = XAiMcpMethods.ToolsList.GetStringValue() - }; - - // - var sessionId = sessionStore.Get(serverId, userInfo.UserId); - var headers = XAiMcpHeaderBuilder.Build( - userInfo: userInfo, - appConfiguration: appConfiguration, - connectionId: connectionId, - sessionId: sessionId, - protocolVersion: ProtocolVersion - ); - - // - var response = await transport - .SendAsync( - endpoint, - headers, - request, - cancellationToken - ); - if (!response.IsSuccess) - { - throw new InvalidOperationException($"tools/list failed: {response.Error?.Message}"); - } - - // - var toolsArray = response.Result?.Deserialize(); - if (toolsArray?.TryGetProperty("tools", out var tools) != true) - { - return new List(); - } - - // - return tools.Deserialize>() ?? new(); - } - - /// - /// Call Specified Tools of MCP Server ... - /// - /// - /// - /// - /// - public async Task CallToolAsync( - string toolName, - JsonObject arguments, - CancellationToken cancellationToken = default - ) - { - // - await EnsureInitializedAsync(cancellationToken); - - // - var request = new XAiMcpJsonRpcRequest - { - Method = XAiMcpMethods.ToolsCall.GetStringValue(), - Params = new - { - name = toolName, - arguments = arguments ?? new JsonObject() - } - }; - - // - var sessionId = sessionStore.Get(serverId, userInfo.UserId); - var headers = XAiMcpHeaderBuilder.Build( - userInfo: userInfo, - sessionId: sessionId, - connectionId: connectionId, - protocolVersion: ProtocolVersion, - appConfiguration: appConfiguration - ); - - // - var response = await transport - .SendAsync( - endpoint, - headers, - request, - cancellationToken - ); - if (!response.IsSuccess) - { - throw new InvalidOperationException($"tools/call failed: {response.Error?.Message}"); - } - - // - var result = response.Result?.Deserialize(); - if (result?.TryGetProperty(XAiMcpConstants.ContentKey, out var content) == true && - content.ValueKind == JsonValueKind.Array && - content.GetArrayLength() > 0 - ) - { - // - var first = content[0]; - if (first.TryGetProperty(XAiMcpConstants.TextKey, out var text)) - { - return text.GetString() ?? string.Empty; - } - } - - // - return result?.GetRawText() ?? string.Empty; - } - - /// - /// Dispose Instanced Client ... - /// - /// - public async ValueTask DisposeAsync() - { - await Task.CompletedTask; - } - - // - #region Private ... - private async Task EnsureInitializedAsync(CancellationToken ct) - { - // - if (!IsInitialized) - { - await InitializeAsync(ct); - } - } - #endregion - } -} - -### FILE: C:\Users\saherelm\Documents\Projects\xSaherelmWorkspace\Modules\xAiService\Services\XAiMcpHandler.cs - -using System; -using System.Threading; -using xAiModels.Models; -using Newtonsoft.Json.Linq; -using xAiService.Interfaces; -using System.Threading.Tasks; -using System.Collections.Generic; -using xIdentityModels.Models; -using xCommons.Extensions; -using System.Linq; -using xIdentityService.Interfaces; - -namespace xAiService.Services -{ - public class XAiMcpHandler : IXAiMcpHandler - { - // - private readonly XAiMcpToolScanner scanner; - private readonly IXPolicyHandler policyHandler; - private readonly IXAiMcpUserContext userContext; - private readonly IServiceProvider serviceProvider; - private readonly Dictionary tools = new(); - - public XAiMcpHandler( - XAiMcpToolScanner scanner, - IXPolicyHandler policyHandler, - IXAiMcpUserContext userContext, - IServiceProvider serviceProvider - ) - { - // - this.scanner = scanner; - this.userContext = userContext; - this.policyHandler = policyHandler; - this.serviceProvider = serviceProvider; - - // - RegisterTools(); - } - - /// - /// Process Specified JSON-RPC Request ... - /// - /// - /// - /// - /// - /// - public async Task ProcessAsync( - JObject request, - string connectionId = null, - XUserClaimsInfoDto userInfo = null, - CancellationToken cancellationToken = default - ) - { - // - // Filling User Context ... - userContext.Set(userInfo, connectionId); - - // - try - { - // - var id = request["id"]; - var method = request["method"]?.ToString(); - - // - return method switch - { - "initialize" => HandleInitialize(id), - "tools/list" => HandleToolsList(id, userInfo), - "tools/call" => await HandleToolCallAsync(request, id, userInfo, cancellationToken), - "ping" => HandlePing(id), - _ => CreateError(id, -32601, $"Method not found: {method}") - }; - } - finally - { - userContext.Clear(); - } - } - - // - #region Private ... - private JObject HandleInitialize(JToken id) - { - return CreateResult(id, new JObject - { - ["protocolVersion"] = "2024-11-05", - ["capabilities"] = new JObject - { - ["tools"] = new JObject { ["listChanged"] = true } - }, - ["serverInfo"] = new JObject - { - ["name"] = "xAiMcpServer", - ["version"] = "1.0.0" - } - }); - } - - private JObject HandleToolsList( - JToken id, - XUserClaimsInfoDto userInfo - ) - { - var jsonTools = new JArray(); - foreach (var tool in tools.Values) - { - // - if (!tool.RequiredPolicy.IsNullOrEmpty() && - !CheckPolicy(userInfo, tool.RequiredPolicy)) - { - continue; - } - - // - jsonTools.Add(new JObject - { - ["name"] = tool.Name, - ["description"] = tool.Description, - ["inputSchema"] = tool.InputSchema - }); - } - - // - return CreateResult(id, new JObject { ["tools"] = jsonTools }); - } - - private async Task HandleToolCallAsync( - JObject request, - JToken id, - XUserClaimsInfoDto userInfo, - CancellationToken ct - ) - { - // - var toolName = request["params"]?["name"]?.ToString(); - var args = request["params"]?["arguments"] as JObject; - - // - if (!tools.ContainsKey(toolName)) - { - return CreateError(id, -32602, $"Tool not found: {toolName}"); - } - - // - var tool = tools[toolName]; - - // - // Check User Info Required or not ... - - // - // Level 1 ... - if (userInfo.IsNull() && tool.RequiresAuthentication) - { - return CreateError(id, -32001, $"Authentication required for tool: {toolName}"); - } - - // - // Level 2 ... - if (!tool.RequiredPolicy.IsNullOrEmpty() && - !CheckPolicy(userInfo, tool.RequiredPolicy)) - { - return CreateError(id, -32002, $"Access denied for tool: {toolName}"); - } - - // - var result = await tool.Execute(args, ct); - return CreateResult(id, new JObject - { - ["content"] = new JArray - { - new JObject - { - ["type"] = "text", - ["text"] = result - } - } - }); - } - - private JObject CreateResult( - JToken id, - JObject result - ) - { - // - return new JObject - { - ["jsonrpc"] = "2.0", - ["id"] = id, - ["result"] = result - }; - } - - private JObject CreateError( - JToken id, - int code, - string message - ) - { - // - return new JObject - { - ["jsonrpc"] = "2.0", - ["id"] = id, - ["error"] = new JObject - { - ["code"] = code, - ["message"] = message - } - }; - } - - private void RegisterTools() - { - // - // 1) Manually Register Tools ... - RegisterManualTools(); - - // - // 2) Register Scanned Tools uding Reflection ... - foreach (var blueprint in scanner.Blueprints) - { - // - // Prevent Double Registration if Name Exists ... - if (tools.ContainsKey(blueprint.Name)) - { - continue; - } - - // - tools[blueprint.Name] = blueprint.ToDescriptor(serviceProvider); - } - } - - private void RegisterManualTools() - { - // Manually Tools Registration ... - // tools["search_knowledge"] = new XAiMcpToolDescriptor - // { - // Name = "search_knowledge", - // Description = "Search in knowledge base", - // InputSchema = new JObject - // { - // ["type"] = "object", - // ["properties"] = new JObject - // { - // ["query"] = new JObject { ["type"] = "string" } - // }, - // ["required"] = new JArray("query") - // }, - // Execute = async (args, ct) => - // { - // var query = args?["query"]?.ToString() ?? ""; - // return $"Results for: {query}"; - // } - // }; - } - - private JObject HandlePing(JToken id) - { - return CreateResult(id, new JObject()); - } - - private bool CheckPolicy(XUserClaimsInfoDto user, string policy) - { - // - var result = false; - - // - if (user.IsNullOrDefault()) - { - return result; - } - - // - // Handle Authorization ... - result = policyHandler.IsPolicyPassed( - policy: policy, - roles: user.Roles - ); - - // - return result; - } - #endregion - } -} - -### FILE: C:\Users\saherelm\Documents\Projects\xSaherelmWorkspace\Modules\xAiService\Services\XAiMcpHttpTransport.cs - -using System; -using System.Text; -using System.Net.Http; -using System.Text.Json; -using System.Threading; -using xAiModels.Models; -using xAiModels.Helpers; -using xAiModels.Constants; -using System.Threading.Tasks; -using System.Net.Http.Headers; -using System.Collections.Generic; -using Microsoft.Extensions.Logging; - -namespace xAiService.Services -{ - public class XAiMcpHttpTransport - { - // - private readonly IHttpClientFactory httpClientFactory; - private readonly ILogger logger; - - public XAiMcpHttpTransport( - IHttpClientFactory httpClientFactory, - ILogger logger - ) - { - // - this.logger = logger; - this.httpClientFactory = httpClientFactory; - } - - public async Task SendAsync( - Uri endpoint, - Dictionary headers, - XAiMcpJsonRpcRequest request, - CancellationToken cancellationToken = default - ) - { - // - var client = httpClientFactory.CreateClient(XAiMcpConstants.XAiMcpClientName); - client.Timeout = Timeout.InfiniteTimeSpan; - - // - using var httpRequest = new HttpRequestMessage(HttpMethod.Post, endpoint); - - // - // Add all Headers ... - foreach (var header in headers) - { - httpRequest.Headers.TryAddWithoutValidation(header.Key, header.Value); - } - - // - // Prepare For Accepting SSE and JSON-RPC ... - httpRequest.Headers.Accept.Clear(); - httpRequest.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json")); - httpRequest.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue("text/event-stream")); - - // - var json = JsonSerializer.Serialize(request); - httpRequest.Content = new StringContent(json, Encoding.UTF8, "application/json"); - headers.TryGetValue(XAiMcpConstants.XAiMcpSessionIdentifier, out var sessionId); - - // - logger.LogDebug( - "MCP → {Method} | {Url} | Session={Session}", - request.Method, - endpoint, - sessionId - ); - - // - var response = await client - .SendAsync( - httpRequest, - HttpCompletionOption.ResponseHeadersRead, - cancellationToken - ); - - // - if (!response.IsSuccessStatusCode) - { - // - var errorBody = await response.Content.ReadAsStringAsync(); - logger.LogError("MCP HTTP {Status} | {Body}", (int)response.StatusCode, errorBody); - - // - throw new HttpRequestException( - $"MCP request failed: {response.StatusCode}. Body: {errorBody}"); - } - - // - // Content Type Detection ... - var contentType = response.Content.Headers.ContentType?.MediaType ?? "application/json"; - if (contentType.Contains("text/event-stream")) - { - // - // SSE Answer ... - var stream = await response.Content.ReadAsStreamAsync(); - await foreach (var data in XAiMcpSseReader.ReadAsync(stream, cancellationToken)) - { - // - var parsed = JsonSerializer.Deserialize(data); - if (parsed?.Id == request.Id || parsed?.Id is null) - { - return parsed; - } - } - - // - throw new InvalidOperationException("SSE stream ended without matching response."); - } - else - { - // - // Simple JSON answer ... - var body = await response.Content.ReadAsStringAsync(); - return JsonSerializer.Deserialize(body); - } - } - } -} - -### FILE: C:\Users\saherelm\Documents\Projects\xSaherelmWorkspace\Modules\xAiService\Services\XAiMcpSessionCleanupService.cs - -using System; -using System.Threading; -using System.Threading.Tasks; -using Microsoft.Extensions.Hosting; -using Microsoft.Extensions.Logging; - -namespace xAiService.Services -{ - public class XAiMcpSessionCleanupService : BackgroundService - { - // - private readonly XAiMcpSessionStore store; - private readonly ILogger logger; - - public XAiMcpSessionCleanupService( - XAiMcpSessionStore store, - ILogger logger - ) - { - // - this.store = store; - this.logger = logger; - } - - protected override async Task ExecuteAsync(CancellationToken stoppingToken) - { - // - while (!stoppingToken.IsCancellationRequested) - { - // - await Task.Delay(TimeSpan.FromMinutes(5), stoppingToken); - var removed = store.CleanupExpired(); - if (removed > 0) - { - // - logger - .LogInformation("MCP Session Cleanup: {Count} expired sessions removed", removed); - } - } - } - } -} - -### FILE: C:\Users\saherelm\Documents\Projects\xSaherelmWorkspace\Modules\xAiService\Services\XAiMcpSessionStore.cs - -using System; -using System.Collections.Concurrent; - -namespace xAiService.Services -{ - public class XAiMcpSessionStore - { - // - private static readonly TimeSpan Ttl = TimeSpan.FromMinutes(15); - private readonly ConcurrentDictionary<(Guid ServerId, string UserId), SessionEntry> sessions = new(); - - public string Get( - Guid serverId, - string userId - ) - { - // - if (!sessions.TryGetValue((serverId, userId), out var entry)) - { - return null; - } - - // - // Expriration Check ... - if (DateTime.UtcNow - entry.LastAccessAt > Ttl) - { - // - sessions.TryRemove((serverId, userId), out _); - return null; - } - - // - entry.LastAccessAt = DateTime.UtcNow; - return entry.SessionId; - } - - public void Set( - Guid serverId, - string userId, - string sessionId - ) - { - // - sessions[(serverId, userId)] = new SessionEntry - { - SessionId = sessionId, - LastAccessAt = DateTime.UtcNow - }; - } - - public void Remove( - Guid serverId, - string userId - ) => sessions.TryRemove((serverId, userId), out _); - - public int CleanupExpired() - { - // - var count = 0; - var now = DateTime.UtcNow; - foreach (var kv in sessions) - { - // - if (now - kv.Value.LastAccessAt > Ttl) - { - if (sessions.TryRemove(kv.Key, out _)) - { - count++; - } - } - } - - // - return count; - } - - private class SessionEntry - { - public string SessionId { get; set; } - public DateTime LastAccessAt { get; set; } - } - } -} - -### FILE: C:\Users\saherelm\Documents\Projects\xSaherelmWorkspace\Modules\xAiService\Services\XAiMcpToolBlueprint.cs - -using System; -using xAiModels.Models; -using System.Threading; -using System.Reflection; -using xAiService.Helpers; -using Newtonsoft.Json.Linq; -using System.Threading.Tasks; - -namespace xAiService.Services -{ - public class XAiMcpToolBlueprint - { - public string Name { get; set; } - public string Description { get; set; } - public JObject InputSchema { get; set; } - public string RequiredPolicy { get; set; } - public bool RequiresAuthentication { get; set; } - - internal MethodInfo Method { get; set; } - internal Type DeclaringType { get; set; } - - /// - /// Create an Specific Descriptor which can Execute on Current IServiceProvider ... - /// - /// - /// - public XAiMcpToolDescriptor ToDescriptor(IServiceProvider serviceProvider) - { - // - var result = new XAiMcpToolDescriptor - { - Name = Name, - Description = Description, - InputSchema = InputSchema, - RequiredPolicy = RequiredPolicy, - Execute = BuildExecute(serviceProvider), - RequiresAuthentication = RequiresAuthentication, - }; - - // - return result; - } - - /// - /// Build Tools Execution for MCP Method ... - /// - /// - /// - private Func> BuildExecute( - IServiceProvider serviceProvider - ) - { - // - var method = Method; - var declaringType = DeclaringType; - return async (args, ct) => - { - // - try - { - // - // 1. Make/Retrieve Instance ... - var instance = method.IsStatic - ? null - : (serviceProvider.GetService(declaringType) - ?? Activator.CreateInstance(declaringType)); - - // - // 2. Binding Method Arguments ... - var parameters = method.GetParameters(); - var values = new object[parameters.Length]; - for (var i = 0; i < parameters.Length; i++) - { - // - var p = parameters[i]; - - // - // Handle CancellationToken Token ... - if (p.ParameterType == typeof(CancellationToken)) - { - values[i] = ct; - continue; - } - - // - // Retrieve Param Attribute ... - var attr = p.GetCustomAttribute(); - var jsonName = attr?.Name ?? p.Name; - values[i] = XAiMcpArgumentHelper.Bind(args?[jsonName], p.ParameterType); - } - - // - // 3. Invoke and Await ... - object raw; - try - { - raw = method.Invoke(instance, values); - } - catch (TargetInvocationException tie) when (tie.InnerException != null) - { - throw tie.InnerException; - } - - // - // 4. Extract Invoking Result ... - return await XAiMcpResultExtractionHelper.ExtractAsync(raw, method.ReturnType); - } - catch (Exception ex) - { - return $"Error: {ex.Message}"; - } - }; - } - } -} - -### FILE: C:\Users\saherelm\Documents\Projects\xSaherelmWorkspace\Modules\xAiService\Services\XAiMcpToolScanner.cs - -using System; -using System.Linq; -using System.Threading; -using System.Reflection; -using Newtonsoft.Json.Linq; -using xAiModels.Attributes; -using System.ComponentModel; -using System.Collections.Generic; - -namespace xAiService.Services -{ - public class XAiMcpToolScanner - { - private readonly Assembly[] assemblies; - private readonly Lazy> blueprints; - - public XAiMcpToolScanner(IEnumerable assemblies) - { - // - this.assemblies = assemblies? - .Where(a => a != null && !a.IsDynamic) - .Distinct() - .ToArray() ?? []; - - // - blueprints = new Lazy>( - Scan, - LazyThreadSafetyMode.ExecutionAndPublication - ); - } - - public IReadOnlyList Blueprints => blueprints.Value; - - // - #region Private ... - private IReadOnlyList Scan() - { - // - var result = new List(); - var seenNames = new HashSet(StringComparer.Ordinal); - foreach (var asm in assemblies) - { - // - foreach (var type in SafeGetTypes(asm)) - { - // - if (type.GetCustomAttribute() == null) - { - continue; - } - - // - foreach (var method in type.GetMethods( - BindingFlags.Public | - BindingFlags.Instance | - BindingFlags.Static)) - { - // - var attr = method.GetCustomAttribute(); - if (attr == null) - { - continue; - } - - // - var name = string.IsNullOrWhiteSpace(attr.Name) - ? method.Name - : attr.Name.Trim(); - - if (!seenNames.Add(name)) - { - // - throw new InvalidOperationException( - $"Duplicate MCP tool name '{name}' detected in {type.FullName}.{method.Name}."); - } - - // - var description = attr.Description - ?? method.GetCustomAttribute()?.Description - ?? string.Empty; - - // - var requiredPolicy = attr.RequiredPolicy - ?? string.Empty; - - // - var requiredAuthenticated = attr.RequiresAuthentication; - - // - result.Add(new XAiMcpToolBlueprint - { - Name = name, - Method = method, - DeclaringType = type, - Description = description, - RequiredPolicy = requiredPolicy, - InputSchema = BuildInputSchema(method), - RequiresAuthentication = requiredAuthenticated - }); - } - } - } - - // - return result; - } - - private static JObject BuildInputSchema(MethodInfo method) - { - // - var properties = new JObject(); - var required = new JArray(); - - // - foreach (var p in method.GetParameters()) - { - // - // CancellationToken doesnt exists in Schema ... - if (p.ParameterType == typeof(CancellationToken)) - { - continue; - } - - // - var attr = p.GetCustomAttribute(); - var jsonName = attr?.Name ?? p.Name; - var description = attr?.Description - ?? p.GetCustomAttribute()?.Description - ?? string.Empty; - - // - var propSchema = new JObject - { - ["type"] = MapJsonType(p.ParameterType) - }; - - // - if (!string.IsNullOrWhiteSpace(description)) - { - propSchema["description"] = description; - } - - // - // Define Items Array ... - var underlying = Nullable.GetUnderlyingType(p.ParameterType) ?? p.ParameterType; - if (underlying.IsArray) - { - // - propSchema["items"] = new JObject - { - ["type"] = MapJsonType(underlying.GetElementType()) - }; - } - - // - properties[jsonName] = propSchema; - - // Check is Required ... - var isRequired = attr?.Required ?? true; - if (isRequired) - { - required.Add(jsonName); - } - } - - // - var result = new JObject - { - ["type"] = "object", - ["required"] = required, - ["properties"] = properties, - }; - - // - return result; - } - - private static string MapJsonType(Type type) - { - // - var t = Nullable.GetUnderlyingType(type) ?? type; - - // - if (t == typeof(string) || t == typeof(char) || t == typeof(Guid) || t == typeof(DateTime)) - { - return "string"; - } - - // - if (t == typeof(int) || t == typeof(long) || t == typeof(short) || t == typeof(byte)) - { - return "integer"; - } - - // - if (t == typeof(float) || t == typeof(double) || t == typeof(decimal)) - { - return "number"; - } - - // - if (t == typeof(bool)) - { - return "boolean"; - } - - // - if (t.IsArray || typeof(System.Collections.IEnumerable).IsAssignableFrom(t)) - { - return "array"; - } - - // - if (t.IsEnum) - { - return "string"; - } - - // - return "object"; - } - - private static IEnumerable SafeGetTypes(Assembly asm) - { - // - try - { - return asm.GetTypes(); - } - catch (ReflectionTypeLoadException ex) - { - return ex.Types.Where(t => t != null)!; - } - } - #endregion - } -} - -### FILE: C:\Users\saherelm\Documents\Projects\xSaherelmWorkspace\Modules\xAiService\Services\XAiMcpUserContext.cs - -using System.Threading; -using xAiService.Interfaces; -using xIdentityModels.Models; - -namespace xAiService.Services -{ - /// - /// User Context for MCP Servers ... - /// - /// Automatic Filled in HTTP Request Execution Time ... - /// When Request Execution Ended, Disposed ... - /// - /// - for Instanced Tools: Accessible using Dependency Injection ... - /// - for Static Tools: Accessible using Static Properties Current* ... - /// - public class XAiMcpUserContext : IXAiMcpUserContext - { - // - private static readonly AsyncLocal connectionIdAsyncLocal = new(); - private static readonly AsyncLocal userAsyncLocal = new(); - - /// - /// User Claims ... - /// - /// - public XUserClaimsInfoDto UserInfo => userAsyncLocal.Value; - - /// - /// Connection Id ... - /// - /// - public string ConnectionId => connectionIdAsyncLocal.Value; - - /// - /// Fill Context ... - /// - /// - /// - public void Set( - XUserClaimsInfoDto userInfo, - string connectionId = null - ) - { - // - userAsyncLocal.Value = userInfo; - connectionIdAsyncLocal.Value = connectionId; - } - - /// - /// Clear Context ... - /// - public void Clear() - { - // - userAsyncLocal.Value = null; - connectionIdAsyncLocal.Value = null; - } - - // - #region Static ... - public static XUserClaimsInfoDto CurrentUser => userAsyncLocal.Value; - public static string CurrentConnectionId => connectionIdAsyncLocal.Value; - public static bool IsAuthenticated => userAsyncLocal.Value != null; - #endregion - } -} diff --git a/Documents/Resources/Json/Requests.md b/Documents/Resources/Json/Requests.md index 182ef40..07b535c 100644 --- a/Documents/Resources/Json/Requests.md +++ b/Documents/Resources/Json/Requests.md @@ -15,9 +15,9 @@ Response: ```json { - "accessToken": "C9B72BA11F1D9562AB0AA0C4DBECAAE459941BDB0C532FC82739C1E0C39EA5FD", - "refreshToken": "4FD4FD2BC4393F8D6314AA97DE8FD32EFD6AD3BD01E837EF72F9006CA9E33271", - "expiresAt": 1794001216 + "accessToken": "905F846AB87139ED016A54A2A59628B4C32FA4629C5C233B026F9C8D56234882", + "refreshToken": "C840D444EC1823800976AD4E17C64D47E9099BFDC18702117F71246F5F912BEB", + "expiresAt": 1794081865 } ``` diff --git a/xAiMcpServer b/xAiMcpServer index 6e4ce28..1b09b4f 160000 --- a/xAiMcpServer +++ b/xAiMcpServer @@ -1 +1 @@ -Subproject commit 6e4ce2883242042c46983cd84ce59f644718525e +Subproject commit 1b09b4f6a08b1dd387d124c04b549586786bfbd9