要從 LLM 輸出在 C# 中生成 Word 或 PDF 文件,讓模型根據 JSON Schema 返回 JSON,然後將該 schema 傳遞給 JsonDataSource,讓 Word 模板生成文件。 模型從不寫入文件;它只提供進入文件的資料。

以下說明為什麼這樣的拆分與 schema 才是關鍵。

要求語言模型產生客戶對帳單時,你會得到一段讀起來不錯但在所有重要方面都錯誤的內容:字體錯誤、沒有標誌、編號與你上次發送的不匹配,以及法律從未見過的措辭。要求它閱讀合約並抽取事實時,它則表現得非常好。

所以把工作拆開。模型返回 資料。模板產生 文件。

這個在投入生產環境後仍能運作的版本多了一個部件:JSON Schema,兩端都使用。完整範例在 GitHub — llm-json-to-branded-documents-net。

沒有 schema 會出什麼問題

new DocumentAssembler().AssembleDocument(
    "Customer card.docx",
    "statement.docx",
    new DataSourceInfo(new JsonDataSource("llm-output.json"), "customer"));

這在模型返回類似以下內容時會正常工作,因為這正是來源文件所說的:

{ "Name": "Quayside Bistro", "Account": "00042", "Cards": [], "Loyalty": null }

接著兩者都會出錯:

An error has been encountered at the end of expression 'customer.Cards.First().Type]>'.
Can not get the value of member 'Type' on type 'System.Data.DataRow'.

以及較不顯眼的情況,帳號 00042 在文件中變成 42。

這都不是模型的錯。沒有 schema 時,引擎必須從資料本身學習資料形狀:空陣列沒有元素類型,且一串數字看起來像是數值。

JSON Schema 如何在雙方解決問題

一次寫好 schema。把它交給模型作為答案的形狀,同時交給組裝器作為資料的形狀。

26.11 版新增 — JsonDataSource 的 JSON Schema 支援。

JsonDataSource dataSource = new JsonDataSource(
    "data/Customer.json",
    "data/Customer.schema.json");

new DocumentAssembler().AssembleDocument(
    "templates/Json schema.docx",
    "output/statement.docx",
    new DataSourceInfo(dataSource, "customer"));

相同的資料現在可以正確呈現:Customer: Quayside Bistro、Account number: 00042、No payment card on file,以及空的 loyalty 行。即使資料中相應欄位為空、null 或缺失,只要 schema 宣告了成員,模板仍可使用,且其類型來源於 schema,而非第一個出現的值。

提示描述的是資料,而非文件

Return only a JSON object that satisfies the JSON Schema below. No prose, no markdown fences.

1. Use exactly the property names of the schema. The template reads those names.
2. Keep the declared types. A value the schema calls a string stays a string, even when it
   looks like a number: an account number 00042 must not become 42.
3. When the source does not mention something, leave it out, or use null, or an empty array —
   whichever the schema allows. Do not invent a value.
4. Do not add properties the schema does not declare.

規則 3 是關鍵。被要求「有幫助」的模型會用看似合理的內容填補空缺,而虛構的 loyalty 等級比空白行更糟——在帶有你標誌的文件中這是錯誤的。

提示中根本不提 Word、字體或版面配置。這正是重點:相同的提示與相同的 schema 今天可服務 DOCX,明天可服務 PDF 或電子郵件。

模型輸出安全地傳遞給文件引擎嗎?

模型讀取了別人的文件。如果該文件包含圖片 URL,模型可能會把它回傳給你,而類似 <<image [customer.PhotoUrl]>> 的標籤會讓 你的伺服器 去抓取——可能是你內部網路的地址。

自 26.11 起預設不會發生這種情況:來自 data 的引用會被跳過,而 template 本身攜帶的引用仍會如往常載入。設計師的標誌仍能正常工作;從傳入郵件衍生的值不會觸及網路。

LoadSaveOptions options = new LoadSaveOptions();
options.WhitelistedResources.Add("images.example.com");          // hosts you trust
options.ExternalResourceHandler = new LocalImageHandler(path);   // and see every decision

處理程式本身可以提供位元組,因此組裝步驟根本不需要任何外部網路:

public override void OnLoading(ExternalResourceLoadingArgs args)
{
    Console.WriteLine($"{args.Origin} resource {args.Uri}: {(args.Skipped ? "skipped" : "allowed")}");

    if (!args.Skipped && args.Uri.StartsWith("https://images.example.com/", StringComparison.OrdinalIgnoreCase))
        args.Data = File.ReadAllBytes(mImagePath);
}

需要注意的事項

  • Validation is still yours. Schema 只保護模板,不保證資料的真實性。與行數不符的 total 是業務規則,業務規則屬於你。
  • Store the JSON. 無法從已儲存資料重建的文件,六個月後也說不清。保留模型的回應,而不僅僅是檔案本身。
  • The library never sees the model. 它只看到 JSON 檔案與 schema,因此更換模型、SDK 或改用本機執行環境都不會影響下游。

常見問題

如何在 C# 中從 LLM 輸出生成 Word 文件?
讓模型返回符合 JSON Schema 的 JSON,使用該 JSON 與相同的 schema 建立 JsonDataSource,然後以 Word 模板呼叫 DocumentAssembler.AssembleDocument。文件來源於模板,永遠不會來自模型。

為什麼模型的 "00042" 在文件中變成了 42?
沒有 schema 時,引擎會從資料推斷類型,而一串數字會被視為數值。於 schema 中將該欄位宣告為 "type": "string",即可保持 00042。

當模型省略可選欄位時會發生什麼?
有 schema 時,該欄位已知且會呈現為空。沒有 schema 時,可使用 DocumentAssemblyOptions.AllowMissingMembers,並先閱讀 Templates that survive incomplete data —— 這樣很容易隱藏真正的問題。

輸出可以是 PDF 而不是 DOCX 嗎?
可以,使用相同的呼叫方式:加入 new LoadSaveOptions(FileFormat.Pdf)。

哪些模型可以使用此方法?
任何能根據 JSON Schema 返回結構化輸出的模型 —— schema 是唯一的合約,模板本身不依賴於提供者。

試試看

git clone https://github.com/groupdocs-assembly/llm-json-to-branded-documents-net.git
cd llm-json-to-branded-documents-net
dotnet run --project src/LlmDocuments -- generate

它會在離線環境下使用範例資料執行。設定 ANTHROPIC_API_KEY 並使用 extract 以將真實模型放在前端。

逐步說明版本位於文件中:Generate documents from model output。如果資料因非模型原因而有缺口,請接著閱讀 Templates for incomplete data。