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);
- ...
This commit is contained in:
2026-10-25 22:25:20 +03:30
parent 43f5cc0cd7
commit a2acb3b055
6 changed files with 1112 additions and 1 deletions
+487
View File
@@ -0,0 +1,487 @@
<!DOCTYPE html>
<html dir="rtl">
<head>
<title>plan1.md</title>
<meta http-equiv="Content-type" content="text/html;charset=UTF-8">
<style>
/* https://github.com/microsoft/vscode/blob/master/extensions/markdown-language-features/media/markdown.css */
/*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
body {
font-family: var(--vscode-markdown-font-family, -apple-system, BlinkMacSystemFont, "Segoe WPC", "Segoe UI", "Ubuntu", "Droid Sans", sans-serif);
font-size: var(--vscode-markdown-font-size, 14px);
padding: 0 26px;
line-height: var(--vscode-markdown-line-height, 22px);
word-wrap: break-word;
}
#code-csp-warning {
position: fixed;
top: 0;
right: 0;
color: white;
margin: 16px;
text-align: center;
font-size: 12px;
font-family: sans-serif;
background-color:#444444;
cursor: pointer;
padding: 6px;
box-shadow: 1px 1px 1px rgba(0,0,0,.25);
}
#code-csp-warning:hover {
text-decoration: none;
background-color:#007acc;
box-shadow: 2px 2px 2px rgba(0,0,0,.25);
}
body.scrollBeyondLastLine {
margin-bottom: calc(100vh - 22px);
}
body.showEditorSelection .code-line {
position: relative;
}
body.showEditorSelection .code-active-line:before,
body.showEditorSelection .code-line:hover:before {
content: "";
display: block;
position: absolute;
top: 0;
left: -12px;
height: 100%;
}
body.showEditorSelection li.code-active-line:before,
body.showEditorSelection li.code-line:hover:before {
left: -30px;
}
.vscode-light.showEditorSelection .code-active-line:before {
border-left: 3px solid rgba(0, 0, 0, 0.15);
}
.vscode-light.showEditorSelection .code-line:hover:before {
border-left: 3px solid rgba(0, 0, 0, 0.40);
}
.vscode-light.showEditorSelection .code-line .code-line:hover:before {
border-left: none;
}
.vscode-dark.showEditorSelection .code-active-line:before {
border-left: 3px solid rgba(255, 255, 255, 0.4);
}
.vscode-dark.showEditorSelection .code-line:hover:before {
border-left: 3px solid rgba(255, 255, 255, 0.60);
}
.vscode-dark.showEditorSelection .code-line .code-line:hover:before {
border-left: none;
}
.vscode-high-contrast.showEditorSelection .code-active-line:before {
border-left: 3px solid rgba(255, 160, 0, 0.7);
}
.vscode-high-contrast.showEditorSelection .code-line:hover:before {
border-left: 3px solid rgba(255, 160, 0, 1);
}
.vscode-high-contrast.showEditorSelection .code-line .code-line:hover:before {
border-left: none;
}
img {
max-width: 100%;
max-height: 100%;
}
a {
text-decoration: none;
}
a:hover {
text-decoration: underline;
}
a:focus,
input:focus,
select:focus,
textarea:focus {
outline: 1px solid -webkit-focus-ring-color;
outline-offset: -1px;
}
hr {
border: 0;
height: 2px;
border-bottom: 2px solid;
}
h1 {
padding-bottom: 0.3em;
line-height: 1.2;
border-bottom-width: 1px;
border-bottom-style: solid;
}
h1, h2, h3 {
font-weight: normal;
}
table {
border-collapse: collapse;
}
table > thead > tr > th {
text-align: left;
border-bottom: 1px solid;
}
table > thead > tr > th,
table > thead > tr > td,
table > tbody > tr > th,
table > tbody > tr > td {
padding: 5px 10px;
}
table > tbody > tr + tr > td {
border-top: 1px solid;
}
blockquote {
margin: 0 7px 0 5px;
padding: 0 16px 0 10px;
border-left-width: 5px;
border-left-style: solid;
}
code {
font-family: Menlo, Monaco, Consolas, "Droid Sans Mono", "Courier New", monospace, "Droid Sans Fallback";
font-size: 1em;
line-height: 1.357em;
}
body.wordWrap pre {
white-space: pre-wrap;
}
pre:not(.hljs),
pre.hljs code > div {
padding: 16px;
border-radius: 3px;
overflow: auto;
}
pre code {
color: var(--vscode-editor-foreground);
tab-size: 4;
}
/** Theming */
.vscode-light pre {
background-color: rgba(220, 220, 220, 0.4);
}
.vscode-dark pre {
background-color: rgba(10, 10, 10, 0.4);
}
.vscode-high-contrast pre {
background-color: rgb(0, 0, 0);
}
.vscode-high-contrast h1 {
border-color: rgb(0, 0, 0);
}
.vscode-light table > thead > tr > th {
border-color: rgba(0, 0, 0, 0.69);
}
.vscode-dark table > thead > tr > th {
border-color: rgba(255, 255, 255, 0.69);
}
.vscode-light h1,
.vscode-light hr,
.vscode-light table > tbody > tr + tr > td {
border-color: rgba(0, 0, 0, 0.18);
}
.vscode-dark h1,
.vscode-dark hr,
.vscode-dark table > tbody > tr + tr > td {
border-color: rgba(255, 255, 255, 0.18);
}
</style>
<style>
/* Tomorrow Theme */
/* http://jmblog.github.com/color-themes-for-google-code-highlightjs */
/* Original theme - https://github.com/chriskempson/tomorrow-theme */
/* Tomorrow Comment */
.hljs-comment,
.hljs-quote {
color: #8e908c;
}
/* Tomorrow Red */
.hljs-variable,
.hljs-template-variable,
.hljs-tag,
.hljs-name,
.hljs-selector-id,
.hljs-selector-class,
.hljs-regexp,
.hljs-deletion {
color: #c82829;
}
/* Tomorrow Orange */
.hljs-number,
.hljs-built_in,
.hljs-builtin-name,
.hljs-literal,
.hljs-type,
.hljs-params,
.hljs-meta,
.hljs-link {
color: #f5871f;
}
/* Tomorrow Yellow */
.hljs-attribute {
color: #eab700;
}
/* Tomorrow Green */
.hljs-string,
.hljs-symbol,
.hljs-bullet,
.hljs-addition {
color: #718c00;
}
/* Tomorrow Blue */
.hljs-title,
.hljs-section {
color: #4271ae;
}
/* Tomorrow Purple */
.hljs-keyword,
.hljs-selector-tag {
color: #8959a8;
}
.hljs {
display: block;
overflow-x: auto;
color: #4d4d4c;
padding: 0.5em;
}
.hljs-emphasis {
font-style: italic;
}
.hljs-strong {
font-weight: bold;
}
</style>
<style>
/*
* Markdown PDF CSS
*/
body {
font-family: -apple-system, BlinkMacSystemFont, "Segoe WPC", "Segoe UI", "Ubuntu", "Droid Sans", sans-serif, "Meiryo";
padding: 0 12px;
}
pre {
background-color: #f8f8f8;
border: 1px solid #cccccc;
border-radius: 3px;
overflow-x: auto;
white-space: pre-wrap;
overflow-wrap: break-word;
}
pre:not(.hljs) {
padding: 23px;
line-height: 19px;
}
blockquote {
background: rgba(127, 127, 127, 0.1);
border-color: rgba(0, 122, 204, 0.5);
}
.emoji {
height: 1.4em;
}
code {
font-size: 14px;
line-height: 19px;
}
/* for inline code */
:not(pre):not(.hljs) > code {
color: #C9AE75; /* Change the old color so it seems less like an error */
font-size: inherit;
}
/* Page Break : use <div class="page"/> or <div class="page"></div> to insert page break
-------------------------------------------------------- */
.page {
page-break-after: always;
}
</style>
<script src="https://unpkg.com/mermaid/dist/mermaid.min.js"></script>
</head>
<body>
<script>
mermaid.initialize({
startOnLoad: true,
theme: document.body.classList.contains('vscode-dark') || document.body.classList.contains('vscode-high-contrast')
? 'dark'
: 'default'
});
</script>
<p>‌<code>xFrameworkTest</code> یک پروژه Cordova/JS است، نه پروژه تست .NET — بنابراین یونیت‌تست C# جایی برای قرارگیری ندارد (در برنامه لحاظ می‌کنم).</p>
<h2 id="وضعیت-فعلی-آنچه-انجام-شده">وضعیت فعلی (آنچه انجام شده)</h2>
<table>
<thead>
<tr>
<th>مؤلفه</th>
<th>وضعیت</th>
<th>محل</th>
</tr>
</thead>
<tbody>
<tr>
<td><code>IXTextChunker</code> / <code>XTextChunker</code></td>
<td>انجام شده، در DI ثبت شده</td>
<td><code>xAiApi\Providers\XTextChunker.cs</code></td>
</tr>
<tr>
<td><code>XTextChunk</code>, <code>XTextChunkerDescriptor</code> + <code>IsValid()</code> + کانفیگ <code>TextChunker</code></td>
<td>انجام شده</td>
<td><code>Models\</code>, <code>Extensions\XModelsExtensions.cs:51</code>, <code>appsettings.Development.json</code></td>
</tr>
<tr>
<td><code>IXInMemoryVectorStore</code> / <code>XInMemoryVectorStore</code> / <code>XAiDocumentSession</code></td>
<td>انجام شده، در DI ثبت شده (TTL پیش‌فرض ۳۰ دقیقه، OwnerId، CosineSimilarity)</td>
<td><code>xAiApi\Providers\XInMemoryVectorStore.cs</code></td>
</tr>
<tr>
<td><code>ChatWithDocumentsController</code></td>
<td><strong>اسکلت خالی</strong> — هنوز <code>IList&lt;XAiVectorDto&gt; vectorStore</code> محلی دارد، <code>using Microsoft.AspNetCore.Components</code> اشتباه (باید <code>Mvc</code> باشد)، هیچ Endpoint ندارد، <code>IXInMemoryVectorStore</code>/<code>IXTextChunker</code> تزریق نشده</td>
<td><code>xAiApi\Controllers\ChatWithDocumentsController.cs:6,30</code></td>
</tr>
<tr>
<td><code>AskWithContextAsync</code> در <code>IXAiServiceBase</code></td>
<td><strong>انجام نشده</strong></td>
<td>—</td>
</tr>
<tr>
<td>پرامپت <code>ChatWithDocuments</code> در appsettings + ثابت‌ها</td>
<td><strong>انجام نشده</strong> (فقط Introduction/ContentExtraction/Embedding وجود دارد)</td>
<td><code>Constants\XAiApiConstants.cs:14-22</code></td>
</tr>
<tr>
<td>مدل‌های Request/Response</td>
<td><strong>انجام نشده</strong></td>
<td>—</td>
</tr>
<tr>
<td>ثبت <code>RemoveExpired</code> دوره‌ای</td>
<td><strong>انجام نشده</strong> (فقط lazy داخل <code>Count</code>/<code>TryGet</code>)</td>
<td>—</td>
</tr>
</tbody>
</table>
<h2 id="گامهای-باقیمانده">گام‌های باقی‌مانده</h2>
<h3 id="گام-۱--ثوابت-و-پرامپت">گام ۱ — ثوابت و پرامپت</h3>
<ul>
<li><code>xAiApi\Constants\XAiApiConstants.cs</code>: افزودن
<code>XAiApiChatWithDocumentsPromptName = &quot;ChatWithDocuments&quot;</code>, <code>XAiDocumentDefaultTopK = 5</code>, <code>XAiDocumentDefaultMinScore = 0.35f</code>, <code>XAiDocumentDefaultTtlMinutes = 30</code>, کلیدهای Metadata (<code>fileName</code>, <code>mimeType</code>, <code>chunkIndex</code>).</li>
<li><code>appsettings.Development.json</code> و <code>appsettings.json</code>: افزودن پرامپت <code>ChatWithDocuments</code> به آرایه <code>Prompts</code> (دستور پاسخ‌دهی فقط بر اساس Context، ذکر منبع، و اعلام «در اسناد یافت نشد»). پرامپت باید placeholder برای Context داشته باشد یا Context به‌صورت پیام جداگانه System ارسال شود (پیشنهاد: پیام جدا، ساده‌تر).</li>
</ul>
<h3 id="گام-۲--مدلهای-dto-پوشه-xaiapimodels">گام ۲ — مدل‌های DTO (پوشه <code>xAiApi\Models\</code>)</h3>
<ul>
<li><code>XAiDocumentIngestResult</code> — <code>SessionId</code>, <code>FilesCount</code>, <code>ChunksCount</code>, <code>SkippedFiles[]</code>, <code>ExpiresAtUtc</code></li>
<li><code>XAiDocumentAskRequest</code> — <code>SessionId</code>, <code>Prompt</code>, <code>TopK?</code>, <code>MinScore?</code> + متد <code>IsValid()</code> در <code>XModelsExtensions</code></li>
<li><code>XAiDocumentAnswer</code> — <code>Answer</code>, <code>NoContextFound</code>, <code>Sources: IList&lt;XAiDocumentSource&gt;</code> (<code>Identifier</code>, <code>FileName</code>, <code>ChunkIndex</code>, <code>Score</code>, <code>Snippet</code>)</li>
<li><code>XAiDocumentSessionInfo</code> — خروجی <code>GET Session/{id}</code> بدون Embeddingها (<code>Id</code>, <code>CreatedAtUtc</code>, <code>LastAccessAtUtc</code>, <code>Ttl</code>, <code>VectorsCount</code>, فهرست فایل‌ها)</li>
</ul>
<h3 id="گام-۳--سرویس-پایه-askwithcontextasync--askwithcontextasenumerable">گام ۳ — سرویس پایه: <code>AskWithContextAsync</code> / <code>AskWithContextAsEnumerable</code></h3>
<ul>
<li><code>Interfaces\IXAiServiceBase.cs</code>: افزودن region جدید «Context Actions» با دو امضا:
<code>Task&lt;string&gt; AskWithContextAsync(string prompt, IEnumerable&lt;XAiVectorSearchResult&gt; context, CancellationToken)</code> و نسخه <code>IAsyncEnumerable&lt;string&gt;</code>.</li>
<li><code>Providers\XAIServiceBase.cs</code>: پیاده‌سازی مشابه <code>AskTextAsync</code> (:97) ولی History =
<code>[System: Introduction] + [System: ChatWithDocuments-Prompt + Context متنی (هر chunk با شماره و Identifier)] + [User: prompt]</code>.
<strong>بدون</strong> هیچ تماسی با <code>dataProvider</code> (ذخیره در DB نمی‌شود). متد کمکی private <code>BuildContextBlock(IEnumerable&lt;XAiVectorSearchResult&gt;)</code>.</li>
</ul>
<h3 id="گام-۴--بازنویسی-chatwithdocumentscontroller">گام ۴ — بازنویسی <code>ChatWithDocumentsController</code></h3>
<ul>
<li>اصلاح <code>using Microsoft.AspNetCore.Components</code> → <code>Microsoft.AspNetCore.Mvc</code>؛ حذف فیلد <code>vectorStore</code> و <code>IDisposable</code>.</li>
<li>تزریق: <code>IXDefaultAiService</code>, <code>IXDefaultEmbeddingService</code>, <code>IXFileContentExtractor</code>, <code>IXTextChunker</code>, <code>IXInMemoryVectorStore</code>, <code>XAiApiConfiguration</code>.</li>
<li>Endpointها (الگو از <code>XAiServiceControllerBase.cs:718-760</code> و SSE از <code>:655-710</code>):
<ul>
<li><code>POST Ingest</code> (<code>multipart/form-data</code>, <code>IFormFileCollection</code>, اختیاری <code>sessionId</code> برای افزودن به Session موجود): هر فایل → <code>CanExtract</code> → <code>ExtractRichAsync</code> → متن = <code>Text ?? AudioTranscript</code> → <code>textChunker.Chunk(text, fileName)</code> → <code>embeddingService.Embeddings(batch)</code> → ساخت <code>XAiVectorDto</code> با <code>Identifier = chunk.Identifier</code>, <code>Metadata{fileName, mimeType, chunkIndex}</code> → <code>vectorStore.CreateSession(vectors, ownerId)</code> یا <code>Add(...)</code> → بازگشت <code>XAiDocumentIngestResult</code>.</li>
<li><code>POST Ask</code> (<code>[FromBody] XAiDocumentAskRequest</code>): <code>embeddingService.Embedding(prompt)</code> → <code>vectorStore.Search(sessionId, emb, topK, minScore, ownerId)</code> → اگر خالی: <code>{ NoContextFound = true }</code> → وگرنه <code>aiService.AskWithContextAsync</code> → <code>XAiDocumentAnswer</code> با Sources.</li>
<li><code>POST AskStream</code>: همان جریان با <code>AskWithContextAsEnumerable</code> و SSE (کپی هدرها و <code>DisableBuffering</code> از کنترلر پایه).</li>
<li><code>GET Session/{id}</code>: <code>TryGet</code> → <code>XAiDocumentSessionInfo</code> یا 404.</li>
<li><code>DELETE Session/{id}</code>: <code>Remove</code> → 200/404.</li>
</ul>
</li>
<li>همه با <code>try/catch</code> + <code>GetExceptionActionResult(ex)</code> و <code>ownerId = (await GetUserInfo()).UserId</code> طبق الگوی موجود.</li>
</ul>
<h3 id="گام-۵--di-و-startup">گام ۵ — DI و Startup</h3>
<ul>
<li><code>DI\XDIHelperExtension.cs</code>: متد <code>AddXAiChatWithDocuments()</code> که <code>AddXAiTextChunker()</code> + <code>AddXAiInMemoryVectorStore()</code> را صدا می‌زند؛ <code>Startup.cs:191-196</code> به یک فراخوانی ساده‌تر تبدیل شود.</li>
<li>(اختیاری) یک <code>BackgroundService</code>/<code>Timer</code> ساده برای <code>RemoveExpired()</code> هر ۵ دقیقه تا حافظه نشت نکند.</li>
</ul>
<h3 id="گام-۶--بهبودهای-کوچک-vector-store-اختیاری-ولی-توصیهشده">گام ۶ — بهبودهای کوچک Vector Store (اختیاری ولی توصیه‌شده)</h3>
<ul>
<li><code>XInMemoryVectorStore.cs:138-139</code>: <code>queryEmbedding.ToArray()</code> در هر iteration حلقه تکرار می‌شود → یک‌بار قبل از حلقه.</li>
<li>محدودیت حداکثر تعداد Session / Vector برای جلوگیری از OOM (ثابت در Constants).</li>
</ul>
<h3 id="گام-۷--اعتبارسنجی">گام ۷ — اعتبارسنجی</h3>
<ul>
<li><code>dotnet build xAiApi\xAiApi.csproj</code></li>
<li>تست دستی: <code>POST ChatWithDocuments/Ingest</code> با یک PDF → دریافت <code>SessionId</code> → <code>POST Ask</code> با سؤال مرتبط و نامرتبط (بررسی <code>NoContextFound</code>) → <code>AskStream</code> → <code>DELETE Session</code>.</li>
<li><strong>یونیت‌تست:</strong> <code>xFrameworkTest</code> پروژه Cordova/JS است، نه .NET؛ پس یا تست‌ها حذف شوند یا یک پروژه <code>xAiApi.Tests</code> (xUnit) جدید ساخته شود — نیاز به تصمیم شما.</li>
</ul>
<h3 id="گام-۸--مستندسازی">گام ۸ — مستندسازی</h3>
<ul>
<li>به‌روزرسانی <code>Documents\Docs\ChangeLogs\1405-08-03.html</code> (یا ChangeLog روز بعد) و حذف فایل‌های موقت <code>Documents\Markdown\tmp.md/tmp.html</code> یا انتقال به <code>Documents\Docs\Developer\17_ChatWithDocuments.html</code>.</li>
</ul>
<h2 id="نکات-تصمیمگیری">نکات تصمیم‌گیری</h2>
<ol>
<li><strong>Context در پرامپت یا پیام جدا؟</strong> پیشنهاد: پیام System جداگانه (بدون نیاز به placeholder).</li>
<li><strong>Ingest روی Session موجود</strong> (<code>Add</code>) پشتیبانی شود یا هر Ingest، Session جدید بسازد؟ پیشنهاد: پارامتر اختیاری <code>sessionId</code>.</li>
<li><strong>یونیت‌تست</strong>: ساخت پروژه <code>xAiApi.Tests</code> یا صرف‌نظر؟</li>
</ol>
<p>اگر طرح مورد تأیید است، گزینه‌های بالا را مشخص کنید و به <strong>Act mode</strong> سوئیچ کنید (toggle to Act mode) تا پیاده‌سازی را از گام ۱ شروع کنم.</p>
</body>
</html>
+68
View File
@@ -0,0 +1,68 @@
‌`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) تا پیاده‌سازی را از گام ۱ شروع کنم.