Files
xSaherelmWorkspace/Documents/Docs/Developer/Ai Agent Support in XAi Platform Roadmap 1.html
T
2026-11-06 21:00:06 +03:30

1454 lines
71 KiB
HTML
Raw Blame History

This file contains ambiguous Unicode characters
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.
<!DOCTYPE html>
<html lang="fa" dir="rtl">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>معماری و پیاده‌سازی AI Agent | راهنمای جامع گام‌به‌گام</title>
<style>
@import url('https://fonts.googleapis.com/css2?family=Vazirmatn:wght@300;400;500;600;700;800&display=swap');
:root {
--primary: #1a365d;
--primary-light: #2c5282;
--accent: #c9a961;
--accent-dark: #a8893f;
--bg: #faf9f6;
--card-bg: #ffffff;
--text: #1a202c;
--text-muted: #4a5568;
--border: #e2e8f0;
--success: #38a169;
--danger: #e53e3e;
--warning: #dd6b20;
--info: #3182ce;
--shadow: 0 4px 6px rgba(0,0,0,0.05), 0 10px 30px rgba(26,54,93,0.08);
}
* { box-sizing: border-box; margin: 0; padding: 0; }
body {
font-family: 'Vazirmatn', Tahoma, sans-serif;
background: var(--bg);
color: var(--text);
line-height: 1.9;
font-size: 15px;
padding: 30px 15px;
}
.document-container {
max-width: 980px;
margin: 0 auto;
background: var(--card-bg);
box-shadow: var(--shadow);
border-radius: 12px;
overflow: hidden;
}
.document-header {
background: linear-gradient(135deg, var(--primary) 0%, var(--primary-light) 100%);
color: white;
padding: 50px 40px 40px;
position: relative;
border-bottom: 4px solid var(--accent);
}
.document-header::before {
content: '';
position: absolute;
top: 0; right: 0;
width: 200px; height: 200px;
background: radial-gradient(circle, rgba(201,169,97,0.15) 0%, transparent 70%);
border-radius: 50%;
transform: translate(50%, -50%);
}
.header-top {
display: flex;
justify-content: space-between;
align-items: center;
margin-bottom: 30px;
position: relative;
z-index: 1;
}
.company-badge {
display: flex;
align-items: center;
gap: 12px;
}
.company-logo {
width: 60px; height: 60px;
background: var(--accent);
border-radius: 12px;
box-shadow: 0 4px 12px rgba(0,0,0,0.2);
display: flex;
align-items: center;
justify-content: center;
font-size: 28px;
font-weight: 800;
color: var(--primary);
}
.doc-meta {
text-align: left;
font-size: 12px;
opacity: 0.9;
}
.doc-meta div { margin-bottom: 3px; }
.document-title {
text-align: center;
position: relative;
z-index: 1;
padding: 20px 0;
}
.document-title .label {
display: inline-block;
background: rgba(201,169,97,0.2);
color: var(--accent);
padding: 4px 16px;
border-radius: 20px;
font-size: 12px;
font-weight: 600;
margin-bottom: 15px;
border: 1px solid rgba(201,169,97,0.4);
}
.document-title h1 {
font-size: 28px;
font-weight: 800;
margin-bottom: 10px;
letter-spacing: -0.5px;
}
.document-title h2 {
font-size: 16px;
font-weight: 400;
opacity: 0.9;
}
.document-body {
padding: 40px;
}
.intro-text {
background: linear-gradient(to left, #f7fafc, #edf2f7);
border-right: 4px solid var(--accent);
padding: 20px 25px;
border-radius: 8px;
margin-bottom: 35px;
font-size: 14px;
color: var(--text-muted);
}
.section {
margin-bottom: 40px;
page-break-inside: avoid;
}
.section-header {
display: flex;
align-items: center;
gap: 15px;
padding-bottom: 12px;
border-bottom: 2px solid var(--border);
margin-bottom: 20px;
}
.section-number {
width: 50px; height: 50px;
background: linear-gradient(135deg, var(--primary), var(--primary-light));
color: white;
border-radius: 12px;
display: flex;
align-items: center;
justify-content: center;
font-weight: 800;
font-size: 20px;
flex-shrink: 0;
box-shadow: 0 4px 10px rgba(26,54,93,0.2);
}
.section-title { flex: 1; }
.section-title h3 {
font-size: 19px;
font-weight: 700;
color: var(--primary);
margin-bottom: 2px;
}
.section-title .subtitle {
font-size: 12px;
color: var(--text-muted);
}
.section-content {
padding-right: 10px;
}
.section-content p {
margin-bottom: 12px;
text-align: justify;
text-indent: 20px;
}
.section-content p.no-indent { text-indent: 0; }
.section-content h4 {
color: var(--primary);
font-size: 16px;
margin: 22px 0 12px;
}
.section-content ul,
.section-content ol {
padding-right: 24px;
margin-bottom: 15px;
}
.section-content ul li,
.section-content ol li {
margin-bottom: 8px;
text-align: justify;
}
.highlight-box {
background: linear-gradient(to left, #fffaf0, #fef5e7);
border: 1px solid #f6e05e;
border-right: 4px solid var(--accent);
padding: 18px 22px;
border-radius: 8px;
margin: 20px 0;
font-size: 14px;
}
.highlight-box strong { color: var(--accent-dark); }
.info-box {
background: linear-gradient(to left, #ebf8ff, #e6f6ff);
border: 1px solid #90cdf4;
border-right: 4px solid var(--info);
padding: 18px 22px;
border-radius: 8px;
margin: 20px 0;
font-size: 14px;
}
.success-box {
background: linear-gradient(to left, #f0fff4, #e6fffa);
border: 1px solid #9ae6b4;
border-right: 4px solid var(--success);
padding: 18px 22px;
border-radius: 8px;
margin: 20px 0;
font-size: 14px;
}
.warning-box {
background: linear-gradient(to left, #fffaf0, #fef5e7);
border: 1px solid #fbd38d;
border-right: 4px solid var(--warning);
padding: 18px 22px;
border-radius: 8px;
margin: 20px 0;
font-size: 14px;
}
.danger-box {
background: linear-gradient(to left, #fff5f5, #fed7d7);
border: 1px solid #fc8181;
border-right: 4px solid var(--danger);
padding: 18px 22px;
border-radius: 8px;
margin: 20px 0;
font-size: 14px;
}
.styled-table {
width: 100%;
border-collapse: collapse;
margin: 20px 0;
background: white;
border-radius: 8px;
overflow: hidden;
box-shadow: 0 2px 8px rgba(0,0,0,0.05);
}
.styled-table thead {
background: linear-gradient(135deg, var(--primary), var(--primary-light));
color: white;
}
.styled-table th {
padding: 14px 16px;
text-align: right;
font-weight: 600;
font-size: 13px;
}
.styled-table td {
padding: 13px 16px;
border-bottom: 1px solid var(--border);
font-size: 13px;
vertical-align: top;
}
.styled-table tbody tr:last-child td { border-bottom: none; }
.styled-table tbody tr:nth-child(even) { background: #f8fafc; }
.styled-table .highlight-row {
background: #fffaf0 !important;
font-weight: 600;
}
.comparison-grid {
display: grid;
grid-template-columns: 1fr 1fr;
gap: 20px;
margin: 25px 0;
}
.comparison-card {
background: #f8fafc;
border: 2px solid var(--border);
border-radius: 10px;
padding: 20px;
position: relative;
}
.comparison-card.recommended {
border-color: var(--success);
background: linear-gradient(to left, #f0fff4, #e6fffa);
}
.comparison-card .card-badge {
position: absolute;
top: -10px;
right: 20px;
background: var(--success);
color: white;
padding: 3px 12px;
border-radius: 15px;
font-size: 11px;
font-weight: 600;
}
.comparison-card h4 {
font-size: 16px;
font-weight: 700;
color: var(--primary);
margin-bottom: 15px;
padding-bottom: 10px;
border-bottom: 2px solid var(--border);
}
.comparison-card.recommended h4 { border-bottom-color: var(--success); }
.comparison-card ul { list-style: none; padding: 0; }
.comparison-card ul li {
padding: 8px 0;
border-bottom: 1px solid var(--border);
font-size: 13px;
display: flex;
justify-content: space-between;
}
.comparison-card ul li:last-child { border-bottom: none; }
.stats-grid {
display: grid;
grid-template-columns: repeat(3, 1fr);
gap: 15px;
margin: 25px 0;
}
.stat-card {
background: linear-gradient(135deg, var(--primary), var(--primary-light));
color: white;
padding: 20px;
border-radius: 10px;
text-align: center;
box-shadow: 0 4px 12px rgba(26,54,93,0.2);
}
.stat-card .stat-value {
font-size: 22px;
font-weight: 800;
margin-bottom: 5px;
color: var(--accent);
line-height: 1.3;
}
.stat-card .stat-label {
font-size: 12px;
opacity: 0.9;
}
.code-block {
background: #1a202c;
color: #e2e8f0;
padding: 18px 22px;
border-radius: 8px;
font-family: 'Consolas', 'Courier New', monospace;
font-size: 12.5px;
line-height: 1.7;
overflow-x: auto;
direction: ltr;
text-align: left;
margin: 15px 0;
border-right: 4px solid var(--accent);
white-space: pre;
}
.code-block .kw { color: #f6ad55; }
.code-block .type { color: #63b3ed; }
.code-block .str { color: #9ae6b4; }
.code-block .cmt { color: #718096; font-style: italic; }
.code-block .fn { color: #fbb6ce; }
.step {
display: flex;
gap: 20px;
margin-bottom: 25px;
padding: 20px;
background: #f8fafc;
border-radius: 10px;
border: 1px solid var(--border);
}
.step-badge {
width: 55px;
height: 55px;
background: linear-gradient(135deg, var(--primary), var(--primary-light));
color: var(--accent);
border-radius: 12px;
display: flex;
align-items: center;
justify-content: center;
font-weight: 800;
font-size: 18px;
flex-shrink: 0;
box-shadow: 0 4px 10px rgba(26,54,93,0.15);
}
.step-content { flex: 1; }
.step-content h4 {
color: var(--primary);
font-size: 16px;
margin-bottom: 8px;
margin-top: 0;
}
.step-content p {
text-indent: 0 !important;
font-size: 14px;
}
.phase-header {
background: linear-gradient(135deg, var(--accent), var(--accent-dark));
color: var(--primary);
padding: 14px 22px;
border-radius: 8px;
margin: 30px 0 20px;
font-weight: 700;
font-size: 16px;
box-shadow: 0 4px 12px rgba(201,169,97,0.3);
}
.tag {
display: inline-block;
padding: 3px 10px;
border-radius: 12px;
font-size: 11px;
font-weight: 600;
margin-left: 5px;
}
.tag-existing { background: #c6f6d5; color: #22543d; }
.tag-missing { background: #fed7d7; color: #742a2a; }
.tag-partial { background: #feebc8; color: #7b341e; }
.tag-new { background: #bee3f8; color: #2a4365; }
.architecture-diagram {
background: #1a202c;
color: #e2e8f0;
padding: 25px;
border-radius: 10px;
font-family: 'Consolas', 'Courier New', monospace;
font-size: 12px;
line-height: 1.6;
direction: ltr;
text-align: left;
overflow-x: auto;
margin: 20px 0;
border-right: 4px solid var(--accent);
white-space: pre;
}
.document-footer {
background: var(--primary);
color: white;
padding: 25px 40px;
text-align: center;
font-size: 12px;
margin-top: 40px;
}
.document-footer .footer-brand {
font-weight: 700;
color: var(--accent);
margin-bottom: 5px;
font-size: 14px;
}
.footer-divider {
width: 60px;
height: 2px;
background: var(--accent);
margin: 10px auto;
}
.page-info {
text-align: center;
padding: 15px;
font-size: 11px;
color: var(--text-muted);
border-top: 1px solid var(--border);
margin-top: 30px;
}
@media print {
body { background: white; padding: 0; }
.document-container { box-shadow: none; border-radius: 0; }
.section { page-break-inside: avoid; }
}
@media (max-width: 768px) {
.document-body { padding: 25px 20px; }
.document-header { padding: 30px 20px; }
.comparison-grid { grid-template-columns: 1fr; }
.stats-grid { grid-template-columns: 1fr; }
.header-top { flex-direction: column; gap: 15px; }
.doc-meta { text-align: center; }
.step { flex-direction: column; }
}
</style>
</head>
<body>
<div class="document-container">
<header class="document-header">
<div class="header-top">
<div class="company-badge">
<div class="company-logo">xAI</div>
</div>
<div class="doc-meta">
<div>شماره مستند: AGENT-ARCH-1405-001</div>
<div>نسخه: ۱.۰</div>
<div>تاریخ تهیه: آبان ۱۴۰۵</div>
<div>طبقه‌بندی: فنی - محرمانه</div>
</div>
</div>
<div class="document-title">
<span class="label">AI AGENT ARCHITECTURE GUIDE</span>
<h1>معماری و پیاده‌سازی AI Agent</h1>
<h2>راهنمای جامع گام‌به‌گام برای افزودن قابلیت‌های اجنتیک به xAiApi</h2>
</div>
</header>
<div class="document-body">
<div class="intro-text">
<strong>مخاطب محترم،</strong><br>
این مستند، ابتدا مفهوم <strong>AI Agent</strong> را به‌صورت علمی و کاربردی تشریح می‌کند، سپس وضعیت فعلی سیستم <strong>xAiApi</strong> شما را از منظر قابلیت‌های اجنتیک تحلیل می‌نماید و در نهایت نقشه راه گام‌به‌گام پیاده‌سازی Agent و قابلیت‌های اجنتیک را با ارجاع دقیق به فایل‌ها و کلاس‌های موجود در کدبیس شما ارائه می‌دهد.
</div>
<!-- SECTION 1: What is AI Agent -->
<div class="section">
<div class="section-header">
<div class="section-number">۱</div>
<div class="section-title">
<h3>AI Agent چیست؟</h3>
<div class="subtitle">Definition, Core Components & Anatomy</div>
</div>
</div>
<div class="section-content">
<p>یک <strong>AI Agent</strong> (عامل هوش مصنوعی) سیستمی است که می‌تواند به‌صورت <strong>خودمختار (Autonomous)</strong> یا <strong>نیمه‌خودمختار (Semi-Autonomous)</strong>، برای رسیدن به یک هدف مشخص، تصمیم بگیرد، برنامه‌ریزی کند، ابزارها را فراخوانی نماید، از نتیجه یاد بگیرد و رفتار خود را اصلاح کند. تفاوت بنیادین Agent با یک LLM ساده (Chatbot) در <strong>حلقه بازخورد (Feedback Loop)</strong> است: چت‌بات یک پاسخ می‌دهد، اما Agent تا رسیدن به هدف <em>مکرراً</em> فکر می‌کند، عمل می‌کند و نتیجه را ارزیابی می‌نماید.</p>
<h4>تفاوت Chatbot و Agent</h4>
<table class="styled-table">
<thead>
<tr>
<th>ویژگی</th>
<th>Chatbot (LLM ساده)</th>
<th>AI Agent</th>
</tr>
</thead>
<tbody>
<tr>
<td>حلقه اجرا</td>
<td>یک‌بار: Prompt → Response</td>
<td style="color: var(--success); font-weight: 600;">چندین بار: Thought → Action → Observation → ...</td>
</tr>
<tr>
<td>حافظه</td>
<td>محدود به Context Window</td>
<td style="color: var(--success); font-weight: 600;">کوتاه‌مدت + بلندمدت + کاری</td>
</tr>
<tr>
<td>توانایی ابزار</td>
<td>Call یک‌بار (Function Calling)</td>
<td style="color: var(--success); font-weight: 600;">Orchestration چندین ابزار با ترتیب و بازخورد</td>
</tr>
<tr>
<td>تصمیم‌گیری</td>
<td>پاسخ مستقیم</td>
<td style="color: var(--success); font-weight: 600;">برنامه‌ریزی، ارزیابی، خوداصلاحی</td>
</tr>
<tr>
<td>کنترل</td>
<td>تمام توسط کاربر</td>
<td style="color: var(--success); font-weight: 600;">خودمختار با Guardrails</td>
</tr>
</tbody>
</table>
<h4>اجزای اصلی یک AI Agent</h4>
<div class="stats-grid">
<div class="stat-card">
<div class="stat-value">۱. Brain</div>
<div class="stat-label">LLM به‌عنوان موتور استدلال</div>
</div>
<div class="stat-card">
<div class="stat-value">۲. Tools</div>
<div class="stat-label">ابزارها برای اثرگذاری بر دنیای بیرون</div>
</div>
<div class="stat-card">
<div class="stat-value">۳. Memory</div>
<div class="stat-label">حافظه کوتاه/بلندمدت</div>
</div>
<div class="stat-card">
<div class="stat-value">۴. Planner</div>
<div class="stat-label">تجزیه و برنامه‌ریزی وظیفه</div>
</div>
<div class="stat-card">
<div class="stat-value">۵. Executor</div>
<div class="stat-label">حلقه اجرای تصمیم‌ها</div>
</div>
<div class="stat-card">
<div class="stat-value">۶. Guardrails</div>
<div class="stat-label">محدودیت‌ها و ایمنی</div>
</div>
</div>
<h4>الگوهای معروف معماری Agent</h4>
<ul>
<li><strong>ReAct (Reasoning + Acting):</strong> چرخه Thought → Action → Observation تا رسیدن به پاسخ نهایی. ساده‌ترین و پرکاربردترین الگو.</li>
<li><strong>Plan-and-Execute:</strong> ابتدا یک برنامه گام‌به‌گام تولید می‌شود، سپس هر گام اجرا و ارزیابی می‌گردد.</li>
<li><strong>Reflexion:</strong> Agent پس از هر تلاش، خود را نقد می‌کند و در تلاش بعدی رفتار را بهبود می‌بخشد.</li>
<li><strong>Multi-Agent (Crew):</strong> چند Agent تخصصی (Researcher, Coder, Reviewer) با هم همکاری می‌کنند.</li>
<li><strong>Tool-Use Agent (Function Calling):</strong> نسخه ساده‌شده که در آن LLM فقط ابزارها را فراخوانی می‌کند.</li>
</ul>
<div class="highlight-box">
<strong>نکته کلیدی:</strong> سیستم xAiApi شما <em>در حال حاضر</em> یک <strong>Tool-Use Chatbot</strong> است — نه یک Agent کامل. در ادامه تفاوت دقیق را با ارجاع به کدبیس نشان می‌دهیم.
</div>
</div>
</div>
<!-- SECTION 2: Current State Analysis -->
<div class="section">
<div class="section-header">
<div class="section-number">۲</div>
<div class="section-title">
<h3>وضعیت فعلی سیستم xAiApi</h3>
<div class="subtitle">Gap Analysis: What You Have vs. What's Missing</div>
</div>
</div>
<div class="section-content">
<p>بر اساس بررسی کدبیس شما (پروژه‌های <code>xAiApi</code>، <code>xAiMcpServer</code>، <code>xAiService</code>، <code>xAiModels</code>)، سیستم فعلی دارای زیرساخت بسیار خوبی است. جدول زیر وضعیت هر مولفه Agent را نشان می‌دهد:</p>
<table class="styled-table">
<thead>
<tr>
<th>مولفه Agent</th>
<th>وضعیت در کدبیس</th>
<th>توضیح</th>
</tr>
</thead>
<tbody>
<tr>
<td>LLM Engine (Brain)</td>
<td><span class="tag tag-existing">موجود ✓</span></td>
<td><code>XAIServiceBase</code> با پشتیبانی OpenAI / Ollama / DeepSeek / HuggingFace</td>
</tr>
<tr>
<td>Tool Registry</td>
<td><span class="tag tag-existing">موجود ✓</span></td>
<td><code>XAiMcpServerProvider</code> و MCP Client/Server</td>
</tr>
<tr>
<td>Function Calling</td>
<td><span class="tag tag-existing">موجود ✓</span></td>
<td><code>ChatClientBuilder.UseFunctionInvocation()</code> در <code>XModelsExtensions.GetClient()</code></td>
</tr>
<tr>
<td>Memory (کوتاه‌مدت)</td>
<td><span class="tag tag-partial">جزئی ~</span></td>
<td>پیام‌ها در DB ذخیره می‌شوند اما Summarization/Window Strategy ندارد</td>
</tr>
<tr>
<td>Memory (بلندمدت)</td>
<td><span class="tag tag-existing">موجود ✓</span></td>
<td>RAG پایدار روی <code>XAiVector</code> و In-Memory Vector Store</td>
</tr>
<tr>
<td>Planner (تجزیه وظیفه)</td>
<td><span class="tag tag-missing">غایب ✗</span></td>
<td>هیچ مکانیزمی برای شکستن وظیفه پیچیده به زیرکارها وجود ندارد</td>
</tr>
<tr>
<td>Agent Loop (ReAct)</td>
<td><span class="tag tag-missing">غایب ✗</span></td>
<td>فقط یک فراخوانی LLM؛ حلقه Thought-Action-Observation پیاده‌سازی نشده</td>
</tr>
<tr>
<td>Reflection / Self-Critique</td>
<td><span class="tag tag-missing">غایب ✗</span></td>
<td>Agent پاسخ خود را نقد نمی‌کند</td>
</tr>
<tr>
<td>Agent State Management</td>
<td><span class="tag tag-missing">غایب ✗</span></td>
<td>هیچ State Machine برای مسیر اجرا نیست</td>
</tr>
<tr>
<td>Guardrails (Limit/Cost)</td>
<td><span class="tag tag-missing">غایب ✗</span></td>
<td>محدودیت Iteration، Token، Cost، و Safety وجود ندارد</td>
</tr>
<tr>
<td>Observability / Tracing</td>
<td><span class="tag tag-partial">جزئی ~</span></td>
<td>Logging پایه هست، اما Trace گام‌های Agent ثبت نمی‌شود</td>
</tr>
<tr>
<td>Human-in-the-Loop</td>
<td><span class="tag tag-missing">غایب ✗</span></td>
<td>هیچ مکانیزم تأیید انسانی برای ابزارهای حساس وجود ندارد</td>
</tr>
<tr>
<td>Multi-Agent</td>
<td><span class="tag tag-missing">غایب ✗</span></td>
<td>تنها یک Agent عمومی وجود دارد</td>
</tr>
</tbody>
</table>
<h4>معماری فعلی (خلاصه)</h4>
<div class="architecture-diagram">┌─────────────────────────────────────────────────────────────┐
│ HTTP Request → XAiController / ChatWithDocumentsController │
└──────────────────────────┬──────────────────────────────────┘
│
▼
┌──────────────────────┐
│ XAIServiceBase │ ← فقط یک بار LLM را صدا می‌زند
│ (AskTextAsync / │
│ AskAsEnumerable) │
└──────────┬───────────┘
│
▼
┌────────────────────────────┐
│ IChatClient │
│ (UseFunctionInvocation) │ ← ابزارها call می‌شوند
└────────────┬───────────────┘
│
▼
┌────────────────┐
│ XAiMcpServer │ ← ابزارها از MCP می‌آیند
│ (Tools) │
└────────────────┘
▲
│ (فقط یک‌بار در هر Request)
│
RAG / XAiDataProvider</div>
<div class="warning-box">
<strong>⚠ تحلیل شکاف:</strong> سیستم شما در سطح <strong>Tool-Use Chatbot</strong> عالی است، اما برای رسیدن به <strong>AI Agent واقعی</strong>، باید حلقه <em>استدلال-عمل-مشاهده</em>، Planner، Reflection و Guardrails اضافه شوند. خبر خوب: زیرساخت MCP و Function Calling شما <em>دقیقاً</em> پایه‌ی لازم برای Agent است.
</div>
</div>
</div>
<!-- SECTION 3: Roadmap -->
<div class="section">
<div class="section-header">
<div class="section-number">۳</div>
<div class="section-title">
<h3>نقشه راه پیاده‌سازی گام‌به‌گام</h3>
<div class="subtitle">Step-by-Step Implementation Roadmap</div>
</div>
</div>
<div class="section-content">
<p>پیاده‌سازی در <strong>۶ فاز</strong> و <strong>۱۲ گام</strong> طراحی شده است. هر فاز به‌تنهایی قابل تحویل و تست است و می‌توانید تدریجاً آن‌ها را فعال کنید.</p>
<!-- PHASE 0 -->
<div class="phase-header">فاز صفر — پیش‌نیازها و آماده‌سازی</div>
<div class="step">
<div class="step-badge">۱</div>
<div class="step-content">
<h4>افزودن پروژه جدید <code>xAiAgent</code></h4>
<p>یک پروژه Class Library جدید در Solution خود بسازید تا موتور Agent را از API جدا نگه دارید. این پروژه به <code>xAiModels</code>، <code>xAiService</code> و <code>Microsoft.Extensions.AI</code> وابسته خواهد بود.</p>
<div class="code-block"><span class="cmt">// xAiAgent/xAiAgent.csproj</span>
&lt;<span class="kw">Project</span> <span class="type">Sdk</span>=<span class="str">"Microsoft.NET.Sdk"</span>&gt;
&lt;<span class="kw">PropertyGroup</span>&gt;
&lt;<span class="kw">TargetFramework</span>&gt;net8.0&lt;/<span class="kw">TargetFramework</span>&gt;
&lt;<span class="kw">Nullable</span>&gt;enable&lt;/<span class="kw">Nullable</span>&gt;
&lt;/<span class="kw">PropertyGroup</span>&gt;
&lt;<span class="kw">ItemGroup</span>&gt;
&lt;<span class="kw">ProjectReference</span> Include=<span class="str">"..\xAiModels\xAiModels.csproj"</span> /&gt;
&lt;<span class="kw">ProjectReference</span> Include=<span class="str">"..\xAiService\xAiService.csproj"</span> /&gt;
&lt;/<span class="kw">ItemGroup</span>&gt;
&lt;/<span class="kw">Project</span>&gt;</div>
</div>
</div>
<div class="step">
<div class="step-badge">۲</div>
<div class="step-content">
<h4>تعریف مدل‌های داده Agent</h4>
<p>در <code>xAiModels/Models/Agent</code> مدل‌های زیر را اضافه کنید:</p>
<div class="code-block"><span class="cmt">// xAiModels/Models/Agent/XAgentStep.cs</span>
<span class="kw">public enum</span> <span class="type">XAgentStepKind</span> { Thought, Action, Observation, Final }
<span class="kw">public class</span> <span class="type">XAgentStep</span>
{
<span class="kw">public int</span> Index { <span class="kw">get</span>; <span class="kw">set</span>; }
<span class="kw">public</span> <span class="type">XAgentStepKind</span> Kind { <span class="kw">get</span>; <span class="kw">set</span>; }
<span class="kw">public string</span> Content { <span class="kw">get</span>; <span class="kw">set</span>; }
<span class="kw">public string</span> ToolName { <span class="kw">get</span>; <span class="kw">set</span>; }
<span class="kw">public string</span> ToolArgs { <span class="kw">get</span>; <span class="kw">set</span>; }
<span class="kw">public string</span> ToolResult { <span class="kw">get</span>; <span class="kw">set</span>; }
<span class="kw">public</span> <span class="type">DateTime</span> Timestamp { <span class="kw">get</span>; <span class="kw">set</span>; } = <span class="type">DateTime</span>.UtcNow;
}
<span class="cmt">// xAiModels/Models/Agent/XAgentRun.cs</span>
<span class="kw">public class</span> <span class="type">XAgentRun</span>
{
<span class="kw">public</span> <span class="type">Guid</span> Id { <span class="kw">get</span>; <span class="kw">set</span>; } = <span class="type">Guid</span>.NewGuid();
<span class="kw">public string</span> Goal { <span class="kw">get</span>; <span class="kw">set</span>; }
<span class="kw">public string</span> OwnerId { <span class="kw">get</span>; <span class="kw">set</span>; }
<span class="kw">public</span> <span class="type">List</span>&lt;<span class="type">XAgentStep</span>&gt; Steps { <span class="kw">get</span>; <span class="kw">set</span>; } = [];
<span class="kw">public string</span> FinalAnswer { <span class="kw">get</span>; <span class="kw">set</span>; }
<span class="kw">public bool</span> Succeeded { <span class="kw">get</span>; <span class="kw">set</span>; }
<span class="kw">public string</span> Error { <span class="kw">get</span>; <span class="kw">set</span>; }
}</div>
</div>
</div>
<!-- PHASE 1 -->
<div class="phase-header">فاز ۱ — پیاده‌سازی Agent Loop (ReAct)</div>
<div class="step">
<div class="step-badge">۳</div>
<div class="step-content">
<h4>ساخت <code>IXAgentService</code> و <code>XAgentService</code></h4>
<p>این سرویس، <code>XAIServiceBase</code> را در یک حلقه <em>Thought → Action → Observation</em> اجرا می‌کند. از <code>IXAiMcpServerProvider.GetAvailableToolsAsync</code> استفاده می‌کند و ابزارها را با <code>ChatOptions.Tools</code> به مدل می‌دهد.</p>
<div class="code-block"><span class="cmt">// xAiAgent/Interfaces/IXAgentService.cs</span>
<span class="kw">public interface</span> <span class="type">IXAgentService</span>
{
<span class="type">Task</span>&lt;<span class="type">XAgentRun</span>&gt; <span class="fn">RunAsync</span>(
<span class="kw">string</span> goal,
<span class="type">XUserClaimsInfoDto</span> userInfo,
<span class="type">XAgentOptions</span> options = <span class="kw">null</span>,
<span class="type">CancellationToken</span> ct = <span class="kw">default</span>);
<span class="type">IAsyncEnumerable</span>&lt;<span class="type">XAgentStep</span>&gt; <span class="fn">RunStreamAsync</span>(
<span class="kw">string</span> goal,
<span class="type">XUserClaimsInfoDto</span> userInfo,
<span class="type">XAgentOptions</span> options = <span class="kw">null</span>,
<span class="type">CancellationToken</span> ct = <span class="kw">default</span>);
}
<span class="cmt">// xAiAgent/Models/XAgentOptions.cs</span>
<span class="kw">public class</span> <span class="type">XAgentOptions</span>
{
<span class="kw">public int</span> MaxIterations { <span class="kw">get</span>; <span class="kw">set</span>; } = 8;
<span class="kw">public int</span> MaxToolCalls { <span class="kw">get</span>; <span class="kw">set</span>; } = 20;
<span class="kw">public bool</span> EnableReflection { <span class="kw">get</span>; <span class="kw">set</span>; } = <span class="kw">true</span>;
<span class="kw">public bool</span> EnablePlanning { <span class="kw">get</span>; <span class="kw">set</span>; } = <span class="kw">true</span>;
<span class="kw">public int</span> MaxTotalTokens { <span class="kw">get</span>; <span class="kw">set</span>; } = 100_000;
<span class="kw">public</span> <span class="type">TimeSpan</span> Timeout { <span class="kw">get</span>; <span class="kw">set</span>; } = <span class="type">TimeSpan</span>.FromMinutes(3);
<span class="kw">public string</span> SystemPrompt { <span class="kw">get</span>; <span class="kw">set</span>; }
}</div>
</div>
</div>
<div class="step">
<div class="step-badge">۴</div>
<div class="step-content">
<h4>پیاده‌سازی حلقه ReAct در <code>XAgentService</code></h4>
<p>هسته اصلی Agent: در هر Iteration، مدل با System Prompt مخصوص Agent + ابزارها فراخوانی می‌شود. اگر پاسخ شامل Tool Call بود، ابزار اجرا و نتیجه به History اضافه می‌شود؛ در غیر این صورت پاسخ نهایی است.</p>
<div class="code-block"><span class="cmt">// xAiAgent/Services/XAgentService.cs (خلاصه)</span>
<span class="kw">public class</span> <span class="type">XAgentService</span> : <span class="type">IXAgentService</span>
{
<span class="kw">private readonly</span> <span class="type">IXAiMcpServerProvider</span> mcpProvider;
<span class="kw">private readonly</span> <span class="type">XAiApiConfiguration</span> config;
<span class="kw">private readonly</span> <span class="type">ILogger</span>&lt;<span class="type">XAgentService</span>&gt; logger;
<span class="kw">public async</span> <span class="type">Task</span>&lt;<span class="type">XAgentRun</span>&gt; <span class="fn">RunAsync</span>(
<span class="kw">string</span> goal, <span class="type">XUserClaimsInfoDto</span> user, <span class="type">XAgentOptions</span> opts, <span class="type">CancellationToken</span> ct)
{
opts ??= <span class="kw">new</span> <span class="type">XAgentOptions</span>();
<span class="kw">var</span> run = <span class="kw">new</span> <span class="type">XAgentRun</span> { Goal = goal, OwnerId = user.UserId };
<span class="kw">var</span> client = config.GetModel(<span class="str">"Gemma"</span>).GetClient();
<span class="kw">var</span> tools = <span class="kw">await</span> mcpProvider.GetAvailableToolsAsync(userInfo: user, ct: ct);
<span class="kw">var</span> history = <span class="kw">new</span> <span class="type">List</span>&lt;<span class="type">ChatMessage</span>&gt;
{
<span class="kw">new</span>(<span class="type">ChatRole</span>.System, BuildAgentPrompt(goal)),
<span class="kw">new</span>(<span class="type">ChatRole</span>.User, goal)
};
<span class="kw">var</span> chatOptions = <span class="kw">new</span> <span class="type">ChatOptions</span> { Tools = [.. tools] };
<span class="kw">for</span> (<span class="kw">int</span> i = <span class="kw">0</span>; i &lt; opts.MaxIterations; i++)
{
ct.ThrowIfCancellationRequested();
<span class="cmt">// 1) Thought + Action Decision</span>
<span class="kw">var</span> response = <span class="kw">await</span> client.GetResponseAsync(history, chatOptions, ct);
<span class="kw">var</span> toolCalls = response.Messages
.SelectMany(m =&gt; m.Contents.OfType&lt;<span class="type">FunctionCallContent</span>&gt;())
.ToList();
<span class="kw">if</span> (toolCalls.Count == <span class="kw">0</span>)
{
<span class="cmt">// پاسخ نهایی</span>
run.FinalAnswer = response.Text;
run.Succeeded = <span class="kw">true</span>;
run.Steps.Add(<span class="kw">new</span> <span class="type">XAgentStep</span> {
Kind = <span class="type">XAgentStepKind</span>.Final, Content = response.Text });
<span class="kw">break</span>;
}
<span class="cmt">// 2) Action + Observation (شبیه‌سازی با Microsoft.Extensions.AI)</span>
history.AddRange(response.Messages);
<span class="kw">foreach</span> (<span class="kw">var</span> tc <span class="kw">in</span> toolCalls)
{
run.Steps.Add(<span class="kw">new</span> <span class="type">XAgentStep</span> {
Kind = <span class="type">XAgentStepKind</span>.Action,
ToolName = tc.Name, ToolArgs = tc.Arguments?.ToJsonString() });
<span class="cmt">// فراخوانی ابزار از طریق MCP</span>
<span class="kw">var</span> result = <span class="kw">await</span> InvokeToolAsync(tc, user, ct);
run.Steps.Add(<span class="kw">new</span> <span class="type">XAgentStep</span> {
Kind = <span class="type">XAgentStepKind</span>.Observation, ToolResult = result });
history.Add(<span class="kw">new</span> <span class="type">ChatMessage</span>(<span class="type">ChatRole</span>.Tool,
[<span class="kw">new</span> <span class="type">FunctionResultContent</span>(tc.CallId, result)]));
}
}
<span class="kw">return</span> run;
}
}</div>
<div class="info-box">
<strong>💡 نکته:</strong> از آنجا که <code>ChatClientBuilder.UseFunctionInvocation()</code> در <code>XModelsExtensions.GetClient()</code> فعال است، Microsoft.Extensions.AI به‌صورت خودکار Function Call را حل می‌کند. اما برای Agent Loop، بهتر است <code>UseFunctionInvocation</code> را در حالت Agent غیرفعال کرده و خودتان حلقه را کنترل کنید تا Trace و Guardrails داشته باشید.
</div>
</div>
</div>
<!-- PHASE 2 -->
<div class="phase-header">فاز ۲ — Planner و Task Decomposition</div>
<div class="step">
<div class="step-badge">۵</div>
<div class="step-content">
<h4>افزودن Prompt برنامه‌ریز و سرویس Plan</h4>
<p>در <code>AiApiConfiguration.Prompts</code> یک Prompt جدید به نام <code>AgentPlanner</code> اضافه کنید که از LLM می‌خواهد هدف کاربر را به زیرکارها بشکند. سپس <code>XAgentPlanner</code> این خروجی JSON را Parse و در <code>XAgentRun</code> ذخیره می‌کند.</p>
<div class="code-block"><span class="cmt">// appsettings.json — AiApiConfiguration</span>
<span class="str">"Prompts"</span>: [
{
<span class="str">"Name"</span>: <span class="str">"AgentPlanner"</span>,
<span class="str">"Template"</span>: <span class="str">"You are a planner. Break the user goal into 3-7 concrete steps.\nReturn ONLY JSON: { \"steps\": [ { \"id\":1, \"title\":\"...\", \"tool\":\"tool_name_or_null\" } ] }\nGoal: {goal}"</span>,
<span class="str">"Params"</span>: [ { <span class="str">"Name"</span>: <span class="str">"goal"</span>, <span class="str">"Param"</span>: <span class="str">"{goal}"</span> } ]
}
]</div>
<div class="code-block"><span class="cmt">// xAiAgent/Services/XAgentPlanner.cs</span>
<span class="kw">public class</span> <span class="type">XAgentPlanner</span> : <span class="type">IXAgentPlanner</span>
{
<span class="kw">public async</span> <span class="type">Task</span>&lt;<span class="type">List</span>&lt;<span class="type">XAgentPlanStep</span>&gt;&gt; <span class="fn">PlanAsync</span>(
<span class="kw">string</span> goal, <span class="type">XUserClaimsInfoDto</span> user, <span class="type">CancellationToken</span> ct)
{
<span class="kw">var</span> prompt = config.GetPrompt(<span class="str">"AgentPlanner"</span>,
<span class="kw">new</span> <span class="type">Dictionary</span>&lt;<span class="kw">string</span>, <span class="kw">string</span>&gt; { [<span class="str">"goal"</span>] = goal });
<span class="kw">var</span> client = config.GetModel(<span class="str">"Gemma"</span>).GetClient();
<span class="kw">var</span> json = (<span class="kw">await</span> client.GetResponseAsync(prompt, cancellationToken: ct)).Text;
<span class="kw">return</span> JsonSerializer.Deserialize&lt;<span class="type">XAgentPlan</span>&gt;(json)?.Steps ?? [];
}
}</div>
</div>
</div>
<div class="step">
<div class="step-badge">۶</div>
<div class="step-content">
<h4>ترکیب Planner با ReAct Loop</h4>
<p>در <code>XAgentService.RunAsync</code>، اگر <code>opts.EnablePlanning == true</code> بود، ابتدا Planner را صدا بزنید و Plan را به System Prompt تزریق کنید. در هر Iteration، Agent باید در مورد اینکه «کدام گام از Plan در حال انجام است» نیز آگاه باشد.</p>
<div class="code-block"><span class="cmt">// در XAgentService.RunAsync</span>
<span class="kw">if</span> (opts.EnablePlanning)
{
<span class="kw">var</span> plan = <span class="kw">await</span> planner.PlanAsync(goal, user, ct);
run.Steps.Add(<span class="kw">new</span> <span class="type">XAgentStep</span> {
Kind = <span class="type">XAgentStepKind</span>.Thought,
Content = <span class="str">$"[PLAN]\n{JsonSerializer.Serialize(plan, JsonOpts.Indented)}"</span> });
history[<span class="kw">0</span>] = <span class="kw">new</span> <span class="type">ChatMessage</span>(<span class="type">ChatRole</span>.System,
BuildAgentPrompt(goal) + <span class="str">$"\n\nPlan:\n{JsonSerializer.Serialize(plan, JsonOpts.Indented)}"</span>);
}</div>
</div>
</div>
<!-- PHASE 3 -->
<div class="phase-header">فاز ۳ — Reflection و Self-Critique</div>
<div class="step">
<div class="step-badge">۷</div>
<div class="step-content">
<h4>افزودن حلقه بازتاب (Reflexion)</h4>
<p>پس از تولید پاسخ نهایی، اگر <code>EnableReflection</code> فعال بود، یک Prompt دیگر به مدل بدهید که پاسخ را نقد کند. اگر نقد نشان داد پاسخ ناقص است، یک Iteration دیگر اجرا شود.</p>
<div class="code-block"><span class="cmt">// prompt: AgentCritic</span>
<span class="str">"You are a strict critic. Review the answer against the goal.\nReturn JSON: { \"isGood\": true|false, \"issues\": [\"...\"], \"hint\": \"...\" }\nGoal: {goal}\nAnswer: {answer}"</span>
<span class="cmt">// در XAgentService، بعد از FinalAnswer</span>
<span class="kw">if</span> (opts.EnableReflection)
{
<span class="kw">var</span> critique = <span class="kw">await</span> critic.CritiqueAsync(goal, run.FinalAnswer, user, ct);
run.Steps.Add(<span class="kw">new</span> <span class="type">XAgentStep</span> {
Kind = <span class="type">XAgentStepKind</span>.Thought,
Content = <span class="str">$"[CRITIC] {JsonSerializer.Serialize(critique)}"</span> });
<span class="kw">if</span> (!critique.IsGood &amp;&amp; iterations &lt; opts.MaxIterations)
{
history.Add(<span class="kw">new</span> <span class="type">ChatMessage</span>(<span class="type">ChatRole</span>.System,
<span class="str">$"Critic feedback: {critique.Hint}. Please retry."</span>));
<span class="kw">continue</span>;
}
}</div>
</div>
</div>
<!-- PHASE 4 -->
<div class="phase-header">فاز ۴ — Memory پیشرفته و Guardrails</div>
<div class="step">
<div class="step-badge">۸</div>
<div class="step-content">
<h4>Memory کوتاه‌مدت با Summarization</h4>
<p>در <code>XAIServiceBase.PrepareMemory</code> که هم‌اکنون TODO است، یک Strategy اضافه کنید: اگر تعداد پیام‌ها از حدی (مثلاً ۲۰) گذشت، پیام‌های قدیمی‌تر را با یک Prompt به خلاصه تبدیل کرده و تنها خلاصه + پیام‌های اخیر را به مدل بدهید. این کار مصرف Token را به‌شدت کاهش می‌دهد.</p>
<div class="code-block"><span class="cmt">// xAiAgent/Services/XAgentMemory.cs</span>
<span class="kw">public async</span> <span class="type">Task</span>&lt;<span class="type">List</span>&lt;<span class="type">ChatMessage</span>&gt;&gt; <span class="fn">CompressAsync</span>(
<span class="type">IEnumerable</span>&lt;<span class="type">XAiMessageDto</span>&gt; messages, <span class="type">CancellationToken</span> ct)
{
<span class="kw">const int</span> Window = <span class="kw">20</span>;
<span class="kw">var</span> list = messages.OrderBy(m =&gt; m.CreatedOn).ToList();
<span class="kw">if</span> (list.Count &lt;= Window) <span class="kw">return</span> list.Select(m =&gt; m.ToChatMessages()).ToList();
<span class="kw">var</span> old = list.Take(list.Count - Window).ToList();
<span class="kw">var</span> recent = list.Skip(list.Count - Window).ToList();
<span class="kw">var</span> summaryPrompt = <span class="str">"Summarize the following conversation briefly, keeping key facts and decisions:\n\n"</span>
+ <span class="kw">string</span>.Join(<span class="str">"\n"</span>, old.Select(m =&gt; <span class="str">$"{m.Role}: {m.Content}"</span>));
<span class="kw">var</span> summary = (<span class="kw">await</span> client.GetResponseAsync(summaryPrompt, cancellationToken: ct)).Text;
<span class="kw">var</span> result = <span class="kw">new</span> <span class="type">List</span>&lt;<span class="type">ChatMessage</span>&gt;
{ <span class="kw">new</span>(<span class="type">ChatRole</span>.System, <span class="str">$"[Conversation Summary]\n{summary}"</span>) };
result.AddRange(recent.Select(m =&gt; m.ToChatMessages()));
<span class="kw">return</span> result;
}</div>
</div>
</div>
<div class="step">
<div class="step-badge">۹</div>
<div class="step-content">
<h4>Guardrails: محدودیت بودجه، تکرار، و ایمنی ابزار</h4>
<p>یک <code>XAgentBudgetTracker</code> بسازید که Token مصرفی، تعداد Iteration، و زمان سپری‌شده را رصد کند. برای ابزارهای حساس (مثلاً حذف داده)، یک Property جدید در <code>XAiMcpToolAttribute</code> به نام <code>RequiresApproval</code> اضافه کنید.</p>
<div class="code-block"><span class="cmt">// افزودن به XAiMcpToolAttribute</span>
[<span class="type">AttributeUsage</span>(<span class="type">AttributeTargets</span>.Method)]
<span class="kw">public class</span> <span class="type">XAiMcpToolAttribute</span> : <span class="type">Attribute</span>
{
<span class="kw">public bool</span> RequiresApproval { <span class="kw">get</span>; <span class="kw">set</span>; } = <span class="kw">false</span>;
<span class="cmt">// ... سایر فیلدهای موجود</span>
}
<span class="cmt">// xAiAgent/Services/XAgentBudgetTracker.cs</span>
<span class="kw">public class</span> <span class="type">XAgentBudgetTracker</span>
{
<span class="kw">public int</span> TotalTokens { <span class="kw">get</span>; <span class="kw">private set</span>; }
<span class="kw">public int</span> Iterations { <span class="kw">get</span>; <span class="kw">private set</span>; }
<span class="kw">public</span> <span class="type">DateTime</span> StartedAt { <span class="kw">get</span>; } = <span class="type">DateTime</span>.UtcNow;
<span class="kw">public void</span> <span class="fn">Record</span>(<span class="type">ChatResponse</span> resp)
{
Iterations++;
TotalTokens += (resp.Usage?.InputTokenCount ?? <span class="kw">0</span>)
+ (resp.Usage?.OutputTokenCount ?? <span class="kw">0</span>);
}
<span class="kw">public void</span> <span class="fn">AssertWithinLimits</span>(<span class="type">XAgentOptions</span> o)
{
<span class="kw">if</span> (Iterations &gt; o.MaxIterations)
<span class="kw">throw new</span> <span class="type">InvalidOperationException</span>(<span class="str">"Max iterations exceeded"</span>);
<span class="kw">if</span> (TotalTokens &gt; o.MaxTotalTokens)
<span class="kw">throw new</span> <span class="type">InvalidOperationException</span>(<span class="str">"Token budget exceeded"</span>);
<span class="kw">if</span> (<span class="type">DateTime</span>.UtcNow - StartedAt &gt; o.Timeout)
<span class="kw">throw new</span> <span class="type">TimeoutException</span>(<span class="str">"Agent timeout"</span>);
}
}</div>
</div>
</div>
<!-- PHASE 5 -->
<div class="phase-header">فاز ۵ — API، Observability و Human-in-the-Loop</div>
<div class="step">
<div class="step-badge">۱۰</div>
<div class="step-content">
<h4>افزودن <code>AgentsController</code> به xAiApi</h4>
<p>یک Controller جدید برای شروع Agent و گرفتن Trace زنده یا نهایی. از الگوی <code>XAiController</code> و SSE موجود (مانند <code>AskStream</code>) استفاده کنید.</p>
<div class="code-block"><span class="cmt">// xAiApi/Controllers/AgentsController.cs</span>
[<span class="type">Authorize</span>]
<span class="kw">public class</span> <span class="type">AgentsController</span> : <span class="type">XBaseIdentityApiV1Controller</span>
{
<span class="kw">private readonly</span> <span class="type">IXAgentService</span> agent;
[<span class="type">HttpPost</span>(<span class="str">"Run"</span>)]
<span class="kw">public async</span> <span class="type">Task</span>&lt;<span class="type">ActionResult</span>&lt;<span class="type">XAgentRun</span>&gt;&gt; <span class="fn">Run</span>(
[<span class="type">FromBody</span>] <span class="type">XAgentRunRequest</span> req, <span class="type">CancellationToken</span> ct)
{
<span class="kw">var</span> user = <span class="kw">await</span> GetUserInfo();
<span class="kw">var</span> run = <span class="kw">await</span> agent.RunAsync(req.Goal, user, req.Options, ct);
<span class="kw">return</span> Ok(run);
}
[<span class="type">HttpGet</span>(<span class="str">"Run/Stream"</span>)]
<span class="kw">public async</span> <span class="type">Task</span> <span class="fn">RunStream</span>(<span class="kw">string</span> goal, <span class="type">CancellationToken</span> ct)
{
<span class="kw">var</span> user = <span class="kw">await</span> GetUserInfo();
Response.PrepareSseResponse();
<span class="kw">await foreach</span> (<span class="kw">var</span> step <span class="kw">in</span> agent.RunStreamAsync(goal, user, <span class="kw">null</span>, ct))
<span class="kw">await</span> Response.WriteSseEventAsync(step, ct);
<span class="kw">await</span> Response.WriteSseDoneAsync(ct);
}
}</div>
<p class="no-indent">در <code>Startup.ConfigureServices</code> سرویس‌های Agent را ثبت کنید:</p>
<div class="code-block">services.AddScoped&lt;<span class="type">IXAgentService</span>, <span class="type">XAgentService</span>&gt;();
services.AddScoped&lt;<span class="type">IXAgentPlanner</span>, <span class="type">XAgentPlanner</span>&gt;();
services.AddScoped&lt;<span class="type">IXAgentCritic</span>, <span class="type">XAgentCritic</span>&gt;();
services.AddScoped&lt;<span class="type">XAgentBudgetTracker</span>&gt;();</div>
</div>
</div>
<div class="step">
<div class="step-badge">۱۱</div>
<div class="step-content">
<h4>Observability — ثبت Trace گام‌های Agent</h4>
<p>هر <code>XAgentRun</code> را در جدول جدید <code>AiAgentRuns</code> ذخیره کنید. با استفاده از <code>XAiDataProvider</code> موجود و الگوی Entity/Repository که دارید، یک <code>XAiAgentRun</code> Entity بسازید و از طریق <code>IXAiDataProvider</code> قابل ذخیره کنید. این کار امکان بازبینی، Debug و آموزش مدل آینده را می‌دهد.</p>
<div class="code-block"><span class="cmt">// xAiModels/Models/Entities/XAiAgentRun.cs</span>
<span class="kw">public class</span> <span class="type">XAiAgentRun</span> : <span class="type">XBaseGuidIDEntity</span>
{
<span class="kw">public string</span> OwnerId { <span class="kw">get</span>; <span class="kw">set</span>; }
<span class="kw">public string</span> Goal { <span class="kw">get</span>; <span class="kw">set</span>; }
<span class="kw">public string</span> FinalAnswer { <span class="kw">get</span>; <span class="kw">set</span>; }
<span class="kw">public bool</span> Succeeded { <span class="kw">get</span>; <span class="kw">set</span>; }
<span class="kw">public string</span> StepsJson { <span class="kw">get</span>; <span class="kw">set</span>; } <span class="cmt">// کل Trace</span>
<span class="kw">public int</span> TotalTokens { <span class="kw">get</span>; <span class="kw">set</span>; }
<span class="kw">public int</span> Iterations { <span class="kw">get</span>; <span class="kw">set</span>; }
<span class="kw">public</span> <span class="type">DateTime</span> StartedAt { <span class="kw">get</span>; <span class="kw">set</span>; }
<span class="kw">public</span> <span class="type">DateTime</span> FinishedAt { <span class="kw">get</span>; <span class="kw">set</span>; }
}</div>
</div>
</div>
<div class="step">
<div class="step-badge">۱۲</div>
<div class="step-content">
<h4>Human-in-the-Loop برای ابزارهای حساس</h4>
<p>در <code>XAgentService.InvokeToolAsync</code>، اگر ابزار <code>RequiresApproval == true</code> بود، به جای اجرای مستقیم، یک Event از نوع <code>ApprovalPending</code> منتشر کنید و منتظر سیگنال از سمت کلاینت (از طریق SignalR Hub که در <code>XAiDataProviderHub</code> دارید) بمانید.</p>
<div class="code-block"><span class="cmt">// شبه‌کد در XAgentService</span>
<span class="kw">if</span> (tool.RequiresApproval)
{
<span class="kw">var</span> approvalTask = approvalService.RequestApprovalAsync(
runId: run.Id, tool: tool, args: tc.Arguments, ct: ct);
<span class="kw">await</span> hub.Clients.User(user.UserId)
.SendAsync(<span class="str">"AgentApprovalRequired"</span>, run.Id, tool.Name);
<span class="kw">var</span> approved = <span class="kw">await</span> approvalTask; <span class="cmt">// منتظر تأیید</span>
<span class="kw">if</span> (!approved) <span class="kw">throw new</span> <span class="type">InvalidOperationException</span>(<span class="str">"User rejected tool call"</span>);
}</div>
<div class="warning-box">
<strong>⚠ توجه:</strong> برای شروع، این گام را اختیاری نگه دارید و فقط روی ابزارهای مخرب (مثل حذف، ارسال ایمیل، پرداخت) اعمال کنید.
</div>
</div>
</div>
<!-- PHASE 6 -->
<div class="phase-header">فاز ۶ (اختیاری و بلندمدت) — Multi-Agent</div>
<div class="step">
<div class="step-badge">+</div>
<div class="step-content">
<h4>Multi-Agent با Crew</h4>
<p>وقتی Agent منفرد پایدار شد، می‌توانید چند Agent تخصصی بسازید (Researcher، Coder، Reviewer) که با یک «Orchestrator» همکاری می‌کنند. هر Agent یک <code>XAgentService</code> با System Prompt و Toolset متفاوت است. Orchestrator از همان حلقه ReAct استفاده می‌کند اما ابزارهایش «صدا زدن Agent دیگر» است.</p>
<div class="code-block"><span class="cmt">// ابزار Agent-to-Agent</span>
[<span class="type">XAiMcpTool</span>(Description = <span class="str">"Delegate a sub-task to the Researcher agent"</span>)]
<span class="kw">public async</span> <span class="type">Task</span>&lt;<span class="kw">string</span>&gt; <span class="fn">DelegateToResearcher</span>(
[<span class="type">XAiMcpToolParam</span>] <span class="kw">string</span> subTask, <span class="type">CancellationToken</span> ct)
{
<span class="kw">var</span> run = <span class="kw">await</span> researcherAgent.RunAsync(subTask, userContext.UserInfo, <span class="kw">null</span>, ct);
<span class="kw">return</span> run.FinalAnswer;
}</div>
<div class="info-box">
<strong>💡 توصیه:</strong> Multi-Agent را فقط زمانی پیاده کنید که Agent تک‌نفره در سناریوهای واقعی به سقف توانایی خود رسیده باشد. در بسیاری از موارد، یک Agent خوب‌طراحی‌شده با ابزارهای درست، از Crew پیچیده بهتر جواب می‌دهد.
</div>
</div>
</div>
</div>
</div>
<!-- SECTION 4: Comparison -->
<div class="section">
<div class="section-header">
<div class="section-number">۴</div>
<div class="section-title">
<h3>مقایسه وضعیت قبل و بعد از پیاده‌سازی</h3>
<div class="subtitle">Before vs. After</div>
</div>
</div>
<div class="section-content">
<div class="comparison-grid">
<div class="comparison-card">
<h4>وضعیت فعلی (Tool-Use Chatbot)</h4>
<ul>
<li><span>حلقه اجرا</span> <span class="value" style="color: var(--danger);">یک‌بار</span></li>
<li><span>ابزار</span> <span class="value">Function Calling</span></li>
<li><span>Planner</span> <span class="value" style="color: var(--danger);">ندارد</span></li>
<li><span>Reflection</span> <span class="value" style="color: var(--danger);">ندارد</span></li>
<li><span>Guardrails</span> <span class="value" style="color: var(--danger);">ندارد</span></li>
<li><span>Trace</span> <span class="value" style="color: var(--warning);">Logging پایه</span></li>
<li><span>Human-in-Loop</span> <span class="value" style="color: var(--danger);">ندارد</span></li>
</ul>
</div>
<div class="comparison-card recommended">
<span class="card-badge">پس از پیاده‌سازی ✓</span>
<h4>وضعیت هدف (AI Agent)</h4>
<ul>
<li><span>حلقه اجرا</span> <span class="value" style="color: var(--success);">ReAct تا ۸ Iteration</span></li>
<li><span>ابزار</span> <span class="value" style="color: var(--success);">Orchestration + بازخورد</span></li>
<li><span>Planner</span> <span class="value" style="color: var(--success);">Task Decomposition</span></li>
<li><span>Reflection</span> <span class="value" style="color: var(--success);">Self-Critique</span></li>
<li><span>Guardrails</span> <span class="value" style="color: var(--success);">Budget + Approval</span></li>
<li><span>Trace</span> <span class="value" style="color: var(--success);">XAiAgentRun کامل</span></li>
<li><span>Human-in-Loop</span> <span class="value" style="color: var(--success);">SignalR Approval</span></li>
</ul>
</div>
</div>
<h4>ماتریس ریسک و پیچیدگی هر فاز</h4>
<table class="styled-table">
<thead>
<tr>
<th>فاز</th>
<th>زمان تقریبی</th>
<th>ریسک</th>
<th>ارزش افزوده</th>
</tr>
</thead>
<tbody>
<tr>
<td>فاز ۰ — پیش‌نیازها</td>
<td>۱–۲ روز</td>
<td style="color: var(--success);">پایین</td>
<td>پایه ساختاری</td>
</tr>
<tr>
<td>فاز ۱ — Agent Loop</td>
<td>۳–۵ روز</td>
<td style="color: var(--warning);">متوسط</td>
<td style="color: var(--success); font-weight: 600;">بالا (هسته اصلی)</td>
</tr>
<tr>
<td>فاز ۲ — Planner</td>
<td>۲–۳ روز</td>
<td style="color: var(--warning);">متوسط</td>
<td style="color: var(--success); font-weight: 600;">بالا</td>
</tr>
<tr>
<td>فاز ۳ — Reflection</td>
<td>۲ روز</td>
<td style="color: var(--success);">پایین</td>
<td style="color: var(--warning);">متوسط</td>
</tr>
<tr>
<td>فاز ۴ — Memory + Guardrails</td>
<td>۳–۴ روز</td>
<td style="color: var(--warning);">متوسط</td>
<td style="color: var(--success); font-weight: 600;">بالا (ایمنی)</td>
</tr>
<tr>
<td>فاز ۵ — API + Observability + HITL</td>
<td>۳–۵ روز</td>
<td style="color: var(--warning);">متوسط</td>
<td style="color: var(--success); font-weight: 600;">بالا (کنترل)</td>
</tr>
<tr class="highlight-row">
<td><strong>مجموع (فاز ۰ تا ۵)</strong></td>
<td><strong>~۲.۵ تا ۳ هفته</strong></td>
<td>—</td>
<td style="color: var(--success); font-weight: 700;">Agent کامل</td>
</tr>
</tbody>
</table>
</div>
</div>
<!-- SECTION 5: Best Practices -->
<div class="section">
<div class="section-header">
<div class="section-number">۵</div>
<div class="section-title">
<h3>نکات کلیدی و اشتباهات رایج</h3>
<div class="subtitle">Best Practices & Common Pitfalls</div>
</div>
</div>
<div class="section-content">
<h4>✓ توصیه‌های کلیدی</h4>
<ul>
<li><strong>ابزارها را کوچک و متمرکز نگه دارید:</strong> هر ابزار فقط یک کار انجام دهد. ابزارهای چندمنظوره مدل را سردرگم می‌کنند.</li>
<li><strong>System Prompt اختصاصی Agent بنویسید:</strong> Agent باید بداند که «یک عامل است» و باید «قبل از پاسخ، فکر کند، در صورت نیاز ابزار صدا بزند و خود را نقد کند».</li>
<li><strong>Trace کامل ذخیره کنید:</strong> بدون Trace، Debug کردن Agent تقریباً غیرممکن است. الگوی <code>XAgentStep</code> را جدی بگیرید.</li>
<li><strong>Iteration و Token را محدود کنید:</strong> هرگز Agent را بدون سقف اجرا نکنید — هزینه و زمان می‌تواند منفجر شود.</li>
<li><strong>ابزارها را طبقه‌بندی کنید:</strong> Read-Only vs. Write vs. Destructive. برای دومی و سومی حتماً Guardrail و Approval داشته باشید.</li>
<li><strong>از RAG موجودتان برای حافظه بلندمدت استفاده کنید:</strong> <code>IXAiRAGService</code> و <code>XAiVector</code> دقیقاً برای همین ساخته شده‌اند — نتایج Agent را در همان فضا ذخیره کنید.</li>
<li><strong>تست A/B و Evaluation بسازید:</strong> مجموعه‌ای از Goals واقعی + پاسخ مورد انتظار داشته باشید تا هر تغییر در Prompt/Planner ارزیابی شود.</li>
</ul>
<h4>✗ اشتباهات رایج</h4>
<div class="danger-box">
<ul style="margin: 0;">
<li><strong>بدون Reflection به Final Answer اعتماد کردن:</strong> اکثر Agentهای شکست‌خورده، مرحله Critic را حذف کرده‌اند.</li>
<li><strong>ابزارهای بدون توضیح واضح به LLM دادن:</strong> <code>Description</code> در <code>XAiMcpTool</code> مستقیماً کیفیت Function Calling را تعیین می‌کند.</li>
<li><strong>در نظر نگرفتن Cost و Latency:</strong> هر Iteration اضافی یعنی چند ثانیه و چند هزار Token. برای UX حتماً از Streaming استفاده کنید.</li>
<li><strong>پیاده‌سازی Multi-Agent قبل از Single-Agent پایدار:</strong> ابتدا یک Agent خوب، سپس Crew.</li>
<li><strong>نادیده گرفتن همزمانی (Concurrency):</strong> اگر چند درخواست همزمان به <code>XAiMcpServerProvider</code> بیاید، مراقب <code>initLock</code> و Client Cache باشید (که در کد فعلی شما به‌درستی مدیریت شده).</li>
<li><strong>فراموش کردن Cancellation:</strong> <code>CancellationToken</code> را در تمام طول حلقه Agent (به‌ویژه <code>InvokeToolAsync</code>) پاس بدهید — در کد فعلی شما این الگو به‌خوبی رعایت شده و باید ادامه یابد.</li>
</ul>
</div>
<h4>نقشه معماری پیشنهادی (پس از پیاده‌سازی)</h4>
<div class="architecture-diagram">┌──────────────────────────────────────────────────────────────────┐
│ HTTP Request → AgentsController.Run / RunStream │
└──────────────────────────┬───────────────────────────────────────┘
│
▼
┌──────────────────────────────┐
│ XAgentService (ReAct Loop) │
│ ┌────────────────────────┐ │
│ │ 1. Planner │ │──► LLM (Prompt: AgentPlanner)
│ │ 2. Thought (LLM) │ │──► LLM (System: AgentPrompt)
│ │ 3. Action (Tool Call) │ │──► IXAiMcpServerProvider
│ │ 4. Observation │ │◄── MCP Result
│ │ 5. Reflection │ │──► LLM (Prompt: AgentCritic)
│ │ 6. Guardrails Check │ │──► BudgetTracker
│ └────────────────────────┘ │
└──────────────┬───────────────┘
│
┌─────────────┼─────────────┐
│ │ │
▼ ▼ ▼
┌──────────────┐ ┌──────────┐ ┌──────────────┐
│ XAiAgentRun │ │ Hub │ │ RAG / Memory │
│ (Trace DB) │ │ (SignalR)│ │ (XAiVector) │
└──────────────┘ └──────────┘ └──────────────┘</div>
</div>
</div>
<!-- SECTION 6: Summary -->
<div class="section">
<div class="section-header">
<div class="section-number">۶</div>
<div class="section-title">
<h3>جمع‌بندی و اقدامات بعدی</h3>
<div class="subtitle">Summary & Next Steps</div>
</div>
</div>
<div class="section-content">
<p>سیستم <strong>xAiApi</strong> شما پایه‌ای بسیار قوی دارد: MCP Server/Client، RAG پایدار و In-Memory، Function Calling با Microsoft.Extensions.AI، مدیریت Project/Conversation/Message، و معماری ماژولار تمیز. تمام آنچه برای تبدیل شدن به یک <strong>AI Agent کامل</strong> لازم است، در قالب ۶ فاز و ۱۲ گام در این مستند تشریح شد.</p>
<div class="stats-grid">
<div class="stat-card">
<div class="stat-value">۱۲</div>
<div class="stat-label">گام اجرایی مشخص</div>
</div>
<div class="stat-card">
<div class="stat-value">~۳</div>
<div class="stat-label">هفته زمان پیاده‌سازی</div>
</div>
<div class="stat-card">
<div class="stat-value">۰</div>
<div class="stat-label">وابستگی به زیرساخت جدید</div>
</div>
</div>
<div class="success-box">
<strong>🎯 ارزش پیشنهادی:</strong> با حفظ کامل معماری فعلی، می‌توانید بدون بازنویسی، قابلیت‌های Agentic را به‌صورت تدریجی و کنترل‌شده اضافه کنید. هر فاز مستقلاً قابل تحویل و تست است و می‌توانید بر اساس بازخورد واقعی، ترتیب و اولویت را تنظیم نمایید.
</div>
<h4>ترتیب پیشنهادی اقدامات فوری</h4>
<ol>
<li>ابتدا <strong>فاز ۰</strong> را انجام دهید (ساخت پروژه <code>xAiAgent</code> و مدل‌های <code>XAgentStep</code> و <code>XAgentRun</code>).</li>
<li>سپس <strong>فاز ۱</strong> را با یک Goal ساده (مثلاً «سه تاریخ آخرین کامیت‌ها را از ابزار Date بگیر و به من بگو») End-to-End تست کنید.</li>
<li>پس از پایداری، <strong>فاز ۲ و ۳</strong> را برای وظایف پیچیده‌تر فعال کنید.</li>
<li>در نهایت <strong>فاز ۴ و ۵</strong> را برای Production آماده کنید.</li>
</ol>
<div class="highlight-box">
<strong>📌 نکته پایانی:</strong> «Agent خوب» = «ابزار خوب + Prompt خوب + حلقه خوب + Trace خوب». هیچ‌کدام به‌تنهایی کافی نیست. با پایه‌ای که دارید، تمرکز اصلی باید روی <em>کیفیت System Prompt</em> و <em>طراحی Tool Descriptions</em> باشد — چون LLM تمام تصمیمات را بر اساس همین دو مورد می‌گیرد.
</div>
</div>
</div>
<div class="page-info">
این مستند فنی و محرمانه بوده و صرفاً جهت استفاده تیم توسعه xSaherelmWorkspace تهیه شده است. هرگونه کپی‌برداری یا افشا بدون اجازه کتبی ممنوع است.
</div>
</div>
<footer class="document-footer">
<div class="footer-brand">معماری و پیاده‌سازی AI Agent در xAiApi</div>
<div class="footer-divider"></div>
<div>تاریخ تهیه: آبان ۱۴۰۵ &nbsp;|&nbsp; نسخه: ۱.۰ &nbsp;|&nbsp; طبقه‌بندی: فنی - محرمانه</div>
</footer>
</div>
</body>
</html>