Files
saherelm a2acb3b055 Update xAiApi Submodule (Chat With Documents) and Add ChangeLog / Plan Documents ...
- Update xAiApi Submodule Pointer to Chat With Documents (In-Memory RAG) Implementation;
- Add Documents/Docs/ChangeLogs/1405-08-03.html (ChangeLog of Pushed Commits);
- Add Documents/Docs/ChangeLogs/1405-08-03-uncommitted.html (ChangeLog of this Commit);
- Add Documents/Docs/ChangeLogs/CommitMessage-1405-08-03.txt;
- Add Documents/Markdown/plan1.md and plan1.html (Chat With Documents Implementation Plan);
- ...
2026-10-25 22:25:20 +03:30

68 lines
7.7 KiB
Markdown
Raw Permalink Blame History

This file contains invisible Unicode characters
This file contains invisible Unicode characters that are indistinguishable to humans but may be processed differently by a computer. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
‌`xFrameworkTest` یک پروژه Cordova/JS است، نه پروژه تست .NET — بنابراین یونیت‌تست C# جایی برای قرارگیری ندارد (در برنامه لحاظ می‌کنم).
## وضعیت فعلی (آنچه انجام شده)
| مؤلفه | وضعیت | محل |
|---|---|---|
| `IXTextChunker` / `XTextChunker` | انجام شده، در DI ثبت شده | `xAiApi\Providers\XTextChunker.cs` |
| `XTextChunk`, `XTextChunkerDescriptor` + `IsValid()` + کانفیگ `TextChunker` | انجام شده | `Models\`, `Extensions\XModelsExtensions.cs:51`, `appsettings.Development.json` |
| `IXInMemoryVectorStore` / `XInMemoryVectorStore` / `XAiDocumentSession` | انجام شده، در DI ثبت شده (TTL پیش‌فرض ۳۰ دقیقه، OwnerId، CosineSimilarity) | `xAiApi\Providers\XInMemoryVectorStore.cs` |
| `ChatWithDocumentsController` | **اسکلت خالی** — هنوز `IList<XAiVectorDto> vectorStore` محلی دارد، `using Microsoft.AspNetCore.Components` اشتباه (باید `Mvc` باشد)، هیچ Endpoint ندارد، `IXInMemoryVectorStore`/`IXTextChunker` تزریق نشده | `xAiApi\Controllers\ChatWithDocumentsController.cs:6,30` |
| `AskWithContextAsync` در `IXAiServiceBase` | **انجام نشده** | — |
| پرامپت `ChatWithDocuments` در appsettings + ثابت‌ها | **انجام نشده** (فقط Introduction/ContentExtraction/Embedding وجود دارد) | `Constants\XAiApiConstants.cs:14-22` |
| مدل‌های Request/Response | **انجام نشده** | — |
| ثبت `RemoveExpired` دوره‌ای | **انجام نشده** (فقط lazy داخل `Count`/`TryGet`) | — |
## گام‌های باقی‌مانده
### گام ۱ — ثوابت و پرامپت
- `xAiApi\Constants\XAiApiConstants.cs`: افزودن
`XAiApiChatWithDocumentsPromptName = "ChatWithDocuments"`, `XAiDocumentDefaultTopK = 5`, `XAiDocumentDefaultMinScore = 0.35f`, `XAiDocumentDefaultTtlMinutes = 30`, کلیدهای Metadata (`fileName`, `mimeType`, `chunkIndex`).
- `appsettings.Development.json` و `appsettings.json`: افزودن پرامپت `ChatWithDocuments` به آرایه `Prompts` (دستور پاسخ‌دهی فقط بر اساس Context، ذکر منبع، و اعلام «در اسناد یافت نشد»). پرامپت باید placeholder برای Context داشته باشد یا Context به‌صورت پیام جداگانه System ارسال شود (پیشنهاد: پیام جدا، ساده‌تر).
### گام ۲ — مدل‌های DTO (پوشه `xAiApi\Models\`)
- `XAiDocumentIngestResult` — `SessionId`, `FilesCount`, `ChunksCount`, `SkippedFiles[]`, `ExpiresAtUtc`
- `XAiDocumentAskRequest` — `SessionId`, `Prompt`, `TopK?`, `MinScore?` + متد `IsValid()` در `XModelsExtensions`
- `XAiDocumentAnswer` — `Answer`, `NoContextFound`, `Sources: IList<XAiDocumentSource>` (`Identifier`, `FileName`, `ChunkIndex`, `Score`, `Snippet`)
- `XAiDocumentSessionInfo` — خروجی `GET Session/{id}` بدون Embeddingها (`Id`, `CreatedAtUtc`, `LastAccessAtUtc`, `Ttl`, `VectorsCount`, فهرست فایل‌ها)
### گام ۳ — سرویس پایه: `AskWithContextAsync` / `AskWithContextAsEnumerable`
- `Interfaces\IXAiServiceBase.cs`: افزودن region جدید «Context Actions» با دو امضا:
`Task<string> AskWithContextAsync(string prompt, IEnumerable<XAiVectorSearchResult> context, CancellationToken)` و نسخه `IAsyncEnumerable<string>`.
- `Providers\XAIServiceBase.cs`: پیاده‌سازی مشابه `AskTextAsync` (:97) ولی History =
`[System: Introduction] + [System: ChatWithDocuments-Prompt + Context متنی (هر chunk با شماره و Identifier)] + [User: prompt]`.
**بدون** هیچ تماسی با `dataProvider` (ذخیره در DB نمی‌شود). متد کمکی private `BuildContextBlock(IEnumerable<XAiVectorSearchResult>)`.
### گام ۴ — بازنویسی `ChatWithDocumentsController`
- اصلاح `using Microsoft.AspNetCore.Components` → `Microsoft.AspNetCore.Mvc`؛ حذف فیلد `vectorStore` و `IDisposable`.
- تزریق: `IXDefaultAiService`, `IXDefaultEmbeddingService`, `IXFileContentExtractor`, `IXTextChunker`, `IXInMemoryVectorStore`, `XAiApiConfiguration`.
- Endpointها (الگو از `XAiServiceControllerBase.cs:718-760` و SSE از `:655-710`):
- `POST Ingest` (`multipart/form-data`, `IFormFileCollection`, اختیاری `sessionId` برای افزودن به Session موجود): هر فایل → `CanExtract` → `ExtractRichAsync` → متن = `Text ?? AudioTranscript` → `textChunker.Chunk(text, fileName)` → `embeddingService.Embeddings(batch)` → ساخت `XAiVectorDto` با `Identifier = chunk.Identifier`, `Metadata{fileName, mimeType, chunkIndex}` → `vectorStore.CreateSession(vectors, ownerId)` یا `Add(...)` → بازگشت `XAiDocumentIngestResult`.
- `POST Ask` (`[FromBody] XAiDocumentAskRequest`): `embeddingService.Embedding(prompt)` → `vectorStore.Search(sessionId, emb, topK, minScore, ownerId)` → اگر خالی: `{ NoContextFound = true }` → وگرنه `aiService.AskWithContextAsync` → `XAiDocumentAnswer` با Sources.
- `POST AskStream`: همان جریان با `AskWithContextAsEnumerable` و SSE (کپی هدرها و `DisableBuffering` از کنترلر پایه).
- `GET Session/{id}`: `TryGet` → `XAiDocumentSessionInfo` یا 404.
- `DELETE Session/{id}`: `Remove` → 200/404.
- همه با `try/catch` + `GetExceptionActionResult(ex)` و `ownerId = (await GetUserInfo()).UserId` طبق الگوی موجود.
### گام ۵ — DI و Startup
- `DI\XDIHelperExtension.cs`: متد `AddXAiChatWithDocuments()` که `AddXAiTextChunker()` + `AddXAiInMemoryVectorStore()` را صدا می‌زند؛ `Startup.cs:191-196` به یک فراخوانی ساده‌تر تبدیل شود.
- (اختیاری) یک `BackgroundService`/`Timer` ساده برای `RemoveExpired()` هر ۵ دقیقه تا حافظه نشت نکند.
### گام ۶ — بهبودهای کوچک Vector Store (اختیاری ولی توصیه‌شده)
- `XInMemoryVectorStore.cs:138-139`: `queryEmbedding.ToArray()` در هر iteration حلقه تکرار می‌شود → یک‌بار قبل از حلقه.
- محدودیت حداکثر تعداد Session / Vector برای جلوگیری از OOM (ثابت در Constants).
### گام ۷ — اعتبارسنجی
- `dotnet build xAiApi\xAiApi.csproj`
- تست دستی: `POST ChatWithDocuments/Ingest` با یک PDF → دریافت `SessionId` → `POST Ask` با سؤال مرتبط و نامرتبط (بررسی `NoContextFound`) → `AskStream` → `DELETE Session`.
- **یونیت‌تست:** `xFrameworkTest` پروژه Cordova/JS است، نه .NET؛ پس یا تست‌ها حذف شوند یا یک پروژه `xAiApi.Tests` (xUnit) جدید ساخته شود — نیاز به تصمیم شما.
### گام ۸ — مستندسازی
- به‌روزرسانی `Documents\Docs\ChangeLogs\1405-08-03.html` (یا ChangeLog روز بعد) و حذف فایل‌های موقت `Documents\Markdown\tmp.md/tmp.html` یا انتقال به `Documents\Docs\Developer\17_ChatWithDocuments.html`.
## نکات تصمیم‌گیری
1. **Context در پرامپت یا پیام جدا؟** پیشنهاد: پیام System جداگانه (بدون نیاز به placeholder).
2. **Ingest روی Session موجود** (`Add`) پشتیبانی شود یا هر Ingest، Session جدید بسازد؟ پیشنهاد: پارامتر اختیاری `sessionId`.
3. **یونیت‌تست**: ساخت پروژه `xAiApi.Tests` یا صرف‌نظر؟
اگر طرح مورد تأیید است، گزینه‌های بالا را مشخص کنید و به **Act mode** سوئیچ کنید (toggle to Act mode) تا پیاده‌سازی را از گام ۱ شروع کنم.