From eeeb132bb2da1d5b7d6bad5c91691005e3f4e6ae Mon Sep 17 00:00:00 2001 From: Hadi Khazaee Asl Date: Thu, 29 Oct 2026 20:08:09 +0330 Subject: [PATCH] - Update submodule pointers: xAiApi, Modules/xAiModels, Modules/xHttpService; - Add Documents/Docs/Developer/xAiApi-14050807-Overview.html and -Overview-1.html (review reports); - Add Documents/GeneratedContext/*-20261029_145645.txt (xAiApi, xAiModels, xAiService); - Add Documents/Docs/ChangeLogs/1405-08-07-v01.html and this commit message file. --- Documents/Docs/ChangeLogs/1405-08-07-v01.html | 950 ++ .../CommitMessage-1405-08-07-v01.txt | 84 + .../Developer/xAiApi-14050807-Overview-1.html | 1297 ++ .../Developer/xAiApi-14050807-Overview-2.html | 1287 ++ .../Developer/xAiApi-14050807-Overview.html | 1413 ++ .../xDashboard-xAiApi-20261029_200138.txt | 13048 ++++++++++++++++ .../xDashboard-xAiModels-20261029_200138.txt | 10671 +++++++++++++ .../xDashboard-xAiService-20261029_200139.txt | 84 + Modules/xAiModels | 2 +- Modules/xHttpService | 2 +- xAiApi | 2 +- 11 files changed, 28837 insertions(+), 3 deletions(-) create mode 100644 Documents/Docs/ChangeLogs/1405-08-07-v01.html create mode 100644 Documents/Docs/ChangeLogs/CommitMessage-1405-08-07-v01.txt create mode 100644 Documents/Docs/Developer/xAiApi-14050807-Overview-1.html create mode 100644 Documents/Docs/Developer/xAiApi-14050807-Overview-2.html create mode 100644 Documents/Docs/Developer/xAiApi-14050807-Overview.html create mode 100644 Documents/GeneratedContext/xDashboard-xAiApi-20261029_200138.txt create mode 100644 Documents/GeneratedContext/xDashboard-xAiModels-20261029_200138.txt create mode 100644 Documents/GeneratedContext/xDashboard-xAiService-20261029_200139.txt diff --git a/Documents/Docs/ChangeLogs/1405-08-07-v01.html b/Documents/Docs/ChangeLogs/1405-08-07-v01.html new file mode 100644 index 0000000..54a810b --- /dev/null +++ b/Documents/Docs/ChangeLogs/1405-08-07-v01.html @@ -0,0 +1,950 @@ + + + + + + ChangeLog ۱۴۰۵/۰۸/۰۷ v01 - Pre-Production Fixes + + + +
+
+

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

+

+ xSaherelmWorkspace | تاریخ: ۱۴۰۵/۰۸/۰۷ (2026-10-29) | نسخه + مستند: v01 +

+

+ موضوع: رفع موانع پیش از Production در xAiApi — Scope واقعی + RAG، حذف ProxyController، ترتیب Middleware، استانداردسازی + SSE و اصلاح باگ‌های منطقی xAiModels +

+
+
+ دامنه: xAiApi، + Modules/xAiModels، + Modules/xHttpService + وضعیت: commit‌نشده (Working Tree) + Build: 0 Error +
+
+
+

۱. خلاصه

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
#موضوعنتیجه
۱Scope در RAG ماندگار + چهار Scope (Conversation / Project / User / + Global) با بررسی مالکیت و بازیابی لایه‌ای + پیاده‌سازی شد. +
۲تداخل Route در ProxyController + Controller حذف شد؛ Proxy فقط از طریق + XAiModelProxyMiddleware. +
۳ترتیب Middleware + ExceptionHandler/HSTS، Static Files پیش از + Routing، Swagger فقط در Development. +
۴قالب SSE + Helper مشترک در xHttpService؛ قالب + data: استاندارد با رویدادهای + done و error. +
۵بازآرایی ساختاری + ثابت‌های Knowledge و enum Scope به + xAiModels منتقل شدند. +
۶باگ‌های منطقی xAiModels + شرط‌های معکوس فیلتر مالکیت و چند خطای دیگر اصلاح + شد. +
+
+ +
+

۲. Scope واقعی در RAG ماندگار (xAiApi)

+

+ اصلاح‌شده + Providers/XAiRAGService.cs — بازنویسی کامل +

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
Scopeقالب شناسهخواندننوشتن
Conversationconversation/{id}/{file}#iمالک گفتگومالک گفتگو
Projectproject/{id}/{file}#iمالک پروژهمالک پروژه
User (پیش‌فرض)user/{ownerId}/{file}#iخود کاربرخود کاربر
Globalglobal/{file}#iهمهٔ کاربران احراز‌شدهفقط نقش admin
+
    +
  • + بررسی مالکیت از طریق GetProject / + GetConversation؛ عدم تطابق ← + NotAuthorized، نبود رکورد ← + NotFound. +
  • +
  • + بازیابی لایه‌ای: Conversation → Project (به‌طور + خودکار پروژهٔ همان گفتگو) → User → Global. Embedding + سؤال یک‌بار، حذف نتایج تکراری، هر لایه باقی‌ماندهٔ + TopK را پر می‌کند. IncludeUser و + IncludeGlobal قابل غیرفعال‌شدن‌اند. +
  • +
  • + فیلتر request.Type اکنون واقعاً به + SearchVectorsAsync ارسال می‌شود (قبلاً + null بود). +
  • +
  • + پاک‌سازی نام فایل: حذف مسیر کلاینت و جایگزینی + /، \ و # تا + ساختار شناسه نشکند. +
  • +
  • + اعمال محدودیت‌های موجود در تنظیمات: + MaxFilesPerIngest، + MaxFileSizeBytes، + MaxDocumentsPerScope (Global بدون + محدودیت تعداد سند). +
  • +
  • + Metadata هر Chunk شامل type، + scope، scopeId، + ownerId، ingestedAtUtc؛ در + Documents و Sources بازگردانده می‌شود. +
  • +
  • + متد جدید MigrateLegacyVectorsAsync: + انتقال داده‌های قدیمی {ownerId}/... به + user/{ownerId}/... (اول ذخیره، سپس حذف؛ + تکرارپذیر). +
  • +
+

+ اصلاح‌شده + Interfaces/IXAiRAGService.cs +

+

+ امضای IngestAsync، + LoadDocumentsAsync و + RemoveDocumentAsync پارامتر + XAiKnowledgeScopeDescriptor scope می‌گیرد؛ + RetrieveAsync اکنون + XAiKnowledgeAskRequest می‌پذیرد؛ + MigrateLegacyVectorsAsync اضافه شد. +

+

+ اصلاح‌شده + Models/XAiKnowledgeModels.cs +

+
    +
  • + حذف usingهای تکراری (هشدار CS0105). +
  • +
  • + مقدار پیش‌فرض Scope در Descriptor به + User تغییر کرد (قبلاً صفر = + Conversation بود و نتایج را غلط گزارش می‌کرد). +
  • +
  • + Factory جدید + XAiKnowledgeScopeDescriptor.User()؛ + فیلدهای IncludeUser و + IncludeGlobal در + XAiKnowledgeAskRequest. +
  • +
+

+ اصلاح‌شده + Controllers/KnowledgeController.cs +

+ + + + + + + + + + + + + + + + + + + + + + + + + +
Endpointتغییر
POST /Knowledge/Ingest + FormData جدید: scope، + scopeId (+ + knowledgeType، + replaceExisting) +
GET /Knowledge/Documents + Query جدید: scope، + scopeId، knowledgeType +
DELETE /Knowledge/Documents + Query جدید: scope، + scopeId +
POST /Knowledge/MigrateLegacy + جدید مهاجرت + داده‌های قدیمی کاربر جاری +
POST /Knowledge/AskStream + اولین آیتم پیش از شروع Stream دریافت می‌شود تا + خطاهای Scope/مالکیت با کد HTTP مناسب برگردند. +
+
+ +
+

۳. حذف ProxyController (xAiApi)

+

+ حذف‌شده + Controllers/ProxyController.cs +

+
    +
  • + Route ریشهٔ {modelName}/{path} با همهٔ + Verbها و [AllowAnonymous] هر مسیر + دوبخشی را تصاحب می‌کرد (مثلاً + GET /Knowledge/Ask به‌جای 405 بدون + احراز هویت وارد Proxy می‌شد). +
  • +
  • + درخواست را با یک Hop اضافه به همین سرویس و مسیر + /ai-model می‌فرستاد؛ فقط بدنهٔ JSON و + فقط یک Segment از مسیر را پشتیبانی می‌کرد. +
  • +
  • + Proxy اکنون صرفاً توسط + XAiModelProxyMiddleware روی + /ai-model/{model}/{**path} با احراز + هویت ApiKey/Token انجام می‌شود. +
  • +
+
+ +
+

۴. ترتیب Middleware (xAiApi)

+

اصلاح‌شده Startup.cs

+
+Development : DeveloperExceptionPage
+Production  : UseExceptionHandler("/error") + UseHsts
+→ UseHttpsRedirection
+→ UseXStorageService      (Static Files — قبلاً بعد از UseEndpoints بود)
+→ UseXSwagger             (فقط Development — قبلاً همیشه فعال)
+→ UseXCors → UseXAiModelProxy
+→ UseRouting → UseXIdentityService → UseAuthorization → UseEndpoints
+→ UseXPushService         (UseSignalR قدیمی؛ عمداً جابه‌جا نشد)
+→ Init: Database / String / Tag / File
+

+ اصلاح‌شده + Controllers/StartupController.cs +

+

+ Endpoint جدید /error (پنهان از Swagger) که + یک XError عمومی با کد 500 برمی‌گرداند و + جزئیات Exception را افشا نمی‌کند. +

+
+ +
+

۵. استانداردسازی SSE

+

+ جدید + Modules/xHttpService/Extensions/XSseExtensions.cs +

+

+ Helper مشترک در ماژول xHttpService (نه در + xAiApi) تا سایر سرویس‌ها هم بتوانند استفاده کنند: +

+ + + + + + + + + + + + + + + + + + + + + + + + + +
متدکار
PrepareSseResponse + Content-Type + text/event-stream; charset=utf-8، + Cache-Control، + X-Accel-Buffering: no، غیرفعال‌سازی + Buffering +
WriteSseEventAsync + سریال‌سازی camelCase و ارسال data:؛ + متن چندخطی به چند خط data: تقسیم + می‌شود +
WriteSseDoneAsync + event: done + + data: [DONE] +
WriteSseErrorAsync + event: error + + data: {"error":"..."} (هرگز + Exception پرتاب نمی‌کند) +
IsClientCancellation + تشخیص قطع اتصال کلاینت برای جلوگیری از لاگ خطای + کاذب +
+

+ اصلاح‌شده + Modules/xHttpService/xHttpService.csproj +

+

+ افزودن + Microsoft.AspNetCore.Http.Features 2.3.13 + (برای IHttpBufferingFeature). +

+

+ اصلاح‌شده Endpointهای + Stream در xAiApi +

+ + + + + + + + + + + + + + + + + + + + + + + + + + +
Endpointقبلبعد
+ XAiServiceControllerBase.AskTextStream + + {text}\n\n بدون data: + data: {"text":"..."} + done
+ XAiServiceControllerBase.AskStream + + {json} بدون data: و + جداکننده + data: {json} + done
KnowledgeController.AskStreamdata: {json} بدون پایان+ done / error
+ ChatWithDocumentsController.AskStream + data: {json} بدون پایان+ done / error
+
    +
  • + اعتبارسنجی پیش از شروع Stream؛ خطا با کد 400 و JSON + برمی‌گردد (قبلاً 200 خالی). +
  • +
  • + خطای پیش از شروع Stream از طریق + GetExceptionActionResult با کد HTTP + درست (401/404/...) برمی‌گردد. +
  • +
  • + هدر Connection: keep-alive حذف شد (در + HTTP/2 نامعتبر است). +
  • +
+
+ تغییر شکننده: کلاینت‌های + AskTextStream و AskStream باید + به قالب جدید (data: + + event: done) مهاجرت کنند. +
+
+data: {"text":"سلام"}
+
+data: {"text":" دنیا"}
+
+event: done
+data: [DONE]
+
+ +
+

۶. بازآرایی ساختاری: انتقال ثابت‌ها به xAiModels

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
نوعمسیرشرح
جدید + Modules/xAiModels/Constants/XAiKnowledgeScope.cs + + enum با Conversation=0، + Project=1، Global=2، + User=3 و + [StringValue] برای پیشوند شناسه +
حذف‌شده + xAiApi/Constants/XAiKnowledgeScope.cs + به xAiModels منتقل شد
اصلاح‌شده + Modules/xAiModels/Constants/XAiModelsConstants.cs + + ثابت‌های Knowledge، پیشوندهای Scope، کلیدهای + Metadata، XAiErrorRoute +
اصلاح‌شده + xAiApi/Constants/XAiApiConstants.cs + + حذف ثابت‌های منتقل‌شده و + XOpenAINoKey +
اصلاح‌شده + xAiApi/Extensions/XModelsExtensions.cs
xAiApi/Providers/XAiEmbeddingServiceBase.cs +
+ ارجاع به + XAiModelsConstants.XOpenAINoKey +
+
+ مقادیر عددی enum و رشته‌های ثابت تغییر نکرده‌اند؛ فقط + namespace از xAiApi.Constants به + xAiModels.Constants رفته است. +
+
+ +
+

۷. رفع باگ‌های منطقی در xAiModels

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
فایل / متدمشکلاصلاح
+ XAiDataProvider.QueryProjects
QueryConversations
QueryMessages +
+ شرط معکوس + if (ownerId.IsNullOrEmpty()): فیلتر + مالکیت فقط با ownerId خالی اعمال می‌شد و کاربر + داده‌های دیگران را می‌دید. + + if (!ownerId.IsNullOrEmpty()) — + رفع نشت داده بین کاربران +
+ XAiDataProvider.LoadConversations + + ignoreSoftDeleteds: false گفتگوهای + حذف‌شده را هم برمی‌گرداند + true
+ CreateProject (۲ مورد)
CreateConversation +
+ پرچم isDefaultLanguageHandled پس از + تنظیم زبان پیش‌فرض false می‌ماند + true
GetDefaultConversation + استفاده از project.Id پیش از + بارگذاری project + id: projectId
+ XAiModelsExtensions.HasDefaultProject
HasDefaultConversation +
+ شرط معکوس if (source.HasChild()): + برای لیست غیرخالی Exception پرتاب می‌شد + if (!source.HasChild() ...)
+
+ +
+

۸. سایر تغییرات xAiApi

+ + + + + + + + + + + + + + + + +
نوعمسیرشرح
اصلاح‌شدهDatabase/XAiApiDbContext.cs + ثبت XAiVectorEntityRegisterar؛ بدون + آن Entity جدول XAiVector در + DbContext ثبت نمی‌شد. +
اصلاح‌شده + Providers/Extractors/XCodeFileContentExtractor.cs + + محتوای فایل واقعاً با + ReadToEndAsync خوانده می‌شود (قبلاً + result.Text خالی می‌ماند)؛ نام فایل + ثابت "book.epub" حذف شد. +
+
+ +
+

۹. وضعیت Git در کل Workspace

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
نوعمسیرشرح
ساب‌ماژولxAiApi + ۱۵ فایل (۱۳ اصلاح، ۲ حذف) — حدود ۹۲۵+ / ۵۹۵− +
ساب‌ماژولModules/xAiModels + ۳ اصلاح + ۱ فایل جدید + (XAiKnowledgeScope.cs) +
ساب‌ماژولModules/xHttpService + ۱ اصلاح (csproj) + ۱ فایل جدید + (XSseExtensions.cs) +
جدید + Documents/Docs/Developer/xAiApi-14050807-Overview*.html + + گزارش بازبینی معماری که این تغییرات بر اساس آن + انجام شد +
جدید + Documents/GeneratedContext/*-20261029_145645.txt + + Context تولیدشدهٔ xAiApi، xAiModels، xAiService + (مستندات کمکی) +
جدید + Documents/Docs/ChangeLogs/1405-08-07-v01.html
CommitMessage-1405-08-07-v01.txt +
همین گزارش و پیام Commit
+
+ ترتیب Commit: ابتدا ساب‌ماژول‌های + Modules/xHttpService و + Modules/xAiModels (وابستگی‌ها)، سپس + xAiApi، و در پایان مخزن اصلی برای + به‌روزرسانی pointerها و مستندات. +
+
+ +
+

۱۰. اعتبارسنجی

+
+dotnet build xAiApi/xAiApi.csproj --nologo -v q
+    392 Warning(s)   (MSB3277 / NU1900 — تعارض نسخهٔ مراجع، از قبل موجود)
+    0 Error(s)
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
درخواست (Development، بدون توکن)نتیجهمعنا
GET /200سرویس بالا آمد
GET /Knowledge/Ask405دیگر توسط ProxyController تصاحب نمی‌شود
GET /foo/bar404مسیر دوبخشی ناشناخته
GET /error500 JSONEndpoint خطای عمومی
+ GET /ai-model/NotExists/v1/models + 404Middleware پروکسی فعال است
+ Endpointهای محافظت‌شده (Knowledge, + AskTextStream) + 401Authorization سالم
+
+ تست End-to-End با کاربر احراز‌شده و مدل Embedding/LLM + واقعی (Ingest/Ask/AskStream در Scopeهای مختلف، بررسی + 403/NotAuthorized روی پروژهٔ کاربر دیگر) هنوز انجام نشده + است. +
+
+ +
+

۱۱. اقدامات بعدی

+
    +
  • + هماهنگی Frontend با قالب جدید SSE در + AskTextStream و AskStream. +
  • +
  • + فراخوانی + POST /Knowledge/MigrateLegacy برای هر + کاربر دارای داده‌های قبلی (یا افزودن یک Job + یک‌باره). +
  • +
  • + بررسی UseHsts در Production اگر سرویس + پشت Reverse Proxy بدون TLS اجرا می‌شود. +
  • +
  • + بررسی دسترسی بدون احراز هویت به فایل‌های آپلودشده در + wwwroot/Storage/Uploads (خارج از این + تغییرات). +
  • +
  • + جستجوی برداری فعلاً همهٔ کاندیداهای پیشوند را در + حافظه امتیازدهی می‌کند؛ برای حجم بالا ایندکس برداری + توصیه می‌شود. +
  • +
+
+ +
+

۱۲. فایل‌های مستند

+

+ گزارش: + Documents/Docs/ChangeLogs/1405-08-07-v01.html +

+

+ Commit message: + Documents/Docs/ChangeLogs/CommitMessage-1405-08-07-v01.txt +

+

+ برای تغییرات بعدی همین تاریخ از پسوند + v02 استفاده شود. +

+
+
+
+ تولیدشده در تاریخ ۱۴۰۵/۰۸/۰۷ (2026-10-29) | xSaherelmWorkspace | + ChangeLog v01 +
+
+ + diff --git a/Documents/Docs/ChangeLogs/CommitMessage-1405-08-07-v01.txt b/Documents/Docs/ChangeLogs/CommitMessage-1405-08-07-v01.txt new file mode 100644 index 0000000..c5a0f25 --- /dev/null +++ b/Documents/Docs/ChangeLogs/CommitMessage-1405-08-07-v01.txt @@ -0,0 +1,84 @@ +=============================================================================== + Commit Message - xSaherelmWorkspace + تاریخ: ۱۴۰۵/۰۸/۰۷ (2026-10-29) + نسخه مستند: v01 + گزارش کامل: Documents/Docs/ChangeLogs/1405-08-07-v01.html +=============================================================================== + +هدف: رفع موانع پیش از Production در xAiApi (Scope واقعی RAG، حذف +ProxyController، ترتیب Middleware، قالب SSE) و اصلاح باگ‌های منطقی xAiModels. + +ترتیب Commit: [1] xHttpService -> [2] xAiModels -> [3] xAiApi -> [4] Root + +[1] Modules/xHttpService +Add Shared Server-Sent Events Helpers +- Add XSseExtensions: PrepareSseResponse, WriteSseEventAsync, WriteSseRawAsync, + WriteSseDoneAsync, WriteSseErrorAsync, IsClientCancellation; +- Spec-compliant "data:" framing, multi-line split, "event: done" / "event: error"; +- Add Microsoft.AspNetCore.Http.Features 2.3.13 reference. +Files: A Extensions/XSseExtensions.cs; M xHttpService.csproj + +[2] Modules/xAiModels +Move Knowledge Constants and Fix Inverted Ownership Filters +- Add XAiKnowledgeScope enum (Conversation=0, Project=1, Global=2, User=3) with StringValue prefixes; +- Add Knowledge constants, scope prefixes, metadata keys and XAiErrorRoute to XAiModelsConstants; +- Fix inverted ownerId condition in QueryProjects / QueryConversations / QueryMessages + (ownership filter was skipped for real owners -> cross-user data exposure); +- Fix inverted HasChild() validation in HasDefaultProject / HasDefaultConversation; +- LoadConversations: ignore soft-deleted conversations; +- CreateProject / CreateConversation: set isDefaultLanguageHandled = true; +- GetDefaultConversation: use projectId instead of unloaded project.Id. +Files: A Constants/XAiKnowledgeScope.cs; M Constants/XAiModelsConstants.cs; + M Extensions/XAiModelsExtensions.cs; M Providers/XAiDataProvider.cs + +[3] xAiApi +Implement RAG Scopes, Remove ProxyController, Fix Pipeline Order and SSE Format +- RAG: real scopes with identifiers conversation/{id}/, project/{id}/, user/{ownerId}/, global/; +- RAG: ownership checks via GetProject/GetConversation; Global write requires admin role; +- RAG: tiered retrieval Conversation -> Project -> User -> Global (single embedding, dedup, TopK fill); +- RAG: apply Type filter, sanitize file names, enforce MaxFilesPerIngest/MaxFileSizeBytes/MaxDocumentsPerScope; +- RAG: store scope/scopeId/type/ownerId metadata; return it in documents and sources; +- RAG: add MigrateLegacyVectorsAsync + POST /Knowledge/MigrateLegacy ({ownerId}/... -> user/{ownerId}/...); +- Knowledge API: scope/scopeId on Ingest, Documents, DELETE Documents; +- Remove ProxyController (root route "{modelName}/{path}" + AllowAnonymous hijacked all 2-segment paths); +- Startup: ExceptionHandler("/error") + HSTS outside Development; Swagger only in Development; + static files before routing; CORS before model proxy; add /error endpoint; +- SSE: all stream endpoints use xHttpService XSseExtensions; validate before streaming; + pre-stream errors return proper HTTP status; remove "Connection: keep-alive"; +- Use xAiModels.Constants for XAiKnowledgeScope / Knowledge constants / XOpenAINoKey; +- Register XAiVectorEntityRegisterar in XAiApiDbContext; +- XCodeFileContentExtractor: actually read stream content; drop hard-coded "book.epub". +BREAKING: AskTextStream emits data: {"text":"..."}; AskStream emits data: {json}; both end with event: done. +Files: D Controllers/ProxyController.cs; D Constants/XAiKnowledgeScope.cs; + M Constants/XAiApiConstants.cs; M Controllers/ChatWithDocumentsController.cs; + M Controllers/KnowledgeController.cs; M Controllers/StartupController.cs; + M Controllers/XAiServiceControllerBase.cs; M Database/XAiApiDbContext.cs; + M Extensions/XModelsExtensions.cs; M Interfaces/IXAiRAGService.cs; + M Models/XAiKnowledgeModels.cs; M Providers/Extractors/XCodeFileContentExtractor.cs; + M Providers/XAiEmbeddingServiceBase.cs; M Providers/XAiRAGService.cs; M Startup.cs + +[4] Workspace (root) +- Update submodule pointers: xAiApi, Modules/xAiModels, Modules/xHttpService; +- Add Documents/Docs/Developer/xAiApi-14050807-Overview.html and -Overview-1.html (review reports); +- Add Documents/GeneratedContext/*-20261029_145645.txt (xAiApi, xAiModels, xAiService); +- Add Documents/Docs/ChangeLogs/1405-08-07-v01.html and this commit message file. + +Validation: +- dotnet build xAiApi/xAiApi.csproj --nologo -v q -> 0 Error(s), 392 pre-existing warnings (MSB3277/NU1900); +- Runtime smoke (Development, anonymous): GET / 200; GET /Knowledge/Ask 405 (no longer proxied); + GET /foo/bar 404; GET /error 500 JSON; /ai-model/NotExists 404 (middleware); protected endpoints 401; +- Authenticated end-to-end tests (Ingest/Ask/AskStream with real embedding/LLM) still pending. + +Follow-ups: +- Frontend must migrate to the new SSE format; +- Call POST /Knowledge/MigrateLegacy for users with legacy vectors; +- Review UseHsts behind TLS-terminating reverse proxy; +- Review anonymous access to wwwroot/Storage/Uploads. + +Suggested root commit title: +Implement RAG Scopes, Remove ProxyController, Fix Pipeline and SSE, Fix xAiModels Ownership Filters (۱۴۰۵/۰۸/۰۷ v01) + +For additional documentation use v02: +1405-08-07-v02.html +CommitMessage-1405-08-07-v02.txt +=============================================================================== diff --git a/Documents/Docs/Developer/xAiApi-14050807-Overview-1.html b/Documents/Docs/Developer/xAiApi-14050807-Overview-1.html new file mode 100644 index 0000000..fae014c --- /dev/null +++ b/Documents/Docs/Developer/xAiApi-14050807-Overview-1.html @@ -0,0 +1,1297 @@ + + + + + + بازبینی دوم و تحلیل اصلاحات | سامانه xAiApi + + + +
+
+
+
+ +
+
+
شماره مستند: ARCH-REV-1405-002
+
نسخه: ۲.۰
+
تاریخ تهیه: آبان ۱۴۰۵
+
طبقه‌بندی: محرمانه
+
+
+
+ REVIEW & CORRECTION ANALYSIS +

بازبینی دوم و تحلیل اصلاحات سامانه xAiApi

+

+ تحلیل تغییرات اعمال‌شده، وضعیت خطاهای قبلی و مسیر + باقی‌مانده +

+
+
+
+
+ خلاصه مدیریتی:
+ در این نسخه از کدها، مجموعه‌ای از اصلاحات هدفمند اعمال شده + است. خطاهای بحرانی مربوط به ثبت Entity، Migration، جداسازی + مالکیت داده و NullReferenceException برطرف شده‌اند. همچنین + بخش قابل توجهی از نقاط ضعف امنیتی در Authorization مرتفع شده + است. با این حال، چند خطای مهم دیگر در حوزه RAG ماندگار + (Scope)، Startup Pipeline، مسیرهای Proxy و قالب SSE همچنان + باز هستند و پیش از استفاده Production باید تعیین تکلیف شوند. +
+
+
+
۱
+
+

خلاصه اجرایی بازبینی دوم

+
Executive Summary
+
+
+
+

+ از میان ۱۷ مورد شناسایی‌شده در بازبینی اول، ۸ مورد + به‌طور کامل اصلاح شده، ۱ مورد به‌صورت جزئی اصلاح شده + و ۸ مورد همچنان باز است. اصلاحات انجام‌شده عمدتاً + روی لایه داده، ثبت Entity و Queryهای مالکیت متمرکز + بوده و همین امر باعث کاهش قابل توجه ریسک نشت داده و + پایداری Runtime شده است. +

+
+
+
۸
+
+ مورد کاملاً اصلاح‌شده +
+
+
+
۱
+
مورد اصلاح جزئی
+
+
+
۸
+
+ مورد باز / اصلاح‌نشده +
+
+
+
۴۷٪
+
نرخ اصلاح کل موارد
+
+
+
+ نتیجه کلیدی: ریسک‌های بحرانی F-01 + تا F-04 که پیش از این امکان نشت داده و خطای Runtime + را ایجاد می‌کردند، برطرف شده‌اند. سامانه اکنون در + حوزه مالکیت داده و ثبت Entity پایدارتر است. +
+
+ نکته مهم: مشکلات مربوط به + پیاده‌سازی واقعی Scope در RAG ماندگار، تداخل Route + در ProxyController، ترتیب Middleware در Startup و + قالب SSE همچنان به قوت خود باقی هستند و باید پیش از + Production تعیین تکلیف شوند. +
+
+
+
+
+
۲
+
+

فهرست تغییرات اعمال‌شده

+
Applied Changes
+
+
+
+

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

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
شناسهمحلتغییر اعمال‌شدهوضعیت
F-01XAiApiDbContext + افزودن + nameof(XAiVectorEntityRegisterar) + به + dynamicEntityRegisterarsNames + + اصلاح شد +
F-02Migration جدید + افزودن ستون Type با + maxLength=100 و دو Index روی + Identifier و + Type در Migration + + اصلاح شد +
F-03 + XAiDataProvider.QueryProjects / + QueryConversations / QueryMessages + + اصلاح شرط به + if (!ownerId.IsNullOrEmpty()) + تا Predicate مالکیت اعمال شود + + اصلاح شد +
F-04 + XAiDataProvider.GetDefaultConversation + + استفاده از id: projectId به + جای id: project.Id در شاخه + else + + اصلاح شد +
F-09XCodeFileContentExtractor + انتساب واقعی متن خوانده‌شده به + result.Text و جایگزینی نام + فایل پیش‌فرض با + string.Empty + + اصلاح شد +
F-12 + XAiModelsExtensions.HasDefaultProject / + HasDefaultConversation + + معکوس شدن شرط اعتبارسنجی به + if (!source.HasChild() ...) + + اصلاح شد +
F-13 + XAiDataProvider.CreateProject / + CreateConversation + + مقدار + isDefaultLanguageHandled = + true + پس از تخصیص زبان پیش‌فرض + + اصلاح شد +
F-14XAiDataProvider.LoadConversations + تنظیم + ignoreSoftDeleteds: true + برای Conversationها + + اصلاح شد +
F-16 + XAiServiceControllerBase / + XAiEmbeddingServiceControllerBase + + حذف [AllowAnonymous] از + اکثر Actionها و افزودن + [Authorize(Policy = + XPolicies.EnabledUser)]؛ اما Embedding و + Embeddings همچنان anonymous + هستند + + جزئی +
F-05XAiRAGService— + باز +
F-06ProxyController— + باز +
F-07Startup.Configure— + باز +
F-08SSE در XAiServiceControllerBase— + باز +
F-10XImageFileContentExtractor— + باز +
F-11XAiEmbeddingServiceBase (Ollama)— + باز +
F-15XAiRAGService.IngestAsync— + باز +
F-17دو مسیر موازی Proxy— + باز +
+
+
+
+
+
۳
+
+

تحلیل تفصیلی اصلاحات انجام‌شده

+
+ Detailed Analysis of Fixes +
+
+
+
+

+ ۳-۱. لایه داده و Migration (F-01، F-02) +

+

+ ثبت XAiVectorEntityRegisterar در + Context به همراه Migration جدید که ستون + Type و دو Index روی + Identifier و Type را ایجاد + می‌کند، پایه ذخیره‌سازی و جستجوی RAG ماندگار را + تثبیت کرده است. اکنون مدل XAiVector با Database + هم‌راستا است و Repositoryهای Vector بدون خطای + Runtime کار می‌کنند. +

+

+ ۳-۲. جداسازی مالکیت داده (F-03) +

+

+ معکوس شدن شرط در QueryProjects، QueryConversations و + QueryMessages باعث شده است که در صورت وجود ownerId، + Predicate مالکیت واقعاً ساخته شود. این تغییر + مستقیماً ریسک نشت داده بین کاربران را از بین می‌برد + و به Validation لایه بالاتر اتکا نمی‌کند. +

+

+ ۳-۳. پایداری GetDefaultConversation + (F-04) +

+

+ استفاده از projectId ورودی به جای + project.Id در زمانی که + project هنوز null است، باعث حذف + NullReferenceException در این متد شده و مسیر بازیابی + پیش‌فرض گفتگو را پایدار کرده است. +

+

+ ۳-۴. استخراج کد منبع (F-09) +

+

+ XCodeFileContentExtractor اکنون محتوای خوانده‌شده را + به result.Text اختصاص می‌دهد. این اصلاح + باعث می‌شود فایل‌های کد در ChatWithDocuments و + Knowledge واقعاً قابل استفاده باشند. +

+

+ ۳-۵. اعتبارسنجی مجموعه‌ها (F-12) و پرچم زبان + پیش‌فرض (F-13) +

+

+ اصلاح شرط در HasDefaultProject و + HasDefaultConversation رفتار این متدها + را به حالت منطقی برگردانده است. همچنین در + CreateProject و + CreateConversation، پرچم + isDefaultLanguageHandled پس از اولین + تخصیص مقدار true می‌گیرد و از اعمال + تکراری زبان پیش‌فرض جلوگیری می‌شود. +

+

+ ۳-۶. حذف Soft-Delete از LoadConversations + (F-14) +

+

+ تغییر ignoreSoftDeleteds از + false به true باعث می‌شود + آیتم‌های حذف‌شده در لیست Conversationها ظاهر نشوند. +

+

+ ۳-۷. اصلاح جزئی Authorization (F-16) +

+

+ اکثر Actionهای + XAiServiceControllerBase اکنون با + [Authorize(Policy = + XPolicies.EnabledUser)] + محافظت می‌شوند. اما در + XAiEmbeddingServiceControllerBase هنوز + روی Embedding و + Embeddings صفت + [AllowAnonymous] باقی مانده است و این + دو Endpoint بدون احراز هویت در دسترس هستند. +

+
+
+
+
+
۴
+
+

موارد باز و تحلیل تأثیر آن‌ها

+
Open Issues & Impact
+
+
+
+

+ موارد زیر همچنان در کدها باز هستند و تأثیر مستقیم بر + آمادگی Production دارند: +

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
شناسهمحلشرحتأثیر
F-05XAiRAGService / KnowledgeController + Scopeهای Conversation، Project و Global + و همچنین فیلتر Type در Ask + و Retrieve اعمال نمی‌شوند. در + SearchVectorsAsync مقدار + type: null ارسال می‌شود و + ProjectId/ConversationId از Request + استفاده نمی‌شود. + + جداسازی دانش بین Scopeها کار نمی‌کند و + همه وکتورهای Owner در یک فضای مشترک + جستجو می‌شوند. +
F-06ProxyController + Route {modelName}/{path} در + سطح Root تعریف شده و می‌تواند با مسیرهای + دو بخشی مانند + DefaultAi/AskText تداخل + داشته باشد. + + ریسک تداخل Routing و همچنین Hop اضافی و + امکان Loop در حالت Proxy غیرفعال. +
F-07Startup.Configure + Middlewareهای Storage، Push، Database، + String، Tag و File بعد از + UseEndpoints ثبت شده‌اند. + + این Middlewareها برای درخواست‌های Match + شده اجرا نمی‌شوند. +
F-08XAiServiceControllerBase + در AskTextStream خروجی + به‌صورت + $"{payload}\n\n" نوشته + می‌شود و در + AskStream به‌صورت + $"{payload}"، بدون prefix + استاندارد data: و بدون + پایان‌بندی دو newline. + + کلاینت‌های استاندارد SSE نمی‌توانند داده + را به درستی دریافت کنند. +
F-10XImageFileContentExtractor + در Constructor، وجود + DataPath و + DefaultLanguage حتی وقتی + EnableOcrFallback = false + است الزامی شده. + + استخراج تصویر بدون OCR نیز شکست می‌خورد. +
F-11XAiEmbeddingServiceBase (Ollama) + در حالت Ollama، مدل Embedding + descriptor.LLM هنگام ساخت + OllamaApiClient استفاده + نمی‌شود. + + ممکن است مدل پیش‌فرض Ollama انتخاب شود و + Embedding با مدل مورد انتظار متفاوت + باشد. +
F-15XAiRAGService.IngestAsync + فیلدهای Scope، + ScopeId و + Type در + XAiKnowledgeIngestResult و + XAiKnowledgeDocumentInfo پر + نمی‌شوند. محدودیت‌های + MaxFilesPerIngest، + MaxFileSizeBytes و + MaxDocumentsPerScope اعمال + نمی‌شوند. + + پاسخ API ناقص است و امکان مصرف بی‌رویه + حافظه و Database وجود دارد. +
F-16XAiEmbeddingServiceControllerBase + [AllowAnonymous] روی + Embedding و + Embeddings باقی مانده است. + + دسترسی بدون احراز هویت به سرویس + Embedding. +
F-17Middleware و ProxyController + دو مسیر موازی برای Proxy وجود دارد و + ProxyController درخواست را دوباره به + همین سامانه می‌فرستد. + + Hop اضافی، ریسک Loop و افزایش هزینه + پردازش. +
+
+ پرخطرترین مورد باقی‌مانده: F-05 + همچنان اجازه می‌دهد تمام وکتورهای یک Owner بدون + تفکیک Project/Conversation/Type جستجو شوند. این + موضوع با اهداف اعلام‌شده در مدل‌های + XAiKnowledgeScope و XAiKnowledgeAskRequest در تناقض + است. +
+
+
+
+
+
۵
+
+

پیشنهادهای اصلاحی مرحله بعد

+
+ Next-Step Recommendations +
+
+
+
+

+ اولویت‌بندی موارد باز بر اساس تأثیر بر پایداری و + امنیت سامانه: +

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
اولویتاقدام پیشنهادیشناسه مرتبط
+ P0 + + پیاده‌سازی واقعی Scope و Type در + XAiRAGService: استخراج + ProjectId/ConversationId از Request، + ساخت Scope در Ingest و اعمال فیلترهای + IdentifierPrefix و Type در + SearchVectorsAsync. + F-05، F-15
+ P0 + + حذف یا محدودکردن Route مربوط به + ProxyController و اتکا به + XAiModelProxyMiddleware. جلوگیری از Loop + در حالت Proxy غیرفعال. + F-06، F-17
+ P1 + + حذف [AllowAnonymous] از + Embedding و Embeddings یا مستندسازی صریح + دلیل آن. + F-16
+ P1 + + یکسان‌سازی قالب SSE در همه Controllerها + با prefix data: و + پایان‌بندی دو newline. + F-08
+ P1 + + جابه‌جایی Middlewareهای Storage، Push، + Database، String، Tag و File به قبل از + UseEndpoints. + F-07
+ P2 + + اعتبارسنجی OCR فقط در صورت + EnableOcrFallback = true و + استفاده از + descriptor.LLM در + OllamaApiClient برای Embedding. + F-10، F-11
+ P2 + + پرکردن فیلدهای Scope/ScopeId/Type در + IngestResult و اعمال محدودیت‌های + MaxFilesPerIngest و MaxFileSizeBytes. + F-15
+ P2 + + افزودن تست‌های End-to-End برای Scope، + مالکیت، SSE و Proxy پس از اصلاحات. + همه موارد
+
+ پیشنهاد کلیدی: با توجه به اینکه + اصلاحات داده و مالکیت انجام شده، بهتر است ابتدا یک + تست پذیرش روی مالکیت داده‌ها، Migration و کارکرد + Knowledge انجام شود و سپس F-05 و F-06 به‌عنوان آخرین + موانع آمادگی Production برطرف شوند. +
+
+
+
+
+
۶
+
+

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

+
Final Conclusion
+
+
+
+

+ اصلاحات اعمال‌شده نشان‌دهنده حرکت درست و هدفمند تیم + توسعه است. خطاهای بحرانی مرتبط با ثبت Entity، + Migration، Queryهای مالکیت و NullReferenceException + برطرف شده‌اند و پایه داده سامانه اکنون پایدارتر است. + همچنین حذف [AllowAnonymous] از بخش + بزرگی از Actionها، سطح حمله را کاهش داده است. +

+

+ با این حال، سامانه هنوز از نظر پیاده‌سازی واقعی + Scope در RAG، مدیریت مسیرهای Proxy، ترتیب + Middlewareها و قالب SSE نیازمند اصلاح است. تا زمانی + که F-05 و F-06 برطرف نشوند، نمی‌توان گفت جداسازی + دانش و رفتار Proxy کاملاً قابل اتکاست. +

+
+

🎯 جمع‌بندی اجرایی بازبینی دوم

+

+ پیشرفت قابل توجهی در پایداری داده و امنیت پایه + حاصل شده است. +

+
+ مسیر باقی‌مانده تا Production:
+ پیاده‌سازی Scope در RAG + تعیین تکلیف + ProxyController + اصلاح Startup Pipeline + + استانداردسازی SSE + حذف AllowAnonymous از + Embedding +
+
+
+
+
+ این مستند محرمانه بوده و صرفاً جهت بررسی فنی داخلی تهیه شده + است. هرگونه کپی‌برداری یا افشا بدون اجازه کتبی ممنوع است. +
+
+
+ + +
+ تاریخ تهیه: آبان ۱۴۰۵  |  نسخه: ۲.۰  |  + طبقه‌بندی: محرمانه +
+
+
+ + diff --git a/Documents/Docs/Developer/xAiApi-14050807-Overview-2.html b/Documents/Docs/Developer/xAiApi-14050807-Overview-2.html new file mode 100644 index 0000000..3722d0f --- /dev/null +++ b/Documents/Docs/Developer/xAiApi-14050807-Overview-2.html @@ -0,0 +1,1287 @@ + + + + + + بازبینی سوم و تحلیل اصلاحات | سامانه xAiApi + + + +
+
+
+
+ +
+
+
شماره مستند: ARCH-REV-1405-003
+
نسخه: ۳.۰
+
تاریخ تهیه: آبان ۱۴۰۵
+
طبقه‌بندی: محرمانه
+
+
+
+ CHANGES REVIEW & RESULTS +

بازبینی سوم و تحلیل اصلاحات سامانه xAiApi

+

+ بررسی تغییرات سطح کد، نتایج اعمال و وضعیت نهایی آمادگی +

+
+
+
+
+ خلاصه مدیریتی:
+ در این نسخه از کدها، اصلاحات گسترده و ساختاری در حوزه RAG + ماندگار، Startup Pipeline، SSE، Proxy و Authorization انجام + شده است. مهم‌ترین دستاورد این نسخه، پیاده‌سازی کامل و واقعی + Scope در RAG (Conversation / Project / User / Global) و حذف + کامل ProxyController است. از میان ۱۷ مورد شناسایی‌شده در + بازبینی اول، ۱۵ مورد کاملاً اصلاح شده، ۱ مورد جزئی اصلاح شده + و تنها ۲ مورد باقی مانده است. +
+
+
+
۱
+
+

خلاصه اجرایی

+
Executive Summary
+
+
+
+

+ این نسخه یک جهش قابل توجه در بلوغ فنی سامانه محسوب + می‌شود. عمده اصلاحات در سطح معماری و نه صرفاً + وصله‌کاری انجام شده است. بازطراحی XAiRAGService با + ساختار Scopeدار، حذف کامل ProxyController، بازنویسی + SSE با Helperهای استاندارد، و سازماندهی مجدد + Pipeline در Startup، همگی نشان‌دهنده رویکرد حرفه‌ای + به رفع مشکلات ساختاری است. +

+
+
+
۱۵
+
+ مورد کاملاً اصلاح‌شده +
+
+
+
۱
+
اصلاح جزئی
+
+
+
۲
+
+ مورد باز باقی‌مانده +
+
+
+
+ دستاورد اصلی: سامانه در حوزه + جداسازی دانش (Scope)، رفتار Streaming (SSE) و + پایداری Pipeline (Startup) اکنون از نظر معماری قابل + اتکاست. جداسازی Conversation/Project/User/Global با + کنترل دسترسی کامل پیاده‌سازی شده و امکان مهاجرت + داده‌های قدیمی نیز فراهم شده است. +
+
+ موارد باقی‌مانده: تنها دو نقص فنی + کوچک اما واقعی وجود دارد: شرط اعتبارسنجی OCR حتی در + حالت غیرفعال، و عدم استفاده از نام مدل در + OllamaApiClient برای Embedding. علاوه بر این، + [AllowAnonymous] روی + Embedding و + Embeddings هنوز برقرار است. +
+
+
+
+
+
۲
+
+

فهرست تغییرات سطح کد

+
Applied Code Changes
+
+
+
+

+ تغییرات اعمال‌شده در این نسخه به تفکیک فایل/ماژول: +

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
فایل / ماژولتغییر اعمال‌شدهنوع
Startup.cs + بازنویسی کامل ترتیب Middlewareها با + کامنت‌گذاری صریح. انتقال Storage به قبل + از Routing، فعال‌سازی Swagger فقط در + Development، افزودن ExceptionHandler و + HSTS در Production. + + ساختاری +
ProxyController.cs + حذف کامل فایل. تنها + XAiModelProxyMiddleware به عنوان مسیر + رسمی Proxy باقی مانده است. + + حذف کامل +
+ StartupController.cs + + افزودن Endpoint جدید + /error برای Production + Error Handling با + ApiExplorerSettings.IgnoreApi. + + افزوده شده +
+ KnowledgeController.cs + + Ingest/Ask/AskStream/Documents/Delete + اکنون پارامترهای scope و + scopeId را پذیرفته و به + XAiKnowledgeScopeDescriptor + تبدیل می‌کنند. AskStream پیش از آغاز + Stream، اولین آیتم را pull می‌کند. + + بازنویسی +
+ ChatWithDocumentsController.cs + + استفاده از + Response.PrepareSseResponse()، WriteSseEventAsync، + WriteSseDoneAsync و + WriteSseErrorAsync. مدیریت + ClientCancellation. + + SSE استاندارد +
+ XAiServiceControllerBase.cs + + SSE کامل با Helperهای استاندارد. حذف + [AllowAnonymous] از + AskText/AskTextStream و جایگزینی با + [Authorize(Policy = + XPolicies.EnabledUser)]. + + SSE + AuthZ +
XAiRAGService.cs + بازنویسی کامل با Scopeدار کردن + Identifier (conversation/, project/, + user/, global/). پیاده‌سازی + RetrieveAsync چندلایه، EnsureAccess، + EnsureProjectOwner، + EnsureConversationOwner، IsAdmin. اعمال + محدودیت‌ها و افزودن + MigrateLegacyVectorsAsync. + + بازنویسی کامل +
+ XAiKnowledgeScope + (xAiModels) + + انتقال از xAiApi به xAiModels/Constants. + افزودن مقدار User و ویژگی StringValue با + پیشوندها. + + جابه‌جایی + توسعه +
XAiModelsConstants + افزودن XAiKnowledgeUserPrefix، + XAiErrorRoute و کلیدهای Metadata برای + Scope. + + افزوده شده +
+ XAiKnowledgeModels.cs + + XAiKnowledgeScopeDescriptor با Factory + Methodهای User()، Global()، Project()، + Conversation(). XAiKnowledgeAskRequest + با IncludeUser و IncludeGlobal. + + توسعه +
IXAiRAGService.cs + امضاهای جدید: IngestAsync(scope), + RetrieveAsync(request), + LoadDocumentsAsync(scope), + RemoveDocumentAsync(scope) و + MigrateLegacyVectorsAsync. + + تغییر قرارداد +
XAiApiConstants + حذف ثابت‌های Knowledge که به XAiModels + منتقل شدند. حذف XOpenAINoKey تکراری. + + پاکسازی +
XAiDataProvider + اصلاح قبلی حفظ شده: شرط‌های Query به + !ownerId.IsNullOrEmpty()، + GetDefaultConversation با + id: projectId، + LoadConversations با + ignoreSoftDeleteds: true. + + حفظ اصلاح +
XAiApiDbContext + ثبت XAiVectorEntityRegisterar در + dynamicEntityRegisterarsNames. + + حفظ اصلاح +
Migration + ستون Type و Indexهای Identifier و Type + در AiVectors موجود است. + + حفظ اصلاح +
+
+
+
+
+
۳
+
+

تحلیل تفصیلی اصلاحات کلیدی

+
+ Deep Analysis of Key Fixes +
+
+
+
+

+ ۳-۱. بازنویسی کامل RAG با Scope (F-05، + F-15) +

+

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

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
Scopeالگوی Identifierنوشتنخواندن
Conversation + conversation/{id}/{fileName}#i + صاحب گفتگوصاحب گفتگو
Project + project/{id}/{fileName}#i + صاحب پروژهصاحب پروژه
User + user/{ownerId}/{fileName}#i + خود کاربرخود کاربر
Globalglobal/{fileName}#iفقط Adminهمه
+

+ متد جدید RetrieveAsync به‌صورت چندلایه + عمل می‌کند: ابتدا Conversation، سپس Project، سپس + User و نهایتاً Global. هر لایه بخش باقی‌مانده از + TopK را پر می‌کند و آیتم‌های تکراری با استفاده از + HashSet حذف می‌شوند. این ساختار دقیقاً با نیاز ذکر + شده در XAiKnowledgeAskRequest هم‌خوان است. +

+
+ نکته کلیدی: متد + MigrateLegacyVectorsAsync نیز برای + مهاجرت امن داده‌های قدیمی با الگوی + {ownerId}/{fileName}#i به ساختار جدید + user/{ownerId}/... اضافه شده است که + نشان‌دهنده توجه به پایداری داده در محیط Production + است. +
+

+ ۳-۲. حذف کامل ProxyController (F-06، + F-17) +

+

+ حذف ProxyController باعث شد که تداخل Route برطرف شود + و تنها یک مسیر رسمی برای Proxy باقی بماند: + XAiModelProxyMiddleware. این تصمیم از + یک سو ریسک Loop را از بین می‌برد و از سوی دیگر منطق + Proxy را در یک نقطه واحد متمرکز می‌کند. +

+

+ ۳-۳. بازنویسی Startup Pipeline (F-07) +

+

+ ترتیب جدید Middlewareها به شکل صریح و با کامنت‌گذاری + توضیح داده شده است. مهم‌ترین تغییر، انتقال + UseXStorageService() به قبل از + UseRouting() است که برای سرو Static + Files ضروری است. همچنین فعال‌سازی + UseXSwagger() فقط در Development و + افزودن + UseExceptionHandler(XAiModelsConstants.XAiErrorRoute) + در Production، سطح امنیت و پایداری را افزایش می‌دهد. +

+

+ ۳-۴. استانداردسازی SSE (F-08) +

+

+ تمام Controllerهای Streaming اکنون از Helperهای + مشترک استفاده می‌کنند: +

+
    +
  • + Response.PrepareSseResponse() برای + تنظیم Headerها و غیرفعال‌سازی Buffering +
  • +
  • + Response.WriteSseEventAsync(data, ct) + برای ارسال رویداد با قالب + data: {json}\n\n +
  • +
  • + Response.WriteSseDoneAsync(ct) برای + رویداد پایانی +
  • +
  • + Response.WriteSseErrorAsync(message) + برای خطای استاندارد +
  • +
  • + ex.IsClientCancellation(ct) برای + تفکیک قطع ارتباط کاربر از خطای واقعی +
  • +
+

+ همچنین در + KnowledgeController.AskStream، الگوی + ظریفی پیاده‌سازی شده است: قبل از شروع Stream، اولین + آیتم با MoveNextAsync خوانده می‌شود تا + خطاهای احتمالی (Scope، Ownership، Retrieval) به‌صورت + HTTP Error استاندارد برگردند نه در میانه Stream. +

+

+ ۳-۵. اصلاح Authorization (F-16 - جزئی) +

+

+ در XAiServiceControllerBase، صفت + [Authorize(Policy = + XPolicies.EnabledUser)] + روی AskText، AskTextStream، Projects، Conversations، + Queries، Creators، ExtractContent، Ask، AskStream و + AskWithFiles اضافه شده است. با این حال، در + XAiEmbeddingServiceControllerBase، صفت + [AllowAnonymous] روی + Embedding و + Embeddings هنوز باقی است. +

+
+ توجه: ممکن است این تصمیم آگاهانه + باشد تا سرویس Embedding به‌عنوان یک Endpoint عمومی + (مثلاً برای استفاده داخلی سایر سرویس‌ها با API Key) + باقی بماند؛ اما این نیازمند مستندسازی صریح است. +
+
+
+
+
+
۴
+
+

ماتریس وضعیت موارد

+
Status Matrix
+
+
+
+

وضعیت نهایی موارد ۱۷گانه بازبینی اول:

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
شناسهشرح مختصروضعیت
F-01 + ثبت XAiVectorEntityRegisterar در + DbContext + + اصلاح شد +
F-02Migration ستون Type و Indexها + اصلاح شد +
F-03شرط ownerId در Queryها + اصلاح شد +
F-04 + NullReferenceException در + GetDefaultConversation + + اصلاح شد +
F-05پیاده‌سازی واقعی Scope در RAG + اصلاح کامل شد +
F-06Route تعریف‌شده ProxyController + حذف کامل +
F-07ترتیب Middlewareها در Startup + اصلاح شد +
F-08قالب SSE در Streaming + اصلاح کامل شد +
F-09XCodeFileContentExtractor + اصلاح شد +
F-10 + اعتبارسنجی OCR در + XImageFileContentExtractor + + باز +
F-11 + نام مدل در OllamaApiClient برای + Embedding + + باز +
F-12 + شرط HasDefaultProject / + HasDefaultConversation + + اصلاح شد +
F-13 + isDefaultLanguageHandled در + CreateProject + + اصلاح شد +
F-14 + ignoreSoftDeleteds در LoadConversations + + اصلاح شد +
F-15 + پرکردن Scope و اعمال محدودیت‌ها در + Ingest + + اصلاح کامل شد +
F-16AllowAnonymous در Actionهای AI + جزئی +
F-17دو مسیر موازی Proxy + حذف کامل +
+
+ نرخ اصلاح: ۱۵ مورد از ۱۷ مورد + کاملاً اصلاح شده (۸۸٪)، یک مورد جزئی (۶٪) و تنها دو + مورد باز (۱۲٪). این نشان‌دهنده پیشرفت چشمگیر در بلوغ + فنی است. +
+
+
+
+
+
۵
+
+

موارد باز باقی‌مانده و پیشنهاد اصلاح

+
+ Remaining Issues & Recommendations +
+
+
+
+

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

+ + + + + + + + + + + + + + + + + + + + + + + + + +
شناسهمحلپیشنهاد اصلاح
F-10XImageFileContentExtractor + در Constructor، شرط اعتبارسنجی باید به + این صورت باشد: اگر + configuration.OCR.EnableOcrFallback + == true، آنگاه وجود DataPath و DefaultLanguage + الزامی باشد. در غیر این صورت، حتی بدون + OCR بتوان تصویر را برای Vision ارسال + کرد. +
F-11 + XAiEmbeddingServiceBase.GetEmbeddingGenerator + + در شاخه Ollama، به جای + new OllamaApiClient(new + Uri(descriptor.Url)) + از + new + OllamaApiClient(descriptor.Url.GetHttpClient(), + descriptor.LLM) + استفاده شود تا مدل Embedding صریحاً + انتخاب شود. +
F-16XAiEmbeddingServiceControllerBase + یا [AllowAnonymous] حذف + شود، یا با کامنت مستندسازی صریح شود که + Embedding به‌صورت آگاهانه برای استفاده + داخلی سرویس‌های دیگر عمومی است و از طریق + ApiKey در سطح زیرساخت محافظت می‌شود. +
+
+ پیشنهاد تکمیلی: پس از اعمال سه + اصلاح فوق، توصیه می‌شود یک Suite تست End-to-End برای + موارد زیر نوشته شود: Ingest در هر چهار Scope، + Retrieval چندلایه، MigrateLegacyVectors، SSE در هر + دو حالت موفق و خطا، و Proxy با API Key و Token. +
+
+ نکته مثبت: ساختار جدید RAG + به‌گونه‌ای طراحی شده است که افزودن Scopeهای آینده + (مثلاً Organization یا Tenant) تنها با افزودن یک + Prefix و یک Factory Method امکان‌پذیر است. این + نشان‌دهنده بلوغ طراحی است. +
+
+
+
+
+
۶
+
+

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

+
Final Conclusion
+
+
+
+

+ این نسخه نشان می‌دهد که تیم توسعه مسیر صحیحی را طی + کرده است: به جای وصله‌کاری، به سراغ بازطراحی معماری + رفته است. بازنویسی کامل XAiRAGService با پشتیبانی از + Scope، حذف ProxyController، استانداردسازی SSE و + بازچینش Startup Pipeline، همگی تغییرات سطح معماری + هستند که پایداری بلندمدت را تضمین می‌کنند. +

+

+ سه مورد باقی‌مانده (F-10، F-11، F-16) هیچ‌کدام + بحرانی نیستند و اصلاح آن‌ها در حد چند خط کد است. با + این حال، برای رسیدن به یک Production کاملاً بالغ، + بهتر است پیش از استقرار نهایی تعیین تکلیف شوند. +

+
+

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

+

+ سامانه از نظر معماری، جداسازی داده، رفتار + Streaming و پایداری Pipeline به بلوغ قابل قبولی + رسیده است. +

+
+ وضعیت آمادگی Production:
+ رفع سه مورد کوچک (OCR Condition + Ollama Model + + Embedding Auth) و سپس اجرای تست‌های End-to-End + کافی است. +
+
+
+ ریسک باقی‌مانده: تنها ریسک پنهان، + عدم استفاده از مدل Embedding درست در حالت Ollama است + که می‌تواند به‌صورت خاموش (Silent) روی کیفیت + Retrieval اثر بگذارد و در تست‌های Functionality دیده + نشود. اصلاح این مورد در اولویت بالاتری قرار دارد. +
+
+
+
+ این مستند محرمانه بوده و صرفاً جهت بررسی فنی داخلی تهیه شده + است. هرگونه کپی‌برداری یا افشا بدون اجازه کتبی ممنوع است. +
+
+
+ + +
+ تاریخ تهیه: آبان ۱۴۰۵  |  نسخه: ۳.۰  |  + طبقه‌بندی: محرمانه +
+
+
+ + diff --git a/Documents/Docs/Developer/xAiApi-14050807-Overview.html b/Documents/Docs/Developer/xAiApi-14050807-Overview.html new file mode 100644 index 0000000..bed7401 --- /dev/null +++ b/Documents/Docs/Developer/xAiApi-14050807-Overview.html @@ -0,0 +1,1413 @@ + + + + + + تحلیل معماری و بررسی فنی سامانه xAiApi | مستند فنی + + + +
+
+
+
+ +
+
+
شماره مستند: ARCH-REV-1405-001
+
نسخه: ۱.۰
+
تاریخ تهیه: آبان ۱۴۰۵
+
طبقه‌بندی: محرمانه
+
+
+
+ TECHNICAL ARCHITECTURE REVIEW +

تحلیل معماری و بررسی فنی سامانه xAiApi

+

+ تحلیل جامع معماری، خطاهای منطقی، شرح عملکرد و پیشنهادهای + بهبود +

+
+
+
+
+ خلاصه مدیریتی:
+ این مستند بر اساس کدهای ارائه‌شده در پروژه + xSaherelmWorkspace تهیه شده است. سامانه xAiApi یک API مبتنی + بر ASP.NET Core است که سرویس‌های هوش مصنوعی، RAG، استخراج + محتوا از فایل، Proxy مدل‌ها و مدیریت پروژه/گفتگو را ارائه + می‌کند. معماری کلی ماژولار و قابل توسعه است؛ اما در وضعیت + فعلی چند خطای منطقی مهم در لایه داده، ثبت Entity، مهاجرت + پایگاه داده، مسیرهای Proxy و قالب Streaming وجود دارد که پیش + از استفاده Production باید اصلاح شوند. +
+
+
+
۱
+
+

خلاصه اجرایی

+
Executive Summary
+
+
+
+

+ سامانه از نظر ساختار ماژولار، تفکیک لایه‌ها و + استفاده از DI بسیار خوب طراحی شده است. وجود + ماژول‌های مستقل برای مدل‌های AI، سرویس‌های AI، + استخراج محتوا، فایل، هویت، Push و داده، توسعه‌پذیری + را افزایش داده است. با این حال، برخی خطاها باعث + می‌شوند رفتار واقعی سیستم با مستندات و انتظارات + طراحی هم‌راستا نباشد. +

+
+
+
۶
+
خطای بحرانی/پرخطر
+
+
+
۹
+
خطای منطقی مهم
+
+
+
۷
+
+ نقطه ضعف امنیتی/عملکردی +
+
+
+
قابل توسعه
+
ارزیابی کلی معماری
+
+
+
+ نتیجه کلیدی: معماری پایه مناسب است، + اما تا زمان اصلاح مواردی مانند ثبت نشدن Entity وکتور + در DbContext، عدم تطابق Migration با مدل XAiVector، + اعمال نشدن فیلتر مالکیت در Queryها، عدم پیاده‌سازی + واقعی Scope در Knowledge و مسیر سراسری + ProxyController، استفاده Production از سامانه توصیه + نمی‌شود. +
+
+
+
+
+
۲
+
+

تحلیل جامع معماری

+
Architecture Analysis
+
+
+
+

+ سامانه xAiApi به عنوان Host اصلی ASP.NET Core عمل + می‌کند و از چندین ماژول داخلی استفاده می‌کند. + لایه‌بندی کلی به شکل زیر است: +

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
لایه / ماژولمسئولیت اصلیاجزای شاخص
xAiApi + Host API، Controllerها، Startup، + Middleware، Proxy، RAG در حافظه + + DefaultAiController، + KnowledgeController، + ChatWithDocumentsController، + ProxyController، XAiModelProxyMiddleware +
xAiModels + مدل‌های دامنه، DTOها، Entityها، + Repositoryها، Providerهای داده، GraphQL، + Hubs + + XAiProject، XAiConversation، XAiMessage، + XAiVector، XAiDataProvider +
xAiService + ثابت‌ها و Extensionهای کمکی سرویس AI + + XAiServiceConstants، + XAiServiceExtensions +
لایه زیرساخت + دسترسی داده، هویت، فایل، Push، String، + Tag، Storage + + xDataService، xIdentityService، + xFileService، xPushService، + xStringService، xTagService، + xStorageService +
لایه AI + اتصال به Ollama/OpenAI، Embedding، + Vision، RAG، Text Chunking + + XAIServiceBase، XAiEmbeddingServiceBase، + XAiRAGService، XTextChunker، + XInMemoryVectorStore +
لایه استخراج محتوا + استخراج متن/تصویر/صدا از فرمت‌های مختلف + + XPdfFileContentExtractor، + XDocxFileContentExtractor، + XAudioFileContentExtractor، + XVisionFileContentExtractor و ... +
+

+ الگوی کلی استفاده از DI، Provider، Repository، + Enricher و Descriptor است. این الگو برای توسعه‌پذیری + مناسب است، اما پیچیدگی آن باعث شده برخی تنظیمات و + ثبت‌ها به‌صورت دستی و ناقص انجام شوند. +

+
+ نقطه قوت معماری: تفکیک Relative خوب + بین Controller، Service، Provider و Repository وجود + دارد. همچنین استفاده از Microsoft.Extensions.AI و + پشتیبانی هم‌زمان از Ollama و OpenAI، انعطاف خوبی + برای تعویض مدل فراهم می‌کند. +
+
+ نقطه ضعف معماری: دو مسیر موازی برای + Proxy وجود دارد: Middleware و ProxyController. + همچنین RAG به دو شکل کاملاً متفاوت پیاده‌سازی شده + است: In-Memory در ChatWithDocuments و Persistent در + Knowledge، اما Scopeهای اعلام‌شده در Knowledge عملاً + در Query اعمال نمی‌شوند. +
+
+
+
+
+
۳
+
+

شرح عملکرد سیستم

+
System Behavior
+
+
+
+

+ ۳-۱. چرخه Startup و DI +

+

+ در Startup، ابتدا XCommons و تنظیمات برنامه ثبت + می‌شود. سپس CORS، Swagger، HttpService، Versioning، + Authorization، Identity، Storage، Push، Database، + StringService، TagService، FileService و در نهایت + XAiDataService و سرویس‌های AI ثبت می‌شوند. تنظیمات + AI از بخش AiApiConfiguration خوانده می‌شود و + اعتبارسنجی آن شامل وجود مدل‌ها و Promptهای معتبر + است. +

+

+ ۳-۲. سرویس‌های AI پایه +

+

+ XAIServiceBase مسئول ارتباط با LLM است. این کلاس + تاریخچه پیام‌ها را می‌سازد، Prompt مقدمه را اضافه + می‌کند و در صورت نیاز Context مربوط به RAG را به + System Message اضافه می‌کند. XDefaultAiService از + مدل پیش‌فرض، XDefaultEmbeddingService از مدل + Embedding و XDefaultThinkingAiService از مدل + Thinking استفاده می‌کند. +

+

+ ۳-۳. ChatWithDocuments (RAG در حافظه) +

+

+ در این جریان، فایل‌ها دریافت می‌شوند، MIME Type + آن‌ها بررسی می‌شود، متن استخراج می‌شود، توسط + XTextChunker به Chunkهای هم‌پوشان تقسیم می‌شود، + Embedding هر Chunk تولید می‌شود و در + XInMemoryVectorStore داخل یک Session نگهداری می‌شود. + سپس Ask یا AskStream با Embedding سؤال، نزدیک‌ترین + Chunkها را بازیابی و به LLM می‌دهد. Sessionها TTL + دارند و سرویس Cleanup دوره‌ای آن‌ها را حذف می‌کند. +

+

+ ۳-۴. Knowledge (RAG ماندگار) +

+

+ در KnowledgeController، فایل‌ها با XAiRAGService + پردازش می‌شوند. متن استخراج، Chunk و Embedding + می‌شود و در جدول AiVectors ذخیره می‌شود. سپس Ask با + Embedding سؤال، جستجوی Cosine Similarity انجام + می‌دهد و پاسخ را با Context تولید می‌کند. شناسه + Chunkها به شکل ownerId/fileName#chunkIndex ساخته + می‌شود تا جداسازی بر اساس مالک انجام شود. +

+

+ ۳-۵. Proxy مدل‌ها +

+

+ XAiModelProxyMiddleware مسیرهای دارای Prefix مشخص را + دریافت می‌کند، مدل را از تنظیمات می‌خواند، API Key + یا Token را اعتبارسنجی می‌کند، درخواست را به سرویس + مدل upstream ارسال می‌کند و پاسخ را Stream می‌کند. + ProxyController نیز یک مسیر جایگزین برای همین کار + فراهم می‌کند. +

+

+ ۳-۶. استخراج محتوا +

+

+ XFileContentExtractor یک Composite Extractor است که + بر اساس MIME Type، Extractor مناسب را انتخاب می‌کند. + Extractorهای PDF، DOCX، RTF، EPUB، HTML، Code، + Image، Audio، Excel، PowerPoint، OpenDocument، + PlainText و Vision وجود دارند. PDF در صورت کم بودن + متن، Fallback به تصویر انجام می‌دهد. تصویر در صورت + فعال بودن OCR، متن استخراج می‌کند و در غیر این صورت + تصویر را برای Vision نگه می‌دارد. +

+
+ جریان کلی موفق: دریافت فایل ← تشخیص + MIME ← استخراج محتوا ← Chunking ← Embedding ← ذخیره + در Session یا جدول Vector ← بازیابی Context ← تولید + پاسخ با LLM. +
+
+
+
+
+
۴
+
+

بررسی فنی و خطاهای منطقی

+
+ Technical Findings & Logical Errors +
+
+
+
+

+ در این بخش، خطاهای شناسایی‌شده بر اساس شدت تأثیر + دسته‌بندی شده‌اند. خطاهای «بحرانی» می‌توانند باعث + شکست Runtime، نشت داده یا عدم کارکرد اصلی شوند. +

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
شناسهمحلشدتشرح خطا و تأثیر
F-01XAiApiDbContext + بحرانی + + در لیست dynamicEntityRegisterarsNames، + XAiVectorEntityRegisterar ثبت نشده است. + در نتیجه ممکن است Entity XAiVector در + Model EF Core وارد نشود و عملیات + Repository و RAG ماندگار با خطای عدم + شناسایی Entity مواجه شود. +
F-02Migration / XAiVector + بحرانی + + Entity XAiVector دارای فیلد Type و Index + روی Identifier و Type است، اما Migration + اولیه ستون Type و Indexها را ایجاد + نمی‌کند. عدم تطابق Model و Database باعث + خطای Runtime در خواندن/نوشتن وکتورها + می‌شود. +
F-03 + XAiDataProvider.QueryProjects / + QueryConversations / QueryMessages + + بحرانی + + شرط ساخت Predicate برعکس نوشته شده است. + وقتی ownerId مقدار دارد، Predicate ساخته + نمی‌شود و Query بدون فیلتر مالک اجرا + می‌شود. این موضوع می‌تواند باعث نشت داده + بین کاربران شود. +
F-04 + XAiDataProvider.GetDefaultConversation + + بحرانی + + در شاخه else از project.Id استفاده شده، + در حالی که project هنوز null است. این خط + باعث NullReferenceException می‌شود. باید + از projectId ورودی استفاده شود. +
F-05XAiRAGService / KnowledgeController + بحرانی + + Scopeهای Conversation، Project و Global + و همچنین Type در Ask و Retrieve عملاً + اعمال نمی‌شوند. XAiRAGService در Search + مقدار type را null می‌فرستد و + ProjectId/ConversationId را نادیده + می‌گیرد. نتیجه: جداسازی دانش بر اساس + پروژه/گفتگو کار نمی‌کند. +
F-06ProxyController + بحرانی + + Route تعریف‌شده به صورت + {modelName}/{path} در سطح Root است و + می‌تواند با مسیرهای دو بخشی دیگر مانند + DefaultAi/AskText تداخل کند. همچنین در + صورت غیرفعال بودن ProxyConfiguration، + احتمال حلقه بی‌نهایت به خود سامانه وجود + دارد. +
F-07Startup.Configure + بالا + + چند Middleware مانند UseXStorageService، + UseXPushService، UseXDatabase، + UseXStringService، UseXTagService و + UseXFileService بعد از UseEndpoints ثبت + شده‌اند. Middlewareهای بعد از + UseEndpoints برای درخواست‌های Match شده + اجرا نمی‌شوند. +
F-08XAiServiceControllerBase + بالا + + در AskTextStream و AskStream، خروجی با + Content-Type برابر text/event-stream + ارسال می‌شود اما داده‌ها با قالب معتبر + SSE یعنی data: ... و پایان‌بندی مناسب + نوشته نمی‌شوند. کلاینت‌های استاندارد SSE + ممکن است داده را دریافت نکنند. +
F-09XCodeFileContentExtractor + بالا + + متن فایل خوانده می‌شود اما به + result.Text اختصاص داده نمی‌شود. در + نتیجه استخراج محتوای فایل‌های کد تقریباً + همیشه خالی است. همچنین نام فایل پیش‌فرض + book.epub به اشتباه استفاده شده است. +
F-10XImageFileContentExtractor + متوسط + + در Constructor حتی وقتی + EnableOcrFallback برابر false است، وجود + DataPath و DefaultLanguage الزامی شده + است. این موضوع باعث می‌شود استخراج تصویر + بدون OCR هم شکست بخورد. +
F-11XAiEmbeddingServiceBase + متوسط + + در حالت Ollama، نام مدل Embedding + (descriptor.LLM) هنگام ساخت + OllamaApiClient استفاده نمی‌شود. ممکن + است مدل پیش‌فرض Ollama انتخاب شود و + Embedding با مدل مورد انتظار متفاوت + باشد. +
F-12 + XAiModelsExtensions.HasDefaultProject / + HasDefaultConversation + + متوسط + + شرط اعتبارسنجی برعکس است: وقتی + Collection دارای Child است، Exception + پرتاب می‌شود. این متدها در صورت استفاده + می‌توانند رفتار نادرست ایجاد کنند. +
F-13 + XAiDataProvider.CreateProject / + CreateConversation + + متوسط + + متغیر isDefaultLanguageHandled پس از + انتساب زبان پیش‌فرض مقدار false می‌گیرد. + بنابراین برای چند Locale بدون زبان، زبان + پیش‌فرض تکراری اعمال می‌شود. +
F-14XAiDataProvider.LoadConversations + متوسط + + برای Conversationها ignoreSoftDeleteds + برابر false است. در نتیجه ممکن است + آیتم‌های حذف‌شده در لیست برگردند. +
F-15XAiRAGService.IngestAsync + متوسط + + فیلدهای Scope، ScopeId و Type در + XAiKnowledgeIngestResult و + XAiKnowledgeDocumentInfo پر نمی‌شوند. + همچنین محدودیت‌های MaxFilesPerIngest، + MaxFileSizeBytes و MaxDocumentsPerScope + اعمال نمی‌شوند. +
F-16 + XAiServiceControllerBase / + DefaultAiController + + امنیتی + + برخی Actionها با وجود [Authorize] در سطح + کلاس، دارای [AllowAnonymous] هستند. این + موضوع باعث می‌شود AskText و Embedding + بدون احراز هویت قابل فراخوانی باشند. +
F-17 + XAiModelProxyMiddleware / + ProxyController + + متوسط + + دو مسیر موازی برای Proxy وجود دارد. + ProxyController درخواست را به همین + سامانه و مسیر ai-model می‌فرستد که یک + Hop اضافی و ریسک Loop ایجاد می‌کند. +
+
+ مهم‌ترین ریسک: خطاهای F-01 تا F-05 + مستقیماً روی صحت داده، جداسازی کاربران و کارکرد RAG + ماندگار اثر می‌گذارند. این موارد باید قبل از هر تست + پذیرش یا استقرار اصلاح شوند. +
+

+ نمونه اصلاح پیشنهادی برای Queryها: +

+
+ به جای شرط + if (ownerId.IsNullOrEmpty()) باید از + if (!ownerId.IsNullOrEmpty()) استفاده + شود تا Predicate مالکیت در زمان وجود ownerId ساخته + شود. همچنین در GetDefaultConversation باید + id: projectId به جای + id: project.Id در شاخه else قرار گیرد. +
+
+
+
+
+
۵
+
+

پیشنهادهای لازم برای بهبود عملکرد

+
+ Improvement Recommendations +
+
+
+
+

+ پیشنهادها بر اساس اولویت اجرایی دسته‌بندی شده‌اند: +

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
اولویتاقدام پیشنهادیاثر مورد انتظار
+ P0 + + ثبت XAiVectorEntityRegisterar در + XAiApiDbContext و ایجاد Migration جدید + برای ستون Type و Indexهای Identifier و + Type. + + رفع خطای Runtime و تضمین کارکرد + Knowledge/RAG ماندگار. +
+ P0 + + اصلاح شرط‌های ownerId در QueryProjects، + QueryConversations و QueryMessages و رفع + NullReferenceException در + GetDefaultConversation. + + جلوگیری از نشت داده و افزایش پایداری + عملیات پیش‌فرض. +
+ P0 + + پیاده‌سازی واقعی Scope و Type در + XAiRAGService: اعمال ProjectId، + ConversationId و Type در + SearchVectorsAsync و ذخیره آن‌ها در + Ingest. + + جداسازی صحیح دانش بین Global، Project و + Conversation. +
+ P0 + + محدودکردن Route مربوط به ProxyController + یا حذف آن و اتکا به Middleware. جلوگیری + از Loop در حالت Proxy غیرفعال. + + رفع تداخل Routing و کاهش ریسک + امنیتی/عملکردی. +
+ P1 + + جابه‌جایی Middlewareهای Storage، Push، + Database، String، Tag و File به قبل از + UseEndpoints. + + اطمینان از اجرای واقعی Middlewareها در + Pipeline. +
+ P1 + + یکسان‌سازی قالب SSE در همه Controllerها + با prefix data: و پایان‌بندی دو newline + و ارسال Event نهایی. + + سازگاری با کلاینت‌های استاندارد SSE و + بهبود تجربه Streaming. +
+ P1 + + اصلاح XCodeFileContentExtractor برای + انتساب واقعی متن خوانده‌شده به + result.Text و حذف نام فایل پیش‌فرض + اشتباه. + + کارکرد صحیح استخراج کد در RAG و + ChatWithDocuments. +
+ P1 + + اعتبارسنجی OCR فقط در صورت + EnableOcrFallback و استفاده از مدل + Embedding Ollama به‌صورت صریح. + + کاهش خطاهای Startup و افزایش دقت + Embedding. +
+ P2 + + افزودن محدودیت‌های Ingest شامل تعداد + فایل، اندازه فایل و تعداد سند در Scope. + + جلوگیری از مصرف بی‌رویه حافظه و پایگاه + داده. +
+ P2 + + بهینه‌سازی جستجوی Vector: استفاده از + Index برداری یا حداقل فیلترهای دقیق‌تر + به جای بارگذاری همه رکوردها در حافظه. + افزایش مقیاس‌پذیری Knowledge.
+ P2 + + افزودن تست‌های واحد و یکپارچه برای + Queryهای مالکیت، RAG Scope، SSE، Proxy و + Extractorها. + + کاهش Regression و افزایش اطمینان از + اصلاحات. +
+ P2 + + بازبینی سیاست دسترسی Actionها و حذف + AllowAnonymousهای ناخواسته از سرویس‌های + AI. + افزایش امنیت API.
+
+ پیشنهاد معماری: بهتر است دو مسیر + RAG (In-Memory و Persistent) در یک Abstraction مشترک + با نام IXAiVectorSearchService ادغام شوند تا + Behavior جستجو، Scope، Type و Source Mapping در همه + جا یکسان باشد. +
+
+ پیشنهاد کوتاه‌مدت: ابتدا F-01 تا + F-06 اصلاح شود، سپس یک تست End-to-End برای Ingest، + Ask، AskStream، Scope و Proxy انجام گیرد. پس از آن + بهبودهای عملکردی و امنیتی در اولویت بعدی قرار گیرند. +
+
+
+
+
+
۶
+
+

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

+
Final Conclusion
+
+
+
+

+ سامانه xAiApi از نظر ساختار ماژولار و استفاده از + الگوهای DI، Provider و Repository یک پایه قابل توسعه + دارد. پشتیبانی از چند Provider مدل، استخراج محتوای + متنوع، RAG در حافظه و RAG ماندگار، و Proxy مدل‌ها + نشان‌دهنده دامنه وسیع قابلیت‌های طراحی‌شده است. +

+

+ با این حال، وضعیت فعلی کد از نظر صحت منطقی و آمادگی + Production نیازمند اصلاحات مشخص است. مهم‌ترین مشکلات + در لایه داده و جداسازی مالکیت، ثبت Entity و + Migration، پیاده‌سازی Scope در Knowledge و مسیرهای + Proxy متمرکز هستند. اصلاح این موارد می‌تواند سامانه + را به یک وضعیت پایدار و قابل اتکا نزدیک کند. +

+
+

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

+

+ معماری کلی مناسب است، اما بدون اصلاح خطاهای P0، + استفاده از سامانه در محیط واقعی ریسک بالایی + دارد. +

+
+ اولویت‌های اصلاح:
+ ثبت Entity وکتور + Migration صحیح + اصلاح + Queryهای مالکیت + پیاده‌سازی Scope در RAG + + محدودسازی ProxyController + اصلاح Startup + Pipeline +
+
+
+
+
+ این مستند محرمانه بوده و صرفاً جهت بررسی فنی داخلی تهیه شده + است. هرگونه کپی‌برداری یا افشا بدون اجازه کتبی ممنوع است. +
+
+
+ + +
+ تاریخ تهیه: آبان ۱۴۰۵  |  نسخه: ۱.۰  |  + طبقه‌بندی: محرمانه +
+
+
+ + diff --git a/Documents/GeneratedContext/xDashboard-xAiApi-20261029_200138.txt b/Documents/GeneratedContext/xDashboard-xAiApi-20261029_200138.txt new file mode 100644 index 0000000..68deaf2 --- /dev/null +++ b/Documents/GeneratedContext/xDashboard-xAiApi-20261029_200138.txt @@ -0,0 +1,13048 @@ + +### FILE: C:\Users\saherelm\Documents\Projects\xSaherelmWorkspace\xAiApi\Program.cs + +using System.Text; +using Microsoft.AspNetCore.Hosting; +using Microsoft.Extensions.Hosting; + +namespace xAiApi +{ + public class Program + { + public static void Main(string[] args) + { + // + Encoding.RegisterProvider(CodePagesEncodingProvider.Instance); + + // + CreateHostBuilder(args).Build().Run(); + } + + public static IHostBuilder CreateHostBuilder(string[] args) + { + // + var result = Host.CreateDefaultBuilder(args) + .ConfigureWebHostDefaults(webBuilder => + { + webBuilder.UseStartup(); + }); + + // + return result; + } + } +} + +### FILE: C:\Users\saherelm\Documents\Projects\xSaherelmWorkspace\xAiApi\Startup.cs + +using System; +using System.IO; +using xAiApi.DI; +using System.Linq; +using xAiModels.DI; +using xTagService.DI; +using System.Net.Http; +using xAiApi.Database; +using xHttpService.DI; +using xPushService.DI; +using xFileService.DI; +using xDataService.DI; +using Newtonsoft.Json; +using System.Reflection; +using xAiApi.Extensions; +using xStringService.DI; +using xStorageService.DI; +using xIdentityService.DI; +using xDataService.Models; +using xCommons.Extensions; +using xAiModels.Constants; +using xPushService.Helpers; +using xCommons.Configurations; +using System.Collections.Generic; +using Microsoft.AspNetCore.Builder; +using Microsoft.AspNetCore.Hosting; +using Microsoft.Extensions.Hosting; +using Newtonsoft.Json.Serialization; +using Microsoft.Extensions.Configuration; +using Microsoft.Extensions.DependencyInjection; +using IdentityModel.AspNetCore.OAuth2Introspection; + +namespace xAiApi +{ + public class Startup + { + // + #region Props ... + public IConfiguration Configuration { get; } + private readonly List databases; + private readonly XAiApiDatabaseDescriptor apiDatabaseDescriptor; + #endregion + + // + #region Constructor(s) ... + public Startup(IConfiguration configuration) + { + // + Configuration = configuration; + + // + // Create an Api Descriptor Class Instance ... + apiDatabaseDescriptor = new XAiApiDatabaseDescriptor(); + databases = new List + { + apiDatabaseDescriptor + }; + } + #endregion + + public void ConfigureServices(IServiceCollection services) + { + // + // Register Validation Provider and all XCommons Module Services ... + services.AddXCommons(Configuration); + + // + // Register App Configuration ... + services.AddXAppConfiguration(Configuration); + var appConfiguration = services.GetRegisteredService(); + + // + // Register Allowed Origins ... + services.AddXCors(appConfiguration.AllowedOrigins); + + // + // Register Swagger ... + var xmlFile = $"{Assembly.GetExecutingAssembly().GetName().Name}.xml"; + var xmlPath = Path.Combine(AppContext.BaseDirectory, xmlFile); + services.AddXSwagger(Configuration, xmlFilePath: xmlPath); + + // + // Register HttpService ... + services.AddXHttpService(Configuration); + + // + // Add Api V1 Versioning ... + services.AddXApiV1Versioning(); + + // + // OAuthIntrospectin Http Client Handler ... + // this is for handling SSLErrors ... + services.AddHttpClient(OAuth2IntrospectionDefaults.BackChannelHttpClientName) + .ConfigurePrimaryHttpMessageHandler(() => + { + return new HttpClientHandler + { + ServerCertificateCustomValidationCallback = (sender, certificate, chain, sslPolicyErrors) => true + }; + }); + + // + // Register Authorizations ... + services.AddXAuthorization(); + + // + services.AddControllers() + .AddNewtonsoftJson(x => + { + x.SerializerSettings.ReferenceLoopHandling = ReferenceLoopHandling.Ignore; + x.SerializerSettings.ContractResolver = new CamelCasePropertyNamesContractResolver(); + }); + + // + var lifeTime = ServiceLifetime.Scoped; + var repositoryType = xDataService.Constants.XRepositoryType.EF; + + // + // Register XIdentity Service ... + services.AddXIdentityService( + lifeTime: lifeTime, + configuration: Configuration + ); + + // + // Storage Service ... + services.AddXStorageService(Configuration); + + // + // Push Service ... + services.AddXPushService( + lifeTime: lifeTime, + config: Configuration + ); + + // + // Preparing DataBases ... + if (databases.HasChild()) + { + // + databases + .ToList() + .ForEach(database => + { + // + // Register DataBase ... + services.AddXDatabase( + lifeTime: lifeTime, + descriptor: database, + configuration: Configuration + ); + }); + } + + // + // Register String Service ... + services.AddXStringService( + lifeTime: lifeTime, + repositoryType: repositoryType + ); + + // + // Register Tag Service ... + services.AddXTagService( + lifeTime: lifeTime, + repositoryType: repositoryType + ); + + // + // Register File Service ... + services.AddXFileService( + lifeTime: lifeTime, + repositoryType: repositoryType + ); + + // + // Register AiApi Data Service ... + services.AddXAiDataService( + lifeTime: lifeTime, + repositoryType: repositoryType + ); + + // + // Register XAiApi Configuration ... + services.AddXAiApiConfiguration(Configuration); + + // + // Register 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 Default AI Services ... + services.AddXAiServices(); + } + + public void Configure(IApplicationBuilder app, IWebHostEnvironment env) + { + // + // Configure the HTTP request pipeline. + // Order: Exception Handling -> Https -> Static Files -> Swagger (Dev) -> Cors + // -> Model Proxy (Terminal for /{RoutePrefix}) -> Routing -> AuthN -> AuthZ -> Endpoints ... + var isDevelopmentEnvironment = env.IsDevelopment(); + if (isDevelopmentEnvironment) + { + app.UseDeveloperExceptionPage(); + } + else + { + app.UseExceptionHandler(XAiModelsConstants.XAiErrorRoute); + app.UseHsts(); + } + + // + // Force Https Redirection ... + app.UseHttpsRedirection(); + + // + // Use Storage Service (Prepare Folders + Static Files) ... + // Must be before Routing so Static Files Short Circuit Pipeline ... + app.UseXStorageService(); + + // + // Use Swagger Middleware (Only in Development) ... + if (isDevelopmentEnvironment) + { + app.UseXSwagger(); + } + + // + // Using Cors (before Proxy so Browser Requests get CORS Headers) ... + app.UseXCors(); + + // + // Enable Model Proxy (Handles its own Authentication) ... + app.UseXAiModelProxy(); + + // + // Using Routing ... + app.UseRouting(); + + // + // Use xIdentityService (Authentication) ... + app.UseXIdentityService(); + + // + // Use Authorization ... + app.UseAuthorization(); + + // + app.UseEndpoints(endpoints => + { + endpoints.MapControllers(); + }); + + // + // Use PushService (Legacy UseSignalR -> Registers its own Router) ... + var pushHelper = new XPushServiceHelper(); + app.UseXPushService(pushHelper); + + // + // Using DataBase ... + if (databases.HasChild()) + { + // + databases + .ToList() + .ForEach(database => + { + // + app.UseXDatabase( + descriptor: database, + isDevelopmentEnvironment: isDevelopmentEnvironment + ); + }); + } + + // + // Using String Service ... + app.UseXStringService( + isDevelopmentEnvironment: isDevelopmentEnvironment + ); + + // + // Using XTag Service ... + app.UseXTagService( + isDevelopmentEnvironment: isDevelopmentEnvironment + ); + + // + // Using File Service ... + app.UseXFileService( + isDevelopmentEnvironment: isDevelopmentEnvironment + ); + } + } +} + +### FILE: C:\Users\saherelm\Documents\Projects\xSaherelmWorkspace\xAiApi\Configurations\XAiApiConfiguration.cs + +using xAiApi.Models; +using xAiModels.Models; + +namespace xAiApi.Configurations +{ + public class XAiApiConfiguration + { + /// + /// Allowed Models to Use ... + /// + public XAiModelDescriptor[] Models { get; set; } = []; + + /// + /// Allowed Prompts to Use ... + /// + public XAiPromptDescriptor[] Prompts { get; set; } = []; + + /// + /// OCR Configuration ... + /// + public XAiOCRDescriptor OCR { get; set; } = new(); + + /// + /// Transcript Configuration ... + /// + public XAiTransciptDescriptor Transcript { get; set; } = new(); + + /// + /// PDF To Image Configuration ... + /// + public XPDFToImageDescriptor PDFToImageDescriptor { get; set; } = new(); + + /// + /// Proxy Configuration ... + /// + /// + public XAiModelProxyConfiguration ProxyConfiguration { get; set; } = new(); + + /// + /// Text Chunker Configuration ... + /// + public XTextChunkerDescriptor TextChunker { get; set; } = new(); + + /// + /// RAG Configuration ... + /// + public XAiDocumentRAGDescriptor RAGDescriptor {get; set;} = new(); + } +} + +### FILE: C:\Users\saherelm\Documents\Projects\xSaherelmWorkspace\xAiApi\Constants\ConfigurationNodeNames.cs + +namespace xAiApi.Constants +{ + public partial struct ConfigurationNodeNames + { + public const string AI_API_NODE = "AiApiConfiguration"; + } +} + +### FILE: C:\Users\saherelm\Documents\Projects\xSaherelmWorkspace\xAiApi\Constants\XAiApiConstants.cs + +namespace xAiApi.Constants +{ + public struct XAiApiConstants + { + // + // Database Descriptor ... + public const string XAiApiDbIdentifier = "xAiApiDb"; + public const string XAiApiMigrationsAssemblyIdentifier = "xAiApi"; + + // + public const string XDILogTag = "XAiApi"; + + // + public const string 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] + [Route("[controller]")] + public class ChatWithDocumentsController : XBaseIdentityApiV1Controller + { + /// + /// Default AI Service ... + /// + private readonly IXDefaultAiService 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 IXDefaultEmbeddingService embeddingService; + + /// + /// File Context Extractor Service ... + /// + private readonly IXFileContentExtractor fileContentExtractor; + + public ChatWithDocumentsController( + IXTextChunker textChunker, + IXDefaultAiService aiService, + IXInMemoryVectorStore vectorStore, + XAppConfiguration appConfiguration, + IXIdentityProvider identityProvider, + XAiApiConfiguration apiConfiguration, + XValidationProvider validationProvider, + IXDefaultEmbeddingService embeddingService, + 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, + mimeType: mimeType, + fileName: file.FileName, + 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.AskWithContextAsync( + prompt: request.Prompt, + context: context, + 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.AskWithContextAsEnumerable( + prompt: request.Prompt, + context: context, + 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\DefaultAiController.cs + +using xAiApi.Interfaces; +using xCommons.Providers; +using xCommons.Configurations; +using Microsoft.AspNetCore.Mvc; +using xIdentityService.Interfaces; +using Microsoft.Extensions.Logging; +using Microsoft.AspNetCore.Authorization; + +namespace xAiApi.Controllers +{ + [Authorize] + [Route("[controller]")] + public class DefaultAiController : XAiServiceControllerBase + { + public DefaultAiController( + ILogger logger, + IXDefaultAiService aiService, + XAppConfiguration appConfiguration, + IXIdentityProvider identityProvider, + XValidationProvider validationProvider + ) : base( + logger, + aiService, + appConfiguration, + identityProvider, + validationProvider + ) + { } + } +} + +### FILE: C:\Users\saherelm\Documents\Projects\xSaherelmWorkspace\xAiApi\Controllers\DefaultEmbeddingController.cs + +using xAiApi.Interfaces; +using xCommons.Providers; +using xCommons.Configurations; +using Microsoft.AspNetCore.Mvc; +using xIdentityService.Interfaces; +using Microsoft.Extensions.Logging; +using Microsoft.AspNetCore.Authorization; + +namespace xAiApi.Controllers +{ + [Authorize] + [Route("[controller]")] + public class DefaultEmbeddingController : XAiEmbeddingServiceControllerBase + { + public DefaultEmbeddingController( + ILogger logger, + IXDefaultEmbeddingService aiService, + XAppConfiguration appConfiguration, + IXIdentityProvider identityProvider, + XValidationProvider validationProvider + ) : base( + logger, + aiService, + appConfiguration, + identityProvider, + validationProvider + ) + { } + } +} + +### FILE: C:\Users\saherelm\Documents\Projects\xSaherelmWorkspace\xAiApi\Controllers\DefaultThinkingAiController.cs + +using xAiApi.Interfaces; +using xCommons.Providers; +using xCommons.Configurations; +using xIdentityService.Interfaces; +using Microsoft.Extensions.Logging; + +namespace xAiApi.Controllers +{ + public class DefaultThinkingAiController : XAiServiceControllerBase + { + public DefaultThinkingAiController( + ILogger logger, + IXDefaultThinkingAiService aiService, + XAppConfiguration appConfiguration, + IXIdentityProvider identityProvider, + XValidationProvider validationProvider + ) : base( + logger, + aiService, + appConfiguration, + identityProvider, + validationProvider + ) + { } + } +} + +### 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; + +namespace xAiApi.Controllers +{ + /// + /// Knowledge (Persistent RAG over XAiVector Table) Controller ... + /// Flow: Ingest Files -> Ask / AskStream (Retrieve from DB -> Generate) -> Documents / Delete + /// + [Authorize] + [Route("[controller]")] + 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")] + 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 Ask ... + /// + /// Ask a Question over Knowledge Base (RAG) ... + /// + /// + /// + /// + [HttpPost("Ask")] + public async Task> Ask( + [FromBody] XAiKnowledgeAskRequest request, + CancellationToken cancellationToken = default + ) + { + // + try + { + // + // Validate ... + if (request.IsNullOrDefault() || request.Prompt.IsNullOrEmpty()) + { + XException.InvalidArgs.Throw(); + } + + // + var userInfo = await GetUserInfo(); + + // + var result = await ragService.AskWithRAGAsync( + request: request, + userInfo: userInfo, + cancellationToken: cancellationToken + ); + + // + return Ok(result); + } + catch (Exception ex) + { + // + var result = GetExceptionActionResult(ex); + return result; + } + } + + /// + /// Ask a Question over Knowledge Base 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] XAiKnowledgeAskRequest request, + CancellationToken cancellationToken = default + ) + { + // + // Validate (before Stream Starts -> Proper Http Error) ... + if (request.IsNullOrDefault() || request.Prompt.IsNullOrEmpty()) + { + Response.StatusCode = StatusCodes.Status400BadRequest; + Response.ContentType = "application/json; charset=utf-8"; + await Response.WriteAsync(XException.InvalidArgs.ToXError().ToJSON()); + return; + } + + // + try + { + // + var userInfo = await GetUserInfo(); + + // + await using var enumerator = ragService + .AskWithRAGAsEnumerable( + request: request, + userInfo: userInfo, + cancellationToken: cancellationToken + ) + .GetAsyncEnumerator(cancellationToken); + + // + // Pull First Item before Starting Stream, so Scope / Ownership / + // Retrieval Errors are Returned as Regular Http Errors ... + var hasItem = await enumerator.MoveNextAsync(); + + // + // Configure SSE Response ... + Response.PrepareSseResponse(); + + // + while (hasItem) + { + // + var chunk = enumerator.Current; + if (!chunk.IsNullOrDefault()) + { + await WriteChunk(chunk, cancellationToken); + } + + // + hasItem = await enumerator.MoveNextAsync(); + } + + // + await Response.WriteSseDoneAsync(cancellationToken); + } + catch (Exception ex) when (ex.IsClientCancellation(cancellationToken)) + { + // Client Disconnected ... + } + catch (Exception ex) + { + // + Logger.LogError(ex, "Knowledge: AskStream Failed"); + if (!Response.HasStarted) + { + // + var result = GetExceptionActionResult(ex); + await result.ExecuteResultAsync(ControllerContext); + return; + } + + // + await Response.WriteSseErrorAsync(ex.Message); + } + } + #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")] + public async Task>> Documents( + [FromQuery] XAiKnowledgeScope scope = XAiKnowledgeScope.User, + [FromQuery] Guid? scopeId = null, + [FromQuery] string knowledgeType = null, + CancellationToken cancellationToken = default + ) + { + // + try + { + // + var userInfo = await GetUserInfo(); + + // + var result = await ragService.LoadDocumentsAsync( + userInfo: userInfo, + cancellationToken: cancellationToken, + scope: BuildScope(scope, scopeId, knowledgeType) + ); + + // + 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")] + public async Task> DeleteDocument( + [FromQuery] string fileName, + [FromQuery] XAiKnowledgeScope scope = XAiKnowledgeScope.User, + [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 + ) + { + // + var result = new XAiKnowledgeScopeDescriptor + { + Scope = scope, + 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\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\XAiEmbeddingServiceControllerBase.cs + +using System; +using System.Threading; +using xAiApi.Interfaces; +using xCommons.Providers; +using System.Threading.Tasks; +using xCommons.Configurations; +using Microsoft.AspNetCore.Mvc; +using System.Collections.Generic; +using xIdentityService.Interfaces; +using Microsoft.Extensions.Logging; +using Microsoft.AspNetCore.Authorization; + +namespace xAiApi.Controllers +{ + [Authorize] + [Route("[controller]")] + public abstract class XAiEmbeddingServiceControllerBase : XAiServiceControllerBase, IXAiEmbeddingServiceControllerBase + where TAiService : IXAiEmbeddingServiceBase + { + private readonly TAiService aiService; + + protected XAiEmbeddingServiceControllerBase( + ILogger logger, + TAiService aiService, + XAppConfiguration appConfiguration, + IXIdentityProvider identityProvider, + XValidationProvider validationProvider + ) : base( + logger, + aiService, + appConfiguration, + identityProvider, + validationProvider + ) + { + this.aiService = aiService; + } + + /// + /// Request For Embedding Specified String ... + /// + /// + /// + /// + [AllowAnonymous] + [HttpGet("Embedding")] + public async Task> Embedding( + [FromQuery] string content, + CancellationToken cancellationToken = default + ) + { + // + try + { + // + // Validate ... + ValidationProvider.NotEmpty(content); + + // + var result = await aiService.Embedding( + content: content, + cancellationToken: cancellationToken + ); + + // + return Ok(result); + } + catch (Exception ex) + { + // + var result = GetExceptionActionResult(ex); + return result; + } + } + + /// + /// Request For Embedding Specified Batch ... + /// + /// + /// + /// + [AllowAnonymous] + [HttpGet("Embeddings")] + public async Task>> Embeddings( + [FromQuery] string[] batch, + CancellationToken cancellationToken = default + ) + { + // + try + { + // + // Validate ... + ValidationProvider.NotZeroChilds(batch); + + // + var result = await aiService.Embeddings( + batch: batch, + cancellationToken: cancellationToken + ); + + // + return Ok(result); + } + catch (Exception ex) + { + // + var result = GetExceptionActionResult(ex); + return result; + } + } + } +} + +### 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] + [Route("[controller]")] + public abstract class XAiServiceControllerBase : XBaseIdentityApiV1Controller, IXAiServiceControllerBase + where TAiService : IXAiServiceBase + { + private readonly TAiService aiService; + + protected XAiServiceControllerBase( + ILogger logger, + TAiService aiService, + XAppConfiguration appConfiguration, + IXIdentityProvider identityProvider, + XValidationProvider validationProvider + ) : base( + logger, + appConfiguration, + identityProvider, + validationProvider + ) + { + this.aiService = aiService; + } + + // + #region Actions ... + /// + /// Ask Question and Get Response ... + /// + /// + /// + /// + [HttpGet("AskText")] + [Authorize(Policy = XPolicies.EnabledUser)] + public virtual async Task> AskText( + [FromQuery] string question, + CancellationToken cancellationToken = default + ) + { + // + try + { + // + // Validate ... + ValidationProvider.NotEmpty(question); + + // + var result = await aiService.AskTextAsync( + prompt: question, + cancellationToken: cancellationToken + ); + + // + return Ok(result); + } + catch (Exception ex) + { + // + var result = GetExceptionActionResult(ex); + return result; + } + } + + /// + /// Ask Question and Get Response Stream ... + /// + /// + /// + /// + [HttpGet("AskTextStream")] + [Authorize(Policy = XPolicies.EnabledUser)] + public virtual async Task AskTextStream( + [FromQuery] string question, + CancellationToken cancellationToken = default + ) + { + // + // Validate (before Stream Starts -> Proper Http Error) ... + if (question.IsNullOrEmpty()) + { + await WriteStreamValidationError(); + return; + } + + // + try + { + // + // Configure SSE Response ... + Response.PrepareSseResponse(); + + // + var enumerable = aiService.AskTextAsEnumerable( + prompt: question, + cancellationToken: cancellationToken + ); + + // + // Format: data: {"text":"..."}\n\n + await foreach (var chunk in enumerable) + { + // + // Skip Empty Chunks ... + if (string.IsNullOrEmpty(chunk)) + { + continue; + } + + // + await Response.WriteSseEventAsync( + data: new { text = chunk }, + cancellationToken: cancellationToken + ); + } + + // + await Response.WriteSseDoneAsync(cancellationToken); + } + catch (Exception ex) when (ex.IsClientCancellation(cancellationToken)) + { + // Client Disconnected ... + } + catch (Exception ex) + { + // + Logger.LogError(ex, "AskTextStream Failed"); + if (!Response.HasStarted) + { + // + var result = GetExceptionActionResult(ex); + await result.ExecuteResultAsync(ControllerContext); + return; + } + + // + await Response.WriteSseErrorAsync(ex.Message); + } + } + + /// + /// 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 + + // + #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 = "*", + 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 Data Actions ... + /// + /// Ask Question and Get Response ... + /// + /// + /// + /// + [HttpPost("Ask")] + [Authorize(Policy = XPolicies.EnabledUser)] + public async Task> Ask( + [FromBody] XAiResponseRequest request, + CancellationToken cancellationToken = default + ) + { + // + try + { + // + // Validate ... + if (!request.IsValid()) + { + XException.InvalidArgs.Throw(); + } + + // + var userInfo = await GetUserInfo(); + var connectionId = GetConnectionId(); + + // + // TODO: Reading Fiels Form Collection and Attach it ... + var result = await aiService.AskAsync( + files: null, + prompt: request.Prompt, + ownerId: userInfo.UserId, + 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 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(); + + // + // TODO: Reading Fiels Form Collection and Attach it ... + var enumerable = aiService.AskAsEnumerable( + files: null, + prompt: request.Prompt, + ownerId: userInfo.UserId, + 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 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, + userInfo: userInfo, + prompt: request.Prompt, + ownerId: userInfo.UserId, + connectionId: connectionId, + projectId: request.ProjectId, + cancellationToken: cancellationToken, + conversationId: request.ConversationId + ); + + // + return Ok(result); + } + catch (Exception ex) + { + var result = GetExceptionActionResult(ex); + return result; + } + } + #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 Microsoft.EntityFrameworkCore; +using xAiApi.Constants; +using xAiModels.Providers; +using xDataService.Configuration; +using xDataService.Db; +using xDataService.Providers; +using xFileService.Providers; +using xStringService.Providers; +using xTagService.Providers; + +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(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 Ai Services ... + /// + /// + public static void AddXAiServices( + this IServiceCollection source + ) + { + // + source.AddScoped(); + source.AddScoped(); + source.AddScoped(); + + // + // Persistent RAG (Knowledge over XAiVector Table) ... + 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() && + (!source.TopK.HasValue || source.TopK.Value > 0) && + (!source.MinScore.HasValue || (source.MinScore.Value >= -1f && source.MinScore.Value <= 1f)); + + // + return result; + } + + /// + /// Extract Default Model Descriptor ... + /// + /// + /// + public static XAiModelDescriptor GetDefaultModel(this XAiApiConfiguration source) + { + // + XAiModelDescriptor result = null; + + // + if (source.IsValid()) + { + result = source.Models[0]; + } + + // + return result; + } + + /// + /// Retrieve Specified Model from Config ... + /// + /// + /// + /// + public static XAiModelDescriptor GetModel( + this XAiApiConfiguration source, + string name + ) + { + // + XAiModelDescriptor result = null; + + // + if (source.IsValid()) + { + // + if (name.IsNullOrEmpty()) + { + result = source.GetDefaultModel(); + } + else + { + result = source.Models + .FirstOrDefault(m => m.Name + .Equals(name, System.StringComparison.InvariantCultureIgnoreCase)); + } + } + + // + return result; + } + + /// + /// Retrieve Introduction Prompt ... + /// + /// + /// + public static XAiPromptDescriptor GetIntroductionPrompt(this XAiApiConfiguration source) + { + // + XAiPromptDescriptor result = null; + + // + if (source.IsValid()) + { + // + result = source.Prompts + .FirstOrDefault(p => p.Name + .Equals( + XAiApiConstants.XAiApiIntroductionPromptName, + System.StringComparison.InvariantCultureIgnoreCase)); + } + + // + return result; + } + + /// + /// Select Specified Prompts and Parse it's Template + /// and Generate Message ... + /// + /// + /// + /// + /// + public static string GetPrompt( + this XAiApiConfiguration source, + string name = null, + IDictionary @params = null + ) + { + // + var result = string.Empty; + + // + // Normalize ... + if (name.IsNullOrEmpty()) + { + name = XAiApiConstants.XAiApiIntroductionPromptName; + } + + // + if (source.IsValid()) + { + // + var prompt = source.Prompts + .FirstOrDefault(p => p.Name + .Equals( + name, + System.StringComparison.InvariantCultureIgnoreCase + ) + ); + if (!prompt.IsNullOrDefault()) + { + // + result = prompt.Template; + + // + // Handle Params ... + if (!@params.IsNullOrDefault() && @params.HasChild()) + { + // + // Select Params ... + var existsParams = prompt.Params + .Where(p => @params.Any(pr => pr.Key == p.Name)) + .Distinct() + .ToList(); + + // + // Replace Selected Params ... + existsParams + .ForEach(pk => + { + result = result.Replace(pk.Param, @params[pk.Name]); + }); + } + } + } + + // + return result; + } + + /// + /// Provide HttpClient for Common Usages ... + /// + /// + /// + public static HttpClient GetHttpClient(this string source) + { + // + var result = new HttpClient + { + // + // Disable timeout completely (not recommended for production) + Timeout = Timeout.InfiniteTimeSpan, + + // + BaseAddress = source.IsNullOrEmpty() + ? null + : new Uri(source), + + // + // OR set a very long timeout (e.g., 30 minutes for large file uploads) + // Timeout = TimeSpan.FromMinutes(30) + }; + + // + return result; + } + + /// + /// Instance and Retrieve Chat Client ... + /// + /// + /// + public static IChatClient GetClient(this XAiModelDescriptor source) + { + // + // Try to Initialize LLm ... + var model = source.LLM; + var apiKey = source.ApiKey; + var url = new Uri(source.Url); + var httpClient = source.Url.GetHttpClient(); + + // + IChatClient result = null; + switch (source.Provider) + { + // + case XAiModelProviderType.Ollama: + // + // Instance Ollama Client using Custom HttpCLient ... + var ollamaClient = new OllamaApiClient(httpClient, model); + result = + new ChatClientBuilder(ollamaClient) + .UseFunctionInvocation() + .Build(); + break; + + // + case XAiModelProviderType.OpenAI: + // + // Instance Ollama Client using Custom HttpCLient ... + var openAiClient = new OpenAIClient( + new ApiKeyCredential(apiKey.IsNullOrEmpty() ? XAiModelsConstants.XOpenAINoKey : apiKey), + new OpenAIClientOptions + { + Endpoint = url, + Transport = new HttpClientPipelineTransport(httpClient) + } + ); + result = + new ChatClientBuilder( + openAiClient + .GetChatClient(model) + .AsIChatClient()) + .UseFunctionInvocation() + .Build(); + break; + + // + case XAiModelProviderType.DeepSeek: + break; + + // + case XAiModelProviderType.HuggingFace: + break; + + // + default: + break; + } + + // + if (result.IsNullOrDefault()) + { + XException.InvalidData.Throw(); + } + + // + return result; + } + + } +} + +### FILE: C:\Users\saherelm\Documents\Projects\xSaherelmWorkspace\xAiApi\Extensions\XProgramExtensions.cs + +using xIdentityHelper; +using xCommons.Extensions; +using xCommons.Authorization; +using System.Collections.Generic; +using Microsoft.AspNetCore.Builder; +using Microsoft.AspNetCore.Authorization; +using Microsoft.AspNetCore.HttpOverrides; +using Microsoft.Extensions.DependencyInjection; + +namespace xAiApi.Extensions +{ + public static class XProgramExtensions + { + /// + /// Register Authorization Policies + /// + /// + /// + public static void AddXAuthorization( + this IServiceCollection services, + IDictionary policies = null + ) + { + // + services.AddAuthorization(options => + { + // + if (!policies.IsNull()) + { + // + // Fill Policies ... + using (var policiesEnumerator = policies.GetEnumerator()) + { + while (policiesEnumerator.MoveNext()) + { + var policyDescriptor = policiesEnumerator.Current; + options.AddPolicy(policyDescriptor.Key, policyDescriptor.Value); + } + } + } + + // + var xPolicies = XAuthorizationHelper.GetXAuthorizationPolicies(); + if (!xPolicies.IsNull()) + { + // + // Fill Policies ... + using (var policiesEnumerator = xPolicies.GetEnumerator()) + { + while (policiesEnumerator.MoveNext()) + { + var policyDescriptor = policiesEnumerator.Current; + options.AddPolicy(policyDescriptor.Key, policyDescriptor.Value); + } + } + } + }); + + // + services.AddSingleton(); + } + + /// + /// Use Forward Headers Options for resolving behind a proxy issues ... + /// + /// + /// + public static void UseXForwardOptions(this IApplicationBuilder source) + { + // + var forwardOptions = new ForwardedHeadersOptions + { + ForwardedHeaders = ForwardedHeaders.XForwardedFor | ForwardedHeaders.XForwardedProto, + RequireHeaderSymmetry = false + }; + + // + forwardOptions.KnownNetworks.Clear(); + forwardOptions.KnownProxies.Clear(); + + // + // ref: https://github.com/aspnet/Docs/issues/2384 + source.UseForwardedHeaders(forwardOptions); + } + } +} + +### FILE: C:\Users\saherelm\Documents\Projects\xSaherelmWorkspace\xAiApi\Interfaces\IXAiEmbeddingServiceBase.cs + +using System.Collections.Generic; +using System.Threading; +using System.Threading.Tasks; +using Microsoft.Extensions.AI; +using OllamaSharp; + +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\IXAiEmbeddingServiceControllerBase.cs + +using System.Collections.Generic; +using System.Threading; +using System.Threading.Tasks; +using Microsoft.AspNetCore.Mvc; + +namespace xAiApi.Interfaces +{ + public interface IXAiEmbeddingServiceControllerBase : IXAiServiceControllerBase + { + /// + /// Request For Embedding Specified String ... + /// + /// + /// + /// + [HttpGet("Embedding")] + Task> Embedding( + [FromQuery] string content, + CancellationToken cancellationToken = default + ); + + /// + /// Request For Embedding Specified Batch ... + /// + /// + /// + /// + [HttpGet("Embeddings")] + Task>> Embeddings( + [FromQuery] string[] batch, + CancellationToken cancellationToken = default + ); + } +} + +### 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 + ); + + /// + /// Ask a Question with RAG (Retrieve from DB then Generate) ... + /// + /// + /// + /// + /// + Task AskWithRAGAsync( + XAiKnowledgeAskRequest request, + XUserClaimsInfoDto userInfo = null, + CancellationToken cancellationToken = default + ); + + /// + /// Ask a Question with RAG and Stream Response ... + /// First Item Carries Sources, Next Items Carry Text Deltas, Last Item has IsFinal = true ... + /// + /// + /// + /// + /// + IAsyncEnumerable AskWithRAGAsEnumerable( + 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, + 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\IXAiServiceBase.cs + +using System; +using xModels.Dtos; +using System.Threading; +using xAiModels.Models; +using xAiModels.Models.Dtos; +using System.Threading.Tasks; +using xIdentityModels.Models; +using Microsoft.Extensions.AI; +using Microsoft.AspNetCore.Http; +using System.Collections.Generic; + +namespace xAiApi.Interfaces +{ + /// + /// Describe a Base Service Actions of any Ai Based Services ... + /// + public interface IXAiServiceBase : IDisposable + { + /// + /// Chat Options ... + /// + ChatOptions Options { get; } + + /// + /// Descriptor of Models which used in Service ... + /// + XAiModelDescriptor Descriptor { get; } + + // + #region Actions ... + /// + /// Base Method for Communicate with LLM ... + /// + /// + /// + /// + Task AskTextAsync( + string prompt, + CancellationToken cancellationToken = default + ); + + /// + /// Base Method for Communicate with LLM ... + /// + /// + /// + /// + IAsyncEnumerable AskTextAsEnumerable( + string prompt, + CancellationToken cancellationToken = default + ); + + /// + /// Prepare a Message History List for LLM Communication based on Prompt ... + /// + /// + /// + /// + IList GetHistory( + string prompt = null, + bool forcePrompt = true + ); + + /// + /// Prepare a Message History List for LLM Communication based on Prompt ... + /// + /// + /// + /// + IList GetHistory( + ChatMessage message = null, + bool forceMessage = true + ); + #endregion + + // + #region Context Actions ... + /// + /// Ask a Question using Provided Context Chunks (RAG) without Persisting ... + /// + /// + /// + /// + /// + Task AskWithContextAsync( + string prompt, + IEnumerable context, + CancellationToken cancellationToken = default + ); + + /// + /// Ask a Question using Provided Context Chunks (RAG) and Stream Response ... + /// + /// + /// + /// + /// + IAsyncEnumerable AskWithContextAsEnumerable( + string prompt, + IEnumerable context, + 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 + + // + #region Data Actions ... + /// + /// Ask a Question as Prompt and Retrieve Response ... + /// + /// + /// + /// + /// + /// + /// + /// + /// + /// + Task AskAsync( + string prompt, + string ownerId, + Guid projectId, + Guid conversationId, + string connectionId = null, + IFormFileCollection files = null, + XUserClaimsInfoDto userInfo = null, + CancellationToken cancellationToken = default + ); + + /// + /// Ask a Question as Prompt and Retrieve Response as Async Enumerable ... + /// + /// + /// + /// + /// + /// + /// + /// + /// + IAsyncEnumerable AskAsEnumerable( + string prompt, + string ownerId, + Guid projectId, + Guid conversationId, + string connectionId = null, + IFormFileCollection files = null, + CancellationToken cancellationToken = default + ); + #endregion + } +} + +### FILE: C:\Users\saherelm\Documents\Projects\xSaherelmWorkspace\xAiApi\Interfaces\IXAiServiceControllerBase.cs + +using System; +using xModels.Dtos; +using System.Threading; +using xAiModels.Models; +using xAiModels.Models.Dtos; +using System.Threading.Tasks; +using Microsoft.AspNetCore.Mvc; +using Microsoft.AspNetCore.Http; +using System.Collections.Generic; + +namespace xAiApi.Interfaces +{ + public interface IXAiServiceControllerBase + { + // + #region Actions ... + /// + /// Ask Question and Get Response ... + /// + /// + /// + /// + [HttpGet("AskText")] + Task> AskText( + [FromQuery] string question, + CancellationToken cancellationToken = default + ); + + /// + /// Ask Question and Get Response Stream ... + /// + /// + /// + /// + [HttpGet("AskTextStream")] + Task AskTextStream( + [FromQuery] string question, + CancellationToken cancellationToken = default + ); + #endregion + + // + #region Loaders ... + /// + /// Retrieve AI Projects ... + /// + /// + /// + /// + [HttpGet("Projects")] + Task>> LoadProjects( + [FromQuery] bool includeDefaults = false, + CancellationToken cancellationToken = default + ); + + /// + /// Retrieve Specified AI Project's Conversations ... + /// + /// + /// + /// + [HttpGet("Projects/{projectId}/Conversations")] + Task>> LoadConversations( + [FromRoute] Guid projectId, + CancellationToken cancellationToken = default + ); + + /// + /// Retrieve Specified AI Conversation's Messages ... + /// + /// + /// + /// + [HttpGet("Conversations/{conversationId}/Messages")] + Task>> LoadMessages( + [FromRoute] Guid conversationId, + CancellationToken cancellationToken = default + ); + #endregion + + // + #region Queries ... + /// + /// Query Projects ... + /// + /// + /// + /// + /// + /// + [HttpGet("Projects/Query")] + Task>> QueryProjects( + [FromQuery] XQuery query, + CancellationToken cancellationToken = default + ); + + /// + /// Query Conversations ... + /// + /// + /// + /// + /// + [HttpGet("Projects/{projectId}/Conversations/Query")] + Task>> QueryConversations( + [FromRoute] Guid projectId, + [FromQuery] XQuery query, + CancellationToken cancellationToken = default + ); + + /// + /// Query Messages ... + /// + /// + /// + /// + /// + [HttpGet("Conversations/{conversationId}/Messages/Query")] + Task>> QueryMessages( + [FromRoute] Guid conversationId, + [FromQuery] XQuery query, + CancellationToken cancellationToken = default + ); + #endregion + + // + #region Creators ... + /// + /// Create an AI Project ... + /// + /// + /// + /// + [HttpPost("Projects")] + Task> CreateProject( + [FromBody] XAiProjectDto item, + CancellationToken cancellationToken = default + ); + + /// + /// Create an AI Conversation ... + /// + /// + /// + /// + /// + [HttpPost("Projects/{projectId}/Conversations")] + Task> CreateConversation( + [FromRoute] Guid projectId, + [FromBody] XAiConversationDto item, + CancellationToken cancellationToken = default + ); + #endregion + + // + #region Content Extraction ... + /// + /// Extract Files Content ... + /// + /// + /// + /// + /// + [HttpPost("ExtractContent")] + [Consumes("multipart/form-data")] + Task> ExtractContent( + [FromForm] IFormFileCollection files, + [FromForm] string extractors = null, + CancellationToken cancellationToken = default + ); + #endregion + + // + #region Data Actions ... + /// + /// Ask Question and Get Response ... + /// + /// + /// + /// + [HttpPost("Ask")] + Task> Ask( + [FromBody] XAiResponseRequest request, + CancellationToken cancellationToken = default + ); + + /// + /// Ask Question and Get Response Stream ... + /// + /// + /// + /// + [HttpPost("AskStream")] + Task AskStream( + [FromBody] XAiResponseRequest request, + CancellationToken cancellationToken = default + ); + + /// + /// Ask Question with Files and Get Response ... + /// + /// + /// + /// + [HttpPost("AskWithFiles")] + [Consumes("multipart/form-data")] + Task> AskWithFiles( + [FromForm] XAiResponseRequest request, + [FromForm] IFormFileCollection files, + CancellationToken cancellationToken = default + ); + #endregion + } +} + +### FILE: C:\Users\saherelm\Documents\Projects\xSaherelmWorkspace\xAiApi\Interfaces\IXDefaultAiService.cs + +namespace xAiApi.Interfaces +{ + public interface IXDefaultAiService : IXAiServiceBase + { } +} + +### FILE: C:\Users\saherelm\Documents\Projects\xSaherelmWorkspace\xAiApi\Interfaces\IXDefaultEmbeddingService.cs + +namespace xAiApi.Interfaces +{ + public interface IXDefaultEmbeddingService : IXAiEmbeddingServiceBase + { } +} + +### 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\20261029105407_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: "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: "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\20261029105407_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("20261029105407_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.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.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, + ScopeId = null, + Scope = XAiKnowledgeScope.User, + }; + + /// + /// Create Global Scope Knowledge Descriptor ... + /// + /// + /// + public static XAiKnowledgeScopeDescriptor Global( + string type = null + ) => new() + { + Type = type, + ScopeId = null, + Scope = XAiKnowledgeScope.Global, + }; + + /// + /// Create Project Scope Knowledge Descriptor ... + /// + /// + /// + /// + public static XAiKnowledgeScopeDescriptor Project( + Guid projectId, + string type = null + ) => new() + { + Type = type, + ScopeId = projectId, + Scope = XAiKnowledgeScope.Project, + }; + + /// + /// Create Conversational Scope Knowledge Descriptor ... + /// + /// + /// + /// + public static XAiKnowledgeScopeDescriptor Conversation( + Guid conversationId, + string type = null + ) => new() + { + Type = type, + 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\XAiModelProxyConfiguration.cs + +namespace xAiApi.Models +{ + public class XAiModelProxyConfiguration + { + /// + /// Enable Proxy or not ... + /// + /// + public bool Enabled { get; set; } = false; + + /// + /// Proxy Prefix ... + /// + /// + public string RoutePrefix { get; set; } = "ai-model"; + } +} + +### FILE: C:\Users\saherelm\Documents\Projects\xSaherelmWorkspace\xAiApi\Models\XAiOCRDescriptor.cs + +using Tesseract; + +namespace xAiApi.Models +{ + public class XAiOCRDescriptor + { + /// + /// Provides Trained Data Path ... + /// + public string DataPath { get; set; } + + /// + /// The Engine for Doing OCR ... + /// + public EngineMode EngineMode { get; set; } + + /// + /// Enable OCR Fallback using Model ... + /// + public bool EnableOcrFallback { get; set; } + + /// + /// Default OCR Language ... + /// + public string DefaultLanguage { get; set; } + } +} + +### FILE: C:\Users\saherelm\Documents\Projects\xSaherelmWorkspace\xAiApi\Models\XAiTransciptDescriptor.cs + +namespace xAiApi.Models +{ + public class XAiTransciptDescriptor + { + public string Language { get; set; } + public string ModelsPath { get; set; } + } +} + +### FILE: C:\Users\saherelm\Documents\Projects\xSaherelmWorkspace\xAiApi\Models\XPDFToImageDescriptor.cs + +namespace xAiApi.Models +{ + public class XPDFToImageDescriptor + { + public int Dpi { get; set; } = 300; + public int Width { get; set; } = 0; + public int Height { get; set; } = 0; + public bool UseTiling { get; set; } = false; + public bool WithFormFill { get; set; } = false; + public bool WithAspectRatio { get; set; } = false; + public bool WithAnnotations { get; set; } = false; + public bool DpiRelativeToBounds { get; set; } = false; + + public int MaxImageWidth { get; set; } = 2000; + public int MinTextLengthThreshold { get; set; } = 50; + public int MaxPagesForImageFallback { get; set; } = 0; + } +} + +### FILE: C:\Users\saherelm\Documents\Projects\xSaherelmWorkspace\xAiApi\Models\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\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 xFileService.Interfaces; +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 : XAIServiceBase, IXAiEmbeddingServiceBase + { + private readonly IXFileProvider fileProvider; + private readonly XAiModelDescriptor descriptor; + private readonly ILogger logger; + + protected XAiEmbeddingServiceBase( + IXFileProvider fileProvider, + IXAiDataProvider dataProvider, + XAiApiConfiguration configuration, + XValidationProvider validationProvider, + ILogger logger, + IXFileContentExtractor fileContentExtractor, + string embeddingModelName = XAiApiConstants.XAiEmbeddingModelName + ) : base( + fileProvider, + dataProvider, + logger, + configuration, + validationProvider, + fileContentExtractor, + null + ) + { + // + // Prepare Embedding Model Descriptor ... + descriptor = configuration.GetModel(embeddingModelName); + if (!descriptor.IsValid()) + { + XException.InvalidConfiguration.Throw(); + } + + this.fileProvider = fileProvider; + + // + this.logger = logger; + } + + /// + /// Embedding Specified String ... + /// + /// + /// + /// + public virtual async Task Embedding( + string content, + CancellationToken cancellationToken = default + ) + { + // + // Validate ... + if (content.IsNullOrEmpty()) + { + XException.InvalidArgs.Throw(); + } + + // + using 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\XAiRAGService.cs + +using System; +using System.IO; +using System.Linq; +using xAiApi.Models; +using System.Threading; +using xIdentityHelper; +using xAiApi.Constants; +using xAiApi.Interfaces; +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 System.Runtime.CompilerServices; +using xAiModels.Constants; + +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 IXDefaultAiService aiService; + private readonly IXAiDataProvider dataProvider; + private readonly ILogger logger; + private readonly XAiApiConfiguration configuration; + private readonly IXDefaultEmbeddingService 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, + IXDefaultAiService aiService, + IXAiDataProvider dataProvider, + ILogger logger, + XAiApiConfiguration configuration, + IXDefaultEmbeddingService embeddingService, + IXFileContentExtractor fileContentExtractor + ) + { + // + this.logger = logger; + this.aiService = aiService; + 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); + + // + foreach (var file in files) + { + // + 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 ... + await fileProvider.Upload( + file: file, + userInfo: userInfo, + connectionId: connectionId, + cancellationToken: cancellationToken + ); + + // + // 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 + ); + } + + // + 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; + } + + /// + /// Ask a Question with RAG (Retrieve from DB then Generate) ... + /// + /// + /// + /// + /// + public async Task AskWithRAGAsync( + XAiKnowledgeAskRequest request, + XUserClaimsInfoDto userInfo = null, + CancellationToken cancellationToken = default + ) + { + // + // Retrieve (Validates Request) ... + var context = await RetrieveAsync( + request: request, + userInfo: userInfo, + cancellationToken: cancellationToken + ); + + // + var result = new XAiDocumentAnswer + { + Sources = ToSources(context) + }; + if (!context.HasChild()) + { + // + result.NoContextFound = true; + return result; + } + + // + // Generate ... + result.Answer = await aiService.AskWithContextAsync( + context: context, + prompt: request.Prompt, + cancellationToken: cancellationToken + ); + + // + return result; + } + + /// + /// Ask a Question with RAG and Stream Response ... + /// First Item Carries Sources, Next Items Carry Text Deltas, Last Item has IsFinal = true ... + /// + /// + /// + /// + /// + public async IAsyncEnumerable AskWithRAGAsEnumerable( + XAiKnowledgeAskRequest request, + XUserClaimsInfoDto userInfo = null, + [EnumeratorCancellation] + CancellationToken cancellationToken = default + ) + { + // + // Retrieve (Validates Request) ... + var context = await RetrieveAsync( + request: request, + userInfo: userInfo, + cancellationToken: cancellationToken + ); + + // + // First Item: Sources ... + var hasContext = context.HasChild(); + yield return new XAiDocumentAnswerChunk + { + Text = string.Empty, + IsFinal = !hasContext, + NoContextFound = !hasContext, + Sources = ToSources(context) + }; + if (!hasContext) + { + yield break; + } + + // + // Stream Deltas ... + var enumerable = aiService.AskWithContextAsEnumerable( + context: context, + prompt: request.Prompt, + cancellationToken: cancellationToken + ); + await foreach (var delta in enumerable) + { + // + if (cancellationToken.IsCancellationRequested) + { + yield break; + } + + // + if (delta.IsNullOrEmpty()) + { + continue; + } + + // + yield return new XAiDocumentAnswerChunk { Text = delta }; + } + + // + // Final Item ... + yield return new XAiDocumentAnswerChunk + { + Text = string.Empty, + IsFinal = true + }; + } + #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, + 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) + ); + + // + 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 Scope ... + /// + /// Normalize Scope (Null => User, Clear ScopeId for User/Global, Require ScopeId for Project/Conversation) ... + /// + private static 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 + + // + #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; + } + #endregion + } +} + +### FILE: C:\Users\saherelm\Documents\Projects\xSaherelmWorkspace\xAiApi\Providers\XAIServiceBase.cs + +using System; +using System.Linq; +using xModels.Dtos; +using System.Threading; +using xAiApi.Constants; +using xAiModels.Models; +using xAiApi.Interfaces; +using xAiApi.Extensions; +using xCommons.Providers; +using xCommons.Extensions; +using xAiModels.Constants; +using xAiModels.Interfaces; +using xAiModels.Extensions; +using xAiService.Constants; +using xAiApi.Configurations; +using xExceptions.Constants; +using xAiModels.Models.Dtos; +using xAiService.Extensions; +using System.Threading.Tasks; +using xIdentityModels.Models; +using xFileService.Interfaces; +using Microsoft.Extensions.AI; +using Microsoft.AspNetCore.Http; +using System.Collections.Generic; +using Microsoft.Extensions.Logging; +using xAiApi.Interfaces.Extractors; +using System.Runtime.CompilerServices; + +namespace xAiApi.Providers +{ + /// + /// Base Ai Service ... + /// + public abstract class XAIServiceBase : IXAiServiceBase + { + /// + /// Chat Options ... + /// + public ChatOptions Options { get; } + + /// + /// Descriptor of Models which used in Service ... + /// + public XAiModelDescriptor Descriptor { get; } + + private readonly IXFileProvider fileProvider; + private readonly IXAiDataProvider dataProvider; + private readonly ILogger logger; + private readonly XAiApiConfiguration configuration; + private readonly XValidationProvider validationProvider; + private readonly IXFileContentExtractor fileContentExtractor; + + protected XAIServiceBase( + IXFileProvider fileProvider, + IXAiDataProvider dataProvider, + ILogger logger, + XAiApiConfiguration configuration, + XValidationProvider validationProvider, + IXFileContentExtractor fileContentExtractor, + string model = null + ) + { + // + this.logger = logger; + this.fileProvider = fileProvider; + this.dataProvider = dataProvider; + this.configuration = configuration; + this.validationProvider = validationProvider; + this.fileContentExtractor = fileContentExtractor; + + // + // Prepare Embedding Model Descriptor ... + Descriptor = configuration.GetModel(model); + if (!Descriptor.IsValid()) + { + XException.InvalidConfiguration.Throw(); + } + + // + // Prepare Chat Options based On Tools ... + Options = new ChatOptions(); + } + + // + #region Actions ... + /// + /// Base Method for Communicate with LLM ... + /// + /// + /// + /// + public virtual async Task AskTextAsync( + string prompt, + CancellationToken cancellationToken = default + ) + { + // + // Check Prompt Exists ... + if (prompt.IsNullOrEmpty()) + { + XException.InvalidArgs.Throw(); + } + + // + using var client = Descriptor.GetClient(); + var history = GetHistory(prompt); + var response = await client.GetResponseAsync( + messages: history, + cancellationToken: cancellationToken + ); + + // + // Validate Response ... + if (!response.IsValid()) + { + // + // Dispose Client ... + client.Dispose(); + XException.ActionFailed.Throw(); + } + + // + // Retrieve Response Text ... + var result = response.Text; + + // + return result; + } + + /// + /// Base Method for Communicate with LLM ... + /// + /// + /// + /// + public virtual async IAsyncEnumerable AskTextAsEnumerable( + string prompt, + [EnumeratorCancellation] + CancellationToken cancellationToken = default + ) + { + // + // Check Prompt Exists ... + if (prompt.IsNullOrEmpty()) + { + XException.InvalidArgs.Throw(); + } + + // + using var client = Descriptor.GetClient(); + var history = GetHistory(prompt); + var enumerable = client.GetStreamingResponseAsync( + options: null, + messages: history + ); + + // + await foreach (var res in enumerable) + { + // + // Cancellation Token ... + if (cancellationToken.IsCancellationRequested) + { + yield break; + } + + // + yield return res.Text; + } + } + + /// + /// Prepare a Message History List for LLM Communication based on Prompt ... + /// + /// + /// + /// + public virtual IList GetHistory( + string prompt = null, + bool forcePrompt = true + ) + { + // + // Validate Args ... + if (prompt.IsNullOrEmpty()) + { + XException.InvalidArgs.Throw(); + } + + // + // User Prompt ... + var promptMessage = new ChatMessage( + ChatRole.User, + prompt + ); + + // + // Preparing Introduction Prompt ... + var introductionPrompt = new ChatMessage( + ChatRole.System, + configuration.GetPrompt() + ); + + // + List result = + [ + introductionPrompt, + ]; + if (forcePrompt && + prompt is not null && + !string.IsNullOrWhiteSpace(prompt)) + { + result.Add(promptMessage); + } + + // + return result; + } + + /// + /// Prepare a Message History List for LLM Communication based on Prompt ... + /// + /// + /// + /// + public virtual IList GetHistory( + ChatMessage message = null, + bool forceMessage = true + ) + { + // + // Preparing Introduction Prompt ... + var introductionPrompt = new ChatMessage( + ChatRole.System, + configuration.GetPrompt(XAiApiConstants.XAiApiIntroductionPromptName) + ); + + // + List result = + [ + introductionPrompt, + ]; + if (forceMessage && + !message.IsNullOrDefault()) + { + result.Add(message); + } + + // + return result; + } + #endregion + + // + #region Context Actions ... + /// + /// Ask a Question using Provided Context Chunks (RAG) without Persisting ... + /// + /// + /// + /// + /// + public virtual async Task AskWithContextAsync( + string prompt, + IEnumerable context, + CancellationToken cancellationToken = default + ) + { + // + // Validate Args ... + if (prompt.IsNullOrEmpty()) + { + XException.InvalidArgs.Throw(); + } + + // + using var client = Descriptor.GetClient(); + var history = GetContextHistory(prompt, context); + var response = await client.GetResponseAsync( + messages: history, + cancellationToken: cancellationToken + ); + + // + // Validate Response ... + if (!response.IsValid()) + { + client.Dispose(); + XException.ActionFailed.Throw(); + } + + // + var result = response.Text; + + // + return result; + } + + /// + /// Ask a Question using Provided Context Chunks (RAG) and Stream Response ... + /// + /// + /// + /// + /// + public virtual async IAsyncEnumerable AskWithContextAsEnumerable( + string prompt, + IEnumerable context, + [EnumeratorCancellation] + CancellationToken cancellationToken = default + ) + { + // + // Validate Args ... + if (prompt.IsNullOrEmpty()) + { + XException.InvalidArgs.Throw(); + } + + // + using var client = Descriptor.GetClient(); + var history = GetContextHistory(prompt, context); + var enumerable = client.GetStreamingResponseAsync( + options: null, + messages: history, + cancellationToken: cancellationToken + ); + + // + await foreach (var res in enumerable) + { + // + if (cancellationToken.IsCancellationRequested) + { + yield break; + } + + // + yield return res.Text; + } + } + + /// + /// Build Chat History for RAG: + /// [System: Introduction + ChatWithDocuments Prompt + Context Block] + [User: Prompt] ... + /// + /// + /// + /// + protected virtual IList GetContextHistory( + string prompt, + IEnumerable context + ) + { + // + var introductionPrompt = configuration.GetPrompt(); + var ragPrompt = configuration.GetPrompt(configuration.RAGDescriptor.PromptName); + if (ragPrompt.IsNullOrEmpty()) + { + XException.InvalidConfiguration.Throw(); + } + + // + var contextBlock = BuildContextBlock(context); + var systemText = + $"{introductionPrompt}{Environment.NewLine}{Environment.NewLine}" + + $"{ragPrompt}{Environment.NewLine}{Environment.NewLine}" + + $"Context:{Environment.NewLine}{contextBlock}"; + + // + List result = + [ + new ChatMessage(ChatRole.System, systemText), + new ChatMessage(ChatRole.User, prompt), + ]; + + // + return result; + } + + /// + /// Convert Context Chunks to a Numbered Text Block ... + /// + /// + /// + protected virtual 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; + } + #endregion + + // + #region Loaders ... + /// + /// Load AI Projects ... + /// + /// + /// + /// + /// + /// + public virtual async Task> LoadProjects( + string ownerId, + string connectionId = null, + bool includeDefaults = false, + CancellationToken cancellationToken = default + ) + { + // + // Validate Args ... + if (ownerId.IsNullOrEmpty()) + { + XException.InvalidArgs.Throw(); + } + + // + var result = await dataProvider.LoadProjects( + ownerId: ownerId, + fillConversations: false, + connectionId: connectionId, + fillConversationMessages: false, + cancellationToken: cancellationToken + ); + + // + // Handle Defaults Including ... + if (includeDefaults) + { + // + // Here we have to fill Conversations of Default Project ... + var defaultProjectId = result.GetDafualtProject(ownerId); + var defaultProject = result.FirstOrDefault(x => x.Id == defaultProjectId); + result = result.Where(x => x.Id != defaultProjectId); + + // + // Reading Conversations of Specified Default Project ... + var defaultProjectConversations = await dataProvider.LoadConversations( + fillMessages: false, + connectionId: connectionId, + projectId: defaultProjectId, + cancellationToken: cancellationToken + ); + var defaultConversationId = defaultProjectConversations.GetDefaultConversation( + ownerId: ownerId, + projectId: defaultProjectId + ); + var defaultConversation = defaultProjectConversations.First(x => x.Id == defaultConversationId); + defaultProjectConversations = defaultProjectConversations.Where(x => x.Id != defaultConversationId); + + // + // Reading Default Conversations Messages ... + var defaultConversationMessages = await dataProvider.LoadMessages( + cancellationToken: cancellationToken, + conversationId: defaultConversationId + ); + + // + defaultConversation.Messages = [.. defaultConversationMessages.OrderByDescending(m => m.CreatedOn)]; + defaultProjectConversations = [defaultConversation, .. defaultProjectConversations]; + defaultProject.Conversations = [.. defaultProjectConversations]; + result = [defaultProject, .. result]; + } + + // + return result; + } + + /// + /// Load Conversations of Specified AI Project ... + /// + /// + /// + /// + /// + public virtual async Task> LoadConversations( + Guid projectId, + string connectionId = null, + CancellationToken cancellationToken = default + ) + { + // + // Validate Args ... + if (projectId.IsDefaultGuid()) + { + XException.InvalidArgs.Throw(); + } + + // + var result = await dataProvider.LoadConversations( + fillMessages: false, + projectId: projectId, + connectionId: connectionId, + cancellationToken: cancellationToken + ); + + // + return result; + } + + /// + /// Load Messages of Specified Conversation ... + /// + /// + /// + /// + public virtual async Task> LoadMessages( + Guid conversationId, + CancellationToken cancellationToken = default + ) + { + // + // Validate Args ... + if (conversationId.IsDefaultGuid()) + { + XException.InvalidArgs.Throw(); + } + + // + var result = await dataProvider.LoadMessages( + conversationId: conversationId, + cancellationToken: cancellationToken + ); + + // + return result; + } + #endregion + + // + #region Queries ... + /// + /// Query Projects ... + /// + /// + /// + /// + /// + public virtual async Task> QueryProjects( + string ownerId, + XQuery query, + CancellationToken cancellationToken = default + ) + { + // + // Validate ... + if (ownerId.IsNullOrEmpty()) + { + XException.InvalidArgs.Throw(); + } + + // + var result = await dataProvider.QueryProjects( + query: query, + ownerId: ownerId, + cancellationToken: cancellationToken + ); + + // + return result; + } + + /// + /// Query Conversations ... + /// + /// + /// + /// + /// + /// + public virtual async Task> QueryConversations( + string ownerId, + Guid projectId, + XQuery query, + CancellationToken cancellationToken = default + ) + { + // + // Validate ... + if (ownerId.IsNullOrEmpty() || + projectId.IsDefaultGuid()) + { + XException.InvalidArgs.Throw(); + } + + // + // Retrieve Project ... + var project = await dataProvider.GetProject( + id: projectId, + fillConversations: false, + fillConversationMessages: false, + cancellationToken: cancellationToken + ); + if (project.IsNullOrDefault()) + { + XException.NotFound.Throw(); + } + + // + // Validate Owner ... + if (ownerId != project.OwnerId) + { + XException.NotAllowed.Throw(); + } + + // + var result = await dataProvider.QueryConversations( + query: query, + ownerId: ownerId, + projectId: projectId, + cancellationToken: cancellationToken + ); + + // + return result; + } + + /// + /// Query Messages ... + /// + /// + /// + /// + /// + /// + public virtual async Task> QueryMessages( + string ownerId, + Guid conversationId, + XQuery query, + CancellationToken cancellationToken = default + ) + { + // + // Validate ... + if (ownerId.IsNullOrEmpty() || + conversationId.IsDefaultGuid()) + { + XException.InvalidArgs.Throw(); + } + + // + // Retrieve Conversation ... + var conversation = await dataProvider.GetConversation( + id: conversationId, + fillMessages: false, + cancellationToken: cancellationToken + ); + if (conversation.IsNullOrDefault()) + { + XException.NotFound.Throw(); + } + + // + // Validate Owner ... + if (ownerId != conversation.OwnerId) + { + XException.NotAllowed.Throw(); + } + + // + var result = await dataProvider.QueryMessages( + query: query, + ownerId: ownerId, + conversationId: conversationId, + cancellationToken: cancellationToken + ); + + // + return result; + } + #endregion + + // + #region Creators ... + /// + /// Create an AI Project ... + /// + /// + /// + /// + /// + /// + public virtual async Task CreateProject( + string ownerId, + XAiProjectDto item, + string connectionId = null, + CancellationToken cancellationToken = default + ) + { + // + var result = await dataProvider.CreateProject( + item: item, + ownerId: ownerId, + connectionId: connectionId, + cancellationToken: cancellationToken + ); + + // + return result; + } + + /// + /// Create an AI Conversation ... + /// + /// + /// + /// + /// + /// + /// + public virtual async Task CreateConversation( + string ownerId, + Guid projectId, + XAiConversationDto item, + string connectionId = null, + CancellationToken cancellationToken = default + ) + { + // + var result = await dataProvider.CreateConversation( + item: item, + ownerId: ownerId, + projectId: projectId, + connectionId: connectionId, + cancellationToken: cancellationToken + ); + + // + return result; + } + #endregion + + // + #region Content Extraction ... + /// + /// Try to Extract Files Content ... + /// + /// + /// + /// + /// + public async Task ExtractContent( + IFormFileCollection files, + string[] extractors = null, + CancellationToken cancellationToken = default + ) + { + // + if (!files.HasChild()) + { + XException.InvalidArgs.Throw(); + } + + // + var extractionResults = new List(); + foreach (var file in files) + { + // + if (file.IsNull() || file.Length == 0) + { + continue; + } + + // + var mimeType = file.ContentType?.ToLowerInvariant() ?? string.Empty; + if (!fileContentExtractor.CanExtract(mimeType, extractors)) + { + continue; + } + + // + try + { + // + using var stream = file.OpenReadStream(); + + // + var fr = await fileContentExtractor.ExtractRichAsync( + fileStream: stream, + mimeType: mimeType, + extractors: extractors, + fileName: file.FileName, + cancellationToken: cancellationToken + ); + + // + if (fr.IsValid()) + { + extractionResults.Add(fr); + } + } + catch (OperationCanceledException) + { + throw; + } + catch + { + continue; + } + + // + // TODO: Implement File Save ... + } + + // + var result = string.Empty; + if (extractionResults.HasChild()) + { + // + extractionResults.ForEach(er => + { + result += $"File {er.FileName} Content:{Environment.NewLine}{er.Text ?? er.AudioTranscript}{Environment.NewLine}----"; + }); + } + + // + return result; + } + #endregion + + // + #region Data Actions ... + /// + /// Ask a Question as Prompt and Retrieve Response ... + /// + /// + /// + /// + /// + /// + /// + /// + /// + /// + public virtual async Task AskAsync( + string prompt, + string ownerId, + Guid projectId, + Guid conversationId, + string connectionId = null, + IFormFileCollection files = null, + XUserClaimsInfoDto userInfo = null, + CancellationToken cancellationToken = default + ) + { + // + // Validate Args ... + validationProvider + .GroupValidationBuilder() + .AddNotEmpty(prompt) + .AddNotEmpty(ownerId) + .ValidateGroup(); + + // + // Check Project ... + XAiProjectDto project = null; + if (projectId.IsDefaultGuid()) + { + // + project = await dataProvider.GetDefaultProject( + ownerId: ownerId, + connectionId: connectionId, + cancellationToken: cancellationToken + ); + + // + projectId = project.Id; + } + else + { + // + project = await dataProvider.GetProject( + id: projectId, + fillConversations: false, + fillConversationMessages: false, + cancellationToken: cancellationToken + ); + } + if (project.IsNullOrDefault()) + { + XException.NotFound.Throw(); + } + + // + // Check Conversation ... + XAiConversationDto conversation = null; + if (conversationId.IsDefaultGuid()) + { + // + conversation = await dataProvider.GetDefaultConversation( + ownerId: ownerId, + projectId: projectId, + connectionId: connectionId, + cancellationToken: cancellationToken + ); + + // + conversationId = conversation.Id; + } + else + { + // + conversation = await dataProvider.GetConversation( + id: conversationId, + fillMessages: false, + cancellationToken: cancellationToken + ); + } + if (conversation.IsNullOrDefault()) + { + XException.NotFound.Throw(); + } + + // + // Reading Messages ... + var messages = await dataProvider.LoadMessages( + conversationId: conversationId, + cancellationToken: cancellationToken + ); + + // + // Upload Files ... + IEnumerable uploadedFiles = null; + if (files.HasChild()) + { + // + // Validate User Info ... + if (userInfo.IsNullOrDefault()) + { + XException.InvalidArgs.Throw(); + } + + // + // Upload Files ... + uploadedFiles = await fileProvider.Upload( + files: files, + userInfo: userInfo, + connectionId: connectionId, + cancellationToken: cancellationToken + ); + } + + // + // Handle Memory ... + IList history = await PrepareMemory( + project: project, + messages: messages, + cancellationToken: cancellationToken + ); + + // + // Prepare and Add Prompt Message ... + var promptMessage = new XAiMessageDto + { + Content = prompt, + OwnerId = ownerId, + Role = XAiChatRole.User, + CreatedOn = DateTime.UtcNow, + ConversationId = conversationId, + ConversationTitle = conversation.Title + }; + + // + // Attached Uploaded File Id's as Meta Data ... + if (uploadedFiles.HasChild()) + { + // + var fileIds = uploadedFiles.Select(f => f.Id).ToList(); + promptMessage.MetaDatas = new Dictionary + { + { XAiServiceConstants.XMetaDataFileIdsIdentifier, fileIds } + }.ToJSON(); + } + + // + // Save Prompt Message ... + promptMessage = await dataProvider.AddMessage( + item: promptMessage, + connectionId: connectionId, + conversationId: conversationId, + cancellationToken: cancellationToken + ); + + // + // Since Prompt Message Has Id now, we can Attach Uploaded Files to it ... + IList fileContents = []; + if (uploadedFiles.HasChild()) + { + // + foreach (var uf in uploadedFiles) + { + // + try + { + // + // Add Reference File to Prompt Message ... + await fileProvider.AddReference( + id: uf.Id, + userInfo: userInfo, + connectionId: connectionId, + forProvidedId: promptMessage.Id, + cancellationToken: cancellationToken, + providedFor: XAiServiceConstants.XAiMessageFilesIdentifier + ); + + // + // Handle File Content Extraction and Attach to Prompt Message ... + var fileDescriptor = await fileProvider.GetFileDescriptor( + id: uf.Id, + cancellationToken: cancellationToken + ); + if (fileDescriptor == null || fileDescriptor.Stream == null) + { + continue; + } + + // + var extractionResult = await fileContentExtractor.ExtractRichAsync( + fileStream: fileDescriptor.Stream, + fileName: uf.FileName ?? uf.Name, + mimeType: fileDescriptor.MIMEType, + cancellationToken: cancellationToken + ); + if (extractionResult.IsValid()) + { + // + var contents = extractionResult.ToAIContents(); + fileContents = [.. fileContents, .. contents]; + + // + // ذخیره Metadata برای ردیابی + logger.LogInformation( + "File {FileName} extracted successfully. Text: {HasText}, Images: {ImageCount}, Fallback: {UsedFallback}", + uf.FileName, + !string.IsNullOrEmpty(extractionResult.Text), + extractionResult.Images.Count, + extractionResult.UsedImageFallback + ); + } + + // + fileDescriptor.Stream.Dispose(); + } + catch (Exception ex) + { + logger.LogError(ex, "Failed to extract content from file: {FileName}", uf.FileName); + } + } + } + + // + // Converts to ChatMessage ... + var promptChatMessage = promptMessage + .ToChatMessages(fileContents); + + // + // Ask Questions From LLM ... + var answer = await AskLLMAsync( + history: history, + prompt: promptChatMessage, + cancellationToken: cancellationToken + ); + + // + // Prepare Answer AI Message ... + var result = new XAiMessageDto + { + Content = answer, + OwnerId = ownerId, + CreatedOn = DateTime.UtcNow, + Role = XAiChatRole.Assistant, + ConversationId = conversationId, + ConversationTitle = conversation.Title + }; + result = await dataProvider.AddMessage( + item: result, + connectionId: connectionId, + conversationId: conversationId, + cancellationToken: cancellationToken + ); + + // + return result; + } + + /// + /// Ask a Question as Prompt and Retrieve Response as Async Enumerable ... + /// + /// + /// + /// + /// + /// + /// + /// + /// + public virtual async IAsyncEnumerable AskAsEnumerable( + string prompt, + string ownerId, + Guid projectId, + Guid conversationId, + string connectionId = null, + IFormFileCollection files = null, + [EnumeratorCancellation] + CancellationToken cancellationToken = default + ) + { + // + // Validate Args ... + validationProvider + .GroupValidationBuilder() + .AddNotEmpty(prompt) + .AddNotEmpty(ownerId) + .ValidateGroup(); + + // + // Check Project ... + XAiProjectDto project = null; + if (projectId.IsDefaultGuid()) + { + // + project = await dataProvider.GetDefaultProject( + ownerId: ownerId, + connectionId: connectionId, + cancellationToken: cancellationToken + ); + + // + projectId = project.Id; + } + else + { + // + project = await dataProvider.GetProject( + id: projectId, + fillConversations: false, + fillConversationMessages: false, + cancellationToken: cancellationToken + ); + } + if (project.IsNullOrDefault()) + { + XException.NotFound.Throw(); + } + + // + // Check Conversation ... + XAiConversationDto conversation = null; + if (conversationId.IsDefaultGuid()) + { + // + conversation = await dataProvider.GetDefaultConversation( + ownerId: ownerId, + projectId: projectId, + connectionId: connectionId, + cancellationToken: cancellationToken + ); + + // + conversationId = conversation.Id; + } + else + { + // + conversation = await dataProvider.GetConversation( + id: conversationId, + fillMessages: false, + cancellationToken: cancellationToken + ); + } + if (conversation.IsNullOrDefault()) + { + XException.NotFound.Throw(); + } + + // + // Reading Messages ... + var messages = await dataProvider.LoadMessages( + conversationId: conversationId, + cancellationToken: cancellationToken + ); + + // + // TODO: Parse Files ... + // for Attached them into Prompt Message ... + + // + // Handle Memory ... + IList history = await PrepareMemory( + project: project, + messages: messages, + cancellationToken: cancellationToken + ); + + // + // Prepare and Add Prompt Message ... + var promptMessage = new XAiMessageDto + { + Content = prompt, + OwnerId = ownerId, + Role = XAiChatRole.User, + CreatedOn = DateTime.UtcNow, + ConversationId = conversationId, + }; + promptMessage = await dataProvider.AddMessage( + item: promptMessage, + connectionId: connectionId, + conversationId: conversationId, + cancellationToken: cancellationToken + ); + promptMessage = await dataProvider.Enrich( + source: promptMessage, + cancellationToken: cancellationToken + ); + + // + // Attach Uploaded Files ... + var promptChatMessage = promptMessage + .ToChatMessages(); + history.Add(promptChatMessage); + + // + // Ask Questions From LLM ... + using var client = Descriptor.GetClient(); + var enumerable = client.GetStreamingResponseAsync( + options: null, + messages: history + ); + + // + long sequence = 1; + var answer = string.Empty; + await foreach (var res in enumerable) + { + // + // Cancellation Token ... + if (cancellationToken.IsCancellationRequested) + { + yield break; + } + + // + var resp = new XAiResonseMessage + { + OwnerId = ownerId, + Content = res.Text, + Sequence = sequence, + Role = XAiChatRole.System, + RespondTo = promptMessage.Id, + RespondedOn = DateTime.UtcNow, + }; + + // + sequence++; + answer += res.Text; + + // + yield return resp; + } + + // + // Prepare Answer AI Message ... + var result = new XAiMessageDto + { + Content = answer, + OwnerId = ownerId, + Role = XAiChatRole.System, + CreatedOn = DateTime.UtcNow, + ConversationId = conversationId + }; + result = await dataProvider.AddMessage( + item: result, + connectionId: connectionId, + conversationId: conversationId, + cancellationToken: cancellationToken + ); + } + #endregion + + /// + /// Base Dispose Action ... + /// + /// + public virtual void Dispose() + { } + + // + #region Private ... + /// + /// Implementing Memory Strategy here ... + /// + /// + /// + /// + /// + private async Task> PrepareMemory( + XAiProjectDto project, + IEnumerable messages, + CancellationToken cancellationToken = default + ) + { + // + var result = new List(); + + // + // Retrieve Introduction Prompt ... + var introductionPrompt = configuration.GetPrompt(XAiApiConstants.XAiApiIntroductionPromptName); + if (introductionPrompt.IsNullOrEmpty()) + { + XException.InvalidData.Throw(); + } + + // + var introductionMessage = new ChatMessage( + role: ChatRole.System, + content: introductionPrompt + ); + + // + result.Add(introductionMessage); + + // + if (!project.IsNullOrDefault() && + !project.Prompt.IsNullOrEmpty()) + { + // + // TODO: Handle Project Files Here ... + var projectMessage = new ChatMessage( + role: ChatRole.System, + contents: [new TextContent(project.Prompt)] + ); + result.Add(projectMessage); + } + + // + 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; + } + + /// + /// Ask Quetion from LLM ... + /// + /// + /// + /// + /// + private async Task AskLLMAsync( + ChatMessage prompt, + IList history, + CancellationToken cancellationToken = default + ) + { + // + if (prompt.IsNullOrDefault()) + { + XException.InvalidArgs.Throw(); + } + + // + history.Add(prompt); + using var client = Descriptor.GetClient(); + var response = await client.GetResponseAsync( + messages: history, + cancellationToken: cancellationToken + ); + + // + // Validate Response ... + if (!response.IsValid()) + { + // + // Dispose Client ... + client.Dispose(); + XException.ActionFailed.Throw(); + } + + // + // Retrieve Response Text ... + var result = response.Text; + + // + return result; + } + #endregion + } +} + +### FILE: C:\Users\saherelm\Documents\Projects\xSaherelmWorkspace\xAiApi\Providers\XDefaultAiService.cs + +using xAiApi.Constants; +using xAiApi.Interfaces; +using xCommons.Providers; +using xAiModels.Interfaces; +using xAiApi.Configurations; +using xFileService.Interfaces; +using Microsoft.Extensions.Logging; +using xAiApi.Interfaces.Extractors; + +namespace xAiApi.Providers +{ + public class XDefaultAiService : XAIServiceBase, IXDefaultAiService + { + public XDefaultAiService( + IXFileProvider fileProvider, + IXAiDataProvider dataProvider, + ILogger logger, + XAiApiConfiguration configuration, + XValidationProvider validationProvider, + IXFileContentExtractor fileContentExtractor + ) : base( + fileProvider, + dataProvider, + logger, + configuration, + validationProvider, + fileContentExtractor, + XAiApiConstants.XAiDefaultModelName + ) + { } + } +} + +### FILE: C:\Users\saherelm\Documents\Projects\xSaherelmWorkspace\xAiApi\Providers\XDefaultEmbeddingService.cs + +using xAiApi.Constants; +using xAiApi.Interfaces; +using xAiModels.Interfaces; +using xAiApi.Configurations; +using xFileService.Interfaces; +using Microsoft.Extensions.Logging; +using xAiApi.Interfaces.Extractors; +using xCommons.Providers; + +namespace xAiApi.Providers +{ + public class XDefaultEmbeddingService : XAiEmbeddingServiceBase, IXDefaultEmbeddingService + { + public XDefaultEmbeddingService( + IXFileProvider fileProvider, + IXAiDataProvider dataProvider, + XAiApiConfiguration configuration, + XValidationProvider validationProvider, + ILogger logger, + IXFileContentExtractor fileContentExtractor + ) : base( + fileProvider, + dataProvider, + configuration, + validationProvider, + logger, + fileContentExtractor, + XAiApiConstants.XAiEmbeddingModelName + ) + { } + } +} + +### 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 xFileService.Interfaces; +using Microsoft.Extensions.Logging; +using xAiApi.Interfaces.Extractors; + +namespace xAiApi.Providers +{ + public class XDefaultThinkingAiService : XAIServiceBase, IXDefaultThinkingAiService + { + public XDefaultThinkingAiService( + IXFileProvider fileProvider, + IXAiDataProvider dataProvider, + ILogger logger, + XAiApiConfiguration configuration, + XValidationProvider validationProvider, + IXFileContentExtractor fileContentExtractor, + ReasoningEffort effort = ReasoningEffort.Medium, + ReasoningOutput output = ReasoningOutput.Full + ) : base( + fileProvider, + dataProvider, + logger, + configuration, + validationProvider, + 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) || !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-xAiModels-20261029_200138.txt b/Documents/GeneratedContext/xDashboard-xAiModels-20261029_200138.txt new file mode 100644 index 0000000..fa34fea --- /dev/null +++ b/Documents/GeneratedContext/xDashboard-xAiModels-20261029_200138.txt @@ -0,0 +1,10671 @@ + +### FILE: C:\Users\saherelm\Documents\Projects\xSaherelmWorkspace\Modules\xAiModels\Configurations\XAiApiConfiguration.cs + +using xAiModels.Models; +using xAiModels.Constants; + +namespace xAiModels.Configurations +{ + public class XAiApiConfiguration + { + /// + /// Model Providers ... + /// + public XAiModelDescriptor[] Models { get; set; } = []; + + /// + /// Each User must Has a Default Project, this is Title Resource Identifier ... + /// + public string DefaultProjectTitleResource { get; set; } = XAiModelsConstants.DefaultXAiProjectTitleResourceID; + + /// + /// Each User must Has a Default Project, this is Description Resource Identifier ... + /// + public string DefaultProjectDescriptionResource { get; set; } = XAiModelsConstants.DefaultXAiProjectDescriptionResourceID; + + /// + /// Each User must Has a Default Conversation, this is Title Resource Identifier ... ... + /// + public string DefaultConversationTitleResource { get; set; } = XAiModelsConstants.DefaultXAiConversationTitleResourceID; + } +} + +### FILE: C:\Users\saherelm\Documents\Projects\xSaherelmWorkspace\Modules\xAiModels\Configurations\XAiModelMappersProfile.cs + +using AutoMapper; +using xAiModels.Models.Dtos; +using xAiModels.Models.Entities; + +namespace xAiModels.Configurations +{ + public class XAiModelMappersProfile : Profile + { + public XAiModelMappersProfile() + { + // + // XAiMessage ... + CreateMap(); + + // + // XAiVector ... + CreateMap() + .ForMember(x => x.Embedding, opt => opt.Ignore()) + .ForMember(x => x.Metadata, opt => opt.Ignore()); + CreateMap() + .ForMember(x => x.Embedding, opt => opt.Ignore()) + .ForMember(x => x.Metadata, opt => opt.Ignore()); + + // + // XAiProject ... + CreateMap(); + + // + // XAiConversation ... + CreateMap(); + } + } +} + +### FILE: C:\Users\saherelm\Documents\Projects\xSaherelmWorkspace\Modules\xAiModels\Configurations\Entities\XAiConversationEntityConfiguration.cs + +using System; +using xAiModels.Constants; +using xDataService.Providers; +using xAiModels.Models.Entities; +using Microsoft.EntityFrameworkCore; +using Microsoft.EntityFrameworkCore.Metadata.Builders; + +namespace xAiModels.Configurations.Entities +{ + public class XAiConversationEntityConfiguration : XBaseEntityTypeConfiguration + { + public override void Configure(EntityTypeBuilder builder) + { + builder.ToTable(XAiModelsConstants.XAiConversationTable); + } + } +} + +### FILE: C:\Users\saherelm\Documents\Projects\xSaherelmWorkspace\Modules\xAiModels\Configurations\Entities\XAiMessageEntityConfiguration.cs + +using System; +using xAiModels.Constants; +using xDataService.Providers; +using xAiModels.Models.Entities; +using Microsoft.EntityFrameworkCore; +using Microsoft.EntityFrameworkCore.Metadata.Builders; + +namespace xAiModels.Configurations.Entities +{ + public class XAiMessageEntityConfiguration : XBaseEntityTypeConfiguration + { + public override void Configure(EntityTypeBuilder builder) + { + builder.ToTable(XAiModelsConstants.XAiMessageTable); + } + } +} + +### FILE: C:\Users\saherelm\Documents\Projects\xSaherelmWorkspace\Modules\xAiModels\Configurations\Entities\XAiProjectEntityConfiguration.cs + +using System; +using xAiModels.Constants; +using xDataService.Providers; +using xAiModels.Models.Entities; +using Microsoft.EntityFrameworkCore; +using Microsoft.EntityFrameworkCore.Metadata.Builders; + +namespace xAiModels.Configurations.Entities +{ + public class XAiProjectEntityConfiguration : XBaseEntityTypeConfiguration + { + public override void Configure(EntityTypeBuilder builder) + { + builder.ToTable(XAiModelsConstants.XAiProjectTable); + } + } +} + +### FILE: C:\Users\saherelm\Documents\Projects\xSaherelmWorkspace\Modules\xAiModels\Configurations\Entities\XAiVectorEntityConfiguration.cs + +using System; +using xAiModels.Constants; +using xDataService.Providers; +using xAiModels.Models.Entities; +using Microsoft.EntityFrameworkCore; +using Microsoft.EntityFrameworkCore.Metadata.Builders; + +namespace xAiModels.Configurations.Entities +{ + public class XAiVectorEntityConfiguration : XBaseEntityTypeConfiguration + { + public override void Configure(EntityTypeBuilder builder) + { + // + builder.ToTable(XAiModelsConstants.XAiVectorTable); + + // + builder.Property(x => x.Type).HasMaxLength(100); + + // + // Indexes for Prefix Scoped Search and Type Filtering ... + builder.HasIndex(x => x.Identifier); + builder.HasIndex(x => x.Type); + } + } +} + +### FILE: C:\Users\saherelm\Documents\Projects\xSaherelmWorkspace\Modules\xAiModels\Constants\ConfigurationNodeNames.cs + +namespace xAiModels.Constants +{ + public partial struct ConfigurationNodeNames + { + public const string AI_API_NODE = "AiApiConfiguration"; + } +} + +### FILE: C:\Users\saherelm\Documents\Projects\xSaherelmWorkspace\Modules\xAiModels\Constants\XAiChatRole.cs + +using xExceptions.Attributes; + +namespace xAiModels.Constants +{ + public struct XAiChatRoles + { + public const string None = "none"; + public const string User = "user"; + public const string Tool = "tool"; + public const string System = "system"; + public const string Assistant = "assistant"; + } + + public enum XAiChatRole + { + [StringValue(XAiChatRoles.None)] + None, + [StringValue(XAiChatRoles.User)] + User, + [StringValue(XAiChatRoles.Tool)] + Tool, + [StringValue(XAiChatRoles.System)] + System, + [StringValue(XAiChatRoles.Assistant)] + Assistant, + } +} + +### FILE: C:\Users\saherelm\Documents\Projects\xSaherelmWorkspace\Modules\xAiModels\Constants\XAiDataProviderConstants.cs + +using xExceptions.Attributes; + +namespace xAiModels.Constants +{ + public struct XAiDataProviderConstants + { + public const string XDefaultAiProjectSuffix = "DefAiPrj"; + public const string XDefaultAiConversationSuffix = "DefAiCnv"; + } + + public enum XAiDataProviderHubActions + { + // + // Project ... + [StringValue("ProjectCreated")] + ProjectCreated, + + [StringValue("ProjectUpdated")] + ProjectUpdated, + + [StringValue("ProjectRemoved")] + ProjectRemoved, + + // + // Conversation ... + [StringValue("ConversationCreated")] + ConversationCreated, + + [StringValue("ConversationUpdated")] + ConversationUpdated, + + [StringValue("ConversationRemoved")] + ConversationRemoved, + + // + // Message ... + [StringValue("MessageCreated")] + MessageCreated, + + [StringValue("MessageUpdated")] + MessageUpdated, + + [StringValue("MessageRemoved")] + MessageRemoved, + } +} + +### FILE: C:\Users\saherelm\Documents\Projects\xSaherelmWorkspace\Modules\xAiModels\Constants\XAiKnowledgeScope.cs + +using xExceptions.Attributes; + +namespace xAiModels.Constants +{ + /// + /// Knowledge Base Scope (Where Ingested Vectors are Visible) ... + /// Identifier Layout: "{scopePrefix}/{scopeKey}/{fileName}#{chunkIndex}" (Global has no scopeKey) ... + /// + public enum XAiKnowledgeScope + { + /// + /// Visible only Inside a Conversation (Key = ConversationId) ... + /// + [StringValue(XAiModelsConstants.XAiKnowledgeConversationPrefix)] + Conversation = 0, + + /// + /// Visible to all Conversations of a Project (Key = ProjectId) ... + /// + [StringValue(XAiModelsConstants.XAiKnowledgeProjectPrefix)] + Project = 1, + + /// + /// Visible to Everyone (Write Requires Admin Role) ... + /// + [StringValue(XAiModelsConstants.XAiKnowledgeGlobalPrefix)] + Global = 2, + + /// + /// Personal Knowledge Base of Owner (Key = UserId) ... + /// + [StringValue(XAiModelsConstants.XAiKnowledgeUserPrefix)] + User = 3, + } +} + +### FILE: C:\Users\saherelm\Documents\Projects\xSaherelmWorkspace\Modules\xAiModels\Constants\XAiModelProviderType.cs + +namespace xAiModels.Constants +{ + /// + /// Specifiy Provider Type ... + /// + public enum XAiModelProviderType + { + None, + OpenAI, + Ollama, + DeepSeek, + HuggingFace + } +} + +### FILE: C:\Users\saherelm\Documents\Projects\xSaherelmWorkspace\Modules\xAiModels\Constants\XAiModelsConstants.cs + +namespace xAiModels.Constants +{ + public struct XAiModelsConstants + { + // + // Service Extensions Log Tag ... + public const string XAiModelsDILogTag = "XAiModels"; + + // + // Table Mapping Identifiers ... + public const string XAiVectorTable = "AiVectors"; + public const string XAiMessageTable = "AiMessages"; + public const string XAiProjectTable = "AiProjects"; + public const string XAiConversationTable = "AiConversations"; + + // + // GraphQL Collection Mappings ... + public const string XAiMessageSingleName = "aiMessage"; + public const string XAiProjectSingleName = "aiProject"; + public const string XAiConversationSignleName = "aiConversation"; + + public const string XAiMessageCollectionName = "aiMessages"; + public const string XAiProjectCollectionName = "AiProjectsa"; + public const string XAiConversationCollectionName = "aiConversations"; + + public const string XAiVectorSingleName = "aiVector"; + public const string XAiVectorCollectionName = "aiVectors"; + + // + // Hubs ... + public const string XAiMessageDtoHub = "aiMessageDto"; + public const string XAiMessageEntityHub = "aiMessageEntity"; + + public const string XAiProjectDtoHub = "aiProjectDto"; + public const string XAiProjectEntityHub = "aiProjectEntity"; + + public const string XAiConversationDtoHub = "aiConversationDto"; + public const string XAiConversationEntityHub = "aiConversationEntity"; + + public const string XAiVectorDtoHub = "aiVectorDto"; + public const string XAiVectorEntityHub = "aiVectorEntity"; + + // + // Resource Provider Identifiers ... + public const string XAiProjectTitleIdentifier = "AiPrjT"; + public const string XAiProjectDescriptionIdentifier = "AiPrjD"; + public const string XAiConversationTitleIdentifier = "AiCnvrT"; + + // + // EF Repositories Helper Extensions ... + public const string GetXAiMessageEFRepositoryDescriptor = "GetXAiMessageEFRepositoryDescriptor"; + public const string GetXAiProjectEFRepositoryDescriptor = "GetXAiProjectEFRepositoryDescriptor"; + public const string GetXAiConversationEFRepositoryDescriptor = "GetXAiConversationEFRepositoryDescriptor"; + public const string GetXAiVectorEFRepositoryDescriptor = "GetXAiVectorEFRepositoryDescriptor"; + + // + public const string DefaultXAiProjectTitleResourceID = "XAiPrjT"; + public const string DefaultXAiConversationTitleResourceID = "XAiCnvT"; + public const string DefaultXAiProjectDescriptionResourceID = "XAiPrjD"; + + // + public const string XOpenAINoKey = "no-key-required"; + + // + // Knowledge (Persistent RAG) ... + public const string XAiDefaultKnowledgeType = "XAiKnowledge"; + public const string XAiKnowledgeSeparator = "/"; + public const string XAiKnowledgeOwnerSeparator = "/"; + public const string XAiKnowledgeChunkSeparator = "#"; + public const string XAiKnowledgeUserPrefix = "user"; + public const string XAiKnowledgeGlobalPrefix = "global"; + public const string XAiKnowledgeProjectPrefix = "project"; + public const string XAiKnowledgeConversationPrefix = "conversation"; + + // + // Error Handler Route (Production) ... + public const string XAiErrorRoute = "/error"; + + // + // Knowledge Metadata Keys ... + public const string XAiKnowledgeMetadataType = "type"; + public const string XAiKnowledgeMetadataScope = "scope"; + public const string XAiKnowledgeMetadataScopeId = "scopeId"; + public const string XAiKnowledgeMetadataOwnerId = "ownerId"; + public const string XAiKnowledgeMetadataIngestedAtUtc = "ingestedAtUtc"; + } +} + +### FILE: C:\Users\saherelm\Documents\Projects\xSaherelmWorkspace\Modules\xAiModels\DI\XDIHelperExtension.cs + +using System; +using xDataService.Db; +using xPushService.DI; +using xDataService.DI; +using xCommons.Helpers; +using xAiModels.Helpers; +using xDataService.Models; +using xAiModels.Providers; +using xAiModels.Constants; +using xCommons.Extensions; +using xPushService.Helpers; +using xAiModels.Interfaces; +using xExceptions.Constants; +using xDataService.Constants; +using xAiModels.Providers.Dtos; +using xAiModels.Interfaces.Dtos; +using Microsoft.AspNetCore.Builder; +using xAiModels.Providers.Entities; +using xAiModels.Interfaces.Entities; +using xAiModels.Providers.Enrichers; +using xAiModels.Interfaces.Enrichers; +using Microsoft.Extensions.DependencyInjection; + +namespace xAiModels.DI +{ + /// + /// Service Registration Extensions Classes ... + /// + public static class XDIHelperExtension + { + /// + /// Register Service ... + /// + /// + /// + /// + public static void AddXAiDataService( + this IServiceCollection services, + XRepositoryType repositoryType, + ServiceLifetime lifeTime = ServiceLifetime.Scoped + ) + { + AddAiDataService( + contextType: null, + services: services, + lifeTime: lifeTime, + repositoryType: repositoryType + ); + } + + /// + /// Register Service ... + /// + /// + /// + /// + /// + public static void AddXAiDataService( + this IServiceCollection services, + XRepositoryType repositoryType, + ServiceLifetime lifeTime = ServiceLifetime.Scoped + ) + where TContext : XDbContext + { + AddAiDataService( + services: services, + lifeTime: lifeTime, + contextType: typeof(TContext), + repositoryType: repositoryType + ); + } + + /// + /// Use XSubCategoryService Middleware ... + /// + /// + /// + public static void UseXAiDataService( + this IApplicationBuilder app, + bool isDevelopmentEnvironment = false + ) + { + // + #region Using Hubs ... + // + var pushHelper = new XPushServiceHelper(); + + // + // XAiVector ... + pushHelper.AddHub(XAiModelsConstants.XAiVectorDtoHub); + pushHelper.AddHub(XAiModelsConstants.XAiVectorEntityHub); + + // + // XAiMessage ... + pushHelper.AddHub(XAiModelsConstants.XAiMessageDtoHub); + pushHelper.AddHub(XAiModelsConstants.XAiMessageEntityHub); + + // + // XAiProject ... + pushHelper.AddHub(XAiModelsConstants.XAiProjectDtoHub); + pushHelper.AddHub(XAiModelsConstants.XAiProjectEntityHub); + + // + // XAiConversation ... + pushHelper.AddHub(XAiModelsConstants.XAiConversationDtoHub); + pushHelper.AddHub(XAiModelsConstants.XAiConversationEntityHub); + + // + app.UseXPushService(pushHelper); + #endregion + + // + // Using XAiConversation Repository Descriptor ... + if (!aiConversationDescriptor.IsNull()) + { + // + app.UseXRepository( + descriptor: aiConversationDescriptor, + isDevelopmentEnvironment: isDevelopmentEnvironment + ); + } + + // + // Using XAiMessage Repository Descriptor ... + if (!aiMessageDescriptor.IsNull()) + { + // + app.UseXRepository( + descriptor: aiMessageDescriptor, + isDevelopmentEnvironment: isDevelopmentEnvironment + ); + } + + // + // Using XAiProject Repository Descriptor ... + if (!aiProjectDescriptor.IsNull()) + { + // + app.UseXRepository( + descriptor: aiProjectDescriptor, + isDevelopmentEnvironment: isDevelopmentEnvironment + ); + } + + // + // Create an Scope for Services Acces ... + // Handle Seeding Category/SubCategory Resources ... + // TODO: Enable Seeding if Required ... + // using (var scope = app.ApplicationServices.CreateScope()) + // { + // // + // // Retrieve Configuratuions ... + // var aiMessageProvider = scope.ServiceProvider.GetService(); + // var aiProjectProvider = scope.ServiceProvider.GetService(); + // var aiConversationProvider = scope.ServiceProvider.GetService(); + // var configuration = scope.ServiceProvider.GetService(); + // if (!configuration.IsNullOrDefault() && + // !categoryProvider.IsNullOrDefault() && + // !subaiConversationDescriptor.IsNullOrDefault() + // ) + // { + // // + // // Logging ... + // Log("Start Seeding ..."); + + // // + // // Count Data in Category ... + // var hasCategory = (categoryProvider.Count().GetAwaiter().GetResult()) > 0; + // var hasSubCategory = (subCategoryProvider.Count().GetAwaiter().GetResult()) > 0; + + // // + // // Seed Category Resources ... + // var canSeed = + // !hasCategory && + // configuration.Categories.HasChild(); + // if (canSeed) + // { + // // + // // Loop through Provided items ... + // foreach (var cat in configuration.Categories) + // { + // // + // try + // { + // // + // Log($"Start Seeding Category: {cat.Titles.Locales.ToArray()[0].Value} ..."); + + // // + // categoryProvider.Refresh( + // resource: cat, + // userInfo: null, + // connectionId: null, + // cancellationToken: default + // ) + // .GetAwaiter() + // .GetResult(); + + // // + // Log($"Seeding Category: {cat.Titles.Locales.ToArray()[0].Value} Finished Successfully ..."); + // } + // catch (Exception ex) + // { + // Log($"Seeding Category: {cat.Titles.Locales.ToArray()[0].Value} Failed due: {ex.Message} ..."); + // } + // } + // } + + // // + // // Seed SubCategory Resources ... + // canSeed = + // !hasSubCategory && + // configuration.SubCategories.HasChild(); + // if (canSeed) + // { + // // + // // Loop through Provided items ... + // foreach (var subcat in configuration.SubCategories) + // { + // // + // try + // { + // // + // Log($"Start Seeding SubCategory: {subcat.Titles.Locales.ToArray()[0].Value} ..."); + + // // + // subCategoryProvider.Refresh( + // userInfo: null, + // resource: subcat, + // connectionId: null, + // cancellationToken: default + // ) + // .GetAwaiter() + // .GetResult(); + + // // + // Log($"Seeding SubCategory: {subcat.Titles.Locales.ToArray()[0].Value} Finished Successfully ..."); + // } + // catch (Exception ex) + // { + // Log($"Seeding SubCategory: {subcat.Titles.Locales.ToArray()[0].Value} Failed due: {ex.Message} ..."); + // } + // } + // } + + // // + // Log("Finish Seeding ..."); + // } + // } + } + + // + #region Private ... + private static XRepositoryDescriptor aiVectorDescriptor = null; + private static XRepositoryDescriptor aiMessageDescriptor = null; + private static XRepositoryDescriptor aiProjectDescriptor = null; + private static XRepositoryDescriptor aiConversationDescriptor = null; + + /// + /// a LogTag for Service ... + /// + private static string XLogTag = XAiModelsConstants.XAiModelsDILogTag; + + /// + /// print a log in Console ... + /// + /// + private static void Log(string message) + { + Console.WriteLine($"{XLogTag} => {message}"); + } + + /// + /// Register Service ... + /// + /// + /// + /// + /// + private static void AddAiDataService( + IServiceCollection services, + XRepositoryType repositoryType, + Type contextType = null, + ServiceLifetime lifeTime = ServiceLifetime.Scoped + ) + { + // + var exception = XException.InvalidArgs.ToException(); ; + + // + // Services ... + var isServicesExists = !services.IsNull(); + if (!isServicesExists) + { + // + Log("Service Registration failed, services not provided ..."); + throw exception; + } + + // + // Lifetime ... + var isLifetimeExists = !lifeTime.IsNull(); + if (!isLifetimeExists) + { + // + Log("Service Registration failed, lifetime not provided ..."); + throw exception; + } + + // + // Validate Repository Type ... + var isRepositoryTypeValid = + (repositoryType == XRepositoryType.EF && + !contextType.IsNull()) || + ((repositoryType == XRepositoryType.Mongo || + repositoryType == XRepositoryType.InMemory) && + contextType.IsNull()); + if (!isRepositoryTypeValid) + { + // + Log("Service Registration failed, Invalid Repository Type and Context Type ..."); + throw exception; + } + + // + // Maske Instance of Repository Descriptor + // Based on Provided Type ... + switch (repositoryType) + { + // + case XRepositoryType.EF: + // + // XAiVector ... + aiVectorDescriptor = typeof(XAiModelsHelper) + .InvokeGenericMethod( + args: null, + runtimeType: contextType, + methodName: XAiModelsConstants.GetXAiVectorEFRepositoryDescriptor + ); + + // + // XAiMessage ... + aiMessageDescriptor = typeof(XAiModelsHelper) + .InvokeGenericMethod( + args: null, + runtimeType: contextType, + methodName: XAiModelsConstants.GetXAiMessageEFRepositoryDescriptor + ); + + // + // XAiProject ... + aiProjectDescriptor = typeof(XAiModelsHelper) + .InvokeGenericMethod( + args: null, + runtimeType: contextType, + methodName: XAiModelsConstants.GetXAiProjectEFRepositoryDescriptor + ); + + // + // XAiConversation ... + aiConversationDescriptor = typeof(XAiModelsHelper) + .InvokeGenericMethod( + args: null, + runtimeType: contextType, + methodName: XAiModelsConstants.GetXAiConversationEFRepositoryDescriptor + ); + break; + + // + case XRepositoryType.Mongo: + // + // XAiVector ... + aiVectorDescriptor = XAiModelsHelper.GetXAiVectorMongoRepositoryDescriptor(); + + // + // XAiMessage ... + aiMessageDescriptor = XAiModelsHelper.GetXAiMessageMongoRepositoryDescriptor(); + + // + // XAiProject ... + aiProjectDescriptor = XAiModelsHelper.GetXAiProjectMongoRepositoryDescriptor(); + + // + // XAiConversation ... + aiConversationDescriptor = XAiModelsHelper.GetXAiConversationMongoRepositoryDescriptor(); + break; + + // + case XRepositoryType.InMemory: + // + // XAiVector ... + aiVectorDescriptor = XAiModelsHelper.GetXAiVectorInMemoryRepositoryDescriptor(); + + // + // XAiMessage ... + aiMessageDescriptor = XAiModelsHelper.GetXAiMessageInMemoryRepositoryDescriptor(); + + // + // XAiProject ... + aiProjectDescriptor = XAiModelsHelper.GetXAiProjectInMemoryRepositoryDescriptor(); + + // + // XAiConversation ... + aiConversationDescriptor = XAiModelsHelper.GetXAiConversationInMemoryRepositoryDescriptor(); + break; + } + + // + #region Register Repository Descriptor ... + // + // XAiVector ... + if (!aiVectorDescriptor.IsNull()) + { + // + services.AddXRepository( + lifeTime: lifeTime, + descriptor: aiVectorDescriptor + ); + } + + // + // XAiMessage ... + if (!aiMessageDescriptor.IsNull()) + { + // + services.AddXRepository( + lifeTime: lifeTime, + descriptor: aiMessageDescriptor + ); + } + + // + // XAiProject ... + if (!aiProjectDescriptor.IsNull()) + { + // + services.AddXRepository( + lifeTime: lifeTime, + descriptor: aiProjectDescriptor + ); + } + + // + // XAiConversation ... + if (!aiConversationDescriptor.IsNull()) + { + // + services.AddXRepository( + lifeTime: lifeTime, + descriptor: aiConversationDescriptor + ); + } + #endregion + + // + #region Register Services ... + // + #region AiVector ... + // + services.Add( + new ServiceDescriptor(typeof(IXAiVectorServiceProvider), typeof(XAiVectorServiceProvider), lifeTime) + ); + services.Add( + new ServiceDescriptor(typeof(IXAiVectorRepositoryService), typeof(XAiVectorRepositoryService), lifeTime) + ); + services.Add( + new ServiceDescriptor(typeof(IXAiVectorRepositoryProvider), typeof(XAiVectorRepositoryProvider), lifeTime) + ); + + // + // Enrichers ... + services.Add( + new ServiceDescriptor(typeof(IXAiVectorEnricher), typeof(XAiVectorEnricher), lifeTime) + ); + #endregion + + // + #region AiMessage ... + // + services.Add( + new ServiceDescriptor(typeof(IXAiMessageServiceProvider), typeof(XAiMessageServiceProvider), lifeTime) + ); + services.Add( + new ServiceDescriptor(typeof(IXAiMessageRepositoryService), typeof(XAiMessageRepositoryService), lifeTime) + ); + services.Add( + new ServiceDescriptor(typeof(IXAiMessageRepositoryProvider), typeof(XAiMessageRepositoryProvider), lifeTime) + ); + + // + // Enrichers ... + services.Add( + new ServiceDescriptor(typeof(IXAiMessageEnricher), typeof(XAiMessageEnricher), lifeTime) + ); + #endregion + + // + #region AiProject ... + // + services.Add( + new ServiceDescriptor(typeof(IXAiProjectServiceProvider), typeof(XAiProjectServiceProvider), lifeTime) + ); + services.Add( + new ServiceDescriptor(typeof(IXAiProjectRepositoryService), typeof(XAiProjectRepositoryService), lifeTime) + ); + services.Add( + new ServiceDescriptor(typeof(IXAiProjectRepositoryProvider), typeof(XAiProjectRepositoryProvider), lifeTime) + ); + + // + // Resource Providers ... + services.Add( + new ServiceDescriptor(typeof(IXAiProjectTitleResourceProvider), typeof(XAiProjectTitleResourceProvider), lifeTime) + ); + services.Add( + new ServiceDescriptor(typeof(IXAiProjectDescriptionResourceProvider), typeof(XAiProjectDescriptionResourceProvider), lifeTime) + ); + + // + // Enrichers ... + services.Add( + new ServiceDescriptor(typeof(IXAiProjectEnricher), typeof(XAiProjectEnricher), lifeTime) + ); + #endregion + + // + #region AiConversation ... + // + services.Add( + new ServiceDescriptor(typeof(IXAiConversationServiceProvider), typeof(XAiConversationServiceProvider), lifeTime) + ); + services.Add( + new ServiceDescriptor(typeof(IXAiConversationRepositoryService), typeof(XAiConversationRepositoryService), lifeTime) + ); + services.Add( + new ServiceDescriptor(typeof(IXAiConversationRepositoryProvider), typeof(XAiConversationRepositoryProvider), lifeTime) + ); + + // + // Resource Providers ... + services.Add( + new ServiceDescriptor(typeof(IXAiConversationTitleResourceProvider), typeof(XAiConversationTitleResourceProvider), lifeTime) + ); + + // + // Enrichers ... + services.Add( + new ServiceDescriptor(typeof(IXAiConversationEnricher), typeof(XAiConversationEnricher), lifeTime) + ); + #endregion + #endregion + + // + // Data Provider ... + services.Add( + new ServiceDescriptor(typeof(IXAiDataProvider), typeof(XAiDataProvider), lifeTime) + ); + + // + Log("Service Regitration Succeed ..."); + } + #endregion + } +} + +### FILE: C:\Users\saherelm\Documents\Projects\xSaherelmWorkspace\Modules\xAiModels\Extensions\ChatResponseExtensions.cs + +using xCommons.Extensions; +using Microsoft.Extensions.AI; + +namespace xAiModels.Extensions +{ + public static class ChatResponseExtensions + { + /// + /// Validate a Chat Response ... + /// + /// + /// + public static bool IsValid(this ChatResponse source) + { + // + var result = + source is not null && + !source.IsNullOrDefault() && + !string.IsNullOrWhiteSpace(source.Text) && + source.FinishReason == ChatFinishReason.Stop; + + // + return result; + } + } +} + +### FILE: C:\Users\saherelm\Documents\Projects\xSaherelmWorkspace\Modules\xAiModels\Extensions\ChatRoleExtensions.cs + +using xAiModels.Constants; +using xCommons.Extensions; +using Microsoft.Extensions.AI; + +namespace xAiModels.Extensions +{ + /// + /// Extensions for ChatRole ... + /// + public static class ChatRoleExtensions + { + /// + /// Normalize an String to Propper Chat Role Value ... + /// > + /// + /// + /// + public static string GetChatRoleTitle(this string source) + { + // + var result = XAiChatRoles.None; + + // + if (source.ToNormalString() == XAiChatRoles.None.ToNormalString()) + { + result = XAiChatRoles.None; + } + else if (source.ToNormalString() == XAiChatRoles.User.ToNormalString()) + { + result = XAiChatRoles.User; + } + else if (source.ToNormalString() == XAiChatRoles.Tool.ToNormalString()) + { + result = XAiChatRoles.Tool; + } + else if (source.ToNormalString() == XAiChatRoles.System.ToNormalString()) + { + result = XAiChatRoles.System; + } + else if (source.ToNormalString() == XAiChatRoles.Assistant.ToNormalString()) + { + result = XAiChatRoles.Assistant; + } + + // + return result; + } + + /// + /// Get Chat Role Title from Chat Role Class ... + /// + /// + /// + /// + public static string GetRole(this ChatRole source) + { + // + var result = source.Value + .GetChatRoleTitle(); + + // + return result; + } + + /// + /// Generate Chat Role Class Based on role Title ... + /// + /// + /// + public static ChatRole ToChatRole(this string source) + { + // + var role = source.GetChatRoleTitle(); + ChatRole result = new ChatRole(role); + + // + return result; + } + + /// + /// Generate Chat Role Class Based on role Title ... + /// + /// + /// + public static ChatRole ToChatRole(this XAiChatRole source) + { + // + var role = source.GetStringValue(); + ChatRole result = new ChatRole(role); + + // + return result; + } + + /// + /// Extract Chat Role Enum from Chat Role ... + /// + /// + /// + /// + /// + public static XAiChatRole ToChatRole(this ChatRole source) + { + // + var role = source + .GetRole() + .GetChatRoleTitle(); + + // + XAiChatRole result = XAiChatRole.User; + + // + if (role == XAiChatRoles.User) + { + result = XAiChatRole.User; + } + else if (role == XAiChatRoles.Tool) + { + result = XAiChatRole.Tool; + } + else if (role == XAiChatRoles.System) + { + result = XAiChatRole.System; + } + else if (role == XAiChatRoles.Assistant) + { + result = XAiChatRole.Assistant; + } + + // + return result; + } + + /// + /// Validate an String as Chat Role ... + /// + /// + /// + public static bool IsValid(this string source) + { + // + var result = + source != XAiChatRoles.None && + source.ToNormalString() != XAiChatRoles.None.ToNormalString(); + + // + return result; + } + + /// + /// Validate Role ... + /// > + /// + /// + /// + public static bool IsValid(this XAiChatRole source) + { + // + var result = source != XAiChatRole.None; + return result; + } + + /// + /// Validate Role ... + /// > + /// + /// + /// + public static bool IsValid(this ChatRole source) + { + // + var role = source.ToChatRole(); + var result = role.IsValid(); + return result; + } + } +} + +### FILE: C:\Users\saherelm\Documents\Projects\xSaherelmWorkspace\Modules\xAiModels\Extensions\XAiApiConfigurationExtensions.cs + +using System.Linq; +using xAiModels.Models; +using xCommons.Extensions; +using xAiModels.Configurations; + +namespace xAiModels.Extensions +{ + public static class XAiApiConfigurationExtensions + { + /// + /// Validate Api Configuration ... + /// + /// + /// + public static bool IsValid(this XAiApiConfiguration source) + { + return + !source.IsNullOrDefault() && + source.Models.HasChild(); + } + + /// + /// Retrieve Default Model Descriptor ... + /// + /// + /// + public static XAiModelDescriptor GetDefaultModel(this XAiApiConfiguration source) + { + // + XAiModelDescriptor result = null; + + // + if (source.IsValid()) + { + result = source.Models.First(); + } + + // + return result; + } + } +} + +### FILE: C:\Users\saherelm\Documents\Projects\xSaherelmWorkspace\Modules\xAiModels\Extensions\XAiModelsExtensions.cs + +using System; +using System.Linq; +using System.Net.Http; +using xAiModels.Models; +using xCommons.Constants; +using xModels.Extensions; +using xCommons.Extensions; +using xAiModels.Constants; +using xAiModels.Models.Dtos; +using xExceptions.Constants; +using Microsoft.Extensions.AI; +using xAiModels.Models.Entities; +using System.Collections.Generic; + +namespace xAiModels.Extensions +{ + /// + /// Extensions Methods for XAiModels ... + /// + public static class XAiModelsExtensions + { + /// + /// Validate a Project for Add Or Update ... + /// + /// + /// + public static bool IsValidForAddOrUpdate(this XAiProject source) + { + // + var result = + !source.IsNullOrDefault() && + !source.OwnerId.IsNullOrEmpty() && + !source.Prompt.IsNullOrEmpty(); + + // + return result; + } + public static bool IsValidForAddOrUpdate(this XAiProjectDto source) + { + // + var result = + !source.IsNullOrDefault() && + !source.OwnerId.IsNullOrEmpty() && + !source.Prompt.IsNullOrEmpty(); + + // + return result; + } + + /// + /// Validate a Conversation for Add Or Update ... + /// + /// + /// + public static bool IsValidForAddOrUpdate(this XAiConversation source) + { + // + var result = + !source.IsNullOrDefault() && + !source.OwnerId.IsNullOrEmpty() && + !source.ProjectId.IsNull() && + !source.ProjectId.IsDefaultGuid(); + + // + return result; + } + public static bool IsValidForAddOrUpdate(this XAiConversationDto source) + { + // + var result = + !source.IsNullOrDefault() && + !source.OwnerId.IsNullOrEmpty() && + !source.ProjectId.IsNull() && + !source.ProjectId.IsDefaultGuid(); + + // + return result; + } + + /// + /// Validate a Message for Add Or Update ... + /// + /// + /// + public static bool IsValidForAddOrUpdate(this XAiMessage source) + { + // + var result = + !source.IsNullOrDefault() && + !source.OwnerId.IsNullOrEmpty() && + source.Role.IsValid() && + !source.ConversationId.IsNull() && + !source.ConversationId.IsDefaultGuid() && + !source.Content.IsNullOrEmpty(); + + // + return result; + } + public static bool IsValidForAddOrUpdate(this XAiMessageDto source) + { + // + var result = + !source.IsNullOrDefault() && + !source.OwnerId.IsNullOrEmpty() && + source.Role.IsValid() && + !source.ConversationId.IsNull() && + !source.ConversationId.IsDefaultGuid() && + !source.Content.IsNullOrEmpty(); + + // + return result; + } + + /// + /// Validate a Model Descriptor ... + /// + /// + /// + public static bool IsValid(this XAiModelDescriptor source) + { + // + var result = + !source.IsNullOrDefault() && + !source.Name.IsNullOrEmpty() && + !source.Url.IsNullOrEmpty() && + source.Url.IsValidUrl() && + !source.LLM.IsNullOrEmpty() && + source.Provider != Constants.XAiModelProviderType.None; + + // + return result; + } + + /// + /// Validate Specified Param ... + /// + /// + /// + public static bool IsValid(this XAiPromptParam source) + { + // + var result = + !source.IsNullOrDefault() && + !source.Name.IsNullOrEmpty() && + !source.Param.IsNullOrEmpty(); + + // + return result; + } + + /// + /// Validate Specified Prompt ... + /// + /// + /// + public static bool IsValid(this XAiPromptDescriptor source) + { + // + var result = + !source.IsNullOrDefault() && + !source.Name.IsNullOrEmpty() && + !source.Template.IsNullOrEmpty(); + if (!result) + { + return result; + } + + // + if (source.Params.HasChild()) + { + result = + result && + source.Params.All(x => x.IsValid()); + } + + // + return result; + } + + /// + /// Validate a Request for Retrieve Response in Controllers ... + /// + /// + /// + public static bool IsValid(this XAiResponseRequest source) + { + // + var result = + !source.IsNullOrDefault() && + !source.Prompt.IsNullOrEmpty(); + + // + return result; + } + + /// + /// Validate a File Extraction Result ... + /// + /// + /// + public static bool IsValid(this XFileExtractionResult source) + { + // + var result = + !source.IsNullOrDefault() && + ( + source.Images.HasChild() || + !source.Text.IsNullOrEmpty() || + !source.AudioTranscript.IsNullOrEmpty() + ); + return result; + } + + /// + /// Converts a File Extraction Result to AI Contents ... + /// + /// + /// + public static IList ToAIContents(this XFileExtractionResult source) + { + // + var result = new List(); + + // + if (source.IsValid()) + { + // + // Main Text ... + if (!source.Text.IsNullOrEmpty()) + { + result.Add(new TextContent(source.Text)); + } + + // + // Images ... + if (source.Images.HasChild()) + { + // + foreach (var img in source.Images) + { + result.Add(new DataContent(img.Bytes, img.MimeType)); + } + } + + // + // Transcripted Audio ... + if (!source.AudioTranscript.IsNullOrEmpty()) + { + result.Add(new TextContent($"[Audio Transcript]\n{source.AudioTranscript}")); + } + } + + // + return result; + } + + /// + /// Check a Collection Contains Default Project for Specified Owner or not ... + /// + /// + /// + /// + public static bool HasDefaultProject( + this IEnumerable source, + string ownerId + ) + { + // + // Validate Args ... + if (!source.HasChild() || + ownerId.IsNullOrEmpty()) + { + XException.InvalidArgs.Throw(); + } + + // + var item = source + .FirstOrDefault(x => + x.Title + .ToNormalString() + .Contains(ownerId.ToNormalString()) && + x.Title + .ToNormalString() + .Contains(XAiModelsConstants.DefaultXAiProjectDescriptionResourceID.ToNormalString()) + ); + + // + var result = !item.IsNullOrDefault(); + + // + return result; + } + + /// + /// Check a Collection Contains Default Conversation for Specified Project or not ... + /// + /// + /// + /// + /// + public static bool HasDefaultConversation( + this IEnumerable source, + string ownerId, + Guid projectId + ) + { + // + // Validate Args ... + if (!source.HasChild() || + projectId.IsDefaultGuid()) + { + XException.InvalidArgs.Throw(); + } + + // + var item = source + .FirstOrDefault(x => + x.Title + .ToNormalString() + .Contains(ownerId.ToNormalString()) && + x.Title + .ToNormalString() + .Contains(projectId.ToString().ToNormalString()) && + x.Title + .ToNormalString() + .Contains(XAiModelsConstants.DefaultXAiConversationTitleResourceID) + ); + + // + var result = !item.IsNullOrDefault(); + + // + return result; + } + + /// + /// Retrieve Default Project Id from a Collection ... + /// + /// + /// + /// + public static Guid GetDafualtProject( + this IEnumerable source, + string ownerId + ) + { + // + // Validate Args ... + if (!source.HasChild() || + ownerId.IsNullOrEmpty()) + { + XException.InvalidArgs.Throw(); + } + + // + var item = source + .FirstOrDefault(x => + x.Title + .ToNormalString() + .Contains(ownerId.ToNormalString()) && + x.Title + .ToNormalString() + .Contains(XAiModelsConstants.XAiProjectTitleIdentifier.ToNormalString()) + ); + if (item.IsNullOrDefault()) + { + XException.NotFound.Throw(); + } + + // + return item.Id; + } + + /// + /// Get Default Conversation Id from a Collection Contains ... + /// + /// + /// + /// + /// + public static Guid GetDefaultConversation( + this IEnumerable source, + string ownerId, + Guid projectId + ) + { + // + // Validate Args ... + if (!source.HasChild() || + ownerId.IsNullOrEmpty() || + projectId.IsDefaultGuid()) + { + XException.InvalidArgs.Throw(); + } + + // + var item = source + .FirstOrDefault(x => + x.Title + .ToNormalString() + .Contains(ownerId.ToNormalString()) && + x.Title + .ToNormalString() + .Contains(XAiModelsConstants.XAiConversationTitleIdentifier.ToNormalString()) + ); + if (item.IsNullOrDefault()) + { + XException.NotFound.Throw(); + } + + // + var result = item.Id; + + // + return result; + } + + /// + /// Converts a Message Dto to ChatMessage ... + /// + /// + /// + /// + public static ChatMessage ToChatMessages( + this XAiMessageDto source, + IList additionalContents = null + ) + { + // + ChatMessage result = null; + + // + if (!source.IsNullOrDefault()) + { + // + var contents = new List + { + // + // Add Source Content ... + new TextContent(source.Content) + }; + + // + // Add Additional Content ... + if (additionalContents.HasChild()) + { + contents.AddRange(additionalContents); + } + + // + result = new ChatMessage + { + Contents = contents, + AuthorName = + source.Role == XAiChatRole.User && + !source.Owner.IsNullOrDefault() + ? source.Owner.GetFullname() + : string.Empty, + Role = source.Role.ToChatRole(), + MessageId = source.Id.ToString(), + }; + } + + // + return result; + } + + /// + /// Add Model Provider API Key ... + /// + /// + /// + public static void AddModelDescriptorApiKey( + this XAiModelDescriptor descriptor, + HttpRequestMessage request + ) + { + // + // Validate ... + if (!descriptor.IsValid() || request.IsNull()) + { + return; + } + + // + var apiKey = + descriptor.Provider != XAiModelProviderType.OpenAI + ? descriptor.ApiKey + : descriptor.ApiKey.IsNullOrEmpty() + ? XAiModelsConstants.XOpenAINoKey + : descriptor.ApiKey; + request.Headers.TryAddWithoutValidation( + name: XAuthorization.Header, + value: $"{XAuthorization.TokenIdentifier} {apiKey}" + ); + } + } +} + +### FILE: C:\Users\saherelm\Documents\Projects\xSaherelmWorkspace\Modules\xAiModels\Extensions\XEmbeddingExtensions.cs + +using xCommons.Extensions; +using System.Collections.Generic; + +namespace xAiModels.Extensions +{ + public static class XEmbeddingExtensions + { + /// + /// Converts String to Embeddings JSON ... + /// + /// + /// + public static float[] AsEmbedding(this string source) + { + // + // Validate ... + if (source.IsNullOrEmpty()) { + return []; + } + + // + // JSON is expected to be like: [0.12, 0.34, ...] ... + var result = source.FromJSON(); + if (!result.HasChild()) + { + result = []; + } + + // + return result; + } + } +} + +### FILE: C:\Users\saherelm\Documents\Projects\xSaherelmWorkspace\Modules\xAiModels\Helpers\VectorHelper.cs + +using System; +using xCommons.Extensions; +using System.Numerics.Tensors; +using xExceptions.Constants; + +namespace xAiModels.Helpers +{ + public static class VectorHelper + { + /// + /// Normalize a Vector ... + /// + /// + public static void Normalize(float[] vector) + { + // + // Validate ... + if (vector.IsNull() || !vector.HasChild()) + { + return; + } + + // + float sum = 0f; + foreach (var value in vector) + { + sum += value * value; + } + + // + float norm = MathF.Sqrt(sum); + if (norm <= 1e-9f) + { + return; + } + + // + for (int i = 0; i < vector.Length; i++) + { + vector[i] /= norm; + } + } + + /// + /// Similarity Check ... + /// + /// + /// + /// + public static float CosineSimilarity( + float[] a, + float[] b + ) + { + // + // Validate ... + if (a.Length != b.Length) + { + XException.InvalidArgs.Throw(); + } + + // + // Check Similarity ... + var result = TensorPrimitives + .CosineSimilarity( + a.AsSpan(), + b.AsSpan() + ); + + // + return result; + } + } +} + +### FILE: C:\Users\saherelm\Documents\Projects\xSaherelmWorkspace\Modules\xAiModels\Helpers\XAiModelsHelper.cs + +using System; +using GraphQL.Types; +using xDataService.Db; +using xDataService.Models; +using xDataService.Providers; +using xAiModels.Models.Entities; +using xAiModels.Providers.GraphQL; +using xAiModels.Providers.Entities; +using xAiModels.Interfaces.Entities; + +namespace xAiModels.Helpers +{ + public static class XAiModelsHelper + { + // + #region XAiConversation ... + // + #region EF Repository Descriptor Provider(s) ... + public static XEFRepositoryDescriptor< + XAiConversation, + Guid, + IXAiConversationKeyGenerator, + XAiConversationKeyGenerator, + IXAiConversationRepositoryEvents, + XAiConversationRepositoryEvents, + XAiConversationGraphType, + GuidGraphType, + XAiConversationGraphQuery, + IXAiConversationGraphQLTypeHelper, + XAiConversationGraphQLTypeHelper, + XAiConversationGraphSchema, + IXAiConversationRepository, + XAiConversationEFRepository, + TContext + > GetXAiConversationEFRepositoryDescriptor() + where TContext : XDbContext + { + // + var result = new XEFRepositoryDescriptor< + XAiConversation, + Guid, + IXAiConversationKeyGenerator, + XAiConversationKeyGenerator, + IXAiConversationRepositoryEvents, + XAiConversationRepositoryEvents, + XAiConversationGraphType, + GuidGraphType, + XAiConversationGraphQuery, + IXAiConversationGraphQLTypeHelper, + XAiConversationGraphQLTypeHelper, + XAiConversationGraphSchema, + IXAiConversationRepository, + XAiConversationEFRepository, + TContext + >(); + + // + return result; + } + + public static XEFRepositoryDescriptor< + XAiConversation, + Guid, + IXAiConversationKeyGenerator, + XAiConversationKeyGenerator, + IXAiConversationRepositoryEvents, + XAiConversationRepositoryEvents, + XAiConversationGraphType, + GuidGraphType, + XAiConversationGraphQuery, + IXAiConversationGraphQLTypeHelper, + XAiConversationGraphQLTypeHelper, + XAiConversationGraphSchema, + IXAiConversationRepository, + XAiConversationEFRepository, + TContext, + IXAiConversationSeeder, + TSeederImplementation + > GetXAiConversationEFRepositoryDescriptor() + where TContext : XDbContext + where TSeederImplementation : XBaseDbSeeder + { + // + var result = new XEFRepositoryDescriptor< + XAiConversation, + Guid, + IXAiConversationKeyGenerator, + XAiConversationKeyGenerator, + IXAiConversationRepositoryEvents, + XAiConversationRepositoryEvents, + XAiConversationGraphType, + GuidGraphType, + XAiConversationGraphQuery, + IXAiConversationGraphQLTypeHelper, + XAiConversationGraphQLTypeHelper, + XAiConversationGraphSchema, + IXAiConversationRepository, + XAiConversationEFRepository, + TContext, + IXAiConversationSeeder, + TSeederImplementation + >(); + + // + return result; + } + #endregion + + // + #region Mongo Repository Descriptor Provider(s) ... + public static XMongoRepositoryDescriptor< + XAiConversation, + Guid, + IXAiConversationKeyGenerator, + XAiConversationKeyGenerator, + IXAiConversationRepositoryEvents, + XAiConversationRepositoryEvents, + XAiConversationGraphType, + GuidGraphType, + XAiConversationGraphQuery, + IXAiConversationGraphQLTypeHelper, + XAiConversationGraphQLTypeHelper, + XAiConversationGraphSchema, + IXAiConversationRepository, + XAiConversationMongoRepository + > GetXAiConversationMongoRepositoryDescriptor() + { + // + var result = new XMongoRepositoryDescriptor< + XAiConversation, + Guid, + IXAiConversationKeyGenerator, + XAiConversationKeyGenerator, + IXAiConversationRepositoryEvents, + XAiConversationRepositoryEvents, + XAiConversationGraphType, + GuidGraphType, + XAiConversationGraphQuery, + IXAiConversationGraphQLTypeHelper, + XAiConversationGraphQLTypeHelper, + XAiConversationGraphSchema, + IXAiConversationRepository, + XAiConversationMongoRepository + >(); + + // + return result; + } + + public static XMongoRepositoryDescriptor< + XAiConversation, + Guid, + IXAiConversationKeyGenerator, + XAiConversationKeyGenerator, + IXAiConversationRepositoryEvents, + XAiConversationRepositoryEvents, + XAiConversationGraphType, + GuidGraphType, + XAiConversationGraphQuery, + IXAiConversationGraphQLTypeHelper, + XAiConversationGraphQLTypeHelper, + XAiConversationGraphSchema, + IXAiConversationRepository, + XAiConversationMongoRepository, + IXAiConversationSeeder, + TSeederImplementation + > GetXAiConversationMongoRepositoryDescriptor() + where TSeederImplementation : XBaseDbSeeder + { + // + var result = new XMongoRepositoryDescriptor< + XAiConversation, + Guid, + IXAiConversationKeyGenerator, + XAiConversationKeyGenerator, + IXAiConversationRepositoryEvents, + XAiConversationRepositoryEvents, + XAiConversationGraphType, + GuidGraphType, + XAiConversationGraphQuery, + IXAiConversationGraphQLTypeHelper, + XAiConversationGraphQLTypeHelper, + XAiConversationGraphSchema, + IXAiConversationRepository, + XAiConversationMongoRepository, + IXAiConversationSeeder, + TSeederImplementation + >(); + + // + return result; + } + #endregion + + // + #region InMemory Repository Descriptor Provider(s) ... + public static XInMemoryRepositoryDescriptor< + XAiConversation, + Guid, + IXAiConversationKeyGenerator, + XAiConversationKeyGenerator, + IXAiConversationRepositoryEvents, + XAiConversationRepositoryEvents, + XAiConversationGraphType, + GuidGraphType, + XAiConversationGraphQuery, + IXAiConversationGraphQLTypeHelper, + XAiConversationGraphQLTypeHelper, + XAiConversationGraphSchema, + IXAiConversationRepository, + XAiConversationInMemoryRepository + > GetXAiConversationInMemoryRepositoryDescriptor() + { + // + var result = new XInMemoryRepositoryDescriptor< + XAiConversation, + Guid, + IXAiConversationKeyGenerator, + XAiConversationKeyGenerator, + IXAiConversationRepositoryEvents, + XAiConversationRepositoryEvents, + XAiConversationGraphType, + GuidGraphType, + XAiConversationGraphQuery, + IXAiConversationGraphQLTypeHelper, + XAiConversationGraphQLTypeHelper, + XAiConversationGraphSchema, + IXAiConversationRepository, + XAiConversationInMemoryRepository + >(); + + // + return result; + } + + public static XInMemoryRepositoryDescriptor< + XAiConversation, + Guid, + IXAiConversationKeyGenerator, + XAiConversationKeyGenerator, + IXAiConversationRepositoryEvents, + XAiConversationRepositoryEvents, + XAiConversationGraphType, + GuidGraphType, + XAiConversationGraphQuery, + IXAiConversationGraphQLTypeHelper, + XAiConversationGraphQLTypeHelper, + XAiConversationGraphSchema, + IXAiConversationRepository, + XAiConversationInMemoryRepository, + IXAiConversationSeeder, + TSeederImplementation + > GetXAiConversationInMemoryRepositoryDescriptor() + where TSeederImplementation : XBaseDbSeeder + { + // + var result = new XInMemoryRepositoryDescriptor< + XAiConversation, + Guid, + IXAiConversationKeyGenerator, + XAiConversationKeyGenerator, + IXAiConversationRepositoryEvents, + XAiConversationRepositoryEvents, + XAiConversationGraphType, + GuidGraphType, + XAiConversationGraphQuery, + IXAiConversationGraphQLTypeHelper, + XAiConversationGraphQLTypeHelper, + XAiConversationGraphSchema, + IXAiConversationRepository, + XAiConversationInMemoryRepository, + IXAiConversationSeeder, + TSeederImplementation + >(); + + // + return result; + } + #endregion + #endregion + + // + #region XAiMessage ... + // + #region EF Repository Descriptor Provider(s) ... + public static XEFRepositoryDescriptor< + XAiMessage, + Guid, + IXAiMessageKeyGenerator, + XAiMessageKeyGenerator, + IXAiMessageRepositoryEvents, + XAiMessageRepositoryEvents, + XAiMessageGraphType, + GuidGraphType, + XAiMessageGraphQuery, + IXAiMessageGraphQLTypeHelper, + XAiMessageGraphQLTypeHelper, + XAiMessageGraphSchema, + IXAiMessageRepository, + XAiMessageEFRepository, + TContext + > GetXAiMessageEFRepositoryDescriptor() + where TContext : XDbContext + { + // + var result = new XEFRepositoryDescriptor< + XAiMessage, + Guid, + IXAiMessageKeyGenerator, + XAiMessageKeyGenerator, + IXAiMessageRepositoryEvents, + XAiMessageRepositoryEvents, + XAiMessageGraphType, + GuidGraphType, + XAiMessageGraphQuery, + IXAiMessageGraphQLTypeHelper, + XAiMessageGraphQLTypeHelper, + XAiMessageGraphSchema, + IXAiMessageRepository, + XAiMessageEFRepository, + TContext + >(); + + // + return result; + } + + public static XEFRepositoryDescriptor< + XAiMessage, + Guid, + IXAiMessageKeyGenerator, + XAiMessageKeyGenerator, + IXAiMessageRepositoryEvents, + XAiMessageRepositoryEvents, + XAiMessageGraphType, + GuidGraphType, + XAiMessageGraphQuery, + IXAiMessageGraphQLTypeHelper, + XAiMessageGraphQLTypeHelper, + XAiMessageGraphSchema, + IXAiMessageRepository, + XAiMessageEFRepository, + TContext, + IXAiMessageSeeder, + TSeederImplementation + > GetXAiMessageEFRepositoryDescriptor() + where TContext : XDbContext + where TSeederImplementation : XBaseDbSeeder + { + // + var result = new XEFRepositoryDescriptor< + XAiMessage, + Guid, + IXAiMessageKeyGenerator, + XAiMessageKeyGenerator, + IXAiMessageRepositoryEvents, + XAiMessageRepositoryEvents, + XAiMessageGraphType, + GuidGraphType, + XAiMessageGraphQuery, + IXAiMessageGraphQLTypeHelper, + XAiMessageGraphQLTypeHelper, + XAiMessageGraphSchema, + IXAiMessageRepository, + XAiMessageEFRepository, + TContext, + IXAiMessageSeeder, + TSeederImplementation + >(); + + // + return result; + } + #endregion + + // + #region Mongo Repository Descriptor Provider(s) ... + public static XMongoRepositoryDescriptor< + XAiMessage, + Guid, + IXAiMessageKeyGenerator, + XAiMessageKeyGenerator, + IXAiMessageRepositoryEvents, + XAiMessageRepositoryEvents, + XAiMessageGraphType, + GuidGraphType, + XAiMessageGraphQuery, + IXAiMessageGraphQLTypeHelper, + XAiMessageGraphQLTypeHelper, + XAiMessageGraphSchema, + IXAiMessageRepository, + XAiMessageMongoRepository + > GetXAiMessageMongoRepositoryDescriptor() + { + // + var result = new XMongoRepositoryDescriptor< + XAiMessage, + Guid, + IXAiMessageKeyGenerator, + XAiMessageKeyGenerator, + IXAiMessageRepositoryEvents, + XAiMessageRepositoryEvents, + XAiMessageGraphType, + GuidGraphType, + XAiMessageGraphQuery, + IXAiMessageGraphQLTypeHelper, + XAiMessageGraphQLTypeHelper, + XAiMessageGraphSchema, + IXAiMessageRepository, + XAiMessageMongoRepository + >(); + + // + return result; + } + + public static XMongoRepositoryDescriptor< + XAiMessage, + Guid, + IXAiMessageKeyGenerator, + XAiMessageKeyGenerator, + IXAiMessageRepositoryEvents, + XAiMessageRepositoryEvents, + XAiMessageGraphType, + GuidGraphType, + XAiMessageGraphQuery, + IXAiMessageGraphQLTypeHelper, + XAiMessageGraphQLTypeHelper, + XAiMessageGraphSchema, + IXAiMessageRepository, + XAiMessageMongoRepository, + IXAiMessageSeeder, + TSeederImplementation + > GetXAiMessageMongoRepositoryDescriptor() + where TSeederImplementation : XBaseDbSeeder + { + // + var result = new XMongoRepositoryDescriptor< + XAiMessage, + Guid, + IXAiMessageKeyGenerator, + XAiMessageKeyGenerator, + IXAiMessageRepositoryEvents, + XAiMessageRepositoryEvents, + XAiMessageGraphType, + GuidGraphType, + XAiMessageGraphQuery, + IXAiMessageGraphQLTypeHelper, + XAiMessageGraphQLTypeHelper, + XAiMessageGraphSchema, + IXAiMessageRepository, + XAiMessageMongoRepository, + IXAiMessageSeeder, + TSeederImplementation + >(); + + // + return result; + } + #endregion + + // + #region InMemory Repository Descriptor Provider(s) ... + public static XInMemoryRepositoryDescriptor< + XAiMessage, + Guid, + IXAiMessageKeyGenerator, + XAiMessageKeyGenerator, + IXAiMessageRepositoryEvents, + XAiMessageRepositoryEvents, + XAiMessageGraphType, + GuidGraphType, + XAiMessageGraphQuery, + IXAiMessageGraphQLTypeHelper, + XAiMessageGraphQLTypeHelper, + XAiMessageGraphSchema, + IXAiMessageRepository, + XAiMessageInMemoryRepository + > GetXAiMessageInMemoryRepositoryDescriptor() + { + // + var result = new XInMemoryRepositoryDescriptor< + XAiMessage, + Guid, + IXAiMessageKeyGenerator, + XAiMessageKeyGenerator, + IXAiMessageRepositoryEvents, + XAiMessageRepositoryEvents, + XAiMessageGraphType, + GuidGraphType, + XAiMessageGraphQuery, + IXAiMessageGraphQLTypeHelper, + XAiMessageGraphQLTypeHelper, + XAiMessageGraphSchema, + IXAiMessageRepository, + XAiMessageInMemoryRepository + >(); + + // + return result; + } + + public static XInMemoryRepositoryDescriptor< + XAiMessage, + Guid, + IXAiMessageKeyGenerator, + XAiMessageKeyGenerator, + IXAiMessageRepositoryEvents, + XAiMessageRepositoryEvents, + XAiMessageGraphType, + GuidGraphType, + XAiMessageGraphQuery, + IXAiMessageGraphQLTypeHelper, + XAiMessageGraphQLTypeHelper, + XAiMessageGraphSchema, + IXAiMessageRepository, + XAiMessageInMemoryRepository, + IXAiMessageSeeder, + TSeederImplementation + > GetXAiMessageInMemoryRepositoryDescriptor() + where TSeederImplementation : XBaseDbSeeder + { + // + var result = new XInMemoryRepositoryDescriptor< + XAiMessage, + Guid, + IXAiMessageKeyGenerator, + XAiMessageKeyGenerator, + IXAiMessageRepositoryEvents, + XAiMessageRepositoryEvents, + XAiMessageGraphType, + GuidGraphType, + XAiMessageGraphQuery, + IXAiMessageGraphQLTypeHelper, + XAiMessageGraphQLTypeHelper, + XAiMessageGraphSchema, + IXAiMessageRepository, + XAiMessageInMemoryRepository, + IXAiMessageSeeder, + TSeederImplementation + >(); + + // + return result; + } + #endregion + #endregion + + // + #region XAiProject ... + // + #region EF Repository Descriptor Provider(s) ... + public static XEFRepositoryDescriptor< + XAiProject, + Guid, + IXAiProjectKeyGenerator, + XAiProjectKeyGenerator, + IXAiProjectRepositoryEvents, + XAiProjectRepositoryEvents, + XAiProjectGraphType, + GuidGraphType, + XAiProjectGraphQuery, + IXAiProjectGraphQLTypeHelper, + XAiProjectGraphQLTypeHelper, + XAiProjectGraphSchema, + IXAiProjectRepository, + XAiProjectEFRepository, + TContext + > GetXAiProjectEFRepositoryDescriptor() + where TContext : XDbContext + { + // + var result = new XEFRepositoryDescriptor< + XAiProject, + Guid, + IXAiProjectKeyGenerator, + XAiProjectKeyGenerator, + IXAiProjectRepositoryEvents, + XAiProjectRepositoryEvents, + XAiProjectGraphType, + GuidGraphType, + XAiProjectGraphQuery, + IXAiProjectGraphQLTypeHelper, + XAiProjectGraphQLTypeHelper, + XAiProjectGraphSchema, + IXAiProjectRepository, + XAiProjectEFRepository, + TContext + >(); + + // + return result; + } + + public static XEFRepositoryDescriptor< + XAiProject, + Guid, + IXAiProjectKeyGenerator, + XAiProjectKeyGenerator, + IXAiProjectRepositoryEvents, + XAiProjectRepositoryEvents, + XAiProjectGraphType, + GuidGraphType, + XAiProjectGraphQuery, + IXAiProjectGraphQLTypeHelper, + XAiProjectGraphQLTypeHelper, + XAiProjectGraphSchema, + IXAiProjectRepository, + XAiProjectEFRepository, + TContext, + IXAiProjectSeeder, + TSeederImplementation + > GetXAiProjectEFRepositoryDescriptor() + where TContext : XDbContext + where TSeederImplementation : XBaseDbSeeder + { + // + var result = new XEFRepositoryDescriptor< + XAiProject, + Guid, + IXAiProjectKeyGenerator, + XAiProjectKeyGenerator, + IXAiProjectRepositoryEvents, + XAiProjectRepositoryEvents, + XAiProjectGraphType, + GuidGraphType, + XAiProjectGraphQuery, + IXAiProjectGraphQLTypeHelper, + XAiProjectGraphQLTypeHelper, + XAiProjectGraphSchema, + IXAiProjectRepository, + XAiProjectEFRepository, + TContext, + IXAiProjectSeeder, + TSeederImplementation + >(); + + // + return result; + } + #endregion + + // + #region Mongo Repository Descriptor Provider(s) ... + public static XMongoRepositoryDescriptor< + XAiProject, + Guid, + IXAiProjectKeyGenerator, + XAiProjectKeyGenerator, + IXAiProjectRepositoryEvents, + XAiProjectRepositoryEvents, + XAiProjectGraphType, + GuidGraphType, + XAiProjectGraphQuery, + IXAiProjectGraphQLTypeHelper, + XAiProjectGraphQLTypeHelper, + XAiProjectGraphSchema, + IXAiProjectRepository, + XAiProjectMongoRepository + > GetXAiProjectMongoRepositoryDescriptor() + { + // + var result = new XMongoRepositoryDescriptor< + XAiProject, + Guid, + IXAiProjectKeyGenerator, + XAiProjectKeyGenerator, + IXAiProjectRepositoryEvents, + XAiProjectRepositoryEvents, + XAiProjectGraphType, + GuidGraphType, + XAiProjectGraphQuery, + IXAiProjectGraphQLTypeHelper, + XAiProjectGraphQLTypeHelper, + XAiProjectGraphSchema, + IXAiProjectRepository, + XAiProjectMongoRepository + >(); + + // + return result; + } + + public static XMongoRepositoryDescriptor< + XAiProject, + Guid, + IXAiProjectKeyGenerator, + XAiProjectKeyGenerator, + IXAiProjectRepositoryEvents, + XAiProjectRepositoryEvents, + XAiProjectGraphType, + GuidGraphType, + XAiProjectGraphQuery, + IXAiProjectGraphQLTypeHelper, + XAiProjectGraphQLTypeHelper, + XAiProjectGraphSchema, + IXAiProjectRepository, + XAiProjectMongoRepository, + IXAiProjectSeeder, + TSeederImplementation + > GetXAiProjectMongoRepositoryDescriptor() + where TSeederImplementation : XBaseDbSeeder + { + // + var result = new XMongoRepositoryDescriptor< + XAiProject, + Guid, + IXAiProjectKeyGenerator, + XAiProjectKeyGenerator, + IXAiProjectRepositoryEvents, + XAiProjectRepositoryEvents, + XAiProjectGraphType, + GuidGraphType, + XAiProjectGraphQuery, + IXAiProjectGraphQLTypeHelper, + XAiProjectGraphQLTypeHelper, + XAiProjectGraphSchema, + IXAiProjectRepository, + XAiProjectMongoRepository, + IXAiProjectSeeder, + TSeederImplementation + >(); + + // + return result; + } + #endregion + + // + #region InMemory Repository Descriptor Provider(s) ... + public static XInMemoryRepositoryDescriptor< + XAiProject, + Guid, + IXAiProjectKeyGenerator, + XAiProjectKeyGenerator, + IXAiProjectRepositoryEvents, + XAiProjectRepositoryEvents, + XAiProjectGraphType, + GuidGraphType, + XAiProjectGraphQuery, + IXAiProjectGraphQLTypeHelper, + XAiProjectGraphQLTypeHelper, + XAiProjectGraphSchema, + IXAiProjectRepository, + XAiProjectInMemoryRepository + > GetXAiProjectInMemoryRepositoryDescriptor() + { + // + var result = new XInMemoryRepositoryDescriptor< + XAiProject, + Guid, + IXAiProjectKeyGenerator, + XAiProjectKeyGenerator, + IXAiProjectRepositoryEvents, + XAiProjectRepositoryEvents, + XAiProjectGraphType, + GuidGraphType, + XAiProjectGraphQuery, + IXAiProjectGraphQLTypeHelper, + XAiProjectGraphQLTypeHelper, + XAiProjectGraphSchema, + IXAiProjectRepository, + XAiProjectInMemoryRepository + >(); + + // + return result; + } + + public static XInMemoryRepositoryDescriptor< + XAiProject, + Guid, + IXAiProjectKeyGenerator, + XAiProjectKeyGenerator, + IXAiProjectRepositoryEvents, + XAiProjectRepositoryEvents, + XAiProjectGraphType, + GuidGraphType, + XAiProjectGraphQuery, + IXAiProjectGraphQLTypeHelper, + XAiProjectGraphQLTypeHelper, + XAiProjectGraphSchema, + IXAiProjectRepository, + XAiProjectInMemoryRepository, + IXAiProjectSeeder, + TSeederImplementation + > GetXAiProjectInMemoryRepositoryDescriptor() + where TSeederImplementation : XBaseDbSeeder + { + // + var result = new XInMemoryRepositoryDescriptor< + XAiProject, + Guid, + IXAiProjectKeyGenerator, + XAiProjectKeyGenerator, + IXAiProjectRepositoryEvents, + XAiProjectRepositoryEvents, + XAiProjectGraphType, + GuidGraphType, + XAiProjectGraphQuery, + IXAiProjectGraphQLTypeHelper, + XAiProjectGraphQLTypeHelper, + XAiProjectGraphSchema, + IXAiProjectRepository, + XAiProjectInMemoryRepository, + IXAiProjectSeeder, + TSeederImplementation + >(); + + // + return result; + } + #endregion + #endregion + + // + #region XAiVector ... + // + #region EF Repository Descriptor Provider(s) ... + public static XEFRepositoryDescriptor< + XAiVector, + Guid, + IXAiVectorKeyGenerator, + XAiVectorKeyGenerator, + IXAiVectorRepositoryEvents, + XAiVectorRepositoryEvents, + XAiVectorGraphType, + GuidGraphType, + XAiVectorGraphQuery, + IXAiVectorGraphQLTypeHelper, + XAiVectorGraphQLTypeHelper, + XAiVectorGraphSchema, + IXAiVectorRepository, + XAiVectorEFRepository, + TContext + > GetXAiVectorEFRepositoryDescriptor() + where TContext : XDbContext + { + // + var result = new XEFRepositoryDescriptor< + XAiVector, + Guid, + IXAiVectorKeyGenerator, + XAiVectorKeyGenerator, + IXAiVectorRepositoryEvents, + XAiVectorRepositoryEvents, + XAiVectorGraphType, + GuidGraphType, + XAiVectorGraphQuery, + IXAiVectorGraphQLTypeHelper, + XAiVectorGraphQLTypeHelper, + XAiVectorGraphSchema, + IXAiVectorRepository, + XAiVectorEFRepository, + TContext + >(); + + // + return result; + } + + public static XEFRepositoryDescriptor< + XAiVector, + Guid, + IXAiVectorKeyGenerator, + XAiVectorKeyGenerator, + IXAiVectorRepositoryEvents, + XAiVectorRepositoryEvents, + XAiVectorGraphType, + GuidGraphType, + XAiVectorGraphQuery, + IXAiVectorGraphQLTypeHelper, + XAiVectorGraphQLTypeHelper, + XAiVectorGraphSchema, + IXAiVectorRepository, + XAiVectorEFRepository, + TContext, + IXAiVectorSeeder, + TSeederImplementation + > GetXAiVectorEFRepositoryDescriptor() + where TContext : XDbContext + where TSeederImplementation : XBaseDbSeeder + { + // + var result = new XEFRepositoryDescriptor< + XAiVector, + Guid, + IXAiVectorKeyGenerator, + XAiVectorKeyGenerator, + IXAiVectorRepositoryEvents, + XAiVectorRepositoryEvents, + XAiVectorGraphType, + GuidGraphType, + XAiVectorGraphQuery, + IXAiVectorGraphQLTypeHelper, + XAiVectorGraphQLTypeHelper, + XAiVectorGraphSchema, + IXAiVectorRepository, + XAiVectorEFRepository, + TContext, + IXAiVectorSeeder, + TSeederImplementation + >(); + + // + return result; + } + #endregion + + // + #region Mongo Repository Descriptor Provider(s) ... + public static XMongoRepositoryDescriptor< + XAiVector, + Guid, + IXAiVectorKeyGenerator, + XAiVectorKeyGenerator, + IXAiVectorRepositoryEvents, + XAiVectorRepositoryEvents, + XAiVectorGraphType, + GuidGraphType, + XAiVectorGraphQuery, + IXAiVectorGraphQLTypeHelper, + XAiVectorGraphQLTypeHelper, + XAiVectorGraphSchema, + IXAiVectorRepository, + XAiVectorMongoRepository + > GetXAiVectorMongoRepositoryDescriptor() + { + // + var result = new XMongoRepositoryDescriptor< + XAiVector, + Guid, + IXAiVectorKeyGenerator, + XAiVectorKeyGenerator, + IXAiVectorRepositoryEvents, + XAiVectorRepositoryEvents, + XAiVectorGraphType, + GuidGraphType, + XAiVectorGraphQuery, + IXAiVectorGraphQLTypeHelper, + XAiVectorGraphQLTypeHelper, + XAiVectorGraphSchema, + IXAiVectorRepository, + XAiVectorMongoRepository + >(); + + // + return result; + } + + public static XMongoRepositoryDescriptor< + XAiVector, + Guid, + IXAiVectorKeyGenerator, + XAiVectorKeyGenerator, + IXAiVectorRepositoryEvents, + XAiVectorRepositoryEvents, + XAiVectorGraphType, + GuidGraphType, + XAiVectorGraphQuery, + IXAiVectorGraphQLTypeHelper, + XAiVectorGraphQLTypeHelper, + XAiVectorGraphSchema, + IXAiVectorRepository, + XAiVectorMongoRepository, + IXAiVectorSeeder, + TSeederImplementation + > GetXAiVectorMongoRepositoryDescriptor() + where TSeederImplementation : XBaseDbSeeder + { + // + var result = new XMongoRepositoryDescriptor< + XAiVector, + Guid, + IXAiVectorKeyGenerator, + XAiVectorKeyGenerator, + IXAiVectorRepositoryEvents, + XAiVectorRepositoryEvents, + XAiVectorGraphType, + GuidGraphType, + XAiVectorGraphQuery, + IXAiVectorGraphQLTypeHelper, + XAiVectorGraphQLTypeHelper, + XAiVectorGraphSchema, + IXAiVectorRepository, + XAiVectorMongoRepository, + IXAiVectorSeeder, + TSeederImplementation + >(); + + // + return result; + } + #endregion + + // + #region InMemory Repository Descriptor Provider(s) ... + public static XInMemoryRepositoryDescriptor< + XAiVector, + Guid, + IXAiVectorKeyGenerator, + XAiVectorKeyGenerator, + IXAiVectorRepositoryEvents, + XAiVectorRepositoryEvents, + XAiVectorGraphType, + GuidGraphType, + XAiVectorGraphQuery, + IXAiVectorGraphQLTypeHelper, + XAiVectorGraphQLTypeHelper, + XAiVectorGraphSchema, + IXAiVectorRepository, + XAiVectorInMemoryRepository + > GetXAiVectorInMemoryRepositoryDescriptor() + { + // + var result = new XInMemoryRepositoryDescriptor< + XAiVector, + Guid, + IXAiVectorKeyGenerator, + XAiVectorKeyGenerator, + IXAiVectorRepositoryEvents, + XAiVectorRepositoryEvents, + XAiVectorGraphType, + GuidGraphType, + XAiVectorGraphQuery, + IXAiVectorGraphQLTypeHelper, + XAiVectorGraphQLTypeHelper, + XAiVectorGraphSchema, + IXAiVectorRepository, + XAiVectorInMemoryRepository + >(); + + // + return result; + } + + public static XInMemoryRepositoryDescriptor< + XAiVector, + Guid, + IXAiVectorKeyGenerator, + XAiVectorKeyGenerator, + IXAiVectorRepositoryEvents, + XAiVectorRepositoryEvents, + XAiVectorGraphType, + GuidGraphType, + XAiVectorGraphQuery, + IXAiVectorGraphQLTypeHelper, + XAiVectorGraphQLTypeHelper, + XAiVectorGraphSchema, + IXAiVectorRepository, + XAiVectorInMemoryRepository, + IXAiVectorSeeder, + TSeederImplementation + > GetXAiVectorInMemoryRepositoryDescriptor() + where TSeederImplementation : XBaseDbSeeder + { + // + var result = new XInMemoryRepositoryDescriptor< + XAiVector, + Guid, + IXAiVectorKeyGenerator, + XAiVectorKeyGenerator, + IXAiVectorRepositoryEvents, + XAiVectorRepositoryEvents, + XAiVectorGraphType, + GuidGraphType, + XAiVectorGraphQuery, + IXAiVectorGraphQLTypeHelper, + XAiVectorGraphQLTypeHelper, + XAiVectorGraphSchema, + IXAiVectorRepository, + XAiVectorInMemoryRepository, + IXAiVectorSeeder, + TSeederImplementation + >(); + + // + return result; + } + #endregion + #endregion + } +} + +### FILE: C:\Users\saherelm\Documents\Projects\xSaherelmWorkspace\Modules\xAiModels\Interfaces\IXAiConversationTitleResourceProvider.cs + +using xStringService.Interfaces; + +namespace xAiModels.Interfaces +{ + public interface IXAiConversationTitleResourceProvider : IXOwnedItemResourceProvider + { } +} + +### FILE: C:\Users\saherelm\Documents\Projects\xSaherelmWorkspace\Modules\xAiModels\Interfaces\IXAiDataProvider.cs + +using System; +using xModels.Dtos; +using System.Threading; +using xAiModels.Models.Dtos; +using System.Threading.Tasks; +using System.Collections.Generic; + +namespace xAiModels.Interfaces +{ + /// + /// All Data Manipulation Requirements ... + /// + public interface IXAiDataProvider + { + // + #region Getters ... + /// + /// Retrieve Specified Project ... + /// + /// + /// + /// + /// + /// + Task GetProject( + Guid id, + bool fillConversations = false, + bool fillConversationMessages = false, + CancellationToken cancellationToken = default + ); + + /// + /// Retrieve Specified Conversation ... + /// + /// + /// + /// + /// + Task GetConversation( + Guid id, + bool fillMessages = false, + CancellationToken cancellationToken = default + ); + #endregion + + // + #region Loaders ... + /// + /// Load Projects List of Specified Owner ... + /// + /// + /// + /// + /// + /// + /// + Task> LoadProjects( + string ownerId, + string connectionId = null, + bool fillConversations = false, + bool fillConversationMessages = false, + CancellationToken cancellationToken = default + ); + + /// + /// Load List of Conversations for Specified Project ... + /// + /// + /// + /// + /// + /// + Task> LoadConversations( + Guid projectId, + bool fillMessages = false, + string connectionId = null, + CancellationToken cancellationToken = default + ); + + /// + /// Load Messages of Specified Conversation ... + /// + /// + /// + /// + Task> LoadMessages( + Guid conversationId, + CancellationToken cancellationToken = default + ); + #endregion + + // + #region Enrichers ... + /// + /// Enrich Specified Item ... + /// + /// + /// + /// + /// + /// + Task Enrich( + XAiProjectDto source, + bool fillConversations = false, + bool fillConversationMessages = false, + CancellationToken cancellationToken = default + ); + + /// + /// Enrich Specified Items ... + /// + /// + /// + /// + /// + /// + Task> EnrichRange( + IEnumerable sources, + bool fillConversations = false, + bool fillConversationMessages = false, + CancellationToken cancellationToken = default + ); + + /// + /// Enrich Specified Item ... + /// + /// + /// + /// + /// + Task Enrich( + XAiConversationDto source, + bool fillMessages = false, + CancellationToken cancellationToken = default + ); + + /// + /// Enrich Specified Items ... + /// + /// + /// + /// + /// + Task> EnrichRange( + IEnumerable sources, + bool fillMessages = false, + CancellationToken cancellationToken = default + ); + + /// + /// Enrich Specified Item ... + /// + /// + /// + /// + Task Enrich( + XAiMessageDto source, + CancellationToken cancellationToken = default + ); + + /// + /// Enrich Specified Items ... + /// + /// + /// + /// + Task> EnrichRange( + IEnumerable sources, + CancellationToken cancellationToken = default + ); + #endregion + + // + #region Defaults ... + /// + /// Retrieve Default Project of Specified Owner ... + /// Create it if not Handled ... + /// + /// + /// + /// + /// + Task GetDefaultProject( + string ownerId, + string connectionId = null, + CancellationToken cancellationToken = default + ); + + /// + /// Retrieve Default Conversation of Specified Owner ... + /// Create it if not Handled ... + /// + /// + /// + /// + /// + /// + Task GetDefaultConversation( + string ownerId, + Guid projectId, + string connectionId = null, + CancellationToken cancellationToken = default + ); + #endregion + + // + #region Creator/Adders ... + /// + /// Create Project ... + /// + /// + /// + /// + /// + /// + Task CreateProject( + string ownerId, + XAiProjectDto item = null, + string connectionId = null, + CancellationToken cancellationToken = default + ); + + /// + /// Create Conversation ... + /// + /// + /// + /// + /// + /// + /// + Task CreateConversation( + string ownerId, + Guid projectId, + XAiConversationDto item = null, + string connectionId = null, + CancellationToken cancellationToken = default + ); + + /// + /// Add Message ... + /// + /// + /// + /// + /// + /// + Task AddMessage( + Guid conversationId, + XAiMessageDto item, + string connectionId = null, + CancellationToken cancellationToken = default + ); + #endregion + + // + #region Query ... + /// + /// 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 Vectors ... + /// + /// Insert or Update a Single Vector (Matched by Identifier) ... + /// + /// + /// + /// + /// + /// + /// + /// + Task UpsertVectorAsync( + string identifier, + string text, + ReadOnlyMemory embedding, + Dictionary metadata = null, + string type = null, + CancellationToken cancellationToken = default + ); + + /// + /// Insert or Update a Batch of Vectors (Matched by Identifier) ... + /// + /// + /// + /// Count of Stored Vectors + Task UpsertVectorsAsync( + IEnumerable items, + CancellationToken cancellationToken = default + ); + + /// + /// Search Vectors by Cosine Similarity (Top K) ... + /// + /// + /// + /// + /// Optional: Restrict Search to Vectors whose Identifier Starts with this Prefix + /// Optional: Restrict Search to Vectors of Specified Type + /// + /// + Task> SearchVectorsAsync( + ReadOnlyMemory queryEmbedding, + int topK = 5, + float minScore = 0f, + string identifierPrefix = null, + string type = null, + CancellationToken cancellationToken = default + ); + + /// + /// Load Vectors whose Identifier Starts with Specified Prefix ... + /// + /// + /// + /// Optional: Restrict to Vectors of Specified Type + /// + /// + Task> LoadVectorsAsync( + string identifierPrefix, + bool includeEmbedding = false, + string type = null, + CancellationToken cancellationToken = default + ); + + /// + /// Remove Vectors whose Identifier Starts with Specified Prefix ... + /// + /// + /// Optional: Restrict to Vectors of Specified Type + /// + /// Count of Removed Vectors + Task RemoveVectorsAsync( + string identifierPrefix, + string type = null, + CancellationToken cancellationToken = default + ); + #endregion + } +} + +### FILE: C:\Users\saherelm\Documents\Projects\xSaherelmWorkspace\Modules\xAiModels\Interfaces\IXAiProjectDescriptionResourceProvider.cs + +using xStringService.Interfaces; + +namespace xAiModels.Interfaces +{ + public interface IXAiProjectDescriptionResourceProvider : IXOwnedItemResourceProvider + { } +} + +### FILE: C:\Users\saherelm\Documents\Projects\xSaherelmWorkspace\Modules\xAiModels\Interfaces\IXAiProjectTitleResourceProvider.cs + +using xStringService.Interfaces; + +namespace xAiModels.Interfaces +{ + public interface IXAiProjectTitleResourceProvider : IXOwnedItemResourceProvider + { } +} + +### FILE: C:\Users\saherelm\Documents\Projects\xSaherelmWorkspace\Modules\xAiModels\Interfaces\Dtos\IXAiConversationDtoHub.cs + +using System; +using xAiModels.Models.Dtos; +using xPushService.Interfaces; +using xAiModels.Models.Entities; + +namespace xAiModels.Interfaces.Dtos +{ + public interface IXAiConversationDtoHub : IXBaseDtoHub + { } +} + +### FILE: C:\Users\saherelm\Documents\Projects\xSaherelmWorkspace\Modules\xAiModels\Interfaces\Dtos\IXAiConversationRepositoryService.cs + +using System; +using System.Threading; +using xAiModels.Models.Dtos; +using System.Threading.Tasks; +using xDataService.Interfaces; +using xAiModels.Models.Entities; +using System.Collections.Generic; + +namespace xAiModels.Interfaces.Dtos +{ + public interface IXAiConversationRepositoryService : IXBaseRepositoryService + { + // + #region Enrichers ... + /// + /// Enrich Specified Item ... + /// + /// + /// + /// + /// + Task Enrich( + XAiConversation source, + bool fillMessages = false, + CancellationToken cancellationToken = default + ); + + /// + /// Enrich Specified Item ... + /// + /// + /// + /// + /// + Task Enrich( + XAiConversationDto source, + bool fillMessages = false, + CancellationToken cancellationToken = default + ); + + /// + /// Enrich Specified Items ... + /// + /// + /// + /// + /// + Task> EnrichRange( + IEnumerable sources, + bool fillMessages = false, + CancellationToken cancellationToken = default + ); + + /// + /// Enrich Specified Items ... + /// + /// + /// + /// + /// + Task> EnrichRange( + IEnumerable sources, + bool fillMessages = false, + CancellationToken cancellationToken = default + ); + #endregion + } +} + +### FILE: C:\Users\saherelm\Documents\Projects\xSaherelmWorkspace\Modules\xAiModels\Interfaces\Dtos\IXAiConversationServiceProvider.cs + +using System; +using xAiModels.Models.Dtos; +using xPushService.Interfaces; +using xAiModels.Providers.Dtos; +using xAiModels.Models.Entities; + +namespace xAiModels.Interfaces.Dtos +{ + public interface IXAiConversationServiceProvider : IXBaseDtoProvider + { } +} + +### FILE: C:\Users\saherelm\Documents\Projects\xSaherelmWorkspace\Modules\xAiModels\Interfaces\Dtos\IXAiMessageDtoHub.cs + +using System; +using xAiModels.Models.Dtos; +using xPushService.Interfaces; +using xAiModels.Models.Entities; + +namespace xAiModels.Interfaces.Dtos +{ + public interface IXAiMessageDtoHub : IXBaseDtoHub + { } +} + +### FILE: C:\Users\saherelm\Documents\Projects\xSaherelmWorkspace\Modules\xAiModels\Interfaces\Dtos\IXAiMessageRepositoryService.cs + +using System; +using System.Threading; +using xAiModels.Models.Dtos; +using System.Threading.Tasks; +using xDataService.Interfaces; +using xAiModels.Models.Entities; +using System.Collections.Generic; + +namespace xAiModels.Interfaces.Dtos +{ + public interface IXAiMessageRepositoryService : IXBaseRepositoryService + { + // + #region Enrichers ... + /// + /// Enrich Specified Item ... + /// + /// + /// + /// + Task Enrich( + XAiMessage source, + CancellationToken cancellationToken = default + ); + + /// + /// Enrich Specified Item ... + /// + /// + /// + /// + Task Enrich( + XAiMessageDto source, + CancellationToken cancellationToken = default + ); + + /// + /// Enrich Specified Items ... + /// + /// + /// + /// + Task> EnrichRange( + IEnumerable sources, + CancellationToken cancellationToken = default + ); + + /// + /// Enrich Specified Items ... + /// + /// + /// + /// + Task> EnrichRange( + IEnumerable sources, + CancellationToken cancellationToken = default + ); + #endregion + } +} + +### FILE: C:\Users\saherelm\Documents\Projects\xSaherelmWorkspace\Modules\xAiModels\Interfaces\Dtos\IXAiMessageServiceProvider.cs + +using System; +using xAiModels.Models.Dtos; +using xPushService.Interfaces; +using xAiModels.Providers.Dtos; +using xAiModels.Models.Entities; + +namespace xAiModels.Interfaces.Dtos +{ + public interface IXAiMessageServiceProvider : IXBaseDtoProvider + { } +} + +### FILE: C:\Users\saherelm\Documents\Projects\xSaherelmWorkspace\Modules\xAiModels\Interfaces\Dtos\IXAiProjectDtoHub.cs + +using System; +using xAiModels.Models.Dtos; +using xPushService.Interfaces; +using xAiModels.Models.Entities; + +namespace xAiModels.Interfaces.Dtos +{ + public interface IXAiProjectDtoHub : IXBaseDtoHub + { } +} + +### FILE: C:\Users\saherelm\Documents\Projects\xSaherelmWorkspace\Modules\xAiModels\Interfaces\Dtos\IXAiProjectRepositoryService.cs + +using System; +using System.Threading; +using xAiModels.Models.Dtos; +using System.Threading.Tasks; +using xDataService.Interfaces; +using xAiModels.Models.Entities; +using System.Collections.Generic; + +namespace xAiModels.Interfaces.Dtos +{ + public interface IXAiProjectRepositoryService : IXBaseRepositoryService + { + // + #region Enrichers ... + /// + /// Enrich Specified Item ... + /// + /// + /// + /// + /// + /// + Task Enrich( + XAiProject source, + bool fillConversations = false, + bool fillConversationMessages = false, + CancellationToken cancellationToken = default + ); + + /// + /// Enrich Specified Item ... + /// + /// + /// + /// + /// + /// + Task Enrich( + XAiProjectDto source, + bool fillConversations = false, + bool fillConversationMessages = false, + CancellationToken cancellationToken = default + ); + + /// + /// Enrich Specified Items ... + /// + /// + /// + /// + /// + /// + Task> EnrichRange( + IEnumerable sources, + bool fillConversations = false, + bool fillConversationMessages = false, + CancellationToken cancellationToken = default + ); + + /// + /// Enrich Specified Items ... + /// + /// + /// + /// + /// + /// + Task> EnrichRange( + IEnumerable sources, + bool fillConversations = false, + bool fillConversationMessages = false, + CancellationToken cancellationToken = default + ); + #endregion + } +} + +### FILE: C:\Users\saherelm\Documents\Projects\xSaherelmWorkspace\Modules\xAiModels\Interfaces\Dtos\IXAiProjectServiceProvider.cs + +using System; +using xAiModels.Models.Dtos; +using xPushService.Interfaces; +using xAiModels.Providers.Dtos; +using xAiModels.Models.Entities; + +namespace xAiModels.Interfaces.Dtos +{ + public interface IXAiProjectServiceProvider : IXBaseDtoProvider + { } +} + +### FILE: C:\Users\saherelm\Documents\Projects\xSaherelmWorkspace\Modules\xAiModels\Interfaces\Dtos\IXAiVectorDtoHub.cs + +using System; +using xAiModels.Models.Dtos; +using xPushService.Interfaces; +using xAiModels.Models.Entities; + +namespace xAiModels.Interfaces.Dtos +{ + public interface IXAiVectorDtoHub : IXBaseDtoHub + { } +} + +### FILE: C:\Users\saherelm\Documents\Projects\xSaherelmWorkspace\Modules\xAiModels\Interfaces\Dtos\IXAiVectorRepositoryService.cs + +using System; +using xAiModels.Models.Dtos; +using xDataService.Interfaces; +using xAiModels.Models.Entities; + +namespace xAiModels.Interfaces.Dtos +{ + public interface IXAiVectorRepositoryService : IXBaseRepositoryService + { + } +} + +### FILE: C:\Users\saherelm\Documents\Projects\xSaherelmWorkspace\Modules\xAiModels\Interfaces\Dtos\IXAiVectorServiceProvider.cs + +using System; +using xAiModels.Models.Dtos; +using xPushService.Interfaces; +using xAiModels.Providers.Dtos; +using xAiModels.Models.Entities; + +namespace xAiModels.Interfaces.Dtos +{ + public interface IXAiVectorServiceProvider : IXBaseDtoProvider + { } +} + +### FILE: C:\Users\saherelm\Documents\Projects\xSaherelmWorkspace\Modules\xAiModels\Interfaces\Enrichers\IXAiConversationEnricher.cs + +using System.Threading; +using xAiModels.Models.Dtos; +using System.Threading.Tasks; +using xAiModels.Models.Entities; +using System.Collections.Generic; + +namespace xAiModels.Interfaces.Enrichers +{ + /// + /// Ai Conversation Enricher ... + /// + public interface IXAiConversationEnricher + { + // + #region Enrichers ... + /// + /// Enrich Specified Item ... + /// + /// + /// + /// + /// + Task Enrich( + XAiConversation source, + bool fillMessages = false, + CancellationToken cancellationToken = default + ); + + /// + /// Enrich Specified Item ... + /// + /// + /// + /// + /// + Task Enrich( + XAiConversationDto source, + bool fillMessages = false, + CancellationToken cancellationToken = default + ); + + /// + /// Enrich Specified Items ... + /// + /// + /// + /// + /// + Task> EnrichRange( + IEnumerable sources, + bool fillMessages = false, + CancellationToken cancellationToken = default + ); + + /// + /// Enrich Specified Items ... + /// + /// + /// + /// + /// + Task> EnrichRange( + IEnumerable sources, + bool fillMessages = false, + CancellationToken cancellationToken = default + ); + #endregion + } +} + +### FILE: C:\Users\saherelm\Documents\Projects\xSaherelmWorkspace\Modules\xAiModels\Interfaces\Enrichers\IXAiMessageEnricher.cs + +using System.Threading; +using xAiModels.Models.Dtos; +using System.Threading.Tasks; +using xAiModels.Models.Entities; +using System.Collections.Generic; + +namespace xAiModels.Interfaces.Enrichers +{ + public interface IXAiMessageEnricher + { + // + #region Enrichers ... + /// + /// Enrich Specified Item ... + /// + /// + /// + /// + Task Enrich( + XAiMessage source, + CancellationToken cancellationToken = default + ); + + /// + /// Enrich Specified Item ... + /// + /// + /// + /// + Task Enrich( + XAiMessageDto source, + CancellationToken cancellationToken = default + ); + + /// + /// Enrich Specified Items ... + /// + /// + /// + /// + Task> EnrichRange( + IEnumerable sources, + CancellationToken cancellationToken = default + ); + + /// + /// Enrich Specified Items ... + /// + /// + /// + /// + Task> EnrichRange( + IEnumerable sources, + CancellationToken cancellationToken = default + ); + #endregion + } +} + +### FILE: C:\Users\saherelm\Documents\Projects\xSaherelmWorkspace\Modules\xAiModels\Interfaces\Enrichers\IXAiProjectEnricher.cs + +using System.Threading; +using xAiModels.Models.Dtos; +using System.Threading.Tasks; +using xAiModels.Models.Entities; +using System.Collections.Generic; + +namespace xAiModels.Interfaces.Enrichers +{ + public interface IXAiProjectEnricher + { + // + #region Enrichers ... + /// + /// Enrich Specified Item ... + /// + /// + /// + /// + /// + /// + Task Enrich( + XAiProject source, + bool fillConversations = false, + bool fillConversationMessages = false, + CancellationToken cancellationToken = default + ); + + /// + /// Enrich Specified Item ... + /// + /// + /// + /// + /// + /// + Task Enrich( + XAiProjectDto source, + bool fillConversations = false, + bool fillConversationMessages = false, + CancellationToken cancellationToken = default + ); + + /// + /// Enrich Specified Items ... + /// + /// + /// + /// + /// + /// + Task> EnrichRange( + IEnumerable sources, + bool fillConversations = false, + bool fillConversationMessages = false, + CancellationToken cancellationToken = default + ); + + /// + /// Enrich Specified Items ... + /// + /// + /// + /// + /// + /// + Task> EnrichRange( + IEnumerable sources, + bool fillConversations = false, + bool fillConversationMessages = false, + CancellationToken cancellationToken = default + ); + #endregion + } +} + +### FILE: C:\Users\saherelm\Documents\Projects\xSaherelmWorkspace\Modules\xAiModels\Interfaces\Enrichers\IXAiVectorEnricher.cs + +using System.Threading; +using xAiModels.Models.Dtos; +using System.Threading.Tasks; +using xAiModels.Models.Entities; +using System.Collections.Generic; + +namespace xAiModels.Interfaces.Enrichers +{ + public interface IXAiVectorEnricher + { + // + #region Enrichers ... + /// + /// Enrich Specified Item ... + /// + /// + /// + /// + Task Enrich( + XAiVector source, + CancellationToken cancellationToken = default + ); + + /// + /// Enrich Specified Item ... + /// + /// + /// + /// + Task Enrich( + XAiVectorDto source, + CancellationToken cancellationToken = default + ); + + /// + /// Enrich Specified Items ... + /// + /// + /// + /// + Task> EnrichRange( + IEnumerable sources, + CancellationToken cancellationToken = default + ); + + /// + /// Enrich Specified Items ... + /// + /// + /// + /// + Task> EnrichRange( + IEnumerable sources, + CancellationToken cancellationToken = default + ); + #endregion + } +} + +### FILE: C:\Users\saherelm\Documents\Projects\xSaherelmWorkspace\Modules\xAiModels\Interfaces\Entities\IXAiConversationEntityHub.cs + +using System; +using xPushService.Interfaces; +using xAiModels.Models.Entities; + +namespace xAiModels.Interfaces.Entities +{ + public interface IXAiConversationEntityHub : IXBaseEntityHub + { } +} + +### FILE: C:\Users\saherelm\Documents\Projects\xSaherelmWorkspace\Modules\xAiModels\Interfaces\Entities\IXAiConversationGraphQLTypeHelper.cs + +using System; +using xDataService.Interfaces; +using xAiModels.Models.Entities; + +namespace xAiModels.Interfaces.Entities +{ + public interface IXAiConversationGraphQLTypeHelper : IXBaseGraphQLTypeHelper + { } +} + +### FILE: C:\Users\saherelm\Documents\Projects\xSaherelmWorkspace\Modules\xAiModels\Interfaces\Entities\IXAiConversationKeyGenerator.cs + +using System; +using xDataService.Interfaces; +using xAiModels.Models.Entities; + +namespace xAiModels.Interfaces.Entities +{ + public interface IXAiConversationKeyGenerator : IXKeyGenerator + { } +} + +### FILE: C:\Users\saherelm\Documents\Projects\xSaherelmWorkspace\Modules\xAiModels\Interfaces\Entities\IXAiConversationRepository.cs + +using System; +using xDataService.Interfaces; +using xAiModels.Models.Entities; + +namespace xAiModels.Interfaces.Entities +{ + public interface IXAiConversationRepository : IXBaseRepository + { } +} + +### FILE: C:\Users\saherelm\Documents\Projects\xSaherelmWorkspace\Modules\xAiModels\Interfaces\Entities\IXAiConversationRepositoryEvents.cs + +using xDataService.Interfaces; +using xAiModels.Models.Entities; + +namespace xAiModels.Interfaces.Entities +{ + public interface IXAiConversationRepositoryEvents : IXBaseRepositoryEvents + { } +} + +### FILE: C:\Users\saherelm\Documents\Projects\xSaherelmWorkspace\Modules\xAiModels\Interfaces\Entities\IXAiConversationRepositoryProvider.cs + +using System; +using xPushService.Interfaces; +using xAiModels.Models.Entities; +using xAiModels.Providers.Entities; + +namespace xAiModels.Interfaces.Entities +{ + public interface IXAiConversationRepositoryProvider : IXBaseEntityProvider + { } +} + +### FILE: C:\Users\saherelm\Documents\Projects\xSaherelmWorkspace\Modules\xAiModels\Interfaces\Entities\IXAiConversationSeeder.cs + +using System; +using xDataService.Interfaces; +using xAiModels.Models.Entities; + +namespace xAiModels.Interfaces.Entities +{ + public interface IXAiConversationSeeder : IXBaseDbSeeder + { } +} + +### FILE: C:\Users\saherelm\Documents\Projects\xSaherelmWorkspace\Modules\xAiModels\Interfaces\Entities\IXAiDocumentEntityHub.cs + +using System; +using System.Collections.Generic; +using System.Linq; +using System.Threading.Tasks; + +namespace xAiModels.Interfaces.Entities +{ + public interface IXAiDocumentEntityHub + { + + } +} + +### FILE: C:\Users\saherelm\Documents\Projects\xSaherelmWorkspace\Modules\xAiModels\Interfaces\Entities\IXAiMessageEntityHub.cs + +using System; +using xPushService.Interfaces; +using xAiModels.Models.Entities; + +namespace xAiModels.Interfaces.Entities +{ + public interface IXAiMessageEntityHub : IXBaseEntityHub + { } +} + +### FILE: C:\Users\saherelm\Documents\Projects\xSaherelmWorkspace\Modules\xAiModels\Interfaces\Entities\IXAiMessageGraphQLTypeHelper.cs + +using System; +using xDataService.Interfaces; +using xAiModels.Models.Entities; + +namespace xAiModels.Interfaces.Entities +{ + public interface IXAiMessageGraphQLTypeHelper : IXBaseGraphQLTypeHelper + { } +} + +### FILE: C:\Users\saherelm\Documents\Projects\xSaherelmWorkspace\Modules\xAiModels\Interfaces\Entities\IXAiMessageKeyGenerator.cs + +using System; +using xDataService.Interfaces; +using xAiModels.Models.Entities; + +namespace xAiModels.Interfaces.Entities +{ + public interface IXAiMessageKeyGenerator : IXKeyGenerator + { } +} + +### FILE: C:\Users\saherelm\Documents\Projects\xSaherelmWorkspace\Modules\xAiModels\Interfaces\Entities\IXAiMessageRepository.cs + +using System; +using xDataService.Interfaces; +using xAiModels.Models.Entities; + +namespace xAiModels.Interfaces.Entities +{ + public interface IXAiMessageRepository : IXBaseRepository + { } +} + +### FILE: C:\Users\saherelm\Documents\Projects\xSaherelmWorkspace\Modules\xAiModels\Interfaces\Entities\IXAiMessageRepositoryEvents.cs + +using xDataService.Interfaces; +using xAiModels.Models.Entities; + +namespace xAiModels.Interfaces.Entities +{ + public interface IXAiMessageRepositoryEvents : IXBaseRepositoryEvents + { } +} + +### FILE: C:\Users\saherelm\Documents\Projects\xSaherelmWorkspace\Modules\xAiModels\Interfaces\Entities\IXAiMessageRepositoryProvider.cs + +using System; +using xPushService.Interfaces; +using xAiModels.Models.Entities; +using xAiModels.Providers.Entities; + +namespace xAiModels.Interfaces.Entities +{ + public interface IXAiMessageRepositoryProvider : IXBaseEntityProvider + { } +} + +### FILE: C:\Users\saherelm\Documents\Projects\xSaherelmWorkspace\Modules\xAiModels\Interfaces\Entities\IXAiMessageSeeder.cs + +using System; +using xDataService.Interfaces; +using xAiModels.Models.Entities; + +namespace xAiModels.Interfaces.Entities +{ + public interface IXAiMessageSeeder : IXBaseDbSeeder + { } +} + +### FILE: C:\Users\saherelm\Documents\Projects\xSaherelmWorkspace\Modules\xAiModels\Interfaces\Entities\IXAiProjectEntityHub.cs + +using System; +using xPushService.Interfaces; +using xAiModels.Models.Entities; + +namespace xAiModels.Interfaces.Entities +{ + public interface IXAiProjectEntityHub : IXBaseEntityHub + { } +} + +### FILE: C:\Users\saherelm\Documents\Projects\xSaherelmWorkspace\Modules\xAiModels\Interfaces\Entities\IXAiProjectGraphQLTypeHelper.cs + +using System; +using xDataService.Interfaces; +using xAiModels.Models.Entities; + +namespace xAiModels.Interfaces.Entities +{ + public interface IXAiProjectGraphQLTypeHelper : IXBaseGraphQLTypeHelper + { } +} + +### FILE: C:\Users\saherelm\Documents\Projects\xSaherelmWorkspace\Modules\xAiModels\Interfaces\Entities\IXAiProjectKeyGenerator.cs + +using System; +using xDataService.Interfaces; +using xAiModels.Models.Entities; + +namespace xAiModels.Interfaces.Entities +{ + public interface IXAiProjectKeyGenerator : IXKeyGenerator + { } +} + +### FILE: C:\Users\saherelm\Documents\Projects\xSaherelmWorkspace\Modules\xAiModels\Interfaces\Entities\IXAiProjectRepository.cs + +using System; +using xDataService.Interfaces; +using xAiModels.Models.Entities; + +namespace xAiModels.Interfaces.Entities +{ + public interface IXAiProjectRepository : IXBaseRepository + { } +} + +### FILE: C:\Users\saherelm\Documents\Projects\xSaherelmWorkspace\Modules\xAiModels\Interfaces\Entities\IXAiProjectRepositoryEvents.cs + +using xDataService.Interfaces; +using xAiModels.Models.Entities; + +namespace xAiModels.Interfaces.Entities +{ + public interface IXAiProjectRepositoryEvents : IXBaseRepositoryEvents + { } +} + +### FILE: C:\Users\saherelm\Documents\Projects\xSaherelmWorkspace\Modules\xAiModels\Interfaces\Entities\IXAiProjectRepositoryProvider.cs + +using System; +using xPushService.Interfaces; +using xAiModels.Models.Entities; +using xAiModels.Providers.Entities; + +namespace xAiModels.Interfaces.Entities +{ + public interface IXAiProjectRepositoryProvider : IXBaseEntityProvider + { } +} + +### FILE: C:\Users\saherelm\Documents\Projects\xSaherelmWorkspace\Modules\xAiModels\Interfaces\Entities\IXAiProjectSeeder.cs + +using System; +using xDataService.Interfaces; +using xAiModels.Models.Entities; + +namespace xAiModels.Interfaces.Entities +{ + public interface IXAiProjectSeeder : IXBaseDbSeeder + { } +} + +### FILE: C:\Users\saherelm\Documents\Projects\xSaherelmWorkspace\Modules\xAiModels\Interfaces\Entities\IXAiVectorEntityHub.cs + +using System; +using xPushService.Interfaces; +using xAiModels.Models.Entities; + +namespace xAiModels.Interfaces.Entities +{ + public interface IXAiVectorEntityHub : IXBaseEntityHub + { } +} + +### FILE: C:\Users\saherelm\Documents\Projects\xSaherelmWorkspace\Modules\xAiModels\Interfaces\Entities\IXAiVectorGraphQLTypeHelper.cs + +using System; +using xDataService.Interfaces; +using xAiModels.Models.Entities; + +namespace xAiModels.Interfaces.Entities +{ + public interface IXAiVectorGraphQLTypeHelper : IXBaseGraphQLTypeHelper + { } +} + +### FILE: C:\Users\saherelm\Documents\Projects\xSaherelmWorkspace\Modules\xAiModels\Interfaces\Entities\IXAiVectorKeyGenerator.cs + +using System; +using xDataService.Interfaces; +using xAiModels.Models.Entities; + +namespace xAiModels.Interfaces.Entities +{ + public interface IXAiVectorKeyGenerator : IXKeyGenerator + { } +} + +### FILE: C:\Users\saherelm\Documents\Projects\xSaherelmWorkspace\Modules\xAiModels\Interfaces\Entities\IXAiVectorRepository.cs + +using System; +using xDataService.Interfaces; +using xAiModels.Models.Entities; + +namespace xAiModels.Interfaces.Entities +{ + public interface IXAiVectorRepository : IXBaseRepository + { } +} + +### FILE: C:\Users\saherelm\Documents\Projects\xSaherelmWorkspace\Modules\xAiModels\Interfaces\Entities\IXAiVectorRepositoryEvents.cs + +using xDataService.Interfaces; +using xAiModels.Models.Entities; + +namespace xAiModels.Interfaces.Entities +{ + public interface IXAiVectorRepositoryEvents : IXBaseRepositoryEvents + { } +} + +### FILE: C:\Users\saherelm\Documents\Projects\xSaherelmWorkspace\Modules\xAiModels\Interfaces\Entities\IXAiVectorRepositoryProvider.cs + +using System; +using xPushService.Interfaces; +using xAiModels.Models.Entities; +using xAiModels.Providers.Entities; + +namespace xAiModels.Interfaces.Entities +{ + public interface IXAiVectorRepositoryProvider : IXBaseEntityProvider + { } +} + +### FILE: C:\Users\saherelm\Documents\Projects\xSaherelmWorkspace\Modules\xAiModels\Interfaces\Entities\IXAiVectorSeeder.cs + +using System; +using xDataService.Interfaces; +using xAiModels.Models.Entities; + +namespace xAiModels.Interfaces.Entities +{ + public interface IXAiVectorSeeder : IXBaseDbSeeder + { } +} + +### FILE: C:\Users\saherelm\Documents\Projects\xSaherelmWorkspace\Modules\xAiModels\Models\XAiModelDescriptor.cs + +using xAiModels.Constants; + +namespace xAiModels.Models +{ + /// + /// Describe a Provided Model ... + /// + public class XAiModelDescriptor + { + /// + /// Provider Name ... + /// + public string Name { get; set; } + + /// + /// LLM Provider Url ... + /// + public string Url { get; set; } + + /// + /// Model Name ... + /// + public string LLM { get; set; } + + /// + /// Api Key for Connection ... + /// + public string ApiKey { get; set; } + + /// + /// Specified Model Provider Type ... + /// + public XAiModelProviderType Provider { get; set; } = XAiModelProviderType.Ollama; + } +} + +### FILE: C:\Users\saherelm\Documents\Projects\xSaherelmWorkspace\Modules\xAiModels\Models\XAiPromptDescriptor.cs + +namespace xAiModels.Models +{ + /// + /// Describe Specified Prompt ... + /// + public class XAiPromptDescriptor + { + /// + /// Prompt Name ... + /// + public string Name { get; set; } + + /// + /// Prompt Template ... + /// + public string Template { get; set; } + + /// + /// Prompt Description ... + /// + public string Description { get; set; } + + /// + /// Prompt Template Params ... + /// + public XAiPromptParam[] Params { get; set; } = []; + } + + /// + /// Specified a Prompt Param ... + /// + public class XAiPromptParam + { + /// + /// Param Name ... + /// + public string Name { get; set; } + + /// + /// Param Identifier ... + /// + public string Param { get; set; } + + /// + /// Parma Description ... + /// + public string Description { get; set; } + } +} + +### FILE: C:\Users\saherelm\Documents\Projects\xSaherelmWorkspace\Modules\xAiModels\Models\XAiResonseMessage.cs + +using System; +using xModels.Base; +using xAiModels.Constants; + +namespace xAiModels.Models +{ + public class XAiResonseMessage : XBaseDto + { + public long Sequence { get; set; } + public Guid RespondTo { get; set; } + public string OwnerId { get; set; } + public string Content { get; set; } + public XAiChatRole Role { get; set; } + public DateTime RespondedOn { get; set; } + } +} + +### FILE: C:\Users\saherelm\Documents\Projects\xSaherelmWorkspace\Modules\xAiModels\Models\XAiResponseRequest.cs + +using System; + +namespace xAiModels.Models +{ + /// + /// /Request for a Response in Controllers ... + /// + public class XAiResponseRequest + { + /// + /// Prompt Text ... + /// + public string Prompt { get; set; } + + /// + /// Specified Project Id ... + /// + public Guid ProjectId { get; set; } + + /// + /// Specified Conversation Id ... + /// + public Guid ConversationId { get; set; } + } +} + +### FILE: C:\Users\saherelm\Documents\Projects\xSaherelmWorkspace\Modules\xAiModels\Models\XFileExtractionResult.cs + +using System.Collections.Generic; + +namespace xAiModels.Models +{ + /// + /// Holds File Extraction Result ... + /// + public class XFileExtractionResult + { + /// + /// Extracted String Content ... + /// + public string Text { get; set; } = string.Empty; + + /// + /// Extracted Images for Vision Model ... + /// + public IList Images { get; set; } = []; + + /// + /// Extracted Content from Audio File ... + /// + public string AudioTranscript { get; set; } = string.Empty; + + /// + /// Main File Name ... + /// + public string FileName { get; set; } + + /// + /// Main File MIME Type ... + /// + public string MimeType { get; set; } + + /// + /// Specified Fallback done using Images or not ... + /// + public bool UsedImageFallback { get; set; } = false; + + /// + /// Error Message ... + /// + public string ErrorMessage { get; set; } + } + + /// + /// Extracted Image ... + /// + public class XExtractedImage + { + /// + /// Content as Byte ... + /// + public byte[] Bytes { get; set; } + + /// + /// MIME Type of Image ... + /// + public string MimeType { get; set; } = "image/png"; + + /// + /// for PDF Files ... + /// + public int? PageNumber { get; set; } + + /// + /// Describe Image ... + /// + public string Description { get; set; } + } +} + +### FILE: C:\Users\saherelm\Documents\Projects\xSaherelmWorkspace\Modules\xAiModels\Models\Dtos\XAiConversationDto.cs + +using System; +using xModels.Base; +using xModels.Dtos; +using System.Collections.Generic; + +namespace xAiModels.Models.Dtos +{ + /// + /// Conversation Describe ... + /// + public class XAiConversationDto : XBaseGuidIDEntityDto + { + /// + /// User Identifier ... + /// + /// + public string OwnerId { get; set; } + + /// + /// Owner Info ... + /// + public virtual XPersonDto Owner { get; set; } = null; + + /// + /// Conversation Title Resource ID ... + /// + public string Title { get; set; } + + /// + /// All Exists Title Locale Resources ... + /// + public virtual XResourceDto TitleResource { get; set; } + + /// + /// Created Time ... + /// + public DateTime CreatedOn { get; set; } + + /// + /// Updated Time ... + /// + public DateTime UpdatedAt { get; set; } + + /// + /// Conversation Messages ... + /// + public virtual IEnumerable Messages { get; set; } = []; + + /// + /// Project ID ... + /// + public Guid ProjectId { get; set; } + + /// + /// Project Title Resource ID ... + /// + public virtual string ProjectTitle { get; set; } = null; + + /// + /// Project Description Resource ID ... + /// + public virtual string ProjectDescription { get; set; } = null; + + /// + /// Project Title Locale Resources ... + /// + public virtual XResourceDto ProjectTitleResource { get; set; } + + /// + /// Project Description Locale Resources ... + /// + public virtual XResourceDto ProjectDescriptionResource { get; set; } + } +} + +### FILE: C:\Users\saherelm\Documents\Projects\xSaherelmWorkspace\Modules\xAiModels\Models\Dtos\XAiMessageDto.cs + +using System; +using xModels.Base; +using xModels.Dtos; +using xAiModels.Constants; +using xCommons.Extensions; +using System.Collections.Generic; +using System.ComponentModel.DataAnnotations.Schema; + +namespace xAiModels.Models.Dtos +{ + public class XAiMessageDto : XBaseGuidIDEntityDto + { + /// + /// User Identifier ... + /// + /// + public string OwnerId { get; set; } + + /// + /// Owner Info ... + /// + public virtual XPersonDto Owner { get; set; } = null; + + /// + /// Message of Chat ... + /// + public string Content { get; set; } + + /// + /// Role of Message ... + /// + public XAiChatRole Role { get; set; } + + /// + /// Created Time ... + /// + public DateTime CreatedOn { get; set; } + + /// + /// Updated Time ... + /// + public DateTime UpdatedAt { get; set; } + + /// + /// Conversation Id ... + /// + public Guid ConversationId { get; set; } + + /// + /// Conversation Info ... + /// + public virtual string ConversationTitle { get; set; } = null; + public virtual XResourceDto ConversationTitleResouce { get; set; } = null; + + // + #region Meta Data Property ... + private string _metadata; + + /// + /// Meta Data of Message ... + /// + [NotMapped] + public IDictionary Metadata { get; private set; } = null; + + /// + /// Meta Data of MEssage in Json ... + /// + public string MetaDatas + { + // + get => _metadata; + + // + set + { + // + // Converts Json String to Dictionary ... + if (!value.IsNullOrEmpty()) + { + Metadata = value.FromJSON>(); + } + + // + _metadata = value; + } + } + #endregion + } +} + +### FILE: C:\Users\saherelm\Documents\Projects\xSaherelmWorkspace\Modules\xAiModels\Models\Dtos\XAiProjectDto.cs + +using System; +using xModels.Base; +using xModels.Dtos; +using System.Collections.Generic; + +namespace xAiModels.Models.Dtos +{ + /// + /// Describe a Project ... + /// + public class XAiProjectDto : XBaseGuidIDEntityDto + { + /// + /// User Identifier ... + /// + /// + public string OwnerId { get; set; } + + /// + /// Owner Info ... + /// + public virtual XPersonDto Owner { get; set; } = null; + + /// + /// Title of Project ... + /// + public string Title { get; set; } + + /// + /// All Exists Title Locale Resources ... + /// + public virtual XResourceDto TitleResource { get; set; } + + /// + /// Description of Project ... + /// + public string Description { get; set; } + + /// + /// All Exists Description Locale Resources ... + /// + public virtual XResourceDto DescriptionResource { get; set; } + + /// + /// a Prompt for Project Start ... + /// + public string Prompt { get; set; } + + /// + /// Created Time ... + /// + public DateTime CreatedOn { get; set; } + + /// + /// Updated Time ... + /// + public DateTime UpdatedAt { get; set; } + + /// + /// Conversations ... + /// + public virtual IList Conversations { get; set; } = []; + } +} + +### FILE: C:\Users\saherelm\Documents\Projects\xSaherelmWorkspace\Modules\xAiModels\Models\Dtos\XAiVectorDto.cs + +using System; +using xModels.Base; +using System.Collections.Generic; + +namespace xAiModels.Models.Dtos +{ + /// + /// Vector DTO for AI Vector data ... + /// + public class XAiVectorDto : XBaseGuidIDEntityDto + { + /// + /// Text content of the vector ... + /// + public string Text { get; set; } + + /// + /// Doc and Chunk Identifier ... + /// + public string Identifier { get; set; } + + /// + /// Knowledge Base Type / Domain (Optional Filter on Search) ... + /// + public string Type { get; set; } + + /// + /// Embedding vector representation ... + /// + public virtual ReadOnlyMemory Embedding { get; set; } = null; + + /// + /// Metadata associated with the vector ... + /// + public virtual Dictionary Metadata { get; set; } = null; + } +} + +### FILE: C:\Users\saherelm\Documents\Projects\xSaherelmWorkspace\Modules\xAiModels\Models\Dtos\XAiVectorSearchResult.cs + +using System; +using System.Collections.Generic; + +namespace xAiModels.Models.Dtos +{ + public class XAiVectorSearchResult + { + public Guid Id { get; set; } + public string Text { get; set; } + public float Score { get; set; } + public string Type { get; set; } + public string Identifier { get; set; } + public Dictionary Metadata { get; set; } = null; + } +} + +### FILE: C:\Users\saherelm\Documents\Projects\xSaherelmWorkspace\Modules\xAiModels\Models\Entities\XAiConversation.cs + +using System; +using xModels.Base; +using System.ComponentModel.DataAnnotations; + +namespace xAiModels.Models.Entities +{ + /// + /// Conversation Describe ... + /// + public class XAiConversation : XBaseGuidIDEntity + { + /// + /// User Identifier ... + /// + /// + [Required] + [StringLength(255)] + public string OwnerId { get; set; } + + /// + /// Title of Conversation ... + /// + [Required] + [StringLength(255)] + public string Title { get; set; } + + /// + /// Created Time ... + /// + public DateTime CreatedOn { get; set; } + + /// + /// Updated Time ... + /// + public DateTime UpdatedAt { get; set; } + + /// + /// Project ID ... + /// + [Required] + public Guid ProjectId { get; set; } + } +} + +### FILE: C:\Users\saherelm\Documents\Projects\xSaherelmWorkspace\Modules\xAiModels\Models\Entities\XAiMessage.cs + +using System; +using xModels.Base; +using xAiModels.Constants; +using xCommons.Extensions; +using System.Collections.Generic; +using System.ComponentModel.DataAnnotations; +using System.ComponentModel.DataAnnotations.Schema; + +namespace xAiModels.Models.Entities +{ + /// + /// Message Model of Ai ... + /// + public class XAiMessage : XBaseGuidIDEntity + { + /// + /// User Identifier ... + /// + /// + [Required] + [StringLength(255)] + public string OwnerId { get; set; } + + /// + /// Message of Chat ... + /// + [Required] + public string Content { get; set; } + + /// + /// Role of Message ... + /// + public XAiChatRole Role { get; set; } + + /// + /// Created Time ... + /// + public DateTime CreatedOn { get; set; } + + /// + /// Updated Time ... + /// + public DateTime UpdatedAt { get; set; } + + /// + /// Conversation Id ... + /// + [StringLength(255)] + public Guid ConversationId { get; set; } + + // + #region Meta Data Property ... + private string _metadata; + + /// + /// Meta Data of Message ... + /// + [NotMapped] + public IDictionary Metadata { get; private set; } = null; + + /// + /// Meta Data of MEssage in Json ... + /// + public string MetaDatas + { + // + get => _metadata; + + // + set + { + // + // Converts Json String to Dictionary ... + if (!value.IsNullOrEmpty()) + { + Metadata = value.FromJSON>(); + } + + // + _metadata = value; + } + } + #endregion + } +} + +### FILE: C:\Users\saherelm\Documents\Projects\xSaherelmWorkspace\Modules\xAiModels\Models\Entities\XAiProject.cs + +using System; +using xModels.Base; +using System.ComponentModel.DataAnnotations; + +namespace xAiModels.Models.Entities +{ + /// + /// Describe a Project ... + /// + public class XAiProject : XBaseGuidIDEntity + { + /// + /// User Identifier ... + /// + /// + [Required] + [StringLength(255)] + public string OwnerId { get; set; } + + /// + /// Title of Project ... + /// + [Required] + [StringLength(255)] + public string Title { get; set; } + + /// + /// Description of Project ... + /// + [StringLength(1000)] + public string Description { get; set; } + + /// + /// a Prompt for Project Start ... + /// + public string Prompt { get; set; } + + /// + /// Created Time ... + /// + public DateTime CreatedOn { get; set; } + + /// + /// Updated Time ... + /// + public DateTime UpdatedAt { get; set; } + } +} + +### FILE: C:\Users\saherelm\Documents\Projects\xSaherelmWorkspace\Modules\xAiModels\Models\Entities\XAiVector.cs + +using xModels.Base; +using System.ComponentModel.DataAnnotations; + +namespace xAiModels.Models.Entities +{ + public class XAiVector : XBaseGuidIDEntity + { + /// + /// Thge Content Which Embedded ... + /// + public string Text { get; set; } + + /// + /// Doc and Chunk Identifier ... + /// + public string Identifier { get; set; } + + /// + /// Knowledge Base Type / Domain (e.g. "Legal", "Medical") ... + /// Used for Filtering on Search and Retrieve ... + /// + [StringLength(100)] + public string Type { get; set; } + + /// + /// a Json String which Represents IReadOnlyList of float ... + /// + public string Embedding { get; set; } + + /// + /// a Json String Which Represents MetaData ... + /// + public string Metadata { get; set; } = string.Empty; + } +} + +### FILE: C:\Users\saherelm\Documents\Projects\xSaherelmWorkspace\Modules\xAiModels\Providers\XAiConversationEntityRegisterar.cs + +using System; +using xDataService.Providers; +using xDataService.Interfaces; +using xAiModels.Models.Entities; +using Microsoft.EntityFrameworkCore; +using xAiModels.Configurations.Entities; + +namespace xAiModels.Providers +{ + public class XAiConversationEntityRegisterar : XBaseEntityRegisterar, IXEntityRegisterar + { + public XAiConversationEntityRegisterar() + : base(nameof(XAiConversationEntityRegisterar)) + { + // + // Add Entity ... + AddEntity(); + } + + /// + /// Configure Entities ... + /// + /// + public override void ConfigureEntities(ModelBuilder modelBuilder) + { + // + // Configure Entity Using Provided ... + modelBuilder + .ApplyConfigurationsFromAssembly(typeof(XAiConversationEntityConfiguration).Assembly); + + // + base.ConfigureEntities(modelBuilder); + } + } +} + +### FILE: C:\Users\saherelm\Documents\Projects\xSaherelmWorkspace\Modules\xAiModels\Providers\XAiConversationTitleResourceProvider.cs + +using xAiModels.Constants; +using xAiModels.Interfaces; +using xCommons.Configurations; +using xStringService.Providers; +using xStringService.Interfaces.Dtos; + +namespace xAiModels.Providers +{ + public class XAiConversationTitleResourceProvider : XBaseOwnedItemResourceProvider, IXAiConversationTitleResourceProvider + { + public XAiConversationTitleResourceProvider( + XAppConfiguration appConfig, + IXStringServiceProvider stringProvider + ) : base( + appConfig: appConfig, + stringProvider: stringProvider, + item: XAiModelsConstants.XAiConversationTitleIdentifier + ) + { } + } +} + +### FILE: C:\Users\saherelm\Documents\Projects\xSaherelmWorkspace\Modules\xAiModels\Providers\XAiDataProvider.cs + +using System; +using System.Linq; +using xModels.Dtos; +using System.Threading; +using xAiModels.Helpers; +using xAiModels.Constants; +using xCommons.Extensions; +using xAiModels.Extensions; +using xAiModels.Interfaces; +using xAiModels.Models.Dtos; +using xExceptions.Constants; +using System.Threading.Tasks; +using xCommons.Configurations; +using System.Linq.Expressions; +using xDataService.Extensions; +using xAiModels.Providers.Hubs; +using xAiModels.Interfaces.Dtos; +using xStringService.Interfaces; +using xAiModels.Models.Entities; +using System.Collections.Generic; +using Microsoft.AspNetCore.SignalR; +using xAiModels.Interfaces.Entities; +using xAiModels.Interfaces.Enrichers; + +namespace xAiModels.Providers +{ + /// + /// All Data Manipulation Requirements ... + /// + public class XAiDataProvider : IXAiDataProvider + { + // + #region Properties ... + private readonly IXStringProvider stringProvider; + private readonly IXAiVectorEnricher vectorEnricher; + private readonly XAppConfiguration appConfiguration; + private readonly IHubContext hub; + private readonly IXAiMessageEnricher messageEnricher; + private readonly IXAiProjectEnricher projectEnricher; + private readonly IXAiVectorRepository vectorRepository; + private readonly IXAiConversationEnricher conversationEnricher; + private readonly IXAiVectorRepositoryService vectorRepositoryService; + private readonly IXAiMessageRepositoryService messageRepositoryService; + private readonly IXAiProjectRepositoryService projectRepositoryService; + private readonly IXAiProjectTitleResourceProvider projectTitleResourceProvider; + private readonly IXAiConversationRepositoryService conversationRepositoryService; + private readonly IXAiConversationTitleResourceProvider conversationTitleResourceProvider; + private readonly IXAiProjectDescriptionResourceProvider projectDescriptionResourceProvider; + #endregion + + public XAiDataProvider( + IXStringProvider stringProvider, + IXAiVectorEnricher vectorEnricher, + XAppConfiguration appConfiguration, + IHubContext hub, + IXAiProjectEnricher projectEnricher, + IXAiMessageEnricher messageEnricher, + IXAiVectorRepository vectorRepository, + IXAiConversationEnricher conversationEnricher, + IXAiVectorRepositoryService vectorRepositoryService, + IXAiMessageRepositoryService messageRepositoryService, + IXAiProjectRepositoryService projectRepositoryService, + IXAiProjectTitleResourceProvider projectTitleResourceProvider, + IXAiConversationRepositoryService conversationRepositoryService, + IXAiConversationTitleResourceProvider conversationTitleResourceProvider, + IXAiProjectDescriptionResourceProvider projectDescriptionResourceProvider + ) + { + this.hub = hub; + this.stringProvider = stringProvider; + this.vectorEnricher = vectorEnricher; + this.projectEnricher = projectEnricher; + this.messageEnricher = messageEnricher; + this.appConfiguration = appConfiguration; + this.vectorRepository = vectorRepository; + this.conversationEnricher = conversationEnricher; + this.vectorRepositoryService = vectorRepositoryService; + this.messageRepositoryService = messageRepositoryService; + this.projectRepositoryService = projectRepositoryService; + this.projectTitleResourceProvider = projectTitleResourceProvider; + this.conversationRepositoryService = conversationRepositoryService; + this.conversationTitleResourceProvider = conversationTitleResourceProvider; + this.projectDescriptionResourceProvider = projectDescriptionResourceProvider; + } + + // + #region Loaders ... + /// + /// Load Projects List of Specified Owner ... + /// + /// + /// + /// + /// + /// + /// + public async Task> LoadProjects( + string ownerId, + string connectionId = null, + bool fillConversations = false, + bool fillConversationMessages = false, + CancellationToken cancellationToken = default + ) + { + // + // Validate Args ... + if (ownerId.IsNullOrEmpty()) + { + XException.InvalidArgs.Throw(); + } + + // + // Handle Default Project and Conversation ... + + // + // Default Project ... + bool hasDefault = await HasDefaultProject( + ownerId: ownerId, + cancellationToken: cancellationToken + ); + if (!hasDefault) + { + // + await CreateDefaultProject( + ownerId: ownerId, + connectionId: connectionId, + cancellationToken: cancellationToken + ); + } + var defaultProject = await GetDefaultProject( + ownerId: ownerId, + connectionId: connectionId, + cancellationToken: cancellationToken + ); + + // + // Default Project's Default Conversation ... + hasDefault = await HasDefaultConversation( + ownerId: ownerId, + projectId: defaultProject.Id, + cancellationToken: cancellationToken + ); + if (!hasDefault) + { + // + await CreateDefaultConversation( + ownerId: ownerId, + connectionId: connectionId, + projectId: defaultProject.Id, + cancellationToken: cancellationToken + ); + } + + // + // Retrieve Project List ... + var result = await projectRepositoryService.FindManyAsync( + includeBuilder: null, + ignoreSoftDeleteds: true, + predicate: x => x.OwnerId == ownerId, + cancellationToken: cancellationToken, + orderBuilder: x => x.OrderBy(y => y.CreatedOn) + ); + + // + if (result.HasChild()) + { + // + result = await projectEnricher.EnrichRange( + sources: result, + cancellationToken: cancellationToken, + fillConversations: fillConversations, + fillConversationMessages: fillConversationMessages + ); + } + + // + return result; + } + + /// + /// Load List of Conversations for Specified Project ... + /// + /// + /// + /// + /// + /// + public async Task> LoadConversations( + Guid projectId, + bool fillMessages = false, + string connectionId = null, + CancellationToken cancellationToken = default + ) + { + // + // Validate Args ... + if (projectId.IsNull() || + projectId.IsDefaultGuid() + ) + { + XException.InvalidArgs.Throw(); + } + + // + // Retrieve Project ... + var project = await projectRepositoryService.GetAsync( + id: projectId, + includeBuilder: null, + ignoreSoftDeleteds: true, + cancellationToken: cancellationToken + ); + if (project.IsNullOrDefault()) + { + XException.NotFound.Throw(); + } + + // + // Default Conversation ... + var hasDefault = await HasDefaultConversation( + projectId: projectId, + ownerId: project.OwnerId, + connectionId: connectionId, + cancellationToken: cancellationToken + ); + if (!hasDefault) + { + // + await CreateDefaultConversation( + projectId: projectId, + ownerId: project.OwnerId, + connectionId: connectionId, + cancellationToken: cancellationToken + ); + } + + // + // Retrieve Conversation's List ... + var result = await conversationRepositoryService.FindManyAsync( + includeBuilder: null, + ignoreSoftDeleteds: true, + cancellationToken: cancellationToken, + predicate: x => x.ProjectId == projectId, + orderBuilder: x => x.OrderBy(y => y.CreatedOn) + ); + + // + if (result.HasChild()) + { + // + result = await conversationEnricher.EnrichRange( + sources: result, + fillMessages: fillMessages, + cancellationToken: cancellationToken + ); + } + + // + return result; + } + + /// + /// Load Messages of Specified Conversation ... + /// + /// + /// + /// + public async Task> LoadMessages( + Guid conversationId, + CancellationToken cancellationToken = default + ) + { + // + // Validate Args ... + if (conversationId.IsNull() || + conversationId.IsDefaultGuid() + ) + { + XException.InvalidArgs.Throw(); + } + + // + var conversation = await conversationRepositoryService.GetAsync( + id: conversationId, + includeBuilder: null, + ignoreSoftDeleteds: true, + cancellationToken: cancellationToken + ); + if (conversation.IsNullOrDefault()) + { + XException.NotFound.Throw(); + } + + // + // Retrieve Message Lists of Specified Conversation ... + var result = await messageRepositoryService.FindManyAsync( + includeBuilder: null, + ignoreSoftDeleteds: true, + cancellationToken: cancellationToken, + orderBuilder: x => x.OrderBy(y => y.CreatedOn), + predicate: x => x.ConversationId == conversationId + ); + + // + if (result.HasChild()) + { + // + result = await messageEnricher.EnrichRange( + sources: result, + cancellationToken: cancellationToken + ); + } + + // + return result; + } + #endregion + + // + #region Getters ... + /// + /// Retrieve Specified Project ... + /// + /// + /// + /// + /// + /// + public async Task GetProject( + Guid id, + bool fillConversations = false, + bool fillConversationMessages = false, + CancellationToken cancellationToken = default + ) + { + // + // Validate Args ... + if (id.IsDefaultGuid()) + { + XException.InvalidArgs.Throw(); + } + + // + var result = await projectRepositoryService.GetAsync( + id: id, + includeBuilder: null, + ignoreSoftDeleteds: true, + cancellationToken: cancellationToken + ); + if (result.IsNullOrDefault()) + { + XException.NotFound.Throw(); + } + + // + // Handle Enrichment ... + result = await projectEnricher.Enrich( + source: result, + fillConversations: fillConversations, + cancellationToken: cancellationToken, + fillConversationMessages: fillConversationMessages + ); + + // + return result; + } + + /// + /// Retrieve Specified Conversation ... + /// + /// + /// + /// + /// + public async Task GetConversation( + Guid id, + bool fillMessages = false, + CancellationToken cancellationToken = default + ) + { + // + // Validate Args ... + if (id.IsDefaultGuid()) + { + XException.InvalidArgs.Throw(); + } + + // + var result = await conversationRepositoryService.GetAsync( + id: id, + includeBuilder: null, + ignoreSoftDeleteds: true, + cancellationToken: cancellationToken + ); + if (result.IsNullOrDefault()) + { + XException.NotFound.Throw(); + } + + // + // Handle Enrichment ... + result = await conversationEnricher.Enrich( + source: result, + fillMessages: fillMessages, + cancellationToken: cancellationToken + ); + + // + return result; + } + #endregion + + // + #region Creator/Adders ... + /// + /// Create Project ... + /// + /// + /// + /// + /// + /// + public async Task CreateProject( + string ownerId, + XAiProjectDto item = null, + string connectionId = null, + CancellationToken cancellationToken = default + ) + { + // + // Validate Args ... + if (ownerId.IsNullOrEmpty()) + { + XException.InvalidArgs.Throw(); + } + + // + // Check Project Provided or not ... + var hasProject = !item.IsNullOrDefault(); + + // + // Normalize Provided Project ... + if (hasProject) + { + // + item.OwnerId = ownerId; + item.CreatedOn = DateTime.UtcNow; + + // + // Validate Item ... + if (!item.IsValidForAddOrUpdate()) + { + XException.InvalidData.Throw(); + } + } + + // + XAiProjectDto result = null; + var defaultLanguage = appConfiguration.DefaultLanguage; + + // + // Create Provided Project ... + if (hasProject) + { + // + // Add Item for ID Gneneration ... + result = await projectRepositoryService.AddAsync( + item: item, + saveChanges: true, + cancellationToken: cancellationToken + ); + + // + // Checking Resources ... + + // + // Titles ... + var titleResource = string.Empty; + if (!item.TitleResource.IsNullOrDefault() && + item.TitleResource.Locales.HasChild()) + { + // + // Adding Title Resource Locales ... + var isDefaultLanguageHandled = false; + foreach (var trl in item.TitleResource.Locales) + { + // + // Attaching Default Language ... + if (!isDefaultLanguageHandled && + trl.Language.IsNullOrEmpty()) + { + // + trl.Language = defaultLanguage; + isDefaultLanguageHandled = true; + } + + // + // Check Value Exists ... + if (trl.Value.IsNullOrEmpty()) + { + continue; + } + + // + var resource = await projectTitleResourceProvider.AddOrUpdateLocale( + locale: trl, + owner: ownerId, + identifier: result.Id, + connectionId: connectionId, + cancellationToken: cancellationToken + ); + if (!resource.IsNullOrDefault() && + titleResource.IsNullOrEmpty()) + { + titleResource = resource.Resource; + } + } + } + + // + // Descriptions ... + var descriptionResource = string.Empty; + if (!item.DescriptionResource.IsNullOrDefault() && + item.DescriptionResource.Locales.HasChild()) + { + // + // Adding Description Resource Locales .... + var isDefaultLanguageHandled = false; + foreach (var trl in item.DescriptionResource.Locales) + { + // + // Attaching Default Language ... + if (!isDefaultLanguageHandled && + trl.Language.IsNullOrEmpty()) + { + // + trl.Language = defaultLanguage; + isDefaultLanguageHandled = true; + } + + // + // Check Value Exists ... + if (trl.Value.IsNullOrEmpty()) + { + continue; + } + + // + var resource = await projectDescriptionResourceProvider.AddOrUpdateLocale( + locale: trl, + owner: ownerId, + identifier: result.Id, + connectionId: connectionId, + cancellationToken: cancellationToken + ); + if (!resource.IsNullOrDefault() && + descriptionResource.IsNullOrEmpty()) + { + descriptionResource = resource.Resource; + } + } + } + + // + // Update Data ... + result.Title = titleResource; + result.Description = descriptionResource; + result = await projectRepositoryService.UpdateAsync( + item: result, + id: result.Id, + saveChanges: true, + cancellationToken: cancellationToken + ); + if (!result.IsNullOrDefault()) + { + // + result = await projectEnricher.Enrich( + source: result, + fillConversations: false, + fillConversationMessages: false, + cancellationToken: cancellationToken + ); + } + + // + // Handling Send Push Notification ... + if (!result.IsNullOrDefault() && + !connectionId.IsNullOrEmpty() + ) + { + // + await SendPush( + connectionId: connectionId, + cancellationToken: cancellationToken, + payLoad: item.ToJSON(camelCase: true), + action: XAiDataProviderHubActions.ProjectCreated.GetStringValue() + ); + } + } + // + // Check Default Project ... + else + { + // + // Check Default Project Exists or not ... + var hasDefault = await HasDefaultProject( + ownerId: ownerId, + cancellationToken: cancellationToken + ); + + // + // If Default Project Exists, Throw Exception ... + if (hasDefault) + { + XException.InvalidArgs.Throw(); + } + + // + // Create and Retrive Default Project ... + result = await GetDefaultProject( + ownerId: ownerId, + connectionId: connectionId, + cancellationToken: cancellationToken + ); + } + + // + // Validate ... + if (result.IsNullOrDefault()) + { + XException.ActionFailed.Throw(); + } + + // + // Handle Enrichment ... + result = await Enrich( + source: result, + fillConversations: false, + fillConversationMessages: false, + cancellationToken: cancellationToken + ); + + // + return result; + } + + /// + /// Create an AI Conversation ... + /// + /// + /// + /// + /// + /// + /// + public async Task CreateConversation( + string ownerId, + Guid projectId, + XAiConversationDto item = null, + string connectionId = null, + CancellationToken cancellationToken = default + ) + { + // + // Validate Args ... + if (projectId.IsNull() || + projectId.IsDefaultGuid()) + { + XException.InvalidArgs.Throw(); + } + + // + // Handle Proejct ... + XAiProjectDto project = await projectRepositoryService.GetAsync( + id: projectId, + includeBuilder: null, + ignoreSoftDeleteds: true, + // fillConversations: false, + // fillConversationMessages: false, + cancellationToken: cancellationToken + ); + if (project.IsNullOrDefault()) + { + XException.NotFound.Throw(); + } + + // + // Check Conversation Provided or not ... + var hasConversation = !item.IsNullOrDefault(); + + // + // Normalize Conversation if Provided ... + if (hasConversation) + { + // + item.OwnerId = ownerId; + item.ProjectId = project.Id; + item.CreatedOn = DateTime.UtcNow; + + // + // Validate Item ... + if (!item.IsValidForAddOrUpdate()) + { + XException.InvalidData.Throw(); + } + } + + // + XAiConversationDto result = null; + var defaultLanguage = appConfiguration.DefaultLanguage; + + // + // Create Provided Conversation ... + if (hasConversation) + { + // + // Add Item for ID Gneneration ... + result = await conversationRepositoryService.AddAsync( + item: item, + saveChanges: true, + // fillMessages: false, + cancellationToken: cancellationToken + ); + + // + // Checking Resources ... + + // + // Titles ... + var titleResource = string.Empty; + if (!item.TitleResource.IsNullOrDefault() && + item.TitleResource.Locales.HasChild()) + { + // + // Adding Title Resource Locales ... + var isDefaultLanguageHandled = false; + foreach (var trl in item.TitleResource.Locales) + { + // + // Attaching Default Language ... + if (!isDefaultLanguageHandled && + trl.Language.IsNullOrEmpty()) + { + // + trl.Language = defaultLanguage; + isDefaultLanguageHandled = true; + } + + // + // Check Value Exists ... + if (trl.Value.IsNullOrEmpty()) + { + continue; + } + + // + var resource = await conversationTitleResourceProvider.AddOrUpdateLocale( + locale: trl, + owner: ownerId, + identifier: result.Id, + connectionId: connectionId, + cancellationToken: cancellationToken + ); + if (!resource.IsNullOrDefault() && + titleResource.IsNullOrEmpty()) + { + titleResource = resource.Resource; + } + } + } + + // + // Update Data ... + result.Title = titleResource; + result = await conversationRepositoryService.UpdateAsync( + item: result, + id: result.Id, + saveChanges: true, + cancellationToken: cancellationToken + ); + if (!result.IsNullOrDefault()) + { + // + result = await conversationEnricher.Enrich( + source: result, + fillMessages: false, + cancellationToken: cancellationToken + ); + } + + // + // Handling Send Push Notification ... + if (!result.IsNullOrDefault() && + !connectionId.IsNullOrEmpty() + ) + { + // + await SendPush( + connectionId: connectionId, + cancellationToken: cancellationToken, + payLoad: item.ToJSON(camelCase: true), + action: XAiDataProviderHubActions.ConversationCreated.GetStringValue() + ); + } + } + // + // Check Default Conversation ... + else + { + // + // Check Default Conversation Exists or not ... + var hasDefault = await HasDefaultConversation( + projectId: project.Id, + ownerId: project.OwnerId, + cancellationToken: cancellationToken + ); + + // + // If Default Project Exists, Throw Exception ... + if (hasDefault) + { + XException.InvalidArgs.Throw(); + } + + // + // Create and Retrive Default Conversation ... + result = await GetDefaultConversation( + projectId: project.Id, + ownerId: project.OwnerId, + connectionId: connectionId, + cancellationToken: cancellationToken + ); + } + + // + // Validate ... + if (result.IsNullOrDefault()) + { + XException.ActionFailed.Throw(); + } + + // + // Handle Enrichment ... + result = await Enrich( + source: result, + fillMessages: false, + cancellationToken: cancellationToken + ); + + // + return result; + } + + /// + /// Add Message ... + /// + /// + /// + /// + /// + /// + public async Task AddMessage( + Guid conversationId, + XAiMessageDto item, + string connectionId = null, + CancellationToken cancellationToken = default + ) + { + // + // Validate Args ... + if (item.IsNullOrDefault() || + conversationId.IsNull() || + conversationId.IsDefaultGuid() + ) + { + XException.InvalidArgs.Throw(); + } + + // + // Normalize ... + item.CreatedOn = DateTime.UtcNow; + item.ConversationId = conversationId; + + // + // Validate Item ... + if (!item.IsValidForAddOrUpdate()) + { + XException.InvalidData.Throw(); + } + + // + var result = await messageRepositoryService.AddAsync( + item: item, + saveChanges: true, + cancellationToken: cancellationToken + ); + + // + // Handle Enrichment ... + if (!result.IsNullOrDefault()) + { + // + result = await Enrich( + source: result, + cancellationToken: cancellationToken + ); + } + + // + // Handling Send Push Notification ... + if (!result.IsNullOrDefault() && + !connectionId.IsNullOrEmpty() + ) + { + // + await SendPush( + connectionId: connectionId, + cancellationToken: cancellationToken, + payLoad: item.ToJSON(camelCase: true), + action: XAiDataProviderHubActions.MessageCreated.GetStringValue() + ); + } + + // + return result; + } + #endregion + + // + #region Updaters ... + #endregion + + // + #region Defaults ... + /// + /// Retrieve Default Project of Specified Owner ... + /// Create it if not Handled ... + /// + /// + /// + /// + /// + public async Task GetDefaultProject( + string ownerId, + string connectionId = null, + CancellationToken cancellationToken = default + ) + { + // + // Check Default Project Exists or noit ... + var isExists = await HasDefaultProject( + ownerId: ownerId, + cancellationToken: cancellationToken + ); + if (!isExists) + { + // + await CreateDefaultProject( + ownerId: ownerId, + connectionId: connectionId, + cancellationToken: cancellationToken + ); + } + + // + var resource = await stringProvider.FindOne( + cancellationToken: cancellationToken, + predicate: x => + x.ResourceTitle + .ToNormalString() + .Contains(ownerId.ToNormalString()) && + x.ResourceTitle + .ToNormalString() + .Contains(XAiModelsConstants.XAiProjectTitleIdentifier.ToNormalString()) && + x.TranslatedValue + .ToNormalString() + .Contains(XAiDataProviderConstants.XDefaultAiProjectSuffix.ToNormalString()) + ); + if (resource.IsNullOrDefault()) + { + XException.NotFound.Throw(); + } + + // + var result = await projectRepositoryService.FindOneAsync( + cancellationToken: cancellationToken, + predicate: x => x.Title + .Equals( + resource.ResourceTitle, + StringComparison.InvariantCultureIgnoreCase + ) + ); + if (result.IsNullOrDefault()) + { + XException.NotFound.Throw(); + } + + // + return result; + } + + /// + /// Retrieve Default Conversation of Specified Owner ... + /// Create it if not Handled ... + /// + /// + /// + /// + /// + /// + public async Task GetDefaultConversation( + string ownerId, + Guid projectId, + string connectionId = null, + CancellationToken cancellationToken = default + ) + { + // + // Validate Args ... + if (ownerId.IsNullOrEmpty()) + { + XException.InvalidArgs.Throw(); + } + + // + // Prepare Project ... + XAiProjectDto project = null; + if (projectId.IsNull() || + projectId.IsDefaultGuid() + ) + { + // + project = await GetDefaultProject( + ownerId: ownerId, + connectionId: connectionId, + cancellationToken: cancellationToken + ); + } + else + { + // + project = await projectRepositoryService.GetAsync( + id: projectId, + includeBuilder: null, + ignoreSoftDeleteds: true, + cancellationToken: cancellationToken + ); + } + if (project.IsNullOrDefault()) + { + XException.NotFound.Throw(); + } + + // + // Check Default Conversation Exists or noit ... + var isExists = await HasDefaultConversation( + ownerId: ownerId, + projectId: project.Id, + connectionId: connectionId, + cancellationToken: cancellationToken + ); + if (!isExists) + { + // + await CreateDefaultConversation( + ownerId: ownerId, + projectId: project.Id, + connectionId: connectionId, + cancellationToken: cancellationToken + ); + } + + // + // Detect Conversation Resource ... + var resource = await stringProvider.FindOne( + cancellationToken: cancellationToken, + predicate: x => + x.ResourceTitle + .ToNormalString() + .Contains(ownerId.ToNormalString()) && + x.ResourceTitle + .ToNormalString() + .Contains(XAiModelsConstants.XAiProjectTitleIdentifier + .ToNormalString()) && + x.TranslatedValue + .ToNormalString() + .Contains(XAiDataProviderConstants.XDefaultAiProjectSuffix) + ); + if (resource.IsNullOrDefault()) + { + XException.NotFound.Throw(); + } + + // + // Find Default Conversation ... + var result = await conversationRepositoryService.FindOneAsync( + cancellationToken: cancellationToken, + predicate: x => x.Title + .Equals( + resource.ResourceTitle, + StringComparison.InvariantCultureIgnoreCase + ) && + x.ProjectId == project.Id + ); + if (result.IsNullOrDefault()) + { + XException.NotFound.Throw(); + } + + // + return result; + } + #endregion + + // + #region Query ... + /// + /// Query Projects ... + /// + /// + /// + /// + /// + public async Task> QueryProjects( + string ownerId, + XQuery query, + CancellationToken cancellationToken = default + ) + { + // + Expression> predicate = null; + if (!ownerId.IsNullOrEmpty()) + { + predicate = x => x.OwnerId == ownerId; + } + + // + var result = await projectRepositoryService.QueryAsync( + query: query, + predicate: predicate, + includeBuilder: null, + ignoreSoftDeleteds: true, + cancellationToken: cancellationToken, + orderBuilder: x => x.OrderBy(y => y.CreatedOn) + ); + if (!result.IsNullOrDefault() && + result.Items.HasChild()) + { + // + result.Items = [..await EnrichRange( + sources: result.Items, + fillConversations: false, + fillConversationMessages: false, + cancellationToken: cancellationToken + )]; + } + + // + return result; + } + + /// + /// Query Conversations ... + /// + /// + /// + /// + /// + /// + public async Task> QueryConversations( + string ownerId, + Guid projectId, + XQuery query, + CancellationToken cancellationToken = default + ) + { + // + // Validate ... + if (projectId.IsDefaultGuid()) + { + XException.InvalidArgs.Throw(); + } + + // + // Retrieve Project ... + var project = await projectRepositoryService.GetAsync( + id: projectId, + includeBuilder: null, + ignoreSoftDeleteds: true, + cancellationToken: cancellationToken + ); + if (project.IsNullOrDefault()) + { + XException.NotFound.Throw(); + } + + // + Expression> predicate = x => + x.ProjectId == projectId; + if (!ownerId.IsNullOrEmpty()) + { + // + predicate = x => + x.OwnerId == ownerId && + x.ProjectId == projectId; + } + + // + var result = await conversationRepositoryService.QueryAsync( + query: query, + predicate: predicate, + includeBuilder: null, + ignoreSoftDeleteds: true, + cancellationToken: cancellationToken, + orderBuilder: x => x.OrderBy(y => y.CreatedOn) + ); + if (!result.IsNullOrDefault() && + result.Items.HasChild()) + { + // + result.Items = [..await EnrichRange( + fillMessages: false, + sources: result.Items, + cancellationToken: cancellationToken + )]; + } + + // + return result; + } + + /// + /// Query Messages ... + /// + /// + /// + /// + /// + /// + public async Task> QueryMessages( + string ownerId, + Guid conversationId, + XQuery query, + CancellationToken cancellationToken = default + ) + { + // + // Validate ... + if (conversationId.IsDefaultGuid()) + { + XException.InvalidArgs.Throw(); + } + + // + // Retrieve Conversation ... + var conversation = await conversationRepositoryService.GetAsync( + id: conversationId, + includeBuilder: null, + ignoreSoftDeleteds: true, + cancellationToken: cancellationToken + ); + if (conversation.IsNullOrDefault()) + { + XException.NotFound.Throw(); + } + + // + Expression> predicate = x => + x.ConversationId == conversationId; + if (!ownerId.IsNullOrEmpty()) + { + // + predicate = x => + x.OwnerId == ownerId && + x.ConversationId == conversationId; + } + + // + var result = await messageRepositoryService.QueryAsync( + query: query, + predicate: predicate, + includeBuilder: null, + ignoreSoftDeleteds: true, + cancellationToken: cancellationToken, + orderBuilder: x => x.OrderBy(y => y.CreatedOn) + ); + if (!result.IsNullOrDefault() && + result.Items.HasChild()) + { + // + result.Items = [..await EnrichRange( + sources: result.Items, + cancellationToken: cancellationToken + )]; + } + + // + return result; + } + #endregion + + // + #region Vectors ... + /// + /// Insert or Update a Single Vector (Matched by Identifier) ... + /// + /// + /// + /// + /// + /// + /// + /// + public async Task UpsertVectorAsync( + string identifier, + string text, + ReadOnlyMemory embedding, + Dictionary metadata = null, + string type = null, + CancellationToken cancellationToken = default + ) + { + // + // Validate ... + if ( + embedding.IsEmpty || + text.IsNullOrEmpty() || + identifier.IsNullOrEmpty() + ) + { + XException.InvalidArgs.Throw(); + } + + // + var exists = await vectorRepository.FindOneAsync( + includeBuilder: null, + ignoreSoftDeleteds: true, + cancellationToken: cancellationToken, + predicate: x => x.Identifier == identifier + ); + var isExists = !exists.IsNullOrDefault(); + if (isExists) + { + // + exists.Text = text; + exists.Embedding = embedding.ToJSON(); + exists.Type = type.IsNullOrEmpty() ? exists.Type : type; + exists.Metadata = metadata.IsNullOrDefault() ? exists.Metadata : metadata.ToJSON(); + } + else + { + // + exists = new XAiVector + { + Text = text, + Type = type, + Identifier = identifier, + Metadata = metadata.ToJSON(), + Embedding = embedding.ToJSON(), + }; + } + + // + await vectorRepository.AddOrUpdateAsync( + item: exists, + saveChanges: true, + cancellationToken: cancellationToken + ); + } + + /// + /// Search Vectors by Cosine Similarity (Top K) ... + /// + /// + /// + /// + /// + /// + /// + /// + public async Task> SearchVectorsAsync( + ReadOnlyMemory queryEmbedding, + int topK = 5, + float minScore = 0f, + string identifierPrefix = null, + string type = null, + CancellationToken cancellationToken = default + ) + { + // + // Validate ... + if ( + topK <= 0 || + queryEmbedding.IsEmpty + ) + { + XException.InvalidArgs.Throw(); + } + + // + // Converts Question Vector to Vector Array ... + var queryVector = queryEmbedding.ToArray(); + var scoredResult = new List<(XAiVectorSearchResult Result, float Score)>(); + + // + // Load Candidates (Restricted by Prefix / Type when Provided) ... + var predicateExp = BuildVectorPredicateExpression(identifierPrefix, type); + IAsyncEnumerable candidates; + if (predicateExp.IsNull()) + { + // + candidates = vectorRepository + .GetAllAsAsyncEnumerable( + ignoreSoftDeleteds: true, + orderBuilder: null, + includeBuilder: null + ); + } + else + { + // + candidates = (await vectorRepository + .FindManyAsync( + predicate: predicateExp, + ignoreSoftDeleteds: true, + orderBuilder: null, + includeBuilder: null, + cancellationToken: cancellationToken + )) + .ToAsyncEnumerable(); + } + + // + await foreach (var vector in candidates.WithCancellation(cancellationToken)) + { + // + // Validate Vector ... + if (vector.Embedding.IsNullOrEmpty()) + { + continue; + } + + // + // Ignore Unsame Vectors ... + var embd = vector.Embedding.AsEmbedding(); + if ( + embd.IsNull() || + embd.Length != queryEmbedding.Length + ) + { + continue; + } + + // + // Calculate Cosine Similarity Score ... + var score = VectorHelper.CosineSimilarity(queryVector, embd); + if (score < minScore) + { + continue; + } + + // + scoredResult.Add((new XAiVectorSearchResult + { + // + Score = score, + Id = vector.Id, + Text = vector.Text, + Type = vector.Type, + Identifier = vector.Identifier, + Metadata = vector.Metadata.AsMetadat(), + }, score)); + } + + // + var result = scoredResult + .OrderByDescending(x => x.Score) + .Take(topK) + .Select(x => x.Result) + .ToList(); + + // + return result; + } + + /// + /// Insert or Update a Batch of Vectors (Matched by Identifier) ... + /// + /// + /// + /// Count of Stored Vectors + public async Task UpsertVectorsAsync( + IEnumerable items, + CancellationToken cancellationToken = default + ) + { + // + // Validate & Normalize (Last One Wins on Duplicate Identifiers) ... + var validItems = (items ?? []) + .Where(x => + !x.IsNullOrDefault() && + !x.Embedding.IsEmpty && + !x.Text.IsNullOrEmpty() && + !x.Identifier.IsNullOrEmpty() + ) + .GroupBy(x => x.Identifier) + .Select(g => g.Last()) + .ToList(); + if (!validItems.HasChild()) + { + return 0; + } + + // + // Load Existing Vectors with Same Identifiers ... + var identifiers = validItems + .Select(x => x.Identifier) + .ToList(); + var existings = await vectorRepository.FindManyAsync( + ignoreSoftDeleteds: true, + cancellationToken: cancellationToken, + predicate: x => identifiers.Contains(x.Identifier) + ); + var existingMap = (existings ?? []) + .GroupBy(x => x.Identifier) + .ToDictionary(g => g.Key, g => g.First()); + + // + // Split to Insert / Update ... + var toAdd = new List(); + var toUpdate = new List(); + foreach (var item in validItems) + { + // + if (existingMap.TryGetValue(item.Identifier, out var exists)) + { + // + exists.Text = item.Text; + exists.Embedding = item.Embedding.ToJSON(); + exists.Type = item.Type.IsNullOrEmpty() ? exists.Type : item.Type; + exists.Metadata = item.Metadata.IsNullOrDefault() ? exists.Metadata : item.Metadata.ToJSON(); + toUpdate.Add(exists); + } + else + { + // + toAdd.Add(new XAiVector + { + Text = item.Text, + Type = item.Type, + Identifier = item.Identifier, + Metadata = item.Metadata.ToJSON(), + Embedding = item.Embedding.ToJSON(), + Id = item.Id.IsDefaultGuid() ? Guid.NewGuid() : item.Id, + }); + } + } + + // + if (toUpdate.HasChild()) + { + await vectorRepository.UpdateRangeAsync( + items: toUpdate, + saveChanges: false, + cancellationToken: cancellationToken + ); + } + if (toAdd.HasChild()) + { + await vectorRepository.AddRangeAsync( + items: toAdd, + saveChanges: false, + cancellationToken: cancellationToken + ); + } + + // + await vectorRepository.SaveChangesAsync(cancellationToken); + + // + var result = toAdd.Count + toUpdate.Count; + return result; + } + + /// + /// Load Vectors whose Identifier Starts with Specified Prefix ... + /// + /// + /// + /// + /// + /// + public async Task> LoadVectorsAsync( + string identifierPrefix, + bool includeEmbedding = false, + string type = null, + CancellationToken cancellationToken = default + ) + { + // + // Validate ... + if (identifierPrefix.IsNullOrEmpty()) + { + XException.InvalidArgs.Throw(); + } + + // + var vectors = await vectorRepository.FindManyAsync( + ignoreSoftDeleteds: true, + cancellationToken: cancellationToken, + predicate: BuildVectorPredicateExpression(identifierPrefix, type) + ); + + // + var result = (vectors ?? []) + .Select(v => new XAiVectorDto + { + Id = v.Id, + Text = v.Text, + Type = v.Type, + Identifier = v.Identifier, + Metadata = v.Metadata.AsMetadat(), + Embedding = includeEmbedding ? v.Embedding.AsEmbedding() : null, + }) + .ToList(); + + // + return result; + } + + /// + /// Remove Vectors whose Identifier Starts with Specified Prefix ... + /// + /// + /// + /// + /// Count of Removed Vectors + public async Task RemoveVectorsAsync( + string identifierPrefix, + string type = null, + CancellationToken cancellationToken = default + ) + { + // + // Validate ... + if (identifierPrefix.IsNullOrEmpty()) + { + XException.InvalidArgs.Throw(); + } + + // + var vectors = await vectorRepository.FindManyAsync( + ignoreSoftDeleteds: true, + cancellationToken: cancellationToken, + predicate: BuildVectorPredicateExpression(identifierPrefix, type) + ); + var toRemove = (vectors ?? []).ToList(); + if (!toRemove.HasChild()) + { + return 0; + } + + // + // Hard Delete (Vectors are Disposable Data) ... + await vectorRepository.RemoveRangeAsync( + items: toRemove, + softDelete: false, + saveChanges: true, + cancellationToken: cancellationToken + ); + + // + var result = toRemove.Count; + return result; + } + #endregion + + // + #region Enrichers ... + /// + /// Enrich Specified Item ... + /// + /// + /// + /// + public async Task Enrich( + XAiVector source, + CancellationToken cancellationToken = default + ) + { + // + var result = await vectorEnricher.Enrich( + source: source, + cancellationToken: cancellationToken + ); + + // + return result; + } + + /// + /// Enrich Specified Items ... + /// + /// + /// + /// + public async Task> EnrichRange( + IEnumerable sources, + CancellationToken cancellationToken = default + ) + { + // + var result = await vectorEnricher.EnrichRange( + sources: sources, + cancellationToken: cancellationToken + ); + + // + return result; + } + + /// + /// Enrich Specified Item ... + /// + /// + /// + /// + public async Task Enrich( + XAiVectorDto source, + CancellationToken cancellationToken = default + ) + { + // + var result = await vectorEnricher.Enrich( + source: source, + cancellationToken: cancellationToken + ); + + // + return result; + } + + /// + /// Enrich Specified Items ... + /// + /// + /// + /// + public async Task> EnrichRange( + IEnumerable sources, + CancellationToken cancellationToken = default + ) + { + // + var result = await vectorEnricher.EnrichRange( + sources: sources, + cancellationToken: cancellationToken + ); + + // + return result; + } + + /// + /// Enrich Specified Item ... + /// + /// + /// + /// + /// + /// + public async Task Enrich( + XAiProjectDto source, + bool fillConversations = false, + bool fillConversationMessages = false, + CancellationToken cancellationToken = default + ) + { + // + var result = await projectEnricher.Enrich( + source: source, + fillConversations: fillConversations, + cancellationToken: cancellationToken, + fillConversationMessages: fillConversationMessages + ); + + // + return result; + } + + /// + /// Enrich Specified Items ... + /// + /// + /// + /// + /// + /// + public async Task> EnrichRange( + IEnumerable sources, + bool fillConversations = false, + bool fillConversationMessages = false, + CancellationToken cancellationToken = default + ) + { + // + var result = await projectEnricher.EnrichRange( + sources: sources, + fillConversations: fillConversations, + cancellationToken: cancellationToken, + fillConversationMessages: fillConversationMessages + ); + + // + return result; + } + + /// + /// Enrich Specified Item ... + /// + /// + /// + /// + /// + public async Task Enrich( + XAiConversationDto source, + bool fillMessages = false, + CancellationToken cancellationToken = default + ) + { + // + var result = await conversationEnricher.Enrich( + source: source, + fillMessages: fillMessages, + cancellationToken: cancellationToken + ); + + // + return result; + } + + /// + /// Enrich Specified Items ... + /// + /// + /// + /// + /// + public async Task> EnrichRange( + IEnumerable sources, + bool fillMessages = false, + CancellationToken cancellationToken = default + ) + { + // + var result = await conversationEnricher.EnrichRange( + sources: sources, + fillMessages: fillMessages, + cancellationToken: cancellationToken + ); + + // + return result; + } + + /// + /// Enrich Specified Item ... + /// + /// + /// + /// + public async Task Enrich( + XAiMessageDto source, + CancellationToken cancellationToken = default + ) + { + // + var result = await messageEnricher.Enrich( + source: source, + cancellationToken: cancellationToken + ); + + // + return result; + } + + /// + /// Enrich Specified Items ... + /// + /// + /// + /// + public async Task> EnrichRange( + IEnumerable sources, + CancellationToken cancellationToken = default + ) + { + // + var result = await messageEnricher.EnrichRange( + sources: sources, + cancellationToken: cancellationToken + ); + + // + return result; + } + #endregion + + // + #region Private ... + /// + /// Check Default Project Exists or not ... + /// + /// + /// + /// + private async Task HasDefaultProject( + string ownerId, + CancellationToken cancellationToken = default + ) + { + // + // Validate Args ... + var result = !ownerId.IsNullOrEmpty(); + if (!result) + { + return result; + } + + // + // Check Default Owner Exists or not ... + var defaultProjectResource = await stringProvider.FindOne( + cancellationToken: cancellationToken, + predicate: x => + x.ResourceTitle + .ToNormalString() + .Contains(ownerId.ToNormalString()) && + x.ResourceTitle + .ToNormalString() + .Contains(XAiModelsConstants.XAiProjectTitleIdentifier.ToNormalString()) && + x.TranslatedValue + .ToNormalString() + .Contains(XAiDataProviderConstants.XDefaultAiProjectSuffix.ToNormalString()) + ); + result = !defaultProjectResource.IsNullOrDefault(); + + // + return result; + } + + /// + /// Create Default Project for Specified Owner ... + /// + /// + /// + /// + /// + private async Task CreateDefaultProject( + string ownerId, + string connectionId = null, + CancellationToken cancellationToken = default + ) + { + // + if (ownerId.IsNullOrEmpty()) + { + return; + } + + // + var defaultLang = appConfiguration.DefaultLanguage; + + // + // Check Default Owner Exists or not ... + var isExists = await HasDefaultProject( + ownerId: ownerId, + cancellationToken: cancellationToken + ); + if (isExists) + { + return; + } + + // + // Create Default ... + var item = new XAiProjectDto() + { + OwnerId = ownerId, + CreatedOn = DateTime.UtcNow, + Title = Guid.NewGuid().ToString(), + Description = Guid.NewGuid().ToString(), + }; + item = await projectRepositoryService.AddAsync( + item: item, + saveChanges: true, + cancellationToken: cancellationToken + ); + + // + // Prepare Tile and Description Resource Ids ... + var titleResource = await projectTitleResourceProvider.AddOrUpdateLocale( + owner: ownerId, + identifier: item.Id, + locale: new XLocaleResourceDto + { + Language = defaultLang, + Value = XAiDataProviderConstants.XDefaultAiProjectSuffix + }, + cancellationToken: cancellationToken + ); + var descriptionResource = await projectDescriptionResourceProvider.AddOrUpdateLocale( + owner: ownerId, + identifier: item.Id, + new XLocaleResourceDto + { + Language = defaultLang, + Value = XAiDataProviderConstants.XDefaultAiProjectSuffix + }, + cancellationToken: cancellationToken + ); + if (titleResource.IsNullOrDefault() || + descriptionResource.IsNullOrDefault() + ) + { + return; + } + + // + // Update Project Resources ... + item.Title = titleResource.Resource; + item.Description = descriptionResource.Resource; + item = await projectRepositoryService.UpdateAsync( + id: item.Id, + item: item, + saveChanges: true, + cancellationToken: cancellationToken + ); + + // + // Sending Push ... + if (!connectionId.IsNullOrEmpty()) + { + // + await SendPush( + connectionId: connectionId, + cancellationToken: cancellationToken, + payLoad: item.ToJSON(camelCase: true), + action: XAiDataProviderHubActions.ProjectCreated.GetStringValue() + ); + } + } + + /// + /// Check Default Conversation Exists or not ... + /// + /// + /// + /// + /// + /// + private async Task HasDefaultConversation( + string ownerId, + Guid projectId, + string connectionId = null, + CancellationToken cancellationToken = default + ) + { + // + // Validate Args ... + var result = !ownerId.IsNullOrEmpty(); + if (!result) + { + return result; + } + + // + // Prepare Project ... + XAiProjectDto project = null; + if (projectId.IsNull() || + projectId.IsDefaultGuid() + ) + { + // + project = await GetDefaultProject( + ownerId: ownerId, + connectionId: connectionId, + cancellationToken: cancellationToken + ); + } + else + { + // + project = await projectRepositoryService.GetAsync( + id: projectId, + includeBuilder: null, + ignoreSoftDeleteds: true, + cancellationToken: cancellationToken + ); + } + if (project.IsNullOrDefault()) + { + XException.NotFound.Throw(); + } + + // + // Check Default Owner Exists or not ... + var resource = await stringProvider.FindOne( + cancellationToken: cancellationToken, + predicate: x => + x.ResourceTitle + .ToNormalString() + .Contains(ownerId.ToString().ToNormalString()) && + x.ResourceTitle + .ToNormalString() + .Contains(XAiModelsConstants.XAiConversationTitleIdentifier.ToNormalString()) && + x.TranslatedValue + .ToNormalString() + .Contains(XAiDataProviderConstants.XDefaultAiConversationSuffix.ToNormalString()) + ); + result = !resource.IsNullOrDefault(); + if (!result) + { + return result; + } + + // + var defaultConversation = await conversationRepositoryService.FindOneAsync( + cancellationToken: cancellationToken, + predicate: x => + x.ProjectId == projectId && + x.Title == resource.ResourceTitle + ); + result = !defaultConversation.IsNullOrDefault(); + + // + return result; + } + + /// + /// Check Default Conversation Exists or not ... + /// + /// + /// + /// + /// + /// + private async Task CreateDefaultConversation( + string ownerId, + Guid projectId, + string connectionId = null, + CancellationToken cancellationToken = default + ) + { + // + // Validate Args ... + var isValid = !ownerId.IsNullOrEmpty(); + if (!isValid) + { + return; + } + + // + var defaultLang = appConfiguration.DefaultLanguage; + + // + // Prepare Project ... + XAiProjectDto project = null; + if (projectId.IsNull() || + projectId.IsDefaultGuid() + ) + { + // + project = await GetDefaultProject( + ownerId: ownerId, + connectionId: connectionId, + cancellationToken: cancellationToken + ); + } + else + { + // + project = await projectRepositoryService.GetAsync( + id: projectId, + includeBuilder: null, + ignoreSoftDeleteds: true, + cancellationToken: cancellationToken + ); + } + if (project.IsNullOrDefault()) + { + XException.NotFound.Throw(); + } + + // + // Check Default Owner Exists or not ... + isValid = await HasDefaultConversation( + ownerId: ownerId, + projectId: project.Id, + cancellationToken: cancellationToken + ); + if (isValid) + { + return; + } + + // + // Create Default Conversation ... + var item = new XAiConversationDto + { + OwnerId = ownerId, + ProjectId = project.Id, + CreatedOn = DateTime.UtcNow, + Title = Guid.NewGuid().ToString() + }; + item = await conversationRepositoryService.AddAsync( + item: item, + saveChanges: true, + cancellationToken: cancellationToken + ); + + // + // Prepare Title Resource Ids ... + var titleResource = await conversationTitleResourceProvider.AddOrUpdateLocale( + owner: ownerId, + identifier: item.Id, + locale: new XLocaleResourceDto + { + Language = defaultLang, + Value = XAiDataProviderConstants.XDefaultAiConversationSuffix + }, + cancellationToken: cancellationToken + ); + if (titleResource.IsNullOrDefault()) + { + return; + } + + // + // Update Conversation Resources ... + item.Title = titleResource.Resource; + item = await conversationRepositoryService.UpdateAsync( + item: item, + id: item.Id, + saveChanges: true, + cancellationToken: cancellationToken + ); + + // + // Sending Push ... + if (!connectionId.IsNullOrEmpty()) + { + // + await SendPush( + connectionId: connectionId, + cancellationToken: cancellationToken, + payLoad: item.ToJSON(camelCase: true), + action: XAiDataProviderHubActions.ConversationCreated.GetStringValue() + ); + } + } + + /// + /// 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.ProjectCreated.GetStringValue(), + XAiDataProviderHubActions.ProjectUpdated.GetStringValue(), + XAiDataProviderHubActions.ProjectRemoved.GetStringValue(), + XAiDataProviderHubActions.MessageCreated.GetStringValue(), + XAiDataProviderHubActions.MessageUpdated.GetStringValue(), + XAiDataProviderHubActions.MessageRemoved.GetStringValue(), + XAiDataProviderHubActions.ConversationCreated.GetStringValue(), + XAiDataProviderHubActions.ConversationUpdated.GetStringValue(), + XAiDataProviderHubActions.ConversationRemoved.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 { } + } + + /// + /// Build Database Predicate Expression for Vectors by Optional Identifier Prefix and Type ... + /// Returns null when no Filter Provided ... + /// + /// + /// + /// + private Expression> BuildVectorPredicateExpression( + string identifierPrefix, + string type + ) + { + // + Expression> result = null; + + // + var hasType = !type.IsNullOrEmpty(); + var hasPrefix = !identifierPrefix.IsNullOrEmpty(); + + // + if (hasPrefix && hasType) + { + // + result = x => x.Identifier + .StartsWith(identifierPrefix) && x.Type == type; + } + else if (hasPrefix) + { + // + result = x => x.Identifier + .StartsWith(identifierPrefix); + } + else if (hasType) + { + result = x => x.Type == type; + } + + // + return result; + } + #endregion + } +} + +### FILE: C:\Users\saherelm\Documents\Projects\xSaherelmWorkspace\Modules\xAiModels\Providers\XAiMessageEntityRegisterar.cs + +using System; +using xDataService.Providers; +using xDataService.Interfaces; +using xAiModels.Models.Entities; +using Microsoft.EntityFrameworkCore; +using xAiModels.Configurations.Entities; + +namespace xAiModels.Providers +{ + public class XAiMessageEntityRegisterar : XBaseEntityRegisterar, IXEntityRegisterar + { + public XAiMessageEntityRegisterar() + : base(nameof(XAiMessageEntityRegisterar)) + { + // + // Add Entity ... + AddEntity(); + } + + /// + /// Configure Entities ... + /// + /// + public override void ConfigureEntities(ModelBuilder modelBuilder) + { + // + // Configure Entity Using Provided ... + modelBuilder + .ApplyConfigurationsFromAssembly(typeof(XAiMessageEntityConfiguration).Assembly); + + // + base.ConfigureEntities(modelBuilder); + } + } +} + +### FILE: C:\Users\saherelm\Documents\Projects\xSaherelmWorkspace\Modules\xAiModels\Providers\XAiProjectDescriptionResourceProvider.cs + +using xAiModels.Constants; +using xAiModels.Interfaces; +using xCommons.Configurations; +using xStringService.Providers; +using xStringService.Interfaces.Dtos; + +namespace xAiModels.Providers +{ + public class XAiProjectDescriptionResourceProvider : XBaseOwnedItemResourceProvider, IXAiProjectDescriptionResourceProvider + { + public XAiProjectDescriptionResourceProvider( + XAppConfiguration appConfig, + IXStringServiceProvider stringProvider + ) : base( + appConfig: appConfig, + stringProvider: stringProvider, + item: XAiModelsConstants.XAiProjectDescriptionIdentifier + ) + { } + } +} + +### FILE: C:\Users\saherelm\Documents\Projects\xSaherelmWorkspace\Modules\xAiModels\Providers\XAiProjectEntityRegisterar.cs + +using System; +using xDataService.Providers; +using xDataService.Interfaces; +using xAiModels.Models.Entities; +using Microsoft.EntityFrameworkCore; +using xAiModels.Configurations.Entities; + +namespace xAiModels.Providers +{ + public class XAiProjectEntityRegisterar : XBaseEntityRegisterar, IXEntityRegisterar + { + public XAiProjectEntityRegisterar() + : base(nameof(XAiProjectEntityRegisterar)) + { + // + // Add Entity ... + AddEntity(); + } + + /// + /// Configure Entities ... + /// + /// + public override void ConfigureEntities(ModelBuilder modelBuilder) + { + // + // Configure Entity Using Provided ... + modelBuilder + .ApplyConfigurationsFromAssembly(typeof(XAiProjectEntityConfiguration).Assembly); + + // + base.ConfigureEntities(modelBuilder); + } + } +} + +### FILE: C:\Users\saherelm\Documents\Projects\xSaherelmWorkspace\Modules\xAiModels\Providers\XAiProjectTitleResourceProvider.cs + +using xAiModels.Constants; +using xAiModels.Interfaces; +using xCommons.Configurations; +using xStringService.Providers; +using xStringService.Interfaces.Dtos; + +namespace xAiModels.Providers +{ + public class XAiProjectTitleResourceProvider : XBaseOwnedItemResourceProvider, IXAiProjectTitleResourceProvider + { + public XAiProjectTitleResourceProvider( + XAppConfiguration appConfig, + IXStringServiceProvider stringProvider + ) : base( + appConfig: appConfig, + stringProvider: stringProvider, + item: XAiModelsConstants.XAiProjectTitleIdentifier + ) + { } + } +} + +### FILE: C:\Users\saherelm\Documents\Projects\xSaherelmWorkspace\Modules\xAiModels\Providers\XAiVectorEntityRegisterar.cs + +using System; +using xDataService.Providers; +using xDataService.Interfaces; +using xAiModels.Models.Entities; +using Microsoft.EntityFrameworkCore; +using xAiModels.Configurations.Entities; + +namespace xAiModels.Providers +{ + public class XAiVectorEntityRegisterar : XBaseEntityRegisterar, IXEntityRegisterar + { + public XAiVectorEntityRegisterar() + : base(nameof(XAiVectorEntityRegisterar)) + { + // + // Add Entity ... + AddEntity(); + } + + /// + /// Configure Entities ... + /// + /// + public override void ConfigureEntities(ModelBuilder modelBuilder) + { + // + // Configure Entity Using Provided ... + modelBuilder + .ApplyConfigurationsFromAssembly(typeof(XAiVectorEntityConfiguration).Assembly); + + // + base.ConfigureEntities(modelBuilder); + } + } +} + +### FILE: C:\Users\saherelm\Documents\Projects\xSaherelmWorkspace\Modules\xAiModels\Providers\Dtos\XAiConversationDtoHub.cs + +using System; +using xPushService.Base; +using xAiModels.Models.Dtos; +using xAiModels.Interfaces.Dtos; +using xAiModels.Models.Entities; +using Microsoft.Extensions.Logging; + +namespace xAiModels.Providers.Dtos +{ + public class XAiConversationDtoHub : XBaseDtoHub, IXAiConversationDtoHub + { + public XAiConversationDtoHub( + ILogger logger + ) : base(logger) + { } + } +} + +### FILE: C:\Users\saherelm\Documents\Projects\xSaherelmWorkspace\Modules\xAiModels\Providers\Dtos\XAiConversationRepositoryService.cs + +using System; +using System.Linq; +using xModels.Dtos; +using System.Threading; +using xCommons.Extensions; +using xAiModels.Interfaces; +using xAiModels.Models.Dtos; +using System.Threading.Tasks; +using xDataService.Providers; +using xAiModels.Configurations; +using xAiModels.Interfaces.Dtos; +using xAiModels.Models.Entities; +using System.Collections.Generic; +using xIdentityService.Interfaces; +using xIdentityService.Extensions; +using xAiModels.Interfaces.Entities; + +namespace xAiModels.Providers.Dtos +{ + public class XAiConversationRepositoryService : XBaseRepositoryService, IXAiConversationRepositoryService + { + private readonly IXIdentityProvider identityProvider; + private readonly IXAiConversationRepository repository; + private readonly IXAiProjectTitleResourceProvider projectTitleResourceProvider; + private readonly IXAiConversationTitleResourceProvider conversationTitleResourceProvider; + private readonly IXAiProjectDescriptionResourceProvider projectDescriptionResourceProvider; + + public XAiConversationRepositoryService( + IXIdentityProvider identityProvider, + IXAiConversationRepository repository, + IXAiProjectTitleResourceProvider projectTitleResourceProvider, + IXAiConversationTitleResourceProvider conversationTitleResourceProvider, + IXAiProjectDescriptionResourceProvider projectDescriptionResourceProvider + ) : base( + repository, + mapperProfiles: + [ + new XAiModelMappersProfile() + ] + ) + { + this.repository = repository; + this.identityProvider = identityProvider; + this.projectTitleResourceProvider = projectTitleResourceProvider; + this.conversationTitleResourceProvider = conversationTitleResourceProvider; + this.projectDescriptionResourceProvider = projectDescriptionResourceProvider; + } + + // + #region Enrichers ... + /// + /// Enrich Specified Item ... + /// + /// + /// + /// + /// + public virtual async Task Enrich( + XAiConversation source, + bool fillMessages = false, + CancellationToken cancellationToken = default + ) + { + // + // Mapping Default ... + var result = Mapper.Map(source); + result = await Enrich( + source: result, + fillMessages: fillMessages, + cancellationToken: cancellationToken + ); + + // + return result; + } + + /// + /// Enrich Specified Item ... + /// + /// + /// + /// + /// + public virtual async Task Enrich( + XAiConversationDto source, + bool fillMessages = false, + CancellationToken cancellationToken = default + ) + { + // + // Handdle Owner ... + XPersonDto owner = null; + if (!source.OwnerId.IsNullOrEmpty()) + { + // + // Try to Retrieve User Info ... + var device = identityProvider.GetDevice(); + var userInfo = await identityProvider.GetUserInfo( + device: device, + userSelectByParam: source.OwnerId + ); + owner = userInfo.ToXPersonDto(); + } + + // + // Handle Title Resource ... + XResourceDto titleResource = null; + if (!source.Title.IsNullOrEmpty()) + { + // + titleResource = await conversationTitleResourceProvider.GetResource( + owner: source.OwnerId, + identifier: source.Id, + cancellationToken: cancellationToken + ); + } + + // + // Handle Project Info ... + XResourceDto projectTitleResource = null; + XResourceDto projectDescriptionResource = null; + if (!source.ProjectId.IsDefaultGuid()) + { + // + projectTitleResource = await projectTitleResourceProvider.GetResource( + owner: source.OwnerId, + identifier: source.ProjectId, + cancellationToken: cancellationToken + ); + + // + projectDescriptionResource = await projectDescriptionResourceProvider.GetResource( + owner: source.OwnerId, + identifier: source.ProjectId, + cancellationToken: cancellationToken + ); + } + + // + // Attach Extracted Items ... + var result = Mapper.Map(source, options => + { + // + options.Items[nameof(source.Owner)] = owner; + options.Items[nameof(source.TitleResource)] = titleResource; + options.Items[nameof(source.ProjectTitleResource)] = projectTitleResource; + options.Items[nameof(source.ProjectDescriptionResource)] = projectDescriptionResource; + }); + + // + return result; + } + + /// + /// Enrich Specified Items ... + /// + /// + /// + /// + /// + public virtual async Task> EnrichRange( + IEnumerable sources, + bool fillMessages = false, + CancellationToken cancellationToken = default + ) + { + // + var tasks = sources + .Select(x => Enrich( + source: x, + fillMessages: fillMessages, + cancellationToken: cancellationToken + )); + + // + var result = await Task.WhenAll(tasks); + return result; + } + + /// + /// Enrich Specified Items ... + /// + /// + /// + /// + /// + public virtual async Task> EnrichRange( + IEnumerable sources, + bool fillMessages = false, + CancellationToken cancellationToken = default + ) + { + // + var tasks = sources + .Select(x => Enrich( + source: x, + fillMessages: fillMessages, + cancellationToken: cancellationToken + )); + + // + var result = await Task.WhenAll(tasks); + return result; + } + #endregion + } +} + +### FILE: C:\Users\saherelm\Documents\Projects\xSaherelmWorkspace\Modules\xAiModels\Providers\Dtos\XAiConversationServiceProvider.cs + +using System; +using xPushService.Base; +using xAiModels.Models.Dtos; +using xAiModels.Interfaces.Dtos; +using xAiModels.Models.Entities; +using xDataService.Configuration; +using xIdentityService.Interfaces; +using Microsoft.AspNetCore.SignalR; + +namespace xAiModels.Providers.Dtos +{ + public class XAiConversationServiceProvider : XBaseDtoProvider, IXAiConversationServiceProvider + { + public XAiConversationServiceProvider( + IHubContext hub, + XDataServiceConfiguration dataConfiguration, + IXAiConversationRepositoryService service, + IXIdentityProvider identityProvider = null + ) : base( + hub, + dataConfiguration, + service, + identityProvider + ) + { } + } +} + +### FILE: C:\Users\saherelm\Documents\Projects\xSaherelmWorkspace\Modules\xAiModels\Providers\Dtos\XAiMessageDtoHub.cs + +using System; +using xPushService.Base; +using xAiModels.Models.Dtos; +using xAiModels.Interfaces.Dtos; +using xAiModels.Models.Entities; +using Microsoft.Extensions.Logging; + +namespace xAiModels.Providers.Dtos +{ + public class XAiMessageDtoHub : XBaseDtoHub, IXAiMessageDtoHub + { + public XAiMessageDtoHub( + ILogger logger + ) : base(logger) + { } + } +} + +### FILE: C:\Users\saherelm\Documents\Projects\xSaherelmWorkspace\Modules\xAiModels\Providers\Dtos\XAiMessageRepositoryService.cs + +using System; +using System.Linq; +using xModels.Dtos; +using System.Threading; +using xCommons.Extensions; +using xAiModels.Interfaces; +using xAiModels.Models.Dtos; +using System.Threading.Tasks; +using xDataService.Providers; +using xAiModels.Configurations; +using xAiModels.Interfaces.Dtos; +using xAiModels.Models.Entities; +using System.Collections.Generic; +using xIdentityService.Interfaces; +using xIdentityService.Extensions; +using xAiModels.Interfaces.Entities; + +namespace xAiModels.Providers.Dtos +{ + public class XAiMessageRepositoryService : XBaseRepositoryService, IXAiMessageRepositoryService + { + private readonly IXIdentityProvider identityProvider; + private readonly IXAiConversationTitleResourceProvider conversationTitleResourceProvider; + + public XAiMessageRepositoryService( + IXAiMessageRepository repository, + IXIdentityProvider identityProvider, + IXAiConversationTitleResourceProvider conversationTitleResourceProvider + ) : base( + repository, + mapperProfiles: + [ + new XAiModelMappersProfile() + ] + ) + { + this.identityProvider = identityProvider; + this.conversationTitleResourceProvider = conversationTitleResourceProvider; + } + + // + #region Enrichers ... + /// + /// Enrich Specified Item ... + /// + /// + /// + /// + public virtual async Task Enrich( + XAiMessage source, + CancellationToken cancellationToken = default + ) + { + // + // Mapping Default ... + var result = Mapper.Map(source); + result = await Enrich( + source: result, + cancellationToken: cancellationToken + ); + + // + return result; + } + + /// + /// Enrich Specified Item ... + /// + /// + /// + /// + public virtual async Task Enrich( + XAiMessageDto source, + CancellationToken cancellationToken = default + ) + { + // + // Handdle Owner ... + XPersonDto owner = null; + if (!source.OwnerId.IsNullOrEmpty()) + { + // + // Try to Retrieve User Info ... + var device = identityProvider.GetDevice(); + var userInfo = await identityProvider.GetUserInfo( + device: device, + userSelectByParam: source.OwnerId + ); + owner = userInfo.ToXPersonDto(); + } + + // + // Hanlde Conversation Title ... + string conversationTitle = string.Empty; + XResourceDto conversationTitleResource = null; + if (!source.ConversationId.IsDefaultGuid()) + { + // + conversationTitleResource = await conversationTitleResourceProvider.GetResource( + owner: source.OwnerId, + identifier: source.ConversationId, + cancellationToken: cancellationToken + ); + if (!conversationTitleResource.IsNullOrDefault()) + { + conversationTitle = conversationTitleResource.Resource; + } + } + + // + // Attach Extracted Items ... + var result = Mapper.Map(source, options => + { + // + options.Items[nameof(source.Owner)] = owner; + options.Items[nameof(source.ConversationTitle)] = conversationTitle; + options.Items[nameof(source.ConversationTitleResouce)] = conversationTitleResource; + }); + + // + return result; + } + + /// + /// Enrich Specified Items ... + /// + /// + /// + /// + public virtual async Task> EnrichRange( + IEnumerable sources, + CancellationToken cancellationToken = default + ) + { + // + var tasks = sources + .Select(x => Enrich(x, cancellationToken)); + + // + var result = await Task.WhenAll(tasks); + return result; + } + + /// + /// Enrich Specified Items ... + /// + /// + /// + /// + public virtual async Task> EnrichRange( + IEnumerable sources, + CancellationToken cancellationToken = default + ) + { + // + var tasks = sources + .Select(x => Enrich(x, cancellationToken)); + + // + var result = await Task.WhenAll(tasks); + return result; + } + #endregion + } +} + +### FILE: C:\Users\saherelm\Documents\Projects\xSaherelmWorkspace\Modules\xAiModels\Providers\Dtos\XAiMessageServiceProvider.cs + +using System; +using xPushService.Base; +using xAiModels.Models.Dtos; +using xAiModels.Interfaces.Dtos; +using xAiModels.Models.Entities; +using xDataService.Configuration; +using xIdentityService.Interfaces; +using Microsoft.AspNetCore.SignalR; + +namespace xAiModels.Providers.Dtos +{ + public class XAiMessageServiceProvider : XBaseDtoProvider, IXAiMessageServiceProvider + { + public XAiMessageServiceProvider( + IHubContext hub, + XDataServiceConfiguration dataConfiguration, + IXAiMessageRepositoryService service, + IXIdentityProvider identityProvider = null + ) : base( + hub, + dataConfiguration, + service, + identityProvider + ) + { } + } +} + +### FILE: C:\Users\saherelm\Documents\Projects\xSaherelmWorkspace\Modules\xAiModels\Providers\Dtos\XAiProjectDtoHub.cs + +using System; +using xPushService.Base; +using xAiModels.Models.Dtos; +using xAiModels.Interfaces.Dtos; +using xAiModels.Models.Entities; +using Microsoft.Extensions.Logging; + +namespace xAiModels.Providers.Dtos +{ + public class XAiProjectDtoHub : XBaseDtoHub, IXAiProjectDtoHub + { + public XAiProjectDtoHub( + ILogger logger + ) : base(logger) + { } + } +} + +### FILE: C:\Users\saherelm\Documents\Projects\xSaherelmWorkspace\Modules\xAiModels\Providers\Dtos\XAiProjectRepositoryService.cs + +using System; +using System.Linq; +using xModels.Dtos; +using System.Threading; +using xCommons.Extensions; +using xAiModels.Interfaces; +using xAiModels.Models.Dtos; +using System.Threading.Tasks; +using xDataService.Providers; +using xAiModels.Configurations; +using xAiModels.Interfaces.Dtos; +using xAiModels.Models.Entities; +using System.Collections.Generic; +using xIdentityService.Interfaces; +using xIdentityService.Extensions; +using xAiModels.Interfaces.Entities; + +namespace xAiModels.Providers.Dtos +{ + public class XAiProjectRepositoryService : XBaseRepositoryService, IXAiProjectRepositoryService + { + private readonly IXIdentityProvider identityProvider; + private readonly IXAiMessageRepository messageRepository; + private readonly IXAiConversationRepository conversationRepository; + private readonly IXAiProjectTitleResourceProvider projectTitleResourceProvider; + private readonly IXAiConversationTitleResourceProvider conversationTitleResourceProvider; + private readonly IXAiProjectDescriptionResourceProvider projectDescriptionResourceProvider; + + public XAiProjectRepositoryService( + IXAiProjectRepository repository, + IXIdentityProvider identityProvider, + IXAiMessageRepository messageRepository, + IXAiConversationRepository conversationRepository, + IXAiProjectTitleResourceProvider projectTitleResourceProvider, + IXAiConversationTitleResourceProvider conversationTitleResourceProvider, + IXAiProjectDescriptionResourceProvider projectDescriptionResourceProvider + ) : base( + repository, + mapperProfiles: + [ + new XAiModelMappersProfile() + ] + ) + { + // + this.identityProvider = identityProvider; + this.messageRepository = messageRepository; + this.conversationRepository = conversationRepository; + this.projectTitleResourceProvider = projectTitleResourceProvider; + this.conversationTitleResourceProvider = conversationTitleResourceProvider; + this.projectDescriptionResourceProvider = projectDescriptionResourceProvider; + } + + // + #region Enrichers ... + /// + /// Enrich Specified Item ... + /// + /// + /// + /// + /// + /// + public virtual async Task Enrich( + XAiProject source, + bool fillConversations = false, + bool fillConversationMessages = false, + CancellationToken cancellationToken = default + ) + { + // + // Mapping Default ... + var result = Mapper.Map(source); + result = await Enrich( + source: result, + fillConversations: fillConversations, + cancellationToken: cancellationToken, + fillConversationMessages: fillConversationMessages + ); + + // + return result; + } + + /// + /// Enrich Specified Item ... + /// + /// + /// + /// + /// + /// + public virtual async Task Enrich( + XAiProjectDto source, + bool fillConversations = false, + bool fillConversationMessages = false, + CancellationToken cancellationToken = default + ) + { + // + // Handle Owner ... + XPersonDto owner = null; + if (!source.OwnerId.IsNullOrEmpty()) + { + // + // Try to Retrieve User Info ... + var device = identityProvider.GetDevice(); + var userInfo = await identityProvider.GetUserInfo( + device: device, + userSelectByParam: source.OwnerId + ); + owner = userInfo.ToXPersonDto(); + } + + // + // Handle Title ... + XResourceDto titleResource = null; + if (!source.Title.IsNullOrEmpty()) + { + // + titleResource = await projectTitleResourceProvider.GetResource( + owner: source.OwnerId, + identifier: source.Id, + cancellationToken: cancellationToken + ); + } + + // + // Handle Description ... + XResourceDto descriptionResource = null; + if (!source.Description.IsNullOrEmpty()) + { + // + descriptionResource = await projectDescriptionResourceProvider.GetResource( + owner: source.OwnerId, + identifier: source.Id, + cancellationToken: cancellationToken + ); + } + + // + // Handle Conversations ... + IEnumerable conversations = []; + if (fillConversations) + { + // + // Reading Entities ... + var entitiies = await conversationRepository.FindManyAsync( + includeBuilder: null, + ignoreSoftDeleteds: true, + cancellationToken: cancellationToken, + predicate: x => x.ProjectId == source.Id, + orderBuilder: x => x.OrderBy(y => y.CreatedOn) + ); + + // + // Converts to Dto Enumerable ... + conversations = entitiies + .MapConvert(); + + // + // Handle Conversation Enrichment ... + foreach (var conversation in conversations) + { + // + // Handle Owner ... + if (!conversation.OwnerId.IsNullOrEmpty()) + { + conversation.Owner = owner; + } + + // + // Handle Title Resource ... + if (!conversation.Title.IsNullOrEmpty()) + { + // + conversation.TitleResource = await conversationTitleResourceProvider.GetResource( + owner: source.OwnerId, + identifier: conversation.Id, + cancellationToken: cancellationToken + ); + } + + // + // Handle Project Info ... + if (!conversation.ProjectId.IsDefaultGuid()) + { + conversation.ProjectTitle = source.Title; + conversation.ProjectTitleResource = titleResource; + conversation.ProjectDescription = source.Description; + conversation.ProjectDescriptionResource = descriptionResource; + } + } + + // + // Handle Fill Messages ... + if (fillConversationMessages) + { + // + foreach (var conversation in conversations) + { + // + IEnumerable messages = []; + + // + // Retrieve Message Entities ... + var messageEntities = await messageRepository.FindManyAsync( + includeBuilder: null, + ignoreSoftDeleteds: true, + cancellationToken: cancellationToken, + orderBuilder: x => x.OrderBy(y => y.CreatedOn), + predicate: x => x.ConversationId == conversation.Id + ); + if (messageEntities.HasChild()) + { + // + // Converts to Message ... + messages = messageEntities + .MapConvert(); + + // + // Ennrich Messages ... + foreach (var message in messages) + { + // + // Handle Owner ... + if (!message.OwnerId.IsNullOrEmpty()) + { + message.Owner = owner; + } + + // + // Handle Conversation ... + if (!message.ConversationId.IsDefaultGuid()) + { + message.ConversationTitle = conversation.Title; + message.ConversationTitleResouce = conversation.TitleResource; + } + } + } + + // + conversation.Messages = [.. messages]; + } + } + } + + // + // Attach Extracted Items ... + var result = Mapper.Map(source, options => + { + // + options.Items[nameof(source.Owner)] = owner; + options.Items[nameof(source.Conversations)] = conversations; + options.Items[nameof(source.TitleResource)] = titleResource; + options.Items[nameof(source.DescriptionResource)] = descriptionResource; + }); + + // + return result; + } + + /// + /// Enrich Specified Items ... + /// + /// + /// + /// + /// + /// + public virtual async Task> EnrichRange( + IEnumerable sources, + bool fillConversations = false, + bool fillConversationMessages = false, + CancellationToken cancellationToken = default + ) + { + // + var tasks = sources + .Select(x => Enrich( + source: x, + cancellationToken: cancellationToken, + fillConversations: fillConversations, + fillConversationMessages: fillConversationMessages + )); + + // + var result = await Task.WhenAll(tasks); + return result; + } + + /// + /// Enrich Specified Items ... + /// + /// + /// + /// + /// + /// + public virtual async Task> EnrichRange( + IEnumerable sources, + bool fillConversations = false, + bool fillConversationMessages = false, + CancellationToken cancellationToken = default + ) + { + // + var tasks = sources + .Select(x => Enrich( + source: x, + cancellationToken: cancellationToken, + fillConversations: fillConversations, + fillConversationMessages: fillConversationMessages + )); + + // + var result = await Task.WhenAll(tasks); + return result; + } + #endregion + } +} + +### FILE: C:\Users\saherelm\Documents\Projects\xSaherelmWorkspace\Modules\xAiModels\Providers\Dtos\XAiProjectServiceProvider.cs + +using System; +using xPushService.Base; +using xAiModels.Models.Dtos; +using xAiModels.Interfaces.Dtos; +using xAiModels.Models.Entities; +using xDataService.Configuration; +using xIdentityService.Interfaces; +using Microsoft.AspNetCore.SignalR; + +namespace xAiModels.Providers.Dtos +{ + public class XAiProjectServiceProvider : XBaseDtoProvider, IXAiProjectServiceProvider + { + public XAiProjectServiceProvider( + IHubContext hub, + XDataServiceConfiguration dataConfiguration, + IXAiProjectRepositoryService service, + IXIdentityProvider identityProvider = null + ) : base( + hub, + dataConfiguration, + service, + identityProvider + ) + { } + } +} + +### FILE: C:\Users\saherelm\Documents\Projects\xSaherelmWorkspace\Modules\xAiModels\Providers\Dtos\XAiVectorDtoHub.cs + +using System; +using xPushService.Base; +using xAiModels.Models.Dtos; +using xAiModels.Interfaces.Dtos; +using xAiModels.Models.Entities; +using Microsoft.Extensions.Logging; + +namespace xAiModels.Providers.Dtos +{ + public class XAiVectorDtoHub : XBaseDtoHub, IXAiVectorDtoHub + { + public XAiVectorDtoHub( + ILogger logger + ) : base(logger) + { } + } +} + +### FILE: C:\Users\saherelm\Documents\Projects\xSaherelmWorkspace\Modules\xAiModels\Providers\Dtos\XAiVectorRepositoryService.cs + +using System; +using xAiModels.Models.Dtos; +using xDataService.Providers; +using xAiModels.Configurations; +using xAiModels.Interfaces.Dtos; +using xAiModels.Models.Entities; +using xAiModels.Interfaces.Entities; + +namespace xAiModels.Providers.Dtos +{ + public class XAiVectorRepositoryService : XBaseRepositoryService, IXAiVectorRepositoryService + { + public XAiVectorRepositoryService( + IXAiVectorRepository repository + ) : base( + repository, + mapperProfiles: + [ + new XAiModelMappersProfile() + ] + ) + { } + } +} + +### FILE: C:\Users\saherelm\Documents\Projects\xSaherelmWorkspace\Modules\xAiModels\Providers\Dtos\XAiVectorServiceProvider.cs + +using System; +using xPushService.Base; +using xAiModels.Models.Dtos; +using xAiModels.Interfaces.Dtos; +using xAiModels.Models.Entities; +using xDataService.Configuration; +using xIdentityService.Interfaces; +using Microsoft.AspNetCore.SignalR; + +namespace xAiModels.Providers.Dtos +{ + public class XAiVectorServiceProvider : XBaseDtoProvider, IXAiVectorServiceProvider + { + public XAiVectorServiceProvider( + IHubContext hub, + XDataServiceConfiguration dataConfiguration, + IXAiVectorRepositoryService service, + IXIdentityProvider identityProvider = null + ) : base( + hub, + dataConfiguration, + service, + identityProvider + ) + { } + } +} + +### FILE: C:\Users\saherelm\Documents\Projects\xSaherelmWorkspace\Modules\xAiModels\Providers\Enrichers\XAiConversationEnricher.cs + +using System.Linq; +using xModels.Dtos; +using System.Threading; +using xCommons.Extensions; +using xAiModels.Interfaces; +using xAiModels.Models.Dtos; +using System.Threading.Tasks; +using xAiModels.Models.Entities; +using System.Collections.Generic; +using xIdentityService.Interfaces; +using xIdentityService.Extensions; +using xAiModels.Interfaces.Entities; +using xAiModels.Interfaces.Enrichers; + +namespace xAiModels.Providers.Enrichers +{ + public class XAiConversationEnricher : IXAiConversationEnricher + { + private readonly IXIdentityProvider identityProvider; + private readonly IXAiConversationRepository repository; + private readonly IXAiProjectTitleResourceProvider projectTitleResourceProvider; + private readonly IXAiConversationTitleResourceProvider conversationTitleResourceProvider; + private readonly IXAiProjectDescriptionResourceProvider projectDescriptionResourceProvider; + + public XAiConversationEnricher( + IXIdentityProvider identityProvider, + IXAiConversationRepository repository, + IXAiProjectTitleResourceProvider projectTitleResourceProvider, + IXAiConversationTitleResourceProvider conversationTitleResourceProvider, + IXAiProjectDescriptionResourceProvider projectDescriptionResourceProvider + ) + { + // + this.repository = repository; + this.identityProvider = identityProvider; + this.projectTitleResourceProvider = projectTitleResourceProvider; + this.conversationTitleResourceProvider = conversationTitleResourceProvider; + this.projectDescriptionResourceProvider = projectDescriptionResourceProvider; + } + + // + #region Enrichers ... + /// + /// Enrich Specified Item ... + /// + /// + /// + /// + /// + public virtual async Task Enrich( + XAiConversation source, + bool fillMessages = false, + CancellationToken cancellationToken = default + ) + { + // + // Mapping Default ... + var result = source.MapConvert(); + result = await Enrich( + source: result, + fillMessages: fillMessages, + cancellationToken: cancellationToken + ); + + // + return result; + } + + /// + /// Enrich Specified Item ... + /// + /// + /// + /// + /// + public virtual async Task Enrich( + XAiConversationDto source, + bool fillMessages = false, + CancellationToken cancellationToken = default + ) + { + // + // Handdle Owner ... + XPersonDto owner = null; + if (!source.OwnerId.IsNullOrEmpty()) + { + // + // Try to Retrieve User Info ... + var device = identityProvider.GetDevice(); + var userInfo = await identityProvider.GetUserInfo( + device: device, + userSelectByParam: source.OwnerId + ); + owner = userInfo.ToXPersonDto(); + } + + // + // Handle Title Resource ... + XResourceDto titleResource = null; + if (!source.Title.IsNullOrEmpty()) + { + // + titleResource = await conversationTitleResourceProvider.GetResource( + owner: source.OwnerId, + identifier: source.Id, + cancellationToken: cancellationToken + ); + } + + // + // Handle Project Info ... + XResourceDto projectTitleResource = null; + XResourceDto projectDescriptionResource = null; + if (!source.ProjectId.IsDefaultGuid()) + { + // + projectTitleResource = await projectTitleResourceProvider.GetResource( + owner: source.OwnerId, + identifier: source.ProjectId, + cancellationToken: cancellationToken + ); + + // + projectDescriptionResource = await projectDescriptionResourceProvider.GetResource( + owner: source.OwnerId, + identifier: source.ProjectId, + cancellationToken: cancellationToken + ); + } + + // + // Attach Extracted Items ... + var result = source.MapConvert(); + result.Owner = owner; + result.TitleResource = titleResource; + result.ProjectTitleResource = projectTitleResource; + result.ProjectTitle = projectTitleResource.Resource; + result.ProjectDescriptionResource = projectDescriptionResource; + result.ProjectDescription = projectDescriptionResource.Resource; + + // + return result; + } + + /// + /// Enrich Specified Items ... + /// + /// + /// + /// + /// + public virtual async Task> EnrichRange( + IEnumerable sources, + bool fillMessages = false, + CancellationToken cancellationToken = default + ) + { + // + var tasks = sources + .Select(x => Enrich( + source: x, + fillMessages: fillMessages, + cancellationToken: cancellationToken + )); + + // + var result = await Task.WhenAll(tasks); + return result; + } + + /// + /// Enrich Specified Items ... + /// + /// + /// + /// + /// + public virtual async Task> EnrichRange( + IEnumerable sources, + bool fillMessages = false, + CancellationToken cancellationToken = default + ) + { + // + var tasks = sources + .Select(x => Enrich( + source: x, + fillMessages: fillMessages, + cancellationToken: cancellationToken + )); + + // + var result = await Task.WhenAll(tasks); + return result; + } + #endregion + } +} + +### FILE: C:\Users\saherelm\Documents\Projects\xSaherelmWorkspace\Modules\xAiModels\Providers\Enrichers\XAiMessageEnricher.cs + +using System.Linq; +using xModels.Dtos; +using System.Threading; +using xCommons.Extensions; +using xAiModels.Interfaces; +using xAiModels.Models.Dtos; +using System.Threading.Tasks; +using xAiModels.Models.Entities; +using System.Collections.Generic; +using xIdentityService.Interfaces; +using xIdentityService.Extensions; +using xAiModels.Interfaces.Enrichers; + +namespace xAiModels.Providers.Enrichers +{ + public class XAiMessageEnricher : IXAiMessageEnricher + { + private readonly IXIdentityProvider identityProvider; + private readonly IXAiConversationTitleResourceProvider conversationTitleResourceProvider; + + public XAiMessageEnricher( + IXIdentityProvider identityProvider, + IXAiConversationTitleResourceProvider conversationTitleResourceProvider + ) + { + this.identityProvider = identityProvider; + this.conversationTitleResourceProvider = conversationTitleResourceProvider; + } + + // + #region Enrichers ... + /// + /// Enrich Specified Item ... + /// + /// + /// + /// + public virtual async Task Enrich( + XAiMessage source, + CancellationToken cancellationToken = default + ) + { + // + // Mapping Default ... + var result = source.MapConvert(); + result = await Enrich( + source: result, + cancellationToken: cancellationToken + ); + + // + return result; + } + + /// + /// Enrich Specified Item ... + /// + /// + /// + /// + public virtual async Task Enrich( + XAiMessageDto source, + CancellationToken cancellationToken = default + ) + { + // + // Handdle Owner ... + XPersonDto owner = null; + if (!source.OwnerId.IsNullOrEmpty()) + { + // + // Try to Retrieve User Info ... + var device = identityProvider.GetDevice(); + var userInfo = await identityProvider.GetUserInfo( + device: device, + userSelectByParam: source.OwnerId + ); + owner = userInfo.ToXPersonDto(); + } + + // + // Hanlde Conversation Title ... + string conversationTitle = string.Empty; + XResourceDto conversationTitleResource = null; + if (!source.ConversationId.IsDefaultGuid()) + { + // + conversationTitleResource = await conversationTitleResourceProvider.GetResource( + owner: source.OwnerId, + identifier: source.ConversationId, + cancellationToken: cancellationToken + ); + if (!conversationTitleResource.IsNullOrDefault()) + { + conversationTitle = conversationTitleResource.Resource; + } + } + + // + // Attach Extracted Items ... + var result = source.MapConvert(); + result.Owner = owner; + result.ConversationTitle = conversationTitle; + result.ConversationTitleResouce = conversationTitleResource; + + // + return result; + } + + /// + /// Enrich Specified Items ... + /// + /// + /// + /// + public virtual async Task> EnrichRange( + IEnumerable sources, + CancellationToken cancellationToken = default + ) + { + // + var tasks = sources + .Select(x => Enrich(x, cancellationToken)); + + // + var result = await Task.WhenAll(tasks); + return result; + } + + /// + /// Enrich Specified Items ... + /// + /// + /// + /// + public virtual async Task> EnrichRange( + IEnumerable sources, + CancellationToken cancellationToken = default + ) + { + // + var tasks = sources + .Select(x => Enrich(x, cancellationToken)); + + // + var result = await Task.WhenAll(tasks); + return result; + } + #endregion + } +} + +### FILE: C:\Users\saherelm\Documents\Projects\xSaherelmWorkspace\Modules\xAiModels\Providers\Enrichers\XAiProjectEnricher.cs + +using System.Linq; +using xModels.Dtos; +using System.Threading; +using xCommons.Extensions; +using xAiModels.Interfaces; +using xAiModels.Models.Dtos; +using System.Threading.Tasks; +using xAiModels.Models.Entities; +using System.Collections.Generic; +using xIdentityService.Interfaces; +using xIdentityService.Extensions; +using xAiModels.Interfaces.Entities; +using xAiModels.Interfaces.Enrichers; + +namespace xAiModels.Providers.Enrichers +{ + public class XAiProjectEnricher : IXAiProjectEnricher + { + private readonly IXIdentityProvider identityProvider; + private readonly IXAiMessageRepository messageRepository; + private readonly IXAiConversationRepository conversationRepository; + private readonly IXAiProjectTitleResourceProvider projectTitleResourceProvider; + private readonly IXAiConversationTitleResourceProvider conversationTitleResourceProvider; + private readonly IXAiProjectDescriptionResourceProvider projectDescriptionResourceProvider; + + public XAiProjectEnricher( + IXIdentityProvider identityProvider, + IXAiMessageRepository messageRepository, + IXAiConversationRepository conversationRepository, + IXAiProjectTitleResourceProvider projectTitleResourceProvider, + IXAiConversationTitleResourceProvider conversationTitleResourceProvider, + IXAiProjectDescriptionResourceProvider projectDescriptionResourceProvider + ) + { + // + this.identityProvider = identityProvider; + this.messageRepository = messageRepository; + this.conversationRepository = conversationRepository; + this.projectTitleResourceProvider = projectTitleResourceProvider; + this.conversationTitleResourceProvider = conversationTitleResourceProvider; + this.projectDescriptionResourceProvider = projectDescriptionResourceProvider; + } + + // + #region Enrichers ... + /// + /// Enrich Specified Item ... + /// + /// + /// + /// + /// + /// + public virtual async Task Enrich( + XAiProject source, + bool fillConversations = false, + bool fillConversationMessages = false, + CancellationToken cancellationToken = default + ) + { + // + // Mapping Default ... + var result = source.MapConvert(); + result = await Enrich( + source: result, + fillConversations: fillConversations, + cancellationToken: cancellationToken, + fillConversationMessages: fillConversationMessages + ); + + // + return result; + } + + /// + /// Enrich Specified Item ... + /// + /// + /// + /// + /// + /// + public virtual async Task Enrich( + XAiProjectDto source, + bool fillConversations = false, + bool fillConversationMessages = false, + CancellationToken cancellationToken = default + ) + { + // + // Handle Owner ... + XPersonDto owner = null; + if (!source.OwnerId.IsNullOrEmpty()) + { + // + // Try to Retrieve User Info ... + var device = identityProvider.GetDevice(); + var userInfo = await identityProvider.GetUserInfo( + device: device, + userSelectByParam: source.OwnerId + ); + owner = userInfo.ToXPersonDto(); + } + + // + // Handle Title ... + XResourceDto titleResource = null; + if (!source.Title.IsNullOrEmpty()) + { + // + titleResource = await projectTitleResourceProvider.GetResource( + owner: source.OwnerId, + identifier: source.Id, + cancellationToken: cancellationToken + ); + } + + // + // Handle Description ... + XResourceDto descriptionResource = null; + if (!source.Description.IsNullOrEmpty()) + { + // + descriptionResource = await projectDescriptionResourceProvider.GetResource( + owner: source.OwnerId, + identifier: source.Id, + cancellationToken: cancellationToken + ); + } + + // + // Handle Conversations ... + IEnumerable conversations = []; + if (fillConversations) + { + // + // Reading Entities ... + var entitiies = await conversationRepository.FindManyAsync( + includeBuilder: null, + ignoreSoftDeleteds: true, + cancellationToken: cancellationToken, + predicate: x => x.ProjectId == source.Id, + orderBuilder: x => x.OrderBy(y => y.CreatedOn) + ); + + // + // Converts to Dto Enumerable ... + conversations = entitiies + .MapConvert(); + + // + // Handle Conversation Enrichment ... + foreach (var conversation in conversations) + { + // + // Handle Owner ... + if (!conversation.OwnerId.IsNullOrEmpty()) + { + conversation.Owner = owner; + } + + // + // Handle Title Resource ... + if (!conversation.Title.IsNullOrEmpty()) + { + // + conversation.TitleResource = await conversationTitleResourceProvider.GetResource( + owner: source.OwnerId, + identifier: conversation.Id, + cancellationToken: cancellationToken + ); + } + + // + // Handle Project Info ... + if (!conversation.ProjectId.IsDefaultGuid()) + { + conversation.ProjectTitle = source.Title; + conversation.ProjectTitleResource = titleResource; + conversation.ProjectDescription = source.Description; + conversation.ProjectDescriptionResource = descriptionResource; + } + } + + // + // Handle Fill Messages ... + if (fillConversationMessages) + { + // + foreach (var conversation in conversations) + { + // + IEnumerable messages = []; + + // + // Retrieve Message Entities ... + var messageEntities = await messageRepository.FindManyAsync( + includeBuilder: null, + ignoreSoftDeleteds: true, + cancellationToken: cancellationToken, + orderBuilder: x => x.OrderBy(y => y.CreatedOn), + predicate: x => x.ConversationId == conversation.Id + ); + if (messageEntities.HasChild()) + { + // + // Converts to Message ... + messages = messageEntities + .MapConvert(); + + // + // Ennrich Messages ... + foreach (var message in messages) + { + // + // Handle Owner ... + if (!message.OwnerId.IsNullOrEmpty()) + { + message.Owner = owner; + } + + // + // Handle Conversation ... + if (!message.ConversationId.IsDefaultGuid()) + { + message.ConversationTitle = conversation.Title; + message.ConversationTitleResouce = conversation.TitleResource; + } + } + } + + // + conversation.Messages = [.. messages]; + } + } + } + + // + // Attach Extracted Items ... + var result = source.MapConvert(); + result.Owner = owner; + result.TitleResource = titleResource; + result.Conversations = [.. conversations]; + result.DescriptionResource = descriptionResource; + + // + return result; + } + + /// + /// Enrich Specified Items ... + /// + /// + /// + /// + /// + /// + public virtual async Task> EnrichRange( + IEnumerable sources, + bool fillConversations = false, + bool fillConversationMessages = false, + CancellationToken cancellationToken = default + ) + { + // + var tasks = sources + .Select(x => Enrich( + source: x, + cancellationToken: cancellationToken, + fillConversations: fillConversations, + fillConversationMessages: fillConversationMessages + )); + + // + var result = await Task.WhenAll(tasks); + return result; + } + + /// + /// Enrich Specified Items ... + /// + /// + /// + /// + /// + /// + public virtual async Task> EnrichRange( + IEnumerable sources, + bool fillConversations = false, + bool fillConversationMessages = false, + CancellationToken cancellationToken = default + ) + { + // + var tasks = sources + .Select(x => Enrich( + source: x, + cancellationToken: cancellationToken, + fillConversations: fillConversations, + fillConversationMessages: fillConversationMessages + )); + + // + var result = await Task.WhenAll(tasks); + return result; + } + #endregion + } +} + +### FILE: C:\Users\saherelm\Documents\Projects\xSaherelmWorkspace\Modules\xAiModels\Providers\Enrichers\XAiVectorEnricher.cs + +using System.Linq; +using System.Threading; +using xCommons.Extensions; +using xAiModels.Extensions; +using xAiModels.Models.Dtos; +using System.Threading.Tasks; +using xAiModels.Models.Entities; +using System.Collections.Generic; +using xAiModels.Interfaces.Enrichers; + +namespace xAiModels.Providers.Enrichers +{ + public class XAiVectorEnricher : IXAiVectorEnricher + { + public XAiVectorEnricher() + { } + + // + #region Enrichers ... + /// + /// Enrich Specified Item ... + /// + /// + /// + /// + public virtual async Task Enrich( + XAiVector source, + CancellationToken cancellationToken = default + ) + { + // + // Mapping Default ... + var result = source.MapConvert(); + + // + // Here we Converts Embeddings ... + result.Metadata = source.Metadata.AsMetadat(); + result.Embedding = source.Embedding.AsEmbedding(); + + // + result = await Enrich( + source: result, + cancellationToken: cancellationToken + ); + + // + return result; + } + + /// + /// Enrich Specified Item ... + /// + /// + /// + /// + public virtual async Task Enrich( + XAiVectorDto source, + CancellationToken cancellationToken = default + ) + { + // + // Currently no additional enrichment needed for XAiVector + // This can be extended in the future if needed + return await Task.FromResult(source); + } + + /// + /// Enrich Specified Items ... + /// + /// + /// + /// + public virtual async Task> EnrichRange( + IEnumerable sources, + CancellationToken cancellationToken = default + ) + { + // + var tasks = sources + .Select(x => Enrich( + source: x, + cancellationToken: cancellationToken + )); + + // + var result = await Task.WhenAll(tasks); + return result; + } + + /// + /// Enrich Specified Items ... + /// + /// + /// + /// + public virtual async Task> EnrichRange( + IEnumerable sources, + CancellationToken cancellationToken = default + ) + { + // + var tasks = sources + .Select(x => Enrich( + source: x, + cancellationToken: cancellationToken + )); + + // + var result = await Task.WhenAll(tasks); + return result; + } + #endregion + } +} + +### FILE: C:\Users\saherelm\Documents\Projects\xSaherelmWorkspace\Modules\xAiModels\Providers\Entities\XAiConversationEFRepository.cs + +using System; +using xDataService.Db; +using xDataService.Providers; +using xDataService.Interfaces; +using xAiModels.Models.Entities; +using xDataService.Configuration; +using xAiModels.Interfaces.Entities; + +namespace xAiModels.Providers.Entities +{ + public class XAiConversationEFRepository : XBaseEFRepository, IXAiConversationRepository + where TContext : XDbContext + { + public XAiConversationEFRepository( + IXUnitOfWorks unitOfWorks, + XDataServiceConfiguration configuration, + IXAiConversationKeyGenerator keyGenerator = null, + IXAiConversationRepositoryEvents baseRepositoryEvents = null + ) : base( + unitOfWorks, + configuration, + keyGenerator, + baseRepositoryEvents + ) + { } + } +} + +### FILE: C:\Users\saherelm\Documents\Projects\xSaherelmWorkspace\Modules\xAiModels\Providers\Entities\XAiConversationEntityHub.cs + +using System; +using xPushService.Base; +using xAiModels.Models.Entities; +using Microsoft.Extensions.Logging; +using xAiModels.Interfaces.Entities; + +namespace xAiModels.Providers.Entities +{ + public class XAiConversationEntityHub : XBaseEntityHub, IXAiConversationEntityHub + { + public XAiConversationEntityHub( + ILogger logger + ) : base(logger) + { } + } +} + +### FILE: C:\Users\saherelm\Documents\Projects\xSaherelmWorkspace\Modules\xAiModels\Providers\Entities\XAiConversationInMemoryRepository.cs + +using System; +using xDataService.Providers; +using xAiModels.Models.Entities; +using xDataService.Configuration; +using xAiModels.Interfaces.Entities; + +namespace xAiModels.Providers.Entities +{ + public class XAiConversationInMemoryRepository : XBaseInMemoryRepository, IXAiConversationRepository + { + public XAiConversationInMemoryRepository( + XDataServiceConfiguration configuration, + IXAiConversationKeyGenerator keyGenerator = null, + IXAiConversationRepositoryEvents baseRepositoryEvents = null + ) : base( + configuration, + keyGenerator, + baseRepositoryEvents + ) + { } + } +} + +### FILE: C:\Users\saherelm\Documents\Projects\xSaherelmWorkspace\Modules\xAiModels\Providers\Entities\XAiConversationKeyGenerator.cs + +using xDataService.Providers; +using xAiModels.Models.Entities; +using xAiModels.Interfaces.Entities; + +namespace xAiModels.Providers.Entities +{ + public class XAiConversationKeyGenerator : XGuidKeyGenerator, IXAiConversationKeyGenerator + { } +} + +### FILE: C:\Users\saherelm\Documents\Projects\xSaherelmWorkspace\Modules\xAiModels\Providers\Entities\XAiConversationMongoRepository.cs + +using System; +using xDataService.Providers; +using xAiModels.Models.Entities; +using xDataService.Configuration; +using xAiModels.Interfaces.Entities; + +namespace xAiModels.Providers.Entities +{ + public class XAiConversationMongoRepository : XBaseMongoRepository, IXAiConversationRepository + { + public XAiConversationMongoRepository( + XDataBaseConfiguration dbConfiguration, + XDataServiceConfiguration configuration, + string collectionName = null, + IXAiConversationKeyGenerator keyGenerator = null, + IXAiConversationRepositoryEvents baseRepositoryEvents = null + ) : base( + dbConfiguration, + configuration, + collectionName, + keyGenerator, + baseRepositoryEvents + ) + { } + } +} + +### FILE: C:\Users\saherelm\Documents\Projects\xSaherelmWorkspace\Modules\xAiModels\Providers\Entities\XAiConversationRepositoryEvents.cs + +using xDataService.Providers; +using xAiModels.Models.Entities; +using xAiModels.Interfaces.Entities; + +namespace xAiModels.Providers.Entities +{ + public class XAiConversationRepositoryEvents : XBaseRepositoryEvents, IXAiConversationRepositoryEvents + { } +} + +### FILE: C:\Users\saherelm\Documents\Projects\xSaherelmWorkspace\Modules\xAiModels\Providers\Entities\XAiConversationRepositoryProvider.cs + +using System; +using xPushService.Base; +using xAiModels.Models.Entities; +using xDataService.Configuration; +using xIdentityService.Interfaces; +using Microsoft.AspNetCore.SignalR; +using xAiModels.Interfaces.Entities; + +namespace xAiModels.Providers.Entities +{ + public class XAiConversationRepositoryProvider : XBaseEntityProvider, IXAiConversationRepositoryProvider + { + public XAiConversationRepositoryProvider( + IHubContext hub, + IXAiConversationRepository repository, + XDataServiceConfiguration dataConfiguration, + IXIdentityProvider identityProvider = null + ) : base( + hub, + repository, + dataConfiguration, + identityProvider + ) + { } + } +} + +### FILE: C:\Users\saherelm\Documents\Projects\xSaherelmWorkspace\Modules\xAiModels\Providers\Entities\XAiConversationSeederBase.cs + +using System; +using xDataService.Providers; +using xAiModels.Models.Entities; +using xDataService.Configuration; +using xAiModels.Interfaces.Entities; + +namespace xAiModels.Providers.Entities +{ + public abstract class XAiConversationSeederBase : XBaseDbSeeder, IXAiConversationSeeder + { + protected XAiConversationSeederBase( + string entity, + string database, + IXAiConversationRepository repository, + XDataServiceConfiguration dataServiceConfiguration + ) : base( + entity, + database, + repository, + dataServiceConfiguration + ) + { } + } +} + +### FILE: C:\Users\saherelm\Documents\Projects\xSaherelmWorkspace\Modules\xAiModels\Providers\Entities\XAiMessageEFRepository.cs + +using System; +using xDataService.Db; +using xDataService.Providers; +using xDataService.Interfaces; +using xAiModels.Models.Entities; +using xDataService.Configuration; +using xAiModels.Interfaces.Entities; + +namespace xAiModels.Providers.Entities +{ + public class XAiMessageEFRepository : XBaseEFRepository, IXAiMessageRepository + where TContext : XDbContext + { + public XAiMessageEFRepository( + IXUnitOfWorks unitOfWorks, + XDataServiceConfiguration configuration, + IXAiMessageKeyGenerator keyGenerator = null, + IXAiMessageRepositoryEvents baseRepositoryEvents = null + ) : base( + unitOfWorks, + configuration, + keyGenerator, + baseRepositoryEvents + ) + { } + } +} + +### FILE: C:\Users\saherelm\Documents\Projects\xSaherelmWorkspace\Modules\xAiModels\Providers\Entities\XAiMessageEntityHub.cs + +using System; +using xPushService.Base; +using xAiModels.Models.Entities; +using Microsoft.Extensions.Logging; +using xAiModels.Interfaces.Entities; + +namespace xAiModels.Providers.Entities +{ + public class XAiMessageEntityHub : XBaseEntityHub, IXAiMessageEntityHub + { + public XAiMessageEntityHub( + ILogger logger + ) : base(logger) + { } + } +} + +### FILE: C:\Users\saherelm\Documents\Projects\xSaherelmWorkspace\Modules\xAiModels\Providers\Entities\XAiMessageInMemoryRepository.cs + +using System; +using xDataService.Providers; +using xAiModels.Models.Entities; +using xDataService.Configuration; +using xAiModels.Interfaces.Entities; + +namespace xAiModels.Providers.Entities +{ + public class XAiMessageInMemoryRepository : XBaseInMemoryRepository, IXAiMessageRepository + { + public XAiMessageInMemoryRepository( + XDataServiceConfiguration configuration, + IXAiMessageKeyGenerator keyGenerator = null, + IXAiMessageRepositoryEvents baseRepositoryEvents = null + ) : base( + configuration, + keyGenerator, + baseRepositoryEvents + ) + { } + } +} + +### FILE: C:\Users\saherelm\Documents\Projects\xSaherelmWorkspace\Modules\xAiModels\Providers\Entities\XAiMessageKeyGenerator.cs + +using xDataService.Providers; +using xAiModels.Models.Entities; +using xAiModels.Interfaces.Entities; + +namespace xAiModels.Providers.Entities +{ + public class XAiMessageKeyGenerator : XGuidKeyGenerator, IXAiMessageKeyGenerator + { } +} + +### FILE: C:\Users\saherelm\Documents\Projects\xSaherelmWorkspace\Modules\xAiModels\Providers\Entities\XAiMessageMongoRepository.cs + +using System; +using xDataService.Providers; +using xAiModels.Models.Entities; +using xDataService.Configuration; +using xAiModels.Interfaces.Entities; + +namespace xAiModels.Providers.Entities +{ + public class XAiMessageMongoRepository : XBaseMongoRepository, IXAiMessageRepository + { + public XAiMessageMongoRepository( + XDataBaseConfiguration dbConfiguration, + XDataServiceConfiguration configuration, + string collectionName = null, + IXAiMessageKeyGenerator keyGenerator = null, + IXAiMessageRepositoryEvents baseRepositoryEvents = null + ) : base( + dbConfiguration, + configuration, + collectionName, + keyGenerator, + baseRepositoryEvents + ) + { } + } +} + +### FILE: C:\Users\saherelm\Documents\Projects\xSaherelmWorkspace\Modules\xAiModels\Providers\Entities\XAiMessageRepositoryEvents.cs + +using xDataService.Providers; +using xAiModels.Models.Entities; +using xAiModels.Interfaces.Entities; + +namespace xAiModels.Providers.Entities +{ + public class XAiMessageRepositoryEvents : XBaseRepositoryEvents, IXAiMessageRepositoryEvents + { } +} + +### FILE: C:\Users\saherelm\Documents\Projects\xSaherelmWorkspace\Modules\xAiModels\Providers\Entities\XAiMessageRepositoryProvider.cs + +using System; +using xPushService.Base; +using xAiModels.Models.Entities; +using xDataService.Configuration; +using xIdentityService.Interfaces; +using Microsoft.AspNetCore.SignalR; +using xAiModels.Interfaces.Entities; + +namespace xAiModels.Providers.Entities +{ + public class XAiMessageRepositoryProvider : XBaseEntityProvider, IXAiMessageRepositoryProvider + { + public XAiMessageRepositoryProvider( + IHubContext hub, + IXAiMessageRepository repository, + XDataServiceConfiguration dataConfiguration, + IXIdentityProvider identityProvider = null + ) : base( + hub, + repository, + dataConfiguration, + identityProvider + ) + { } + } +} + +### FILE: C:\Users\saherelm\Documents\Projects\xSaherelmWorkspace\Modules\xAiModels\Providers\Entities\XAiMessageSeederBase.cs + +using System; +using xDataService.Providers; +using xAiModels.Models.Entities; +using xDataService.Configuration; +using xAiModels.Interfaces.Entities; + +namespace xAiModels.Providers.Entities +{ + public abstract class XAiMessageSeederBase : XBaseDbSeeder, IXAiMessageSeeder + { + protected XAiMessageSeederBase( + string entity, + string database, + IXAiMessageRepository repository, + XDataServiceConfiguration dataServiceConfiguration + ) : base( + entity, + database, + repository, + dataServiceConfiguration + ) + { } + } +} + +### FILE: C:\Users\saherelm\Documents\Projects\xSaherelmWorkspace\Modules\xAiModels\Providers\Entities\XAiProjectEFRepository.cs + +using System; +using xDataService.Db; +using xDataService.Providers; +using xDataService.Interfaces; +using xAiModels.Models.Entities; +using xDataService.Configuration; +using xAiModels.Interfaces.Entities; + +namespace xAiModels.Providers.Entities +{ + public class XAiProjectEFRepository : XBaseEFRepository, IXAiProjectRepository + where TContext : XDbContext + { + public XAiProjectEFRepository( + IXUnitOfWorks unitOfWorks, + XDataServiceConfiguration configuration, + IXAiProjectKeyGenerator keyGenerator = null, + IXAiProjectRepositoryEvents baseRepositoryEvents = null + ) : base( + unitOfWorks, + configuration, + keyGenerator, + baseRepositoryEvents + ) + { } + } +} + +### FILE: C:\Users\saherelm\Documents\Projects\xSaherelmWorkspace\Modules\xAiModels\Providers\Entities\XAiProjectEntityHub.cs + +using System; +using xPushService.Base; +using xAiModels.Models.Entities; +using Microsoft.Extensions.Logging; +using xAiModels.Interfaces.Entities; + +namespace xAiModels.Providers.Entities +{ + public class XAiProjectEntityHub : XBaseEntityHub, IXAiProjectEntityHub + { + public XAiProjectEntityHub( + ILogger logger + ) : base(logger) + { } + } +} + +### FILE: C:\Users\saherelm\Documents\Projects\xSaherelmWorkspace\Modules\xAiModels\Providers\Entities\XAiProjectInMemoryRepository.cs + +using System; +using xDataService.Providers; +using xAiModels.Models.Entities; +using xDataService.Configuration; +using xAiModels.Interfaces.Entities; + +namespace xAiModels.Providers.Entities +{ + public class XAiProjectInMemoryRepository : XBaseInMemoryRepository, IXAiProjectRepository + { + public XAiProjectInMemoryRepository( + XDataServiceConfiguration configuration, + IXAiProjectKeyGenerator keyGenerator = null, + IXAiProjectRepositoryEvents baseRepositoryEvents = null + ) : base( + configuration, + keyGenerator, + baseRepositoryEvents + ) + { } + } +} + +### FILE: C:\Users\saherelm\Documents\Projects\xSaherelmWorkspace\Modules\xAiModels\Providers\Entities\XAiProjectKeyGenerator.cs + +using xDataService.Providers; +using xAiModels.Models.Entities; +using xAiModels.Interfaces.Entities; + +namespace xAiModels.Providers.Entities +{ + public class XAiProjectKeyGenerator : XGuidKeyGenerator, IXAiProjectKeyGenerator + { } +} + +### FILE: C:\Users\saherelm\Documents\Projects\xSaherelmWorkspace\Modules\xAiModels\Providers\Entities\XAiProjectMongoRepository.cs + +using System; +using xDataService.Providers; +using xAiModels.Models.Entities; +using xDataService.Configuration; +using xAiModels.Interfaces.Entities; + +namespace xAiModels.Providers.Entities +{ + public class XAiProjectMongoRepository : XBaseMongoRepository, IXAiProjectRepository + { + public XAiProjectMongoRepository( + XDataBaseConfiguration dbConfiguration, + XDataServiceConfiguration configuration, + string collectionName = null, + IXAiProjectKeyGenerator keyGenerator = null, + IXAiProjectRepositoryEvents baseRepositoryEvents = null + ) : base( + dbConfiguration, + configuration, + collectionName, + keyGenerator, + baseRepositoryEvents + ) + { } + } +} + +### FILE: C:\Users\saherelm\Documents\Projects\xSaherelmWorkspace\Modules\xAiModels\Providers\Entities\XAiProjectRepositoryEvents.cs + +using xDataService.Providers; +using xAiModels.Models.Entities; +using xAiModels.Interfaces.Entities; + +namespace xAiModels.Providers.Entities +{ + public class XAiProjectRepositoryEvents : XBaseRepositoryEvents, IXAiProjectRepositoryEvents + { } +} + +### FILE: C:\Users\saherelm\Documents\Projects\xSaherelmWorkspace\Modules\xAiModels\Providers\Entities\XAiProjectRepositoryProvider.cs + +using System; +using xPushService.Base; +using xAiModels.Models.Entities; +using xDataService.Configuration; +using xIdentityService.Interfaces; +using Microsoft.AspNetCore.SignalR; +using xAiModels.Interfaces.Entities; + +namespace xAiModels.Providers.Entities +{ + public class XAiProjectRepositoryProvider : XBaseEntityProvider, IXAiProjectRepositoryProvider + { + public XAiProjectRepositoryProvider( + IHubContext hub, + IXAiProjectRepository repository, + XDataServiceConfiguration dataConfiguration, + IXIdentityProvider identityProvider = null + ) : base( + hub, + repository, + dataConfiguration, + identityProvider + ) + { } + } +} + +### FILE: C:\Users\saherelm\Documents\Projects\xSaherelmWorkspace\Modules\xAiModels\Providers\Entities\XAiProjectSeederBase.cs + +using System; +using xDataService.Providers; +using xAiModels.Models.Entities; +using xDataService.Configuration; +using xAiModels.Interfaces.Entities; + +namespace xAiModels.Providers.Entities +{ + public abstract class XAiProjectSeederBase : XBaseDbSeeder, IXAiProjectSeeder + { + protected XAiProjectSeederBase( + string entity, + string database, + IXAiProjectRepository repository, + XDataServiceConfiguration dataServiceConfiguration + ) : base( + entity, + database, + repository, + dataServiceConfiguration + ) + { } + } +} + +### FILE: C:\Users\saherelm\Documents\Projects\xSaherelmWorkspace\Modules\xAiModels\Providers\Entities\XAiVectorEFRepository.cs + +using System; +using xDataService.Db; +using xDataService.Providers; +using xDataService.Interfaces; +using xAiModels.Models.Entities; +using xDataService.Configuration; +using xAiModels.Interfaces.Entities; + +namespace xAiModels.Providers.Entities +{ + public class XAiVectorEFRepository : XBaseEFRepository, IXAiVectorRepository + where TContext : XDbContext + { + public XAiVectorEFRepository( + IXUnitOfWorks unitOfWorks, + XDataServiceConfiguration configuration, + IXAiVectorKeyGenerator keyGenerator = null, + IXAiVectorRepositoryEvents baseRepositoryEvents = null + ) : base( + unitOfWorks, + configuration, + keyGenerator, + baseRepositoryEvents + ) + { } + } +} + +### FILE: C:\Users\saherelm\Documents\Projects\xSaherelmWorkspace\Modules\xAiModels\Providers\Entities\XAiVectorEntityHub.cs + +using System; +using xPushService.Base; +using xAiModels.Models.Entities; +using Microsoft.Extensions.Logging; +using xAiModels.Interfaces.Entities; + +namespace xAiModels.Providers.Entities +{ + public class XAiVectorEntityHub : XBaseEntityHub, IXAiVectorEntityHub + { + public XAiVectorEntityHub( + ILogger logger + ) : base(logger) + { } + } +} + +### FILE: C:\Users\saherelm\Documents\Projects\xSaherelmWorkspace\Modules\xAiModels\Providers\Entities\XAiVectorInMemoryRepository.cs + +using System; +using xDataService.Providers; +using xAiModels.Models.Entities; +using xDataService.Configuration; +using xAiModels.Interfaces.Entities; + +namespace xAiModels.Providers.Entities +{ + public class XAiVectorInMemoryRepository : XBaseInMemoryRepository, IXAiVectorRepository + { + public XAiVectorInMemoryRepository( + XDataServiceConfiguration configuration, + IXAiVectorKeyGenerator keyGenerator = null, + IXAiVectorRepositoryEvents baseRepositoryEvents = null + ) : base( + configuration, + keyGenerator, + baseRepositoryEvents + ) + { } + } +} + +### FILE: C:\Users\saherelm\Documents\Projects\xSaherelmWorkspace\Modules\xAiModels\Providers\Entities\XAiVectorKeyGenerator.cs + +using xDataService.Providers; +using xAiModels.Models.Entities; +using xAiModels.Interfaces.Entities; + +namespace xAiModels.Providers.Entities +{ + public class XAiVectorKeyGenerator : XGuidKeyGenerator, IXAiVectorKeyGenerator + { } +} + +### FILE: C:\Users\saherelm\Documents\Projects\xSaherelmWorkspace\Modules\xAiModels\Providers\Entities\XAiVectorMongoRepository.cs + +using System; +using xDataService.Providers; +using xAiModels.Models.Entities; +using xDataService.Configuration; +using xAiModels.Interfaces.Entities; + +namespace xAiModels.Providers.Entities +{ + public class XAiVectorMongoRepository : XBaseMongoRepository, IXAiVectorRepository + { + public XAiVectorMongoRepository( + XDataBaseConfiguration dbConfiguration, + XDataServiceConfiguration configuration, + string collectionName = null, + IXAiVectorKeyGenerator keyGenerator = null, + IXAiVectorRepositoryEvents baseRepositoryEvents = null + ) : base( + dbConfiguration, + configuration, + collectionName, + keyGenerator, + baseRepositoryEvents + ) + { } + } +} + +### FILE: C:\Users\saherelm\Documents\Projects\xSaherelmWorkspace\Modules\xAiModels\Providers\Entities\XAiVectorRepositoryEvents.cs + +using xDataService.Providers; +using xAiModels.Models.Entities; +using xAiModels.Interfaces.Entities; + +namespace xAiModels.Providers.Entities +{ + public class XAiVectorRepositoryEvents : XBaseRepositoryEvents, IXAiVectorRepositoryEvents + { } +} + +### FILE: C:\Users\saherelm\Documents\Projects\xSaherelmWorkspace\Modules\xAiModels\Providers\Entities\XAiVectorRepositoryProvider.cs + +using System; +using xPushService.Base; +using xAiModels.Models.Entities; +using xDataService.Configuration; +using xIdentityService.Interfaces; +using Microsoft.AspNetCore.SignalR; +using xAiModels.Interfaces.Entities; + +namespace xAiModels.Providers.Entities +{ + public class XAiVectorRepositoryProvider : XBaseEntityProvider, IXAiVectorRepositoryProvider + { + public XAiVectorRepositoryProvider( + IHubContext hub, + IXAiVectorRepository repository, + XDataServiceConfiguration dataConfiguration, + IXIdentityProvider identityProvider = null + ) : base( + hub, + repository, + dataConfiguration, + identityProvider + ) + { } + } +} + +### FILE: C:\Users\saherelm\Documents\Projects\xSaherelmWorkspace\Modules\xAiModels\Providers\Entities\XAiVectorSeederBase.cs + +using System; +using xDataService.Providers; +using xAiModels.Models.Entities; +using xDataService.Configuration; +using xAiModels.Interfaces.Entities; + +namespace xAiModels.Providers.Entities +{ + public abstract class XAiVectorSeederBase : XBaseDbSeeder, IXAiVectorSeeder + { + protected XAiVectorSeederBase( + string entity, + string database, + IXAiVectorRepository repository, + XDataServiceConfiguration dataServiceConfiguration + ) : base( + entity, + database, + repository, + dataServiceConfiguration + ) + { } + } +} + +### FILE: C:\Users\saherelm\Documents\Projects\xSaherelmWorkspace\Modules\xAiModels\Providers\GraphQL\XAiConversationGraphQLTypeHelper.cs + +using System; +using xAiModels.Constants; +using xDataService.GraphQL; +using xAiModels.Models.Entities; +using xAiModels.Interfaces.Entities; + +namespace xAiModels.Providers.GraphQL +{ + public class XAiConversationGraphQLTypeHelper : XBaseGraphQLTypeHelper, IXAiConversationGraphQLTypeHelper + { + public override string GetInQueryCollectionName() + { + return XAiModelsConstants.XAiConversationCollectionName; + } + + public override string GetInQuerySingleName() + { + return XAiModelsConstants.XAiConversationSignleName; + } + } +} + +### FILE: C:\Users\saherelm\Documents\Projects\xSaherelmWorkspace\Modules\xAiModels\Providers\GraphQL\XAiConversationGraphQuery.cs + +using System; +using GraphQL.Types; +using xDataService.GraphQL; +using xAiModels.Models.Entities; +using xDataService.Configuration; +using xAiModels.Interfaces.Entities; + +namespace xAiModels.Providers.GraphQL +{ + public class XAiConversationGraphQuery : XBaseGraphQLQuery + { + public XAiConversationGraphQuery( + XDataServiceConfiguration configuration, + IXAiConversationRepository repository, + IXAiConversationGraphQLTypeHelper helper + ) : base( + configuration, + repository, + helper + ) + { } + } +} + +### FILE: C:\Users\saherelm\Documents\Projects\xSaherelmWorkspace\Modules\xAiModels\Providers\GraphQL\XAiConversationGraphSchema.cs + +using System; +using GraphQL.Types; + +namespace xAiModels.Providers.GraphQL +{ + public class XAiConversationGraphSchema : Schema + { + public XAiConversationGraphSchema(IServiceProvider services) : base(services) + { + Query = (XAiConversationGraphQuery)services.GetService(typeof(XAiConversationGraphQuery)); + } + } +} + +### FILE: C:\Users\saherelm\Documents\Projects\xSaherelmWorkspace\Modules\xAiModels\Providers\GraphQL\XAiConversationGraphType.cs + +using System; +using xDataService.GraphQL; +using xAiModels.Models.Entities; + +namespace xAiModels.Providers.GraphQL +{ + public class XAiConversationGraphType : XBaseGraphObjectType + { + public XAiConversationGraphType() : base() + { + Field(x => x.Title); + Field(x => x.OwnerId); + Field(x => x.CreatedOn); + Field(x => x.UpdatedAt); + Field(x => x.ProjectId); + } + } +} + +### FILE: C:\Users\saherelm\Documents\Projects\xSaherelmWorkspace\Modules\xAiModels\Providers\GraphQL\XAiMessageGraphQLTypeHelper.cs + +using System; +using xAiModels.Constants; +using xDataService.GraphQL; +using xAiModels.Models.Entities; +using xAiModels.Interfaces.Entities; + +namespace xAiModels.Providers.GraphQL +{ + public class XAiMessageGraphQLTypeHelper : XBaseGraphQLTypeHelper, IXAiMessageGraphQLTypeHelper + { + public override string GetInQueryCollectionName() + { + return XAiModelsConstants.XAiMessageCollectionName; + } + + public override string GetInQuerySingleName() + { + return XAiModelsConstants.XAiMessageSingleName; + } + } +} + +### FILE: C:\Users\saherelm\Documents\Projects\xSaherelmWorkspace\Modules\xAiModels\Providers\GraphQL\XAiMessageGraphQuery.cs + +using System; +using GraphQL.Types; +using xDataService.GraphQL; +using xAiModels.Models.Entities; +using xDataService.Configuration; +using xAiModels.Interfaces.Entities; + +namespace xAiModels.Providers.GraphQL +{ + public class XAiMessageGraphQuery : XBaseGraphQLQuery + { + public XAiMessageGraphQuery( + XDataServiceConfiguration configuration, + IXAiMessageRepository repository, + IXAiMessageGraphQLTypeHelper helper + ) : base( + configuration, + repository, + helper + ) + { } + } +} + +### FILE: C:\Users\saherelm\Documents\Projects\xSaherelmWorkspace\Modules\xAiModels\Providers\GraphQL\XAiMessageGraphSchema.cs + +using System; +using GraphQL.Types; + +namespace xAiModels.Providers.GraphQL +{ + public class XAiMessageGraphSchema : Schema + { + public XAiMessageGraphSchema(IServiceProvider services) : base(services) + { + Query = (XAiMessageGraphQuery)services.GetService(typeof(XAiMessageGraphQuery)); + } + } +} + +### FILE: C:\Users\saherelm\Documents\Projects\xSaherelmWorkspace\Modules\xAiModels\Providers\GraphQL\XAiMessageGraphType.cs + +using System; +using xDataService.GraphQL; +using xAiModels.Models.Entities; + +namespace xAiModels.Providers.GraphQL +{ + public class XAiMessageGraphType: XBaseGraphObjectType + { + public XAiMessageGraphType() : base() + { + Field(x => x.Role); + Field(x => x.OwnerId); + Field(x => x.Content); + Field(x => x.Metadata); + Field(x => x.CreatedOn); + Field(x => x.UpdatedAt); + Field(x => x.ConversationId); + } + } +} + +### FILE: C:\Users\saherelm\Documents\Projects\xSaherelmWorkspace\Modules\xAiModels\Providers\GraphQL\XAiProjectGraphQLTypeHelper.cs + +using System; +using xAiModels.Constants; +using xDataService.GraphQL; +using xAiModels.Models.Entities; +using xAiModels.Interfaces.Entities; + +namespace xAiModels.Providers.GraphQL +{ + public class XAiProjectGraphQLTypeHelper : XBaseGraphQLTypeHelper, IXAiProjectGraphQLTypeHelper + { + public override string GetInQueryCollectionName() + { + return XAiModelsConstants.XAiProjectCollectionName; + } + + public override string GetInQuerySingleName() + { + return XAiModelsConstants.XAiProjectSingleName; + } + } +} + +### FILE: C:\Users\saherelm\Documents\Projects\xSaherelmWorkspace\Modules\xAiModels\Providers\GraphQL\XAiProjectGraphQuery.cs + +using System; +using GraphQL.Types; +using xDataService.GraphQL; +using xAiModels.Models.Entities; +using xDataService.Configuration; +using xAiModels.Interfaces.Entities; + +namespace xAiModels.Providers.GraphQL +{ + public class XAiProjectGraphQuery : XBaseGraphQLQuery + { + public XAiProjectGraphQuery( + XDataServiceConfiguration configuration, + IXAiProjectRepository repository, + IXAiProjectGraphQLTypeHelper helper + ) : base( + configuration, + repository, + helper + ) + { } + } +} + +### FILE: C:\Users\saherelm\Documents\Projects\xSaherelmWorkspace\Modules\xAiModels\Providers\GraphQL\XAiProjectGraphSchema.cs + +using System; +using GraphQL.Types; + +namespace xAiModels.Providers.GraphQL +{ + public class XAiProjectGraphSchema : Schema + { + public XAiProjectGraphSchema(IServiceProvider services) : base(services) + { + Query = (XAiProjectGraphQuery)services.GetService(typeof(XAiProjectGraphQuery)); + } + } +} + +### FILE: C:\Users\saherelm\Documents\Projects\xSaherelmWorkspace\Modules\xAiModels\Providers\GraphQL\XAiProjectGraphType.cs + +using System; +using xDataService.GraphQL; +using xAiModels.Models.Entities; + +namespace xAiModels.Providers.GraphQL +{ + public class XAiProjectGraphType : XBaseGraphObjectType + { + public XAiProjectGraphType() : base() + { + Field(x => x.Title); + Field(x => x.OwnerId); + Field(x => x.Prompt); + Field(x => x.CreatedOn); + Field(x => x.UpdatedAt); + Field(x => x.Description); + } + } +} + +### FILE: C:\Users\saherelm\Documents\Projects\xSaherelmWorkspace\Modules\xAiModels\Providers\GraphQL\XAiVectorGraphQLTypeHelper.cs + +using System; +using xAiModels.Constants; +using xDataService.GraphQL; +using xAiModels.Models.Entities; +using xAiModels.Interfaces.Entities; + +namespace xAiModels.Providers.GraphQL +{ + public class XAiVectorGraphQLTypeHelper : XBaseGraphQLTypeHelper, IXAiVectorGraphQLTypeHelper + { + public override string GetInQueryCollectionName() + { + return XAiModelsConstants.XAiVectorCollectionName; + } + + public override string GetInQuerySingleName() + { + return XAiModelsConstants.XAiVectorSingleName; + } + } +} + +### FILE: C:\Users\saherelm\Documents\Projects\xSaherelmWorkspace\Modules\xAiModels\Providers\GraphQL\XAiVectorGraphQuery.cs + +using System; +using GraphQL.Types; +using xDataService.GraphQL; +using xAiModels.Models.Entities; +using xDataService.Configuration; +using xAiModels.Interfaces.Entities; + +namespace xAiModels.Providers.GraphQL +{ + public class XAiVectorGraphQuery : XBaseGraphQLQuery + { + public XAiVectorGraphQuery( + XDataServiceConfiguration configuration, + IXAiVectorRepository repository, + IXAiVectorGraphQLTypeHelper helper + ) : base( + configuration, + repository, + helper + ) + { } + } +} + +### FILE: C:\Users\saherelm\Documents\Projects\xSaherelmWorkspace\Modules\xAiModels\Providers\GraphQL\XAiVectorGraphSchema.cs + +using System; +using GraphQL.Types; + +namespace xAiModels.Providers.GraphQL +{ + public class XAiVectorGraphSchema : Schema + { + public XAiVectorGraphSchema(IServiceProvider services) : base(services) + { + Query = (XAiVectorGraphQuery)services.GetService(typeof(XAiVectorGraphQuery)); + } + } +} + +### FILE: C:\Users\saherelm\Documents\Projects\xSaherelmWorkspace\Modules\xAiModels\Providers\GraphQL\XAiVectorGraphType.cs + +using System; +using xDataService.GraphQL; +using xAiModels.Models.Entities; + +namespace xAiModels.Providers.GraphQL +{ + public class XAiVectorGraphType : XBaseGraphObjectType + { + public XAiVectorGraphType() : base() + { + Field(x => x.Text); + Field(x => x.Metadata); + Field(x => x.Embedding); + } + } +} + +### FILE: C:\Users\saherelm\Documents\Projects\xSaherelmWorkspace\Modules\xAiModels\Providers\Hubs\XAiDataProviderHub.cs + +using System.Threading; +using xPushService.Base; +using xAiModels.Constants; +using xCommons.Extensions; +using xAiModels.Models.Dtos; +using System.Threading.Tasks; +using Microsoft.AspNetCore.SignalR; +using Microsoft.Extensions.Logging; + +namespace xAiModels.Providers.Hubs +{ + public class XAiDataProviderHub : XBaseHub + { + public XAiDataProviderHub( + ILogger logger + ) : base(logger) + { } + + // + #region XAiProject ... + /// + /// Notify a New Item Created ... + /// + /// + /// + /// + public async Task ProjectCreated( + XAiProjectDto item, + CancellationToken cancellationToken = default + ) + { + // + var connectionId = Context.ConnectionId; + if (!connectionId.IsNullOrEmpty()) + { + // + await Clients + .AllExcept(connectionId) + .SendAsync( + XAiDataProviderHubActions.ProjectCreated.GetStringValue(), + item.ToJSON(camelCase: true), + connectionId, + cancellationToken + ); + } + } + + /// + /// Notify an Item Removed ... + /// + /// + /// + /// + public async Task ProjectRemoved( + XAiProjectDto item, + CancellationToken cancellationToken = default + ) + { + // + var connectionId = Context.ConnectionId; + if (!connectionId.IsNullOrEmpty()) + { + // + await Clients + .AllExcept(connectionId) + .SendAsync( + XAiDataProviderHubActions.ProjectRemoved.GetStringValue(), + item.ToJSON(camelCase: true), + connectionId, + cancellationToken + ); + } + } + + /// + /// Notify an Item Updated ... + /// + /// + /// + /// + public async Task ProjectUpdated( + XAiProjectDto item, + CancellationToken cancellationToken = default + ) + { + // + var connectionId = Context.ConnectionId; + if (!connectionId.IsNullOrEmpty()) + { + // + await Clients + .AllExcept(connectionId) + .SendAsync( + XAiDataProviderHubActions.ProjectUpdated.GetStringValue(), + item.ToJSON(camelCase: true), + connectionId, + cancellationToken + ); + } + } + #endregion + + // + #region XAiConversation ... + /// + /// Notify a New Item Created ... + /// + /// + /// + /// + public async Task ConversationCreated( + XAiProjectDto item, + CancellationToken cancellationToken = default + ) + { + // + var connectionId = Context.ConnectionId; + if (!connectionId.IsNullOrEmpty()) + { + // + await Clients + .AllExcept(connectionId) + .SendAsync( + XAiDataProviderHubActions.ConversationCreated.GetStringValue(), + item.ToJSON(camelCase: true), + connectionId, + cancellationToken + ); + } + } + + /// + /// Notify an Item Removed ... + /// + /// + /// + /// + public async Task ConversationRemoved( + XAiProjectDto item, + CancellationToken cancellationToken = default + ) + { + // + var connectionId = Context.ConnectionId; + if (!connectionId.IsNullOrEmpty()) + { + // + await Clients + .AllExcept(connectionId) + .SendAsync( + XAiDataProviderHubActions.ConversationRemoved.GetStringValue(), + item.ToJSON(camelCase: true), + connectionId, + cancellationToken + ); + } + } + + /// + /// Notify an Item Updated ... + /// + /// + /// + /// + public async Task ConversationUpdated( + XAiProjectDto item, + CancellationToken cancellationToken = default + ) + { + // + var connectionId = Context.ConnectionId; + if (!connectionId.IsNullOrEmpty()) + { + // + await Clients + .AllExcept(connectionId) + .SendAsync( + XAiDataProviderHubActions.ConversationUpdated.GetStringValue(), + item.ToJSON(camelCase: true), + connectionId, + cancellationToken + ); + } + } + #endregion + + // + #region XAiMessage ... + /// + /// Notify a New Item Created ... + /// + /// + /// + /// + public async Task MessageCreated( + XAiProjectDto item, + CancellationToken cancellationToken = default + ) + { + // + var connectionId = Context.ConnectionId; + if (!connectionId.IsNullOrEmpty()) + { + // + await Clients + .AllExcept(connectionId) + .SendAsync( + XAiDataProviderHubActions.MessageCreated.GetStringValue(), + item.ToJSON(camelCase: true), + connectionId, + cancellationToken + ); + } + } + + /// + /// Notify an Item Removed ... + /// + /// + /// + /// + public async Task MessageRemoved( + XAiProjectDto item, + CancellationToken cancellationToken = default + ) + { + // + var connectionId = Context.ConnectionId; + if (!connectionId.IsNullOrEmpty()) + { + // + await Clients + .AllExcept(connectionId) + .SendAsync( + XAiDataProviderHubActions.MessageRemoved.GetStringValue(), + item.ToJSON(camelCase: true), + connectionId, + cancellationToken + ); + } + } + + /// + /// Notify an Item Updated ... + /// + /// + /// + /// + public async Task MessageUpdated( + XAiProjectDto item, + CancellationToken cancellationToken = default + ) + { + // + var connectionId = Context.ConnectionId; + if (!connectionId.IsNullOrEmpty()) + { + // + await Clients + .AllExcept(connectionId) + .SendAsync( + XAiDataProviderHubActions.MessageUpdated.GetStringValue(), + item.ToJSON(camelCase: true), + connectionId, + cancellationToken + ); + } + } + #endregion + } +} diff --git a/Documents/GeneratedContext/xDashboard-xAiService-20261029_200139.txt b/Documents/GeneratedContext/xDashboard-xAiService-20261029_200139.txt new file mode 100644 index 0000000..31bac46 --- /dev/null +++ b/Documents/GeneratedContext/xDashboard-xAiService-20261029_200139.txt @@ -0,0 +1,84 @@ + +### 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\DI\XDIHelperExtension.cs + +namespace xAiService.DI +{ + public static partial class XDIHelperExtension + { } +} + +### FILE: C:\Users\saherelm\Documents\Projects\xSaherelmWorkspace\Modules\xAiService\Extensions\XAiServiceExtensions.cs + +using xCommons.Extensions; +using xExceptions.Constants; +using xIdentityModels.Models; + +namespace xAiService.Extensions +{ + public static class XAiServiceExtensions + { + /// + /// Validate User Info ... + /// + /// + /// + public static bool IsValid(this XUserClaimsInfoDto source) + { + // + var result = + !source.IsNullOrDefault() && + !source.UserId.IsNullOrEmpty() && + !source.AccessToken.IsNullOrEmpty(); + + // + return result; + } + + /// + /// Validate User Info ... + /// + /// + /// + public static void Validate( + this XUserClaimsInfoDto source, + XException invalidException = XException.InvalidArgs + ) + { + // + var isValid = source.IsValid(); + if (!isValid) + { + invalidException.Throw(); + } + } + } +} diff --git a/Modules/xAiModels b/Modules/xAiModels index 093fc08..ef1421d 160000 --- a/Modules/xAiModels +++ b/Modules/xAiModels @@ -1 +1 @@ -Subproject commit 093fc08e14350179c235a821805d2b61b24ea011 +Subproject commit ef1421def4c2b03ad2c86ca0adcfe82f900cd89b diff --git a/Modules/xHttpService b/Modules/xHttpService index d412141..f337233 160000 --- a/Modules/xHttpService +++ b/Modules/xHttpService @@ -1 +1 @@ -Subproject commit d4121411937eaa0bba7c459e0fa3e82f78e58e7e +Subproject commit f3372333fdc30a2cdeddd01dde161c59f2f1ede1 diff --git a/xAiApi b/xAiApi index d3ecc8f..37d4e62 160000 --- a/xAiApi +++ b/xAiApi @@ -1 +1 @@ -Subproject commit d3ecc8feea15a2d8cbcef9d783f189d5590e0bd3 +Subproject commit 37d4e622e9cf3b114146128a613d7a0bb5bbfe42