Files
xSaherelmWorkspace/Documents/Docs/Developer/LLM Routing Middleware xAiApi.html
T

1048 lines
40 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>پیشنهاد طراحی Middleware پروکسی مدل‌های هوش مصنوعی</title>
<style>
@import url('https://fonts.googleapis.com/css2?family=Vazirmatn:wght@300;400;500;600;700;800&amp;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;
--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);
}
.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; }
.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(--primary-light);
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;
}
.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;
}
.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;
}
.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: 20px;
font-weight: 800;
margin-bottom: 5px;
color: var(--accent);
line-height: 1.4;
}
.stat-card .stat-label { font-size: 12px; opacity: 0.9; }
.conclusion-box {
background: linear-gradient(135deg, var(--primary), var(--primary-light));
color: white;
padding: 30px;
border-radius: 12px;
margin: 30px 0;
text-align: center;
box-shadow: 0 8px 20px rgba(26,54,93,0.3);
}
.conclusion-box h3 {
font-size: 22px;
font-weight: 800;
margin-bottom: 15px;
color: var(--accent);
}
.conclusion-box p {
font-size: 14px;
line-height: 1.8;
text-indent: 0 !important;
margin-bottom: 15px;
}
.conclusion-box .highlight {
background: rgba(201,169,97,0.2);
padding: 15px 20px;
border-radius: 8px;
margin-top: 20px;
border: 1px solid rgba(201,169,97,0.4);
}
.code-block {
background: #0f172a;
color: #e2e8f0;
padding: 18px;
border-radius: 8px;
overflow-x: auto;
direction: ltr;
text-align: left;
font-family: Consolas, Monaco, 'Courier New', monospace;
font-size: 12px;
line-height: 1.65;
margin: 20px 0;
border: 1px solid #1e293b;
}
.code-block code { white-space: pre; }
.inline-code {
background: #edf2f7;
color: #2d3748;
padding: 1px 6px;
border-radius: 4px;
font-family: Consolas, Monaco, monospace;
font-size: 12px;
direction: ltr;
display: inline-block;
}
.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; }
.stats-grid { grid-template-columns: 1fr; }
.header-top { flex-direction: column; gap: 15px; }
.doc-meta { text-align: center; }
}
</style>
</head>
<body>
<div class="document-container">
<header class="document-header">
<div class="header-top">
<div class="company-badge">
<div class="company-logo"></div>
</div>
<div class="doc-meta">
<div>شماره مستند: PROP-1405-002</div>
<div>نسخه: ۱.۰</div>
<div>تاریخ تهیه: آبان ۱۴۰۵</div>
<div>طبقه‌بندی: محرمانه</div>
</div>
</div>
<div class="document-title">
<span class="label">ARCHITECTURE & IMPLEMENTATION</span>
<h1>طراحی Middleware پروکسی مدل‌های هوش مصنوعی</h1>
<h2>مسیریابی و انتقال شفاف درخواست‌ها بر اساس XAiModelDescriptor</h2>
</div>
</header>
<div class="document-body">
<div class="intro-text">
<strong>هدف این مستند،</strong> ارائه طراحی و پیاده‌سازی یک Middleware در پروژه <span class="inline-code">xAiApi</span> است که بر اساس تعریف مدل‌ها در <span class="inline-code">XAiModelDescriptor</span>، درخواست‌های دارای پیشوند مسیر مشخص را شناسایی کرده و نام مدل را از URL استخراج و کل درخواست را به آدرس <span class="inline-code">Url</span> همان مدل منتقل کند. این رویکرد، یک لایه پروکسی شفاف و قابل کنترل برای مدل‌های Ollama، OpenAI و سایر Providerها فراهم می‌آورد.
</div>
<div class="section">
<div class="section-header">
<div class="section-number">۱</div>
<div class="section-title">
<h3>خلاصه اجرایی</h3>
<div class="subtitle">Executive Summary</div>
</div>
</div>
<div class="section-content">
<p>
در معماری فعلی، مدل‌ها از طریق <span class="inline-code">XAiApiConfiguration.Models</span> و با ساختار <span class="inline-code">XAiModelDescriptor</span> تعریف می‌شوند. هر Descriptor شامل <span class="inline-code">Name</span>، <span class="inline-code">Url</span>، <span class="inline-code">LLM</span>، <span class="inline-code">ApiKey</span> و <span class="inline-code">Provider</span> است. با استفاده از یک Middleware سبک، می‌توان مسیرهایی مانند <span class="inline-code">/ai-model/{modelName}/...</span> را شناسایی کرد و بدون تغییر در کنترلرهای موجود، درخواست را به سرویس مدل مقصد هدایت نمود.
</p>
<div class="stats-grid">
<div class="stat-card">
<div class="stat-value">تشخیص<br>از مسیر</div>
<div class="stat-label">استخراج نام مدل از Route</div>
</div>
<div class="stat-card">
<div class="stat-value">انتقال<br>شفاف</div>
<div class="stat-label">حفظ Method، Header و Body</div>
</div>
<div class="stat-card">
<div class="stat-value">پشتیبانی<br>از Streaming</div>
<div class="stat-label">مناسب SSE و پاسخ‌های تدریجی</div>
</div>
</div>
<div class="highlight-box">
<strong>نتیجه کلیدی:</strong> با افزودن یک Middleware با نام پیشنهادی <span class="inline-code">XAiModelProxyMiddleware</span> و ثبت آن با <span class="inline-code">UseXAiModelProxy()</span>، می‌توان بدون تغییر ساختار فعلی API، درخواست‌های مدل‌محور را به سرویس‌های مقصد منتقل کرد. مدل‌های مجاز صرفاً از Configuration خوانده می‌شوند و بنابراین سطح حمله و مسیرهای ناخواسته محدود می‌شود.
</div>
</div>
</div>
<div class="section">
<div class="section-header">
<div class="section-number">۲</div>
<div class="section-title">
<h3>معماری و جریان پردازش درخواست</h3>
<div class="subtitle">Request Flow & Architecture</div>
</div>
</div>
<div class="section-content">
<p>
Middleware پیشنهادی در ابتدای Pipeline قرار می‌گیرد و تنها در صورتی فعال می‌شود که مسیر درخواست با پیشوند تعیین‌شده شروع شود. در غیر این صورت، درخواست با فراخوانی <span class="inline-code">_next(context)</span> به Pipeline اصلی منتقل می‌شود. این رفتار تضمین می‌کند که سایر کنترلرها و سرویس‌های موجود بدون تغییر باقی بمانند.
</p>
<table class="styled-table">
<thead>
<tr>
<th>مرحله</th>
<th>عملیات</th>
<th>خروجی / نتیجه</th>
</tr>
</thead>
<tbody>
<tr>
<td>۱</td>
<td>دریافت درخواست HTTP</td>
<td>درخواست وارد Pipeline می‌شود</td>
</tr>
<tr>
<td>۲</td>
<td>بررسی پیشوند مسیر با <span class="inline-code">StartsWithSegments</span></td>
<td>در صورت عدم تطابق، ادامه Pipeline اصلی</td>
</tr>
<tr>
<td>۳</td>
<td>استخراج نخستین Segment پس از پیشوند به‌عنوان نام مدل</td>
<td>مثلاً <span class="inline-code">Gemma</span> از <span class="inline-code">/ai-model/Gemma/api/chat</span></td>
</tr>
<tr>
<td>۴</td>
<td>فراخوانی <span class="inline-code">configuration.GetModel(modelName)</span></td>
<td>دریافت <span class="inline-code">XAiModelDescriptor</span> مربوطه</td>
</tr>
<tr>
<td>۵</td>
<td>اعتبارسنجی Descriptor با <span class="inline-code">IsValid()</span></td>
<td>در صورت نامعتبر بودن، پاسخ 404 یا 500 کنترل‌شده</td>
</tr>
<tr>
<td>۶</td>
<td>ساخت URI مقصد بر اساس <span class="inline-code">descriptor.Url</span> و باقی مسیر</td>
<td>آدرس کامل Upstream</td>
</tr>
<tr>
<td>۷</td>
<td>کپی Headerها و Body درخواست</td>
<td>درخواست شفاف به سمت مدل</td>
</tr>
<tr>
<td>۸</td>
<td>ارسال با <span class="inline-code">HttpClient</span> و <span class="inline-code">ResponseHeadersRead</span></td>
<td>پاسخ Streaming بدون بافر کامل</td>
</tr>
<tr>
<td>۹</td>
<td>کپی Status، Headerها و Body پاسخ به کلاینت</td>
<td>پاسخ نهایی به درخواست‌کننده</td>
</tr>
</tbody>
</table>
<div class="info-box">
<strong>نکته معماری:</strong> این Middleware یک پروکسی شفاف است؛ یعنی Body را بازنویسی نمی‌کند. اگر نیاز به تغییر فیلد <span class="inline-code">model</span> در JSON بدنه یا تبدیل ساختار درخواست وجود داشته باشد، باید یک مرحله پردازش بدنه جداگانه اضافه شود. در نسخه پیشنهادی، اصل بر «انتقال کامل درخواست» است.
</div>
</div>
</div>
<div class="section">
<div class="section-header">
<div class="section-number">۳</div>
<div class="section-title">
<h3>قرارداد مسیر و قواعد تشخیص مدل</h3>
<div class="subtitle">Route Contract & Model Resolution</div>
</div>
</div>
<div class="section-content">
<p>
الگوی پیشنهادی مسیر به صورت <span class="inline-code">/{RoutePrefix}/{modelName}/{**remainingPath}</span> است. پیشوند مسیر باید قابل تنظیم باشد تا با سایر Endpointها تداخل نداشته باشد. نام مدل، نخستین Segment پس از پیشوند است و با <span class="inline-code">Uri.UnescapeDataString</span>解码 می‌شود. تطابق نام مدل در <span class="inline-code">GetModel</span> به‌صورت Case-Insensitive انجام می‌شود.
</p>
<table class="styled-table">
<thead>
<tr>
<th>درخواست ورودی</th>
<th>نام مدل استخراج‌شده</th>
<th>مسیر باقی‌مانده</th>
<th>نتیجه</th>
</tr>
</thead>
<tbody>
<tr>
<td><span class="inline-code">/ai-model/Gemma/api/chat</span></td>
<td>Gemma</td>
<td><span class="inline-code">api/chat</span></td>
<td>پروکسی به <span class="inline-code">descriptor.Url/api/chat</span></td>
</tr>
<tr>
<td><span class="inline-code">/ai-model/Embed/v1/embeddings?x=1</span></td>
<td>Embed</td>
<td><span class="inline-code">v1/embeddings</span></td>
<td>پروکسی همراه با Query String</td>
</tr>
<tr>
<td><span class="inline-code">/ai-model/Gemma</span></td>
<td>Gemma</td>
<td>خالی</td>
<td>پروکسی به ریشه <span class="inline-code">descriptor.Url</span></td>
</tr>
<tr>
<td><span class="inline-code">/ai-model/Unknown/api/chat</span></td>
<td>Unknown</td>
<td>—</td>
<td>پاسخ 404 با پیام مدل نامعتبر</td>
</tr>
<tr>
<td><span class="inline-code">/api/other</span></td>
<td>—</td>
<td>—</td>
<td>عدم تطابق؛ ادامه Pipeline اصلی</td>
</tr>
</tbody>
</table>
<div class="warning-box">
<strong>الزامات امنیتی:</strong>
<ul style="padding-right: 20px; margin-top: 10px;">
<li>پیشوند مسیر نباید با Routeهای موجود تداخل داشته باشد؛ پیشنهاد: <span class="inline-code">/ai-model</span>.</li>
<li>نام مدل فقط از میان مدل‌های تعریف‌شده در <span class="inline-code">AiApiConfiguration.Models</span> پذیرفته شود.</li>
<li>آدرس مقصد فقط از فیلد <span class="inline-code">Url</span> همان Descriptor ساخته شود؛ نه از ورودی کاربر.</li>
<li>Headerهای Hop-by-Hop مانند <span class="inline-code">Connection</span>، <span class="inline-code">Transfer-Encoding</span> و <span class="inline-code">Upgrade</span> کپی نشوند.</li>
</ul>
</div>
</div>
</div>
<div class="section">
<div class="section-header">
<div class="section-number">۴</div>
<div class="section-title">
<h3>پیاده‌سازی Middleware</h3>
<div class="subtitle">Implementation</div>
</div>
</div>
<div class="section-content">
<p>
کلاس زیر یک Middleware کامل و قابل استفاده است. برای جلوگیری از Timeout در پاسخ‌های طولانی و Streaming، از <span class="inline-code">HttpCompletionOption.ResponseHeadersRead</span> و یک <span class="inline-code">HttpClient</span> با Timeout نامحدود استفاده می‌شود. همچنین در صورت وجود <span class="inline-code">ApiKey</span> و نبود Header احراز هویت، به‌صورت اختیاری کلید مدل تزریق می‌شود.
</p>
<pre class="code-block"><code>using System;
using System.Collections.Generic;
using System.Linq;
using System.Net.Http;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Http;
using Microsoft.Extensions.Logging;
using Microsoft.Net.Http.Headers;
using xAiApi.Configurations;
using xAiApi.Extensions;
using xCommons.Extensions;
namespace xAiApi.Middlewares
{
public sealed class XAiModelProxyOptions
{
public string RoutePrefix { get; set; } = "/ai-model";
public bool InjectApiKeyIfMissing { get; set; } = true;
}
public sealed class XAiModelProxyMiddleware
{
private static readonly HashSet&lt;string&gt; HopByHopHeaders = new(StringComparer.OrdinalIgnoreCase)
{
"Connection", "Keep-Alive", "Proxy-Authenticate", "Proxy-Authorization",
"TE", "Trailer", "Transfer-Encoding", "Upgrade"
};
private readonly RequestDelegate _next;
private readonly XAiApiConfiguration _configuration;
private readonly XAiModelProxyOptions _options;
private readonly IHttpClientFactory _httpClientFactory;
private readonly ILogger&lt;XAiModelProxyMiddleware&gt; _logger;
public XAiModelProxyMiddleware(
RequestDelegate next,
XAiApiConfiguration configuration,
XAiModelProxyOptions options,
IHttpClientFactory httpClientFactory,
ILogger&lt;XAiModelProxyMiddleware&gt; logger)
{
_next = next;
_configuration = configuration;
_options = options;
_httpClientFactory = httpClientFactory;
_logger = logger;
}
public async Task InvokeAsync(HttpContext context)
{
if (!context.Request.Path.StartsWithSegments(_options.RoutePrefix, out var remaining))
{
await _next(context);
return;
}
var rawSegments = remaining.Value?
.Trim('/')
.Split('/', StringSplitOptions.RemoveEmptyEntries);
if (rawSegments is null || rawSegments.Length == 0)
{
await _next(context);
return;
}
var modelName = Uri.UnescapeDataString(rawSegments[0]);
var descriptor = _configuration.GetModel(modelName);
if (descriptor is null || !descriptor.IsValid())
{
context.Response.StatusCode = StatusCodes.Status404NotFound;
await context.Response.WriteAsJsonAsync(new
{
error = $"Model '{modelName}' is not configured."
});
return;
}
var suffixPath = string.Join('/', rawSegments.Skip(1));
var targetUri = BuildTargetUri(
descriptor.Url,
suffixPath,
context.Request.QueryString);
using var upstreamRequest = new HttpRequestMessage(
new HttpMethod(context.Request.Method),
targetUri);
CopyRequestHeaders(context, upstreamRequest);
if (context.Request.ContentLength &gt; 0 ||
context.Request.Headers.ContainsKey(HeaderNames.TransferEncoding))
{
upstreamRequest.Content = new StreamContent(context.Request.Body);
CopyContentHeaders(context, upstreamRequest.Content);
}
if (_options.InjectApiKeyIfMissing &amp;&amp;
!descriptor.ApiKey.IsNullOrEmpty() &amp;&amp;
!upstreamRequest.Headers.Contains("Authorization"))
{
upstreamRequest.Headers.TryAddWithoutValidation(
"Authorization",
$"Bearer {descriptor.ApiKey}");
}
try
{
var client = _httpClientFactory.CreateClient("XAiModelProxy");
using var upstreamResponse = await client.SendAsync(
upstreamRequest,
HttpCompletionOption.ResponseHeadersRead,
context.RequestAborted);
context.Response.StatusCode = (int)upstreamResponse.StatusCode;
CopyResponseHeaders(upstreamResponse, context.Response);
await using var responseStream = await upstreamResponse.Content
.ReadAsStreamAsync(context.RequestAborted);
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)
{
context.Response.StatusCode = StatusCodes.Status502BadGateway;
await context.Response.WriteAsJsonAsync(new
{
error = "Upstream model is unavailable."
});
}
}
}
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 = string.IsNullOrWhiteSpace(suffixPath)
? basePath
: $"{basePath}/{suffixPath.TrimStart('/')}";
builder.Query = query.HasValue
? query.Value.TrimStart('?')
: string.Empty;
return builder.Uri;
}
private static void CopyRequestHeaders(
HttpContext context,
HttpRequestMessage upstreamRequest)
{
foreach (var header in context.Request.Headers)
{
if (HopByHopHeaders.Contains(header.Key) ||
header.Key.Equals(HeaderNames.Host, StringComparison.OrdinalIgnoreCase) ||
header.Key.Equals(HeaderNames.ContentLength, StringComparison.OrdinalIgnoreCase) ||
header.Key.Equals(HeaderNames.ContentType, StringComparison.OrdinalIgnoreCase))
{
continue;
}
upstreamRequest.Headers.TryAddWithoutValidation(
header.Key,
header.Value.ToArray());
}
}
private static void CopyContentHeaders(
HttpContext context,
HttpContent content)
{
foreach (var header in context.Request.Headers)
{
if (header.Key.Equals(HeaderNames.ContentType, StringComparison.OrdinalIgnoreCase) ||
header.Key.Equals(HeaderNames.ContentEncoding, StringComparison.OrdinalIgnoreCase) ||
header.Key.Equals(HeaderNames.ContentLanguage, StringComparison.OrdinalIgnoreCase) ||
header.Key.Equals(HeaderNames.ContentDisposition, StringComparison.OrdinalIgnoreCase))
{
content.Headers.TryAddWithoutValidation(
header.Key,
header.Value.ToArray());
}
}
}
private static void CopyResponseHeaders(
HttpResponseMessage upstreamResponse,
HttpResponse response)
{
foreach (var header in upstreamResponse.Headers)
{
if (HopByHopHeaders.Contains(header.Key))
{
continue;
}
response.Headers[header.Key] = header.Value.ToArray();
}
foreach (var header in upstreamResponse.Content.Headers)
{
if (HopByHopHeaders.Contains(header.Key) ||
header.Key.Equals(HeaderNames.TransferEncoding, StringComparison.OrdinalIgnoreCase))
{
continue;
}
response.Headers[header.Key] = header.Value.ToArray();
}
}
}
public static class XAiModelProxyExtensions
{
public static IApplicationBuilder UseXAiModelProxy(this IApplicationBuilder app)
{
return app.UseMiddleware&lt;XAiModelProxyMiddleware&gt;();
}
}
}</code></pre>
<div class="success-box">
<strong>مزیت پیاده‌سازی:</strong> Middleware فوق نه Body را کاملاً در حافظه نگه می‌دارد و نه پاسخ را بافر می‌کند. بنابراین برای Endpointهای Chat، Embedding و حتی پاسخ‌های SSE/Streaming مناسب است. همچنین مسیرهای غیرمرتبط بدون هیچ تغییری به Pipeline اصلی منتقل می‌شوند.
</div>
</div>
</div>
<div class="section">
<div class="section-header">
<div class="section-number">۵</div>
<div class="section-title">
<h3>ثبت سرویس‌ها و تنظیمات در Startup</h3>
<div class="subtitle">Dependency Injection & Pipeline Registration</div>
</div>
</div>
<div class="section-content">
<p>
در متد <span class="inline-code">ConfigureServices</span> باید گزینه‌های Middleware و <span class="inline-code">HttpClient</span> اختصاصی آن ثبت شوند. سپس در متد <span class="inline-code">Configure</span>، فراخوانی <span class="inline-code">UseXAiModelProxy()</span> پیش از <span class="inline-code">UseRouting()</span> قرار می‌گیرد تا درخواست‌های پروکسی وارد سیستم Routing و Authorization کنترلرهای موجود نشوند.
</p>
<pre class="code-block"><code>// Startup.ConfigureServices
var proxyOptions = Configuration
.GetSection("AiModelProxy")
.Get&lt;XAiModelProxyOptions&gt;() ?? new XAiModelProxyOptions();
services.AddSingleton(proxyOptions);
services.AddHttpClient("XAiModelProxy", client =&gt;
{
// برای پاسخ‌های طولانی و Streaming
client.Timeout = Timeout.InfiniteTimeSpan;
});
// Startup.Configure
app.UseXSwagger();
app.UseHttpsRedirection();
app.UseXCors();
// پروکسی مدل‌ها پیش از Routing
app.UseXAiModelProxy();
app.UseRouting();
app.UseXIdentityService();
app.UseAuthorization();
app.UseEndpoints(endpoints =&gt;
{
endpoints.MapControllers();
});</code></pre>
<p>
نمونه تنظیمات در <span class="inline-code">appsettings.json</span> به‌صورت زیر است. توجه شود که مدل‌ها همان ساختار موجود <span class="inline-code">AiApiConfiguration.Models</span> را دارند و Middleware از همان بخش Configuration استفاده می‌کند.
</p>
<pre class="code-block"><code>{
"AiModelProxy": {
"RoutePrefix": "/ai-model",
"InjectApiKeyIfMissing": true
},
"AiApiConfiguration": {
"Models": [
{
"Name": "Gemma",
"Url": "http://localhost:11434",
"LLM": "gemma3",
"Provider": "Ollama"
},
{
"Name": "Embed",
"Url": "http://localhost:11434",
"LLM": "nomic-embed-text",
"Provider": "Ollama"
},
{
"Name": "OpenAI",
"Url": "https://api.openai.com",
"LLM": "gpt-4o-mini",
"ApiKey": "sk-...",
"Provider": "OpenAI"
}
]
}
}</code></pre>
<div class="info-box">
<strong>ترتیب Middleware:</strong> اگر سیاست CORS شما برای درخواست‌های مرورگری حساس است، محل قرارگیری <span class="inline-code">UseXAiModelProxy()</span> نسبت به <span class="inline-code">UseXCors()</span> را بر اساس نیاز تنظیم کنید. برای پروکسی شفاف API، قرارگیری پیش از <span class="inline-code">UseRouting()</span> توصیه می‌شود.
</div>
</div>
</div>
<div class="section">
<div class="section-header">
<div class="section-number">۶</div>
<div class="section-title">
<h3>ملاحظات عملیاتی، خطاها و تست</h3>
<div class="subtitle">Operational Notes, Errors & Testing</div>
</div>
</div>
<div class="section-content">
<p>
رفتار خطا در Middleware باید قابل پیش‌بینی باشد. مدل ناموجود باید پاسخ 404، خطای اتصال به Upstream پاسخ 502 و لغو درخواست توسط کلاینت بدون نوشتن پاسخ اضافی مدیریت شود. برای پاسخ‌های Streaming، Headerهای مربوط به Upstream باید تا حد امکان حفظ شوند.
</p>
<table class="styled-table">
<thead>
<tr>
<th>سناریو</th>
<th>رفتار مورد انتظار</th>
<th>کد وضعیت</th>
</tr>
</thead>
<tbody>
<tr>
<td>مسیر بدون پیشوند <span class="inline-code">/ai-model</span></td>
<td>ادامه Pipeline اصلی</td>
<td>بدون تغییر</td>
</tr>
<tr>
<td>مدل در Configuration وجود ندارد</td>
<td>پاسخ JSON با پیام خطا</td>
<td>404</td>
</tr>
<tr>
<td>Descriptor نامعتبر است</td>
<td>عدم ارسال به Upstream</td>
<td>404 یا 500 کنترل‌شده</td>
</tr>
<tr>
<td>Upstream در دسترس نیست</td>
<td>پاسخ خطای پروکسی</td>
<td>502</td>
</tr>
<tr>
<td>کلاینت اتصال را قطع می‌کند</td>
<td>لغو عملیات بدون نوشتن پاسخ</td>
<td>—</td>
</tr>
<tr>
<td>پاسخ SSE یا Streaming</td>
<td>انتقال تدریجی بدون بافر کامل</td>
<td>مطابق Upstream</td>
</tr>
</tbody>
</table>
<p class="no-indent"><strong>نمونه تست با curl:</strong></p>
<pre class="code-block"><code># درخواست به مدل Gemma
curl -i http://localhost:5000/ai-model/Gemma/api/chat ^
-H "Content-Type: application/json" ^
-d "{\"model\":\"gemma3\",\"messages\":[{\"role\":\"user\",\"content\":\"سلام\"}]}"
# درخواست Embedding
curl -i "http://localhost:5000/ai-model/Embed/v1/embeddings?x=1" ^
-H "Content-Type: application/json" ^
-d "{\"input\":\"متن نمونه\"}"
# مدل ناموجود
curl -i http://localhost:5000/ai-model/Unknown/api/chat</code></pre>
<div class="warning-box">
<strong>نکات مهم:</strong>
<ul style="padding-right: 20px; margin-top: 10px;">
<li>Body درخواست بازنویسی نمی‌شود؛ بنابراین اگر Upstream انتظار نام مدل متفاوتی در JSON دارد، باید لایه تبدیل اضافه شود.</li>
<li>Header <span class="inline-code">Host</span> و <span class="inline-code">Content-Length</span> کپی نمی‌شوند تا <span class="inline-code">HttpClient</span> مقدار صحیح را تنظیم کند.</li>
<li>برای احراز هویت، در صورت وجود <span class="inline-code">Authorization</span> ورودی، همان مقدار حفظ می‌شود و ApiKey مدل فقط در صورت نبود آن تزریق می‌شود.</li>
<li>در محیط Production، پیشوند مسیر و فهرست مدل‌ها را از Configuration کنترل‌شده و معتبر بارگذاری کنید.</li>
</ul>
</div>
</div>
</div>
<div class="section">
<div class="section-header">
<div class="section-number">۷</div>
<div class="section-title">
<h3>جمع‌بندی و پیشنهاد نهایی</h3>
<div class="subtitle">Final Summary & Recommendation</div>
</div>
</div>
<div class="section-content">
<p>
طراحی پیشنهادی، یک لایه پروکسی مدل‌محور و کم‌هزینه است که بر پایه همان <span class="inline-code">XAiModelDescriptor</span> موجود کار می‌کند و نیاز به تغییر کنترلرهای فعلی را حذف می‌کند. با تنظیم پیشوند مسیر، استخراج نام مدل، اعتبارسنجی از Configuration و انتقال شفاف درخواست و پاسخ، می‌توان مدل‌های مختلف را پشت یک API واحد ارائه کرد.
</p>
<div class="conclusion-box">
<h3>🎯 پیشنهاد نهایی</h3>
<p>
پیاده‌سازی <span class="inline-code">XAiModelProxyMiddleware</span> با مسیر <span class="inline-code">/ai-model/{modelName}/...</span> و ثبت آن پیش از <span class="inline-code">UseRouting()</span>، بهترین گزینه برای این نیاز است.
</p>
<div class="highlight">
<strong>💎 ارزش پیشنهادی:</strong><br>
مسیریابی مدل‌محور + انتقال شفاف درخواست + پشتیبانی از Streaming + عدم تغییر کنترلرهای موجود + کنترل امنیتی از طریق Whitelist مدل‌ها
</div>
</div>
<div class="info-box">
<strong>📞 گام بعدی:</strong> پس از تأیید نام پیشوند مسیر و سیاست احراز هویت، می‌توان کلاس‌های <span class="inline-code">XAiModelProxyMiddleware</span> و <span class="inline-code">XAiModelProxyOptions</span> را به پروژه <span class="inline-code">xAiApi</span> اضافه کرد و ثبت DI و Pipeline را در <span class="inline-code">Startup.cs</span> انجام داد.
</div>
</div>
</div>
<div class="page-info">
این مستند محرمانه بوده و صرفاً جهت ارائه راهکار فنی تهیه شده است. هرگونه کپی‌برداری یا افشا بدون اجازه کتبی ممنوع است.
</div>
</div>
<footer class="document-footer">
<div class="footer-brand">طراحی و توسعه: تیم معماری xSaherelmWorkspace</div>
<div class="footer-divider"></div>
<div>تاریخ تهیه: آبان ۱۴۰۵ &nbsp;|&nbsp; نسخه: ۱.۰ &nbsp;|&nbsp; طبقه‌بندی: محرمانه</div>
</footer>
</div>
</body>
</html>