+
+
برای تولید فایل با فرمت دلخواه کاربر، دو رویکرد وجود دارد. رویکرد ساده (مستقیم) شکننده است چون مدل باید مستقیماً کد فایل را تولید کند. رویکرد حرفهای، دو مرحلهای است: مدل محتوا را به یک Schema استاندارد میانی تبدیل میکند، سپس یک Renderer قطعی، فایل را تولید میکند.
+
+
+
+
رویکرد مستقیم (ناکارآمد)
+
+ - مدل مستقیماً HTML/MD مینویسد
+ - کیفیت متغیر و غیرقابل پیشبینی
+ - سخت برای تست و اعتبارسنجی
+ - خطای ساختاری محتمل
+
+
+
+
رویکرد دو مرحلهای (پیشنهادی)
+
+ - مدل به Schema ساختاریافته تبدیل میکند
+ - Renderer قطعی، فایل را میسازد
+ - قابل تست، اعتبارسنجی و توسعه
+ - پشتیبانی از چند فرمت با یک Schema
+
+
+
+
+
۴.۱ Schema استاندارد میانی — XDocumentSpec
+
+
+
public enum XDocumentFormat
+{
+ Html, Markdown, PlainText, Pdf, Docx, Xlsx
+}
+
+public sealed class XDocumentSpec
+{
+ public XDocumentFormat Format { get; set; }
+ public string Title { get; set; } = "";
+ public string? Subtitle { get; set; }
+ public string? Author { get; set; }
+ public DateTime? GeneratedAtUtc { get; set; }
+ public string? Language { get; set; } = "fa";
+ public bool Rtl { get; set; } = true;
+ public IList<XDocumentSection> Sections { get; set; } = [];
+ public XDocumentStyle Style { get; set; } = new();
+}
+
+public sealed class XDocumentSection
+{
+ public string Heading { get; set; } = "";
+ public int Level { get; set; } = 1;
+ public IList<XDocumentBlock> Blocks { get; set; } = [];
+ public IList<XDocumentSection> Children { get; set; } = [];
+}
+
+public abstract class XDocumentBlock { }
+public sealed class XParagraphBlock : XDocumentBlock { public string Text { get; set; } = ""; }
+public sealed class XListBlock : XDocumentBlock { public bool Ordered { get; set; } public IList<string> Items { get; set; } = []; }
+public sealed class XTableBlock : XDocumentBlock { public IList<string> Headers { get; set; } = []; public IList<IList<string>> Rows { get; set; } = []; }
+public sealed class XCodeBlock : XDocumentBlock { public string Language { get; set; } = "text"; public string Code { get; set; } = ""; }
+public sealed class XQuoteBlock : XDocumentBlock { public string Text { get; set; } = ""; }
+public sealed class XImageBlock : XDocumentBlock { public string Url { get; set; } = ""; public string? Alt { get; set; } }
+
+public sealed class XDocumentStyle
+{
+ public string PrimaryColor { get; set; } = "#1a365d";
+ public string AccentColor { get; set; } = "#c9a961";
+ public string FontFamily { get; set; } = "Vazirmatn, Tahoma, sans-serif";
+}
+
+
۴.۲ مرحله اول: مدل به Schema تبدیل میکند
+
+
از Structured Output (JSON Mode) یا Prompt مهندسیشده استفاده کنید تا مدل، محتوای خام را به XDocumentSpec تبدیل کند:
+
+
+
[Description("Converts raw content into a structured XDocumentSpec JSON for file generation.")]
+public async Task<XDocumentSpec> BuildSpecAsync(
+ [Description("Raw content to structure.")] string content,
+ [Description("Target format: Html|Markdown|Pdf|Docx|Xlsx.")] string format,
+ [Description("Optional title.")] string? title = null,
+ CancellationToken cancellationToken = default)
+{
+ var systemPrompt = """
+ You are a document structuring engine.
+ Convert the user's raw content into a strict JSON object matching this schema:
+ {
+ "format": "Html|Markdown|Pdf|Docx|Xlsx",
+ "title": "...",
+ "subtitle": "...",
+ "author": "...",
+ "language": "fa|en",
+ "rtl": true,
+ "sections": [
+ {
+ "heading": "...",
+ "level": 1,
+ "blocks": [
+ { "type": "paragraph", "text": "..." },
+ { "type": "list", "ordered": false, "items": ["...", "..."] },
+ { "type": "table", "headers": ["..."], "rows": [["..."]] },
+ { "type": "code", "language": "...", "code": "..." },
+ { "type": "quote", "text": "..." }
+ ],
+ "children": []
+ }
+ ],
+ "style": { "primaryColor": "#1a365d", "accentColor": "#c9a961", "fontFamily": "Vazirmatn" }
+ }
+ Rules:
+ - Output ONLY valid JSON. No markdown fences, no explanations.
+ - If the source is long, prefer more sections over larger sections.
+ - Preserve Persian text as-is (do not translate).
+ """;
+
+ var response = await chatClient.GetResponseAsync<XDocumentSpec>(
+ messages: new[]
+ {
+ new ChatMessage(ChatRole.System, systemPrompt),
+ new ChatMessage(ChatRole.User, $"Format: {format}\nTitle: {title}\n\n{content}")
+ },
+ serializerOptions: new JsonSerializerOptions
+ {
+ Converters = { new JsonStringEnumConverter() },
+ PropertyNamingPolicy = JsonNamingPolicy.CamelCase,
+ },
+ cancellationToken: cancellationToken);
+
+ return response.Result;
+}
+
+
۴.۳ مرحله دوم: Renderer قطعی + ذخیره + لینک دانلود
+
+
+
[Description("Renders the XDocumentSpec to a real file, stores it, and returns a download URL.")]
+public async Task<XFileDownloadResult> CreateFile(
+ [Description("The structured document spec (JSON).")] XDocumentSpec spec,
+ XUserClaimsInfoDto userInfo,
+ CancellationToken cancellationToken = default)
+{
+
+ var renderer = rendererFactory.Resolve(spec.Format);
+ var (bytes, fileName, mimeType) = await renderer.RenderAsync(spec, cancellationToken);
+
+
+ using var stream = new MemoryStream(bytes);
+ var formFile = new FormFile(stream, 0, bytes.Length, fileName, fileName);
+ var uploaded = await fileProvider.Upload(formFile, userInfo, connectionId: null, cancellationToken);
+
+
+ var downloadUrl = $"/api/v1/files/{uploaded.Id}/download";
+
+ return new XFileDownloadResult(
+ FileId: uploaded.Id,
+ FileName: fileName,
+ Url: downloadUrl,
+ MimeType: mimeType,
+ SizeBytes: bytes.Length);
+}
+
+
+public sealed class XDocumentRendererFactory
+{
+ private readonly IReadOnlyDictionary<XDocumentFormat, IXDocumentRenderer> renderers;
+
+ public IXDocumentRenderer Resolve(XDocumentFormat format)
+ => renderers.TryGetValue(format, out var r) ? r
+ : throw new NotSupportedException($"Format {format} not supported.");
+}
+
+
۴.۴ نگاشت Rendererها به کتابخانههای موجود
+
+
+
+
+ | فرمت |
+ Renderer |
+ کتابخانه |
+ توضیح |
+
+
+
+
+ | Html |
+ XHtmlDocumentRenderer |
+ Razor / StringBuilder |
+ مستقیم از Schema به HTML با CSS استاندارد |
+
+
+ | Markdown |
+ XMarkdownDocumentRenderer |
+ StringBuilder |
+ تبدیل Schema به MD ساده |
+
+
+ | Pdf |
+ XPdfDocumentRenderer |
+ QuestPDF |
+ پشتیبانی کامل RTL؛ QuestPDF در پروژه شما موجود است |
+
+
+ | Docx |
+ XDocxDocumentRenderer |
+ DocumentFormat.OpenXml |
+ در پروژه شما برای خواندن DOCX استفاده شده؛ برای نوشتن هم کار میکند |
+
+
+ | Xlsx |
+ XXlsxDocumentRenderer |
+ ClosedXML |
+ در پروژه شما برای Excel اشاره شده |
+
+
+
+
+
+ 💡 نکته مهم: دو متد BuildSpecAsync و CreateFile بهعنوان دو Tool جداگانه در فهرست AITool ثبت میشوند. این کار به مدل اجازه میدهد در صورت خطا در مرحله ۱ (JSON نامعتبر)، دوباره تلاش کند بدون آنکه فایلی ساخته شود. همچنین امکان بازبینی توسط کاربر (Human-in-the-loop) بین دو مرحله وجود دارد.
+
+
+
+ ✓ نتیجه: با این طراحی، پشتیبانی از فرمتهای جدید فقط با افزودن یک Renderer جدید ممکن است. کیفیت خروجی قطعی و قابل تست است. لینک دانلود از همان زیرساخت IXFileProvider و Storage موجود استفاده میکند و نیازی به سرویس جدید نیست.
+
+