odforge 0.3.0__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (66) hide show
  1. odforge/__init__.py +1 -0
  2. odforge/benchmark.py +287 -0
  3. odforge/check.py +416 -0
  4. odforge/cli.py +1027 -0
  5. odforge/components.py +270 -0
  6. odforge/critic.py +1260 -0
  7. odforge/docfonts.py +104 -0
  8. odforge/editor_api.py +33 -0
  9. odforge/editor_launch.py +134 -0
  10. odforge/editor_routes.py +131 -0
  11. odforge/extract.py +478 -0
  12. odforge/feedback.py +86 -0
  13. odforge/fontembed.py +166 -0
  14. odforge/ir.py +1181 -0
  15. odforge/layoutcheck.py +602 -0
  16. odforge/llm.py +1865 -0
  17. odforge/localguard.py +42 -0
  18. odforge/mcp_server.py +552 -0
  19. odforge/media.py +352 -0
  20. odforge/odpedit.py +1219 -0
  21. odforge/package.py +114 -0
  22. odforge/pagefacts.py +388 -0
  23. odforge/preview.py +104 -0
  24. odforge/references.py +153 -0
  25. odforge/render/__init__.py +40 -0
  26. odforge/render/odp.py +5687 -0
  27. odforge/render/ods.py +155 -0
  28. odforge/render/odt.py +223 -0
  29. odforge/scene.py +657 -0
  30. odforge/setup_agents.py +274 -0
  31. odforge/skills/odforge-design/SKILL.md +298 -0
  32. odforge/skills/odforge-design/themes/academic.md +52 -0
  33. odforge/skills/odforge-design/themes/clay.md +53 -0
  34. odforge/skills/odforge-design/themes/color-system.md +59 -0
  35. odforge/skills/odforge-design/themes/crimson.md +53 -0
  36. odforge/skills/odforge-design/themes/dark.md +53 -0
  37. odforge/skills/odforge-design/themes/forest.md +54 -0
  38. odforge/skills/odforge-design/themes/gold.md +53 -0
  39. odforge/skills/odforge-design/themes/minimal.md +53 -0
  40. odforge/skills/odforge-design/themes/navy.md +56 -0
  41. odforge/skills/odforge-design/themes/plum.md +53 -0
  42. odforge/skills/odforge-design/themes/sky.md +53 -0
  43. odforge/skills/odforge-design/themes/slate.md +53 -0
  44. odforge/skills/odforge-design/themes/teal.md +53 -0
  45. odforge/skills/odforge-design/themes/violet.md +56 -0
  46. odforge/templates.py +250 -0
  47. odforge/textmetrics.py +616 -0
  48. odforge/textutil.py +24 -0
  49. odforge/themes.py +886 -0
  50. odforge/validate.py +403 -0
  51. odforge/watch.py +266 -0
  52. odforge/webapi.py +2617 -0
  53. odforge/webui/assets/editor-CjpYXM1a.css +1 -0
  54. odforge/webui/assets/editor-DPToJGio.js +3 -0
  55. odforge/webui/assets/jsx-runtime-C7KMcVI_.js +8 -0
  56. odforge/webui/assets/main-BLOs7Hnk.js +7 -0
  57. odforge/webui/assets/main-D21yFVE6.css +1 -0
  58. odforge/webui/editor.html +14 -0
  59. odforge/webui/index.html +25 -0
  60. odforge/xmlsafe.py +46 -0
  61. odforge/zipguard.py +91 -0
  62. odforge-0.3.0.dist-info/METADATA +95 -0
  63. odforge-0.3.0.dist-info/RECORD +66 -0
  64. odforge-0.3.0.dist-info/WHEEL +4 -0
  65. odforge-0.3.0.dist-info/entry_points.txt +3 -0
  66. odforge-0.3.0.dist-info/licenses/LICENSE +21 -0
odforge/llm.py ADDED
@@ -0,0 +1,1865 @@
1
+ """ODForge LLM backend abstraction layer.
2
+
3
+ Turns a natural-language prompt into a validated Document IR. Everything that
4
+ decides *what* to ask — the prompts, the retries, the gates — lives once, in
5
+ ``StructuredLLMBackend``; each transport implements a single method:
6
+
7
+ * ``OpenAICompatBackend`` drives an OpenAI-compatible chat endpoint with forced
8
+ function calling — Ollama, or any hosted provider that speaks the OpenAI API
9
+ (``custom``: DeepSeek, OpenAI, OpenRouter, DashScope, vLLM …).
10
+ * ``CodexCliBackend`` drives the locally installed Codex CLI as a subprocess,
11
+ where ``--output-schema`` plays the part the forced tool call plays above.
12
+ It authenticates through the operator's own ChatGPT login, so it spends no
13
+ API key and hits no per-key quota.
14
+
15
+ The ``BACKENDS`` registry makes adding a source a one-liner.
16
+
17
+ This module contains no rendering logic. API-key material is read from
18
+ environment variables only and never hard-coded.
19
+ """
20
+
21
+ from __future__ import annotations
22
+
23
+ import json
24
+ import math
25
+ import os
26
+ import re
27
+ import shutil
28
+ import subprocess
29
+ import tempfile
30
+ from pathlib import Path
31
+ from typing import (
32
+ Callable,
33
+ Dict,
34
+ List,
35
+ Optional,
36
+ Protocol,
37
+ Type,
38
+ Union,
39
+ runtime_checkable,
40
+ )
41
+
42
+ import json_repair
43
+ from openai import OpenAI
44
+ from pydantic import BaseModel, Field, ValidationError, field_validator
45
+
46
+ from odforge.ir import (
47
+ LANGUAGES,
48
+ MIN_OUTLINE_PAGES,
49
+ BulletItem,
50
+ Outline,
51
+ Presentation,
52
+ Spreadsheet,
53
+ TextDoc,
54
+ parse_ir,
55
+ )
56
+ from odforge.textmetrics import bare_cards, check_budget, count_mismatch
57
+ from odforge.themes import THEME_LABELS, THEMES, Theme, resolve_design, resolve_style
58
+
59
+ Document = Union[TextDoc, Presentation, Spreadsheet]
60
+
61
+ # doc_type -> IR model class
62
+ DOC_TYPES: Dict[str, Type[Document]] = {
63
+ "text": TextDoc,
64
+ "presentation": Presentation,
65
+ "spreadsheet": Spreadsheet,
66
+ }
67
+
68
+ TOOL_NAME = "emit_document"
69
+
70
+ SYSTEM_PROMPT = """\
71
+ 你是 ODForge 的文件內容產生器,專門為教學場景產出結構化文件。請嚴格遵守以下規則:
72
+
73
+ 【語言與語氣】
74
+ - 一律輸出繁體中文(zh-TW),用詞、標點皆使用台灣慣用寫法。
75
+ - 面向教學用途,內容須準確、清楚、有條理,適合教師授課或學生自學。
76
+
77
+ 【輸出方式】
78
+ - 只透過 emit_document 工具輸出結果,不要輸出任何一般文字或說明。
79
+ - 產出內容必須完全符合工具參數的 JSON Schema。
80
+ - 工具參數必須是嚴格合法的 JSON,所有字串值(含 notes)一律以雙引號包裹。
81
+
82
+ 【一般文件(text)】
83
+ - 建立清楚的標題階層(章、節、小節),善用標題、段落、清單與表格。
84
+ - 段落文字流暢完整,必要時使用引言(quote)或註記(note)樣式。
85
+
86
+ 【簡報(presentation)】
87
+ - 張數控制在 8 到 20 張之間。
88
+ - 每張投影片的重點條列(bullets)不超過 5 條,每一條不超過 30 個字。
89
+ - 適時穿插 section(分節)與 big-fact(關鍵數據)版面,調整敘事節奏。
90
+ - 每一張投影片都必須填寫 notes(講者備忘稿),說明講述重點與延伸。
91
+
92
+ 【試算表(spreadsheet)】
93
+ - 數字欄位一律使用數值(number),不要用字串包裝數字。
94
+ - 公式使用 of:= 命名空間(OpenFormula),欄位標題清楚。
95
+
96
+ 請依使用者的需求,產出恰當且完整的文件內容。"""
97
+
98
+
99
+ OUTLINE_TOOL_NAME = "emit_outline"
100
+
101
+ OUTLINE_SYSTEM_PROMPT = """\
102
+ 你是 ODForge 的簡報總監,負責在正式撰稿之前,先為整份簡報「定調」:一次決定
103
+ 美術方向(DesignSpec)與整份大綱的頁面角色(page roles)。這是兩段式流程的第一段,
104
+ 你只做設計與骨架,不寫每頁的細節內容(那是下一段的工作)。
105
+
106
+ 【語言】
107
+ - 一律以繁體中文(zh-TW)思考與輸出,用詞、標點皆採台灣慣用寫法。
108
+
109
+ 【輸出方式】
110
+ - 只透過 emit_outline 工具輸出結果,不要輸出任何一般文字。
111
+ - 產出必須完全符合工具參數的 JSON Schema,且為嚴格合法的 JSON(所有字串以雙引號包裹)。
112
+
113
+ 【第一步:美術方向(design)】
114
+ 1. 先從主題「內心」推導 2–3 個候選美術方向(例如:學術淨白、科技深色控制室、暖調人文…),
115
+ 衡量各自的調性、受眾與場合。
116
+ 2. 從中「挑定一個」並具體化為 DesignSpec 輸出,不要交出多個選項:
117
+ - palette:五色 bg / surface / text / muted / accent,皆為 6 位十六進位色碼("#RRGGBB")。
118
+ - fonts:display 與 body 各挑一,只能從白名單選:
119
+ Noto Sans TC、Noto Serif TC、微軟正黑體、標楷體。
120
+ - scale:compact / standard / display 三選一(講者型偏 display,自讀型偏 compact/standard)。
121
+ 3. 對比度自我檢查(務必在送出前自行驗算,否則會被退件):
122
+ - text 對 bg 的對比度需 ≥ 4.5。
123
+ - accent 對 bg、muted 對 bg 的對比度需 ≥ 3.0。
124
+ 深色底就搭亮色字、亮色底就搭深色字。若沒把握,寧可選對比明確的安全色。
125
+
126
+ 【第二步:頁面角色大綱(pages)】
127
+ 可用的 role(與投影片版型一致):
128
+ title、agenda、section、title-content、two-col、comparison、big-fact、quote、chart、closing。
129
+ 排版紀律:
130
+ - 「一頁一個想法」:每頁只承載一個重點,gist 用一句話說清楚這頁要講什麼。
131
+ - 開場第一頁一定是 title;整份 ≥ 15 頁才放 agenda,且緊接在 title 之後。
132
+ - section 分節頁只在整份 ≥ 20 頁時使用,最多 3 頁;較短的簡報不要放 section,
133
+ 改把章節名寫進該段第一頁的 kicker(例如「02 研究方法」)。
134
+ - 適時穿插 big-fact(關鍵數據)、quote(引言)、chart(圖表)來調節敘事節奏。
135
+ - 同一種 role 不得連續出現 ≥ 3 頁,避免版面單調。
136
+ - 最後一頁一定是 closing 收尾;若需求含決策、風險或下一步,closing 的 gist
137
+ 必須明確寫出決策請求與具體行動,不得只寫「謝謝」或空泛口號。
138
+ - chart 只有在「使用者的需求裡有真實數據」時才可出現;沒有數據就不要放 chart 頁(不要編造數字)。
139
+
140
+ 【mode:講述型態】
141
+ - presenter(講者型):大字級、極少字,靠講者口述;適合上台簡報。
142
+ - detailed(自讀型):文字完整,能獨立閱讀;適合講義或寄送。
143
+ 從使用者意圖判斷該用哪一種:審查、提案、計畫書、報告、講義、會議資料等
144
+ 「會被拿來讀、會被追問」的簡報用 detailed;演講、發表、上台說服用 presenter。
145
+ 無明確線索時預設 detailed。
146
+
147
+ 請據此輸出一份「設計已定案、骨架已排好」的大綱。"""
148
+
149
+
150
+ SLIDES_TOOL_NAME = "emit_slides"
151
+
152
+ SLIDES_SYSTEM_PROMPT = """\
153
+ 你是 ODForge 的簡報撰稿人,負責兩段式流程的第二段:大綱與美術方向都已定案,
154
+ 你要「逐頁填內容」,把每一頁的角色(role)實作成一張完整的投影片(Slide)。
155
+
156
+ 【語言】
157
+ - 一律以繁體中文(zh-TW)撰寫,用詞、標點皆採台灣慣用寫法。
158
+
159
+ 【輸出方式】
160
+ - 只透過 emit_slides 工具輸出結果,不要輸出任何一般文字。
161
+ - 產出必須完全符合工具參數的 JSON Schema,且為嚴格合法的 JSON(所有字串以雙引號包裹)。
162
+ - 投影片的「張數」與「每一頁的版型(layout)」必須與大綱完全一致、逐頁對齊,
163
+ 不得增刪、不得改動順序、不得換版型。
164
+
165
+ 【蒸餾鐵則(依講述型態 mode)】
166
+ - presenter(講者型):每一條 bullet ≤ 20 字、每頁 ≤ 4 條;字少,但每條都是一個完整觀點。
167
+ - detailed(自讀型):每一條 bullet 15–40 字、每頁 3–6 條;文字完整、能獨立閱讀。
168
+ - 內容文字裡「不要」寫出版型名稱(如「title-content」「two-col」),
169
+ 那是給引擎看的,不是給讀者看的。
170
+
171
+ 【各版型填寫要點】
172
+ - title / section:標題精煉。
173
+ - closing:title 寫結論或決策請求;bullets 放 2 到 4 個具體風險、責任或下一步。
174
+ 使用者要求的內容必須出現在投影片可見欄位,不得只藏在 notes。
175
+ - agenda:bullets 逐條對應大綱各分節(section)的標題,順序一致。
176
+ - title-content:bullets 逐條列重點,必要時用巢狀 children 補一層次要細節。
177
+ - two-col:left / right 兩欄各放各自的重點。
178
+ - comparison:left[0] 與 right[0] 是兩欄的「欄位標題」,其後才是各欄內容。
179
+ - big-fact:fact 放關鍵數據或一句重話,bullets 放一行輔助說明。
180
+ - quote:quote 放引言原文,attribution 放出處。
181
+ - chart:chart 欄必須給「真數據」——labels 與 values 一一對應,
182
+ 數據來源是該頁 gist 或使用者需求,不可捏造。
183
+
184
+ 【講者備忘稿】
185
+ - 每一張投影片都必須填寫 notes(講者備忘稿),說明這頁怎麼講與延伸重點,不可留空。
186
+
187
+ 請依大綱逐頁填出完整、精簡、可直接上台的投影片內容。"""
188
+
189
+
190
+ OUTLINE_VISUAL_GUIDANCE = """
191
+
192
+ 【視覺敘事規則】
193
+ - 每頁除了 gist,也要填 visual_intent,具體描述觀眾應該看見的關係,
194
+ 例如「四階段由左到右推進」或「三個關鍵指標並列比較」,不要只寫「簡潔」。
195
+ - 遇到步驟、方法或工作流,使用 process;遇到時間演進,使用 timeline;
196
+ 遇到兩到四個 KPI 或成果數字,使用 metrics;遇到兩到四個平行觀點、
197
+ 支柱或功能,使用 cards。
198
+ - 遇到系統架構、因果關係、中心與周邊或上下層級,使用 diagram。
199
+ - 不要把本來應該是圖解的內容塞進 title-content。除封面、章節與結尾外,
200
+ title-content 不應壟斷整份簡報;語意適合時優先使用視覺頁型。
201
+ - 版型服務敘事,不要為了湊版型捏造數字、日期或來源。
202
+ """
203
+
204
+ SLIDES_VISUAL_GUIDANCE = """
205
+
206
+ 【內容與視覺元件規則】
207
+ - 原始需求是事實、受眾與語氣的主要依據;outline 的 gist 只是頁面摘要,
208
+ 不得用 gist 取代或遺忘原始需求。
209
+ - presenter 的字數限制是上限,不是要求內容空泛。每頁要有可講述的觀點、
210
+ 因果或證據;notes 補充講者需要的脈絡。
211
+ - process:steps 放 2–5 個步驟,每個 step 使用 title 與 detail。
212
+ - timeline:events 放 2–5 個事件,每個 event 使用 label、title、detail。
213
+ - metrics:metrics 放 2–4 個指標,每個 metric 使用 value、label、detail。
214
+ - cards:bullets 放 2–4 個平行且可獨立閱讀的觀點。
215
+ - diagram:diagram.kind 使用 hub 或 hierarchy;nodes 放 2–6 個節點,
216
+ edges 使用 source、target 與可選 label,所有 id 必須存在且唯一。
217
+ - sources:只有原始需求確實提供資料來源時才填,最多 3 筆;
218
+ label 要短,url 必須是真實的 http(s) 網址。不得捏造引用。
219
+ - 不得用「圖解示意」、「放圖片」、「待補」等佔位文字假裝已完成視覺內容。
220
+ - 原始需求沒有提供的精確統計數字、日期、引言或來源,不要自行捏造。
221
+ - 原始需求沒有提供的技術棧、程式框架、資料庫、雲端服務、產品名稱或版本,
222
+ 一律不得自行補上。資訊不足時使用「前端介面」「API 服務」「資料庫」等通用名稱。
223
+ - 送出前自查所有英文技術名與品牌名:若原始需求沒有逐字提供,就改成通用名稱。
224
+ """
225
+
226
+ # Image layouts are intentionally described in a clean, machine-stable suffix:
227
+ # some legacy prompt text above is kept byte-for-byte for compatibility.
228
+ OUTLINE_VISUAL_GUIDANCE += """
229
+
230
+ - 有可用圖片素材,而且圖片本身承載主要證據或情境時,優先規劃
231
+ image-focus;圖片與三到四個結論並列時使用 image-split。
232
+ - 不要為了裝飾而安排圖片頁;visual_intent 必須說明圖片要證明什麼。
233
+ """
234
+
235
+ SLIDES_VISUAL_GUIDANCE += """
236
+
237
+ - image-focus / image-split:必須填 image。
238
+ - 若「可用圖片素材」列出 asset id,image.src 只能填 asset://<id>,
239
+ 並依描述選擇真正相關的素材,不得虛構 id。
240
+ - 若圖片生成可用且沒有合適素材,可留空 src 並填具體的 image.prompt。
241
+ - image.alt 必填;caption 與 credit 要精簡且不可捏造。
242
+ - image-split 的 bullets 放 2–4 個由圖片支持的結論。
243
+ """
244
+
245
+ # Keep the established prompt intact while extending its source-grounding and
246
+ # visual-planning contract.
247
+ OUTLINE_SYSTEM_PROMPT += OUTLINE_VISUAL_GUIDANCE
248
+ SLIDES_SYSTEM_PROMPT += SLIDES_VISUAL_GUIDANCE
249
+
250
+
251
+ # ---------------------------------------------------------------------------
252
+ # Deck quality contract
253
+ #
254
+ # Generated decks read as sparse and interchangeable for three reasons the
255
+ # prompts themselves caused: a presenter default that asked for "寧缺勿雜",
256
+ # free-form palettes that left every deck on the default composition, and no
257
+ # instruction to fill the lede / takeaway / kicker fields the renderer draws.
258
+ # The rules below follow what the tools that do this well converge on —
259
+ # action titles (consulting "horizontal logic"), a reading-deck density for
260
+ # review/proposal decks (Duarte slidedoc), minimum as well as maximum content
261
+ # per layout (Presenton's per-layout schemas), no adjacent repeat layouts, and
262
+ # structural pages budgeted by deck length (agenda ≥ 12 pages).
263
+ # ---------------------------------------------------------------------------
264
+
265
+
266
+ def _palette_menu() -> str:
267
+ rows = []
268
+ for tid, t in THEMES.items():
269
+ rows.append(
270
+ f" - {THEME_LABELS[tid]}:bg={t.bg} surface={t.surface} "
271
+ f"text={t.text} muted={t.muted} accent={t.accent};"
272
+ f"display 字體={t.font_display}"
273
+ )
274
+ return "\n".join(rows)
275
+
276
+
277
+ OUTLINE_QUALITY_GUIDANCE = f"""
278
+
279
+ 【配色(覆寫第一步中「自行推導色盤」的做法)】
280
+ - design.palette 的五色必須從下列精選配色「擇一、逐字照抄」,不要自行調色;
281
+ fonts.display 用該組建議字體,fonts.body 用 Noto Sans TC。
282
+ - 審查、學術、公部門場合偏淺底穩重色;科技發表、上台演講可用深色底。
283
+ {_palette_menu()}
284
+
285
+ 【版式(style)】
286
+ - 另外填 style,決定整份簡報的構圖個性,依場合擇一:
287
+ - passport:審查、計畫書、成果報告、評鑑(白卡 + 右側深色重點面板,資訊密度最高)
288
+ - report:顧問式匯報、商業提案、議會與主管報告
289
+ - academic:論文口試、課堂講授、研究成果
290
+ - editorial:人文、設計、展覽、故事敘事
291
+ - keynote:演講、產品發表、上台說服(搭深色配色)
292
+ - zen:品牌、作品集、極簡發表
293
+ - classic:一般教學、通用
294
+ - passport、report、academic、editorial 搭淺底配色;keynote 搭深色配色。
295
+
296
+ 【標題寫法】
297
+ - 除 title、section、closing 外,每頁標題寫成一句完整的結論(10–22 字),
298
+ 不要只寫主題名詞。例:「志工分不清入侵種,專家人力成了瓶頸」優於「研究動機」。
299
+ - 依序只讀每頁標題,就要能讀懂整份簡報的論點。
300
+
301
+ 【版型多樣】
302
+ - 相鄰兩頁不得使用相同版型。
303
+ - cards、process、timeline、metrics 任一種不超過全份的五分之一;title-content
304
+ 整份最多 2 頁。目錄、章節分隔、引言、大數字頁合計不超過全份約 18%。
305
+ - 標題寫了數量(「三項」「五個建議」)時,該頁列出的項目數必須剛好相同。
306
+ - 有「項目 × 屬性」的比較(評估方式、方案比較、經費明細)用 table;
307
+ 同時有 2–4 個關鍵數字與 2–3 個觀點時用 dashboard。
308
+ """
309
+
310
+ SLIDES_QUALITY_GUIDANCE = """
311
+
312
+ 【封面(title 頁)】
313
+ - kicker 寫場合或活動(例:「國科會大專學生研究計畫 · 審查簡報」)。
314
+ - bullets 放 2–4 條封面資訊:單位、報告人、日期或計畫期間(原始需求沒有的不要編)。
315
+
316
+ 【每頁結構(內容頁:title、section、closing、quote 以外的頁面)】
317
+ - kicker:這頁所屬章節,格式為「兩位數編號 + 章節名」,例如「02 研究方法」;
318
+ 同一章節的頁面用同一個 kicker。
319
+ - subtitle:一句說明行(15–40 字),補充標題的脈絡、範圍或證據來源,不要重複標題。
320
+ - takeaway:這頁的「所以呢」,一句 30 字以內的結論。只在這頁真的推得出結論時填,
321
+ 大約三分之一的內容頁有即可(系統最多保留四成)。takeaway 必須帶出標題沒有的
322
+ 新資訊——一個數字、一個影響或下一步;只是換句話重述標題的,寧可不填。
323
+
324
+ 【一致性】
325
+ - 數字一律用阿拉伯數字(41.8 分、104.2%),標題與內文寫法一致,不要寫成「四十一點八分」。
326
+ - 標題說「五件事」「三個原因」,頁面上就要剛好有五項、三項;標題裡的數字必須和
327
+ 頁面上的數字相同。
328
+
329
+ 【內容密度下限】
330
+ - 寫洞見,不寫主題:「誤判率從 32% 降到 8%」優於「降低誤判」。
331
+ 原始需求裡的數字、名稱、條件要盡量帶進頁面。
332
+ - cards:每個 bullets 項目的 text 寫 4–14 字小標,children 放 1–2 句具體說明
333
+ (每句 10–30 字)。
334
+ - process 的每個步驟、timeline 的每個事件、metrics 的每個指標都要填 detail。
335
+ - table:columns 2–5 欄、rows 2–6 列,每格 20 字以內;highlight 標出最關鍵的一列。
336
+ - 需要「欄標題」的左右對照(改善前/改善後、既有/本計畫)用 comparison,
337
+ left[0]、right[0] 就是欄標題;two-col 是沒有欄標題的兩欄條列。
338
+ - dashboard:metrics 放 2–4 個關鍵數字,bullets 放 2–3 個觀點(寫法同 cards)。
339
+ - big-fact:title 寫這個數字代表的結論(不要重複數字本身),fact 只放數字,
340
+ subtitle 交代比較基準或來源(例:「相較去年同期」),bullets 放一行說明。
341
+ - closing:bullets 放 3–4 個具體的下一步或請求,每項用 children 補一句說明。
342
+
343
+ 【實用字數(超過會縮字或被截斷)】
344
+ - cards(3 張並排):小標 ≤ 10 字,每句 children ≤ 22 字;4 張(2×2)可再長一些。
345
+ - process:4 步時每步 title ≤ 7 字、detail ≤ 18 字;5 步時 5 字 / 14 字。
346
+ - timeline:5 個事件時 title ≤ 6 字、detail ≤ 18 字;4 個時 8 字 / 24 字。
347
+ - metrics:value 含單位 ≤ 7 字(如「12,000」「≥ 90%」),label ≤ 10 字。
348
+ - chart:每個 label ≤ 5 字。diagram:節點 title ≤ 6 字、detail ≤ 10 字。table:≤ 5 欄,每格 ≤ 12 字。
349
+ - closing:每項 text ≤ 10 字,children 一句 ≤ 20 字。
350
+ """
351
+
352
+ OUTLINE_SYSTEM_PROMPT += OUTLINE_QUALITY_GUIDANCE
353
+ SLIDES_SYSTEM_PROMPT += SLIDES_QUALITY_GUIDANCE
354
+
355
+
356
+ # ---------------------------------------------------------------------------
357
+ # Output language
358
+ #
359
+ # The three system prompts above all say「一律繁體中文」, and they stay that way
360
+ # byte-for-byte: zh-TW is the default and by far the common case. A non-default
361
+ # language is expressed as an OVERRIDE block appended after that rule, which
362
+ # says outright that it supersedes it. Editing the original line per language
363
+ # would fork three prompts into nine; an explicit, later, more specific
364
+ # instruction is both shorter and what models actually follow.
365
+ # ---------------------------------------------------------------------------
366
+
367
+ _LANGUAGE_OVERRIDES: Dict[str, str] = {
368
+ "en": """
369
+
370
+ 【語言(覆寫上面的語言規則)】
371
+ - 這一份文件的輸出語言是 English:所有讀者看得到的文字(title、subtitle、
372
+ bullets、left/right、fact、quote、attribution、kicker、圖表標籤、
373
+ notes)一律以英文撰寫,不得夾雜中文。
374
+ - 需求以中文寫成時由你翻譯成自然、專業的英文;專有名詞沿用需求中的原文寫法。
375
+ - 標點使用英文半形標點,句首大寫,標題採 Title Case 或 Sentence case 擇一並全份一致。
376
+ """,
377
+ "bilingual": """
378
+
379
+ 【語言(覆寫上面的語言規則)】
380
+ - 這一份文件採「中英對照」:每一則讀者看得到的文字先寫繁體中文,再以半形括號
381
+ 補上英文,格式為「中文(English)」。
382
+ - notes(講者備忘稿)只寫繁體中文,不必對照——備忘稿加倍長只會讓講者更難用。
383
+ - 對照會讓每一行大約加長一倍:請主動把句子縮短,寧可少一條重點,
384
+ 也不要讓一頁塞不下(超載的頁面會被系統自動刪減內容)。
385
+ """,
386
+ }
387
+
388
+
389
+ def language_label(language: str) -> str:
390
+ """Human-readable name of an output language (falls back to the code)."""
391
+ return LANGUAGES.get(language, language)
392
+
393
+
394
+ def system_prompt_for(base: str, language: str) -> str:
395
+ """``base`` with the output-language override appended (no-op for zh-TW)."""
396
+ return base + _LANGUAGE_OVERRIDES.get(language, "")
397
+
398
+
399
+ DISCOVERY_TOOL_NAME = "emit_discovery_questions"
400
+
401
+ DISCOVERY_SYSTEM_PROMPT = """\
402
+ 你是 ODForge 的「需求編輯」。使用者通常只會提供一句模糊的簡報需求;你的工作不是
403
+ 立刻寫簡報,而是找出最會影響成品質量、目前卻缺少的資訊。
404
+
405
+ 【任務】
406
+ - 先用一句繁體中文 summary 重述你已經理解的需求。
407
+ - known_context 只列出使用者已明確提供的事實,不得自行補完。
408
+ - 提出 2 到 8 個高資訊量問題;一般情況以 3 到 5 題為佳,需求龐大、缺口確實很多時
409
+ 最多問到 8 題。題數由缺口決定,不得為湊滿而問。
410
+ - 優先釐清:受眾要做的決策、核心訊息、具體內容/證據、目前進度、
411
+ 風險、可用圖片或數據。依題目動態選擇,不要每次照同一份問卷。
412
+ - 簡報是立刻生成的,交期不存在:絕對不要詢問這份簡報何時要用、截稿日、
413
+ 可用製作時間或緊急程度,那些答案不會改變任何一頁內容。
414
+ (簡報「內容裡」要講的專案時程、里程碑或排程仍可詢問。)
415
+ - 提案型需求若尚未說明「希望聽眾做什麼決定」,必須優先詢問決策目標。
416
+ - 若需求明確要求說明「系統架構」,但沒有提供實際技術棧、模組或資料流,
417
+ 必須詢問其中一項具體架構資訊,不得只問架構完成到哪個階段。
418
+ - 問題要彼此獨立且不重疊;送出前先自查,不得用兩題換句話詢問同一件事。
419
+ - 一題只問一個決策變數,不得把產業與階段、受眾與輪次等兩件事綁在同一題。
420
+ - question 只放直接、簡短的問句;原因與解釋全部放在 why。
421
+ - 先問內容、事實與證據,再問表達方式。除非使用者明確要求,或內容資訊已完整,
422
+ 否則不要浪費問題詢問視覺風格、配色或版型偏好。
423
+ - 不要詢問 prompt 或已有設定中已經回答的資訊。
424
+ - 每題提供 2 到 4 個互斥、可快速選擇的 options;不要提供「其他」,
425
+ 介面會另外提供自由輸入。
426
+ - options 必須直接回答該題,不得發明使用者未提供的金額、日期、比例、效能數字、
427
+ 公司名稱或技術成果。需要數字時可問「已有核定範圍/有初估/尚未確認」。
428
+ - 若需求已相當完整,只問仍會改變內容策略的缺口,不得為湊題數詢問低價值偏好。
429
+ - 問題必須讓一般使用者看得懂,不使用簡報或模型術語。
430
+ - question 與 why 都不要使用 Call to Action、pipeline、framework 等英文術語。
431
+ - id 使用簡短 ASCII snake_case,所有內容使用繁體中文。
432
+ - completeness 是目前需求完整度的保守估計,0 到 100。
433
+
434
+ 只透過 emit_discovery_questions 工具輸出,不要輸出一般文字。"""
435
+
436
+
437
+ # The UI supplies its own free-text field, so a catch-all "other" option is
438
+ # dead weight — but only when the option IS the catch-all: bare 其他/其它,
439
+ # optionally trailed by punctuation or a parenthetical like 其他(請說明).
440
+ # A real answer that merely *starts* with 其他 ("其他部門主導") must survive,
441
+ # or a valid plan can be rejected for having too few options.
442
+ _CATCH_ALL_OPTION = re.compile(r"(?:其他|其它)(?:[\s((【\[::,,、。.].*)?$")
443
+
444
+
445
+ class DiscoveryQuestion(BaseModel):
446
+ """One high-information question asked before presentation generation."""
447
+
448
+ id: str = Field(min_length=1, max_length=48, pattern=r"^[a-z][a-z0-9_]*$")
449
+ question: str = Field(min_length=1, max_length=160)
450
+ why: str = Field(min_length=1, max_length=160)
451
+ options: list[str] = Field(min_length=2, max_length=4)
452
+
453
+ @field_validator("options")
454
+ @classmethod
455
+ def options_are_direct_choices(cls, values: list[str]) -> list[str]:
456
+ cleaned: list[str] = []
457
+ for value in values:
458
+ option = value.strip()
459
+ if not option or _CATCH_ALL_OPTION.fullmatch(option):
460
+ continue
461
+ if option not in cleaned:
462
+ cleaned.append(option)
463
+ if len(cleaned) < 2:
464
+ raise ValueError("questions need at least two distinct direct options")
465
+ return cleaned
466
+
467
+
468
+ # The two list caps live here, not inline in Field(...), because the validators
469
+ # below have to trim to exactly the same numbers.
470
+ #
471
+ # 已知資訊的上限放寬到 10:6 是憑空訂的,而需求越長、模型越會列出 7、8 條——那些
472
+ # 條目全是使用者自己給過的事實,沒有一條該被丟掉。10 條 bullet 對 prompt 預算不
473
+ # 痛不癢,卻能讓「裁切」退回它該待的位置:最後一道防線,不是日常行為。
474
+ DISCOVERY_MAX_KNOWN_CONTEXT = 10
475
+ # 問題數的上限是刻意的產品決定而非技術限制:每多一題都是使用者多按一次的成本。
476
+ # 8 是 2026-08-17 使用者定的上限;系統提示仍然要求「一般 3 到 5 題」,8 是留給
477
+ # 需求龐大、缺口真的很多的那種案子,不是預設題數。
478
+ DISCOVERY_MAX_QUESTIONS = 8
479
+
480
+
481
+ class DiscoveryPlan(BaseModel):
482
+ """Structured pre-generation interview produced from a short prompt.
483
+
484
+ Both lists are *trimmed* to their cap rather than rejected for exceeding it.
485
+ Over-supply used to end the interview with a raw pydantic ``too_long`` on
486
+ screen, and the retry — same long prompt — overshoots again, so the user
487
+ simply never got past this screen.
488
+
489
+ Trimming is not free, so the caps carry the weight: ``known_context`` is set
490
+ high enough that a real plan fits inside it, and what it restates reaches
491
+ generation anyway (the user's prompt goes in verbatim, and reference PDFs
492
+ are re-attached at generation time). ``questions`` is capped by choice at a
493
+ number the user picked, so anything past it is a question nobody wanted.
494
+ """
495
+
496
+ summary: str = Field(min_length=1, max_length=500)
497
+ known_context: list[str] = Field(
498
+ default_factory=list, max_length=DISCOVERY_MAX_KNOWN_CONTEXT
499
+ )
500
+ questions: list[DiscoveryQuestion] = Field(
501
+ min_length=2, max_length=DISCOVERY_MAX_QUESTIONS
502
+ )
503
+ completeness: int = Field(ge=0, le=100)
504
+
505
+ @field_validator("known_context", mode="before")
506
+ @classmethod
507
+ def known_context_fits(cls, value: object) -> object:
508
+ """Drop blank/duplicate facts, then keep at most the cap.
509
+
510
+ Blanks and duplicates go first on purpose: they are the cheapest things
511
+ to lose, and clearing them usually means the real facts all fit.
512
+ """
513
+ if not isinstance(value, list) or not all(
514
+ isinstance(item, str) for item in value
515
+ ):
516
+ # Not our shape — let the field's own validation report it properly.
517
+ return value
518
+ kept: list[str] = []
519
+ for item in value:
520
+ text = item.strip()
521
+ if text and text not in kept:
522
+ kept.append(text)
523
+ return kept[:DISCOVERY_MAX_KNOWN_CONTEXT]
524
+
525
+ @field_validator("questions", mode="before")
526
+ @classmethod
527
+ def questions_fit(cls, value: object) -> object:
528
+ """Keep the first N questions; asking six is not worth a failed run."""
529
+ if isinstance(value, list) and len(value) > DISCOVERY_MAX_QUESTIONS:
530
+ return value[:DISCOVERY_MAX_QUESTIONS]
531
+ return value
532
+
533
+
534
+ # Generation is immediate, so this deck has no delivery date: asking when it is
535
+ # needed, when it is due, or how urgent it is cannot change a single page — it
536
+ # only spends one of the user's few answers. A timeline the deck must *describe*
537
+ # (專案時程、里程碑、排程) is content and stays; so does how long the speaker has
538
+ # on stage, which sets the page count. Hence subject + timing, not timing alone.
539
+ _DELIVERY_SUBJECTS = ("簡報", "投影片", "這份", "成品", "檔案", "報告", "文件")
540
+ _DELIVERY_TIMING = (
541
+ "何時",
542
+ "什麼時候",
543
+ "甚麼時候",
544
+ "哪一天",
545
+ "期限",
546
+ "截稿",
547
+ "截止",
548
+ "交期",
549
+ "交付",
550
+ "deadline",
551
+ "時間點",
552
+ )
553
+
554
+ # Bare 緊急 is not enough to condemn a question: emergency response (緊急應變、
555
+ # 緊急救護) is a realistic deck *topic*, and "簡報要涵蓋哪些緊急應變流程?" is a
556
+ # content question we must keep. Only urgency-about-the-deck phrasing — how
557
+ # urgent the request itself is — marks a delivery question.
558
+ _DELIVERY_URGENCY = ("緊急程度", "多緊急", "有多急", "急著要", "趕著要")
559
+
560
+ # Subject + timing can still collide with content: "這份系統的交付時程規劃" and
561
+ # "報告涵蓋的期間到何時" ask about the timeline the deck *describes*, not when
562
+ # the deck is due. These markers flag material the slides must cover, so any
563
+ # question carrying one is treated as a content question and kept.
564
+ _CONTENT_MARKERS = (
565
+ "時程規劃",
566
+ "里程碑",
567
+ "排程",
568
+ "涵蓋",
569
+ "流程",
570
+ "應變",
571
+ "進度",
572
+ "階段",
573
+ )
574
+
575
+
576
+ def _asks_delivery_deadline(question: DiscoveryQuestion) -> bool:
577
+ """Is this a question about *this deck's* due date or urgency?"""
578
+ text = question.question
579
+ if any(marker in text for marker in _CONTENT_MARKERS):
580
+ return False
581
+ if any(phrase in text for phrase in _DELIVERY_URGENCY):
582
+ return True
583
+ return any(subject in text for subject in _DELIVERY_SUBJECTS) and any(
584
+ timing in text for timing in _DELIVERY_TIMING
585
+ )
586
+
587
+
588
+ def _without_delivery_deadline_questions(plan: DiscoveryPlan) -> DiscoveryPlan:
589
+ """Drop delivery-deadline questions, keeping the plan valid.
590
+
591
+ Two questions is the schema's floor, but the floor is no reason to keep
592
+ every delivery question: drop as many as possible, then re-add dropped
593
+ ones in their original order only until the floor is met again. One
594
+ wasted question beats a failed interview — but never waste more than the
595
+ floor demands.
596
+ """
597
+ keep = [not _asks_delivery_deadline(q) for q in plan.questions]
598
+ missing = 2 - sum(keep)
599
+ for index, kept in enumerate(keep):
600
+ if missing <= 0:
601
+ break
602
+ if not kept:
603
+ keep[index] = True
604
+ missing -= 1
605
+ if all(keep):
606
+ return plan
607
+ questions = [q for q, kept in zip(plan.questions, keep, strict=True) if kept]
608
+ return plan.model_copy(update={"questions": questions})
609
+
610
+
611
+ @runtime_checkable
612
+ class LLMBackend(Protocol):
613
+ """A source that turns a prompt into a validated Document IR."""
614
+
615
+ def generate_ir(
616
+ self, prompt: str, doc_type: str, language: str = "zh-TW"
617
+ ) -> Document: # pragma: no cover
618
+ ...
619
+
620
+ def generate_outline(
621
+ self, prompt: str, pages: int | None = None, language: str = "zh-TW"
622
+ ) -> Outline: # pragma: no cover
623
+ ...
624
+
625
+ def generate_slides(
626
+ self, outline: Outline, dropped: Optional[List[DroppedContent]] = None
627
+ ) -> Presentation: # pragma: no cover
628
+ ...
629
+
630
+ def discover_questions(
631
+ self,
632
+ prompt: str,
633
+ context: str = "",
634
+ progress: Optional[Callable[[str], None]] = None,
635
+ ) -> DiscoveryPlan: # pragma: no cover
636
+ ...
637
+
638
+
639
+ def _require_env(name: str) -> str:
640
+ """Return the value of env var ``name`` or raise a helpful RuntimeError."""
641
+ value = os.environ.get(name)
642
+ if not value:
643
+ raise RuntimeError(
644
+ f"環境變數 {name} 未設定。請先設定後再執行,例如:\n"
645
+ f' PowerShell: $env:{name} = "你的金鑰"\n'
646
+ f' bash: export {name}="你的金鑰"'
647
+ )
648
+ return value
649
+
650
+
651
+ def _loads_tool_args(args_json: str) -> dict:
652
+ """Parse a tool call's ``arguments`` string into a dict.
653
+
654
+ Mirrors ``generate_ir``'s JSON handling: plain ``json.loads`` first, then a
655
+ best-effort ``json_repair`` (DeepSeek occasionally emits malformed JSON).
656
+ Raises ``json.JSONDecodeError`` if repair also fails, or ``TypeError`` if the
657
+ payload is valid JSON but not an object.
658
+ """
659
+ try:
660
+ data = json.loads(args_json)
661
+ except json.JSONDecodeError:
662
+ data = json_repair.loads(args_json)
663
+ if not isinstance(data, dict):
664
+ raise # repair failed too: re-raise the original JSONDecodeError
665
+ if not isinstance(data, dict):
666
+ raise TypeError(
667
+ f"tool arguments must be a JSON object, got {type(data).__name__}"
668
+ )
669
+ return data
670
+
671
+
672
+ def _outline_parses_without_design(data: dict) -> bool:
673
+ """True iff dropping ``design`` makes ``data`` validate as an Outline.
674
+
675
+ Used to tell a *design-only* failure (a bad palette — tolerable, the design
676
+ can be stripped) apart from a *pages-invalid* failure (structural — must be
677
+ retried then raised).
678
+ """
679
+ probe = dict(data)
680
+ probe.pop("design", None)
681
+ try:
682
+ Outline.model_validate(probe)
683
+ return True
684
+ except ValidationError:
685
+ return False
686
+
687
+
688
+ # ---------------------------------------------------------------------------
689
+ # Stage-2 (generate_slides) helpers: outline → prompt, structural + budget gates
690
+ # ---------------------------------------------------------------------------
691
+
692
+
693
+ def _render_outline_for_prompt(outline: Outline) -> str:
694
+ """Serialize an outline into a page-numbered brief for the stage-2 prompt."""
695
+ lines: list[str] = []
696
+ if outline.source_prompt.strip():
697
+ lines.extend(
698
+ [
699
+ "【原始需求/資料】",
700
+ outline.source_prompt.strip(),
701
+ "【頁面藍圖】",
702
+ ]
703
+ )
704
+ if outline.mode == "presenter":
705
+ lines.append("【講述型態】presenter(講者型):每條 bullet ≤ 20 字、每頁 ≤ 4 條,每條是完整觀點。")
706
+ else:
707
+ lines.append("【講述型態】detailed(自讀型):每條 bullet 15–40 字、每頁 3–6 條,能獨立閱讀。")
708
+ if outline.design is not None:
709
+ d = outline.design
710
+ pal = d.palette
711
+ lines.append(
712
+ f"【美術方向】scale={d.scale};display 字體={d.fonts.display}、"
713
+ f"body 字體={d.fonts.body};色盤 bg={pal.bg}/surface={pal.surface}/"
714
+ f"text={pal.text}/muted={pal.muted}/accent={pal.accent}"
715
+ )
716
+ else:
717
+ lines.append("【美術方向】未指定(引擎將套用預設主題)。")
718
+ lines.append("【頁面大綱】請「逐頁」填內容;張數與每頁版型(layout)必須與下列完全一致:")
719
+ if outline.media_assets:
720
+ lines.append("【可用圖片素材】只能用下列 asset id:")
721
+ for asset in outline.media_assets:
722
+ credit = f";來源:{asset.credit}" if asset.credit else ""
723
+ lines.append(
724
+ f" - asset://{asset.id}:{asset.description}{credit}"
725
+ )
726
+ else:
727
+ lines.append("【可用圖片素材】無")
728
+ lines.append(
729
+ "【圖片生成】"
730
+ + (
731
+ "可用,可在 image.prompt 描述需求"
732
+ if outline.image_generation_available
733
+ else "不可用"
734
+ )
735
+ )
736
+ for i, page in enumerate(outline.pages, start=1):
737
+ lines.append(
738
+ f" 第 {i} 頁 | 版型(layout)={page.role} | 標題={page.title} | "
739
+ f"這頁要點(gist):{page.gist}"
740
+ )
741
+ if page.visual_intent:
742
+ lines.append(f" 視覺意圖:{page.visual_intent}")
743
+ return "\n".join(lines)
744
+
745
+
746
+ def _slides_user_content(outline: Outline) -> str:
747
+ """The base user turn for stage-2: the instruction plus the outline brief."""
748
+ return (
749
+ "請根據以下「已定案」的大綱與美術方向,逐頁填出完整的投影片內容,"
750
+ "並透過 emit_slides 工具回傳整份簡報:\n\n" + _render_outline_for_prompt(outline)
751
+ )
752
+
753
+
754
+ def _with_error_feedback(base: str, error_summary: Optional[str]) -> str:
755
+ """Append a structural-error retry hint to ``base`` (no-op when None)."""
756
+ if error_summary is None:
757
+ return base
758
+ return (
759
+ f"{base}\n\n[系統提示] 上一次的輸出無法通過驗證,錯誤如下,請修正後重新輸出:\n"
760
+ f"{error_summary}"
761
+ )
762
+
763
+
764
+ def _slides_structure_errors(pres: Presentation, outline: Outline) -> Optional[str]:
765
+ """Return a zh-TW summary if the deck's shape drifts from the outline, else None.
766
+
767
+ Enforces the two structural invariants: the slide count equals the outline's
768
+ page count, and each ``slide.layout`` matches the outline's role at that index.
769
+ """
770
+ expected = [page.role for page in outline.pages]
771
+ got = pres.slides
772
+ problems: list[str] = []
773
+ if len(got) != len(expected):
774
+ problems.append(
775
+ f"投影片張數不符:大綱共 {len(expected)} 頁,但收到 {len(got)} 張——"
776
+ "必須逐頁對齊,不得增刪。"
777
+ )
778
+ for i, (slide, role) in enumerate(zip(got, expected, strict=False), start=1):
779
+ if slide.layout != role:
780
+ problems.append(
781
+ f"第 {i} 頁版型不符:大綱要求 layout「{role}」,但收到「{slide.layout}」。"
782
+ )
783
+ return " ".join(problems) if problems else None
784
+
785
+
786
+ def _budget_overloads(
787
+ pres: Presentation, theme: Theme, *, counts: bool = True
788
+ ) -> list[tuple[int, list[str]]]:
789
+ """List ``(page_number, messages)`` for every slide that overruns its frames
790
+ — and, for the rewrite turns, every title whose count 「三項」 its page does
791
+ not show (``counts=False`` for the degrade step: dropping bullets is not
792
+ how a wrong number gets fixed)."""
793
+ overloads: list[tuple[int, list[str]]] = []
794
+ style = resolve_style(pres)
795
+ for i, slide in enumerate(pres.slides, start=1):
796
+ msgs = check_budget(slide, theme, style)
797
+ if counts:
798
+ msgs = [*msgs, *filter(None, (count_mismatch(slide), bare_cards(slide)))]
799
+ if msgs:
800
+ overloads.append((i, msgs))
801
+ return overloads
802
+
803
+
804
+ def _budget_feedback(
805
+ overloads: list[tuple[int, list[str]]], prior_deck_json: str
806
+ ) -> str:
807
+ """One retry turn naming the overloaded pages and asking to shorten only them.
808
+
809
+ The previous deck's JSON is echoed back so 「其餘頁面照抄」 is an instruction a
810
+ stateless retry can actually keep — without it the model has no record of
811
+ what "the rest" contained.
812
+ """
813
+ header = (
814
+ "這是你上一次的輸出:\n"
815
+ f"{prior_deck_json}\n\n"
816
+ "其中下列頁面的文字超出版面(超載)。請「只」精簡這些頁面——縮短字數或"
817
+ "減少每頁條數——其餘頁面照抄上面的輸出,並重新輸出「完整」的簡報:"
818
+ )
819
+ lines = [f"第 {n} 頁超載:{' '.join(msgs)}" for n, msgs in overloads]
820
+ return header + "\n" + "\n".join(lines)
821
+
822
+
823
+ class DroppedContent(BaseModel):
824
+ """Content the layout budget forced off a page, verbatim.
825
+
826
+ A note saying 「部分要點因版面限制省略」 tells the user that *something* was
827
+ lost without telling them *what* — which, for their purposes, is the same as
828
+ losing it silently. This carries the removed lines back to the caller so the
829
+ CLI can print them and the web console can show them, and so "information is
830
+ never lost without saying so" becomes a property that can be tested rather
831
+ than hoped for.
832
+ """
833
+
834
+ slide_no: int
835
+ title: str
836
+ items: List[str] = Field(default_factory=list)
837
+
838
+
839
+ _MIN_BULLETS = {"cards": 2, "dashboard": 2}
840
+
841
+ # Structural pages earn their place by deck length (consulting convention:
842
+ # an agenda past ~15 slides, dividers only in long decks). Models kept adding
843
+ # an agenda and three dividers to a 15-page talk — a quarter of the deck with
844
+ # nothing on it.
845
+ _AGENDA_MIN_PAGES = 15
846
+ _SECTION_MIN_PAGES = 20
847
+ _SECTION_MAX = 3
848
+ # Pages _degrade_slide cannot rescue (it only sheds bullets); overruns there
849
+ # earn a second rewrite instead of shipping as 「…」.
850
+ _UNDEGRADABLE = frozenset({"process", "timeline", "metrics", "diagram", "chart", "table"})
851
+ # Image pages with no image to show render an honest placeholder — which
852
+ # reviewers read, correctly, as an unfinished deck. With no uploaded media and
853
+ # no image generation, plan the page as cards instead.
854
+ _IMAGE_ROLES = {"image-focus", "image-split"}
855
+ # A takeaway band is emphasis; on every page it is wallpaper.
856
+ _TAKEAWAY_SHARE = 0.4
857
+ _EVIDENCE_LAYOUTS = (
858
+ "table", "chart", "comparison", "metrics", "dashboard", "process",
859
+ "timeline", "diagram", "big-fact",
860
+ )
861
+
862
+
863
+ _PAGE_CAP = re.compile(
864
+ r"(?:(\d{1,3})\s*(?:頁|張)(?:以內|以下|內)"
865
+ r"|(?:不超過|不要超過|最多|至多|上限)\s*(\d{1,3})\s*(?:頁|張))"
866
+ )
867
+ # Pages a cap gives up first, in order: the deck loses furniture before it
868
+ # loses an argument.
869
+ _CAP_DROP_ORDER = ("agenda", "section", "quote", "big-fact", "title-content")
870
+
871
+
872
+ def _page_cap(prompt: str) -> int | None:
873
+ """An explicit upper bound in the request (「10 頁以內」「不超過 12 頁」)."""
874
+ m = _PAGE_CAP.search(prompt or "")
875
+ if not m:
876
+ return None
877
+ n = int(m.group(1) or m.group(2))
878
+ return n if n >= MIN_OUTLINE_PAGES else None
879
+
880
+
881
+ def _cap_pages(outline: Outline, cap: int | None) -> Outline:
882
+ """Hold the outline to the user's page limit. A soft 「約 N 頁」 target
883
+ let the model return 11 pages for 「10 頁以內」 — a promise the user made
884
+ to an audience, so it is enforced, structural pages first."""
885
+ pages = list(outline.pages)
886
+ if cap is None or len(pages) <= cap:
887
+ return outline
888
+ for role in _CAP_DROP_ORDER:
889
+ while len(pages) > cap:
890
+ # Never the cover or the closing (first / last page).
891
+ idx = next(
892
+ (i for i in range(len(pages) - 2, 0, -1) if pages[i].role == role), None
893
+ )
894
+ if idx is None:
895
+ break
896
+ del pages[idx]
897
+ return outline.model_copy(update={"pages": pages})
898
+
899
+
900
+ def _trim_structure(outline: Outline) -> Outline:
901
+ """Stage 1: drop structural pages the deck is too short to earn. Done
902
+ before the outline is shown, so what the user confirms is what renders."""
903
+ total = len(outline.pages)
904
+ kept = []
905
+ sections = 0
906
+ heroes = 0
907
+ hero_cap = max(1, total // 10)
908
+ section_cap = _SECTION_MAX if total >= 30 else 2
909
+ quotes = 0
910
+ for page in outline.pages:
911
+ if page.role == "big-fact":
912
+ # A lone number is a punctuation mark, not a page type: past one
913
+ # per eight pages, reviewers read them as empty slides.
914
+ heroes += 1
915
+ if heroes > hero_cap:
916
+ page = page.model_copy(update={"role": "metrics"})
917
+ if page.role == "agenda" and total < _AGENDA_MIN_PAGES:
918
+ continue
919
+ if page.role == "section":
920
+ sections += 1
921
+ if total < _SECTION_MIN_PAGES or sections > section_cap:
922
+ continue
923
+ if page.role == "quote":
924
+ # One opening line is a hook; a second is a structural page.
925
+ quotes += 1
926
+ if quotes > 1:
927
+ continue
928
+ kept.append(page)
929
+ if len(kept) < MIN_OUTLINE_PAGES or kept == list(outline.pages):
930
+ return outline
931
+ return outline.model_copy(update={"pages": kept})
932
+
933
+
934
+ def _polish_outline(outline: Outline) -> Outline:
935
+ """Stage 2: image pages with nothing to show become cards (media is only
936
+ known once the caller attaches it, after stage 1)."""
937
+ if outline.media_assets or outline.image_generation_available:
938
+ return outline
939
+ if not any(page.role in _IMAGE_ROLES for page in outline.pages):
940
+ return outline
941
+ pages = [
942
+ page.model_copy(update={"role": "cards"}) if page.role in _IMAGE_ROLES else page
943
+ for page in outline.pages
944
+ ]
945
+ return outline.model_copy(update={"pages": pages})
946
+
947
+
948
+ def _spread(items: list[int], k: int) -> list[int]:
949
+ """``k`` items evenly spaced through ``items`` (first and last included)."""
950
+ if k <= 0 or not items:
951
+ return []
952
+ if k >= len(items):
953
+ return list(items)
954
+ if k == 1:
955
+ return [items[len(items) // 2]]
956
+ return [items[round(j * (len(items) - 1) / (k - 1))] for j in range(k)]
957
+
958
+
959
+ def _cap_takeaways(pres: Presentation) -> Presentation:
960
+ """Keep takeaway bands on at most ~60% of content pages, preferring the
961
+ pages that carry evidence (a table, a chart, numbers) over the rest."""
962
+ content = [
963
+ i for i, s in enumerate(pres.slides)
964
+ if s.layout not in {"title", "section", "closing", "quote", "agenda"}
965
+ ]
966
+ carrying = [i for i in content if pres.slides[i].takeaway.strip()]
967
+ limit = math.ceil(len(content) * _TAKEAWAY_SHARE)
968
+ if len(carrying) <= limit:
969
+ return pres
970
+ # Evidence pages first, and spread across the deck rather than the first
971
+ # N: capped by position, every takeaway landed in the opening half and the
972
+ # results / decision pages — where a conclusion matters most — had none.
973
+ evidence = [i for i in carrying if pres.slides[i].layout in _EVIDENCE_LAYOUTS]
974
+ others = [i for i in carrying if i not in evidence]
975
+ keep = set(_spread(evidence, limit))
976
+ keep |= set(_spread(others, limit - len(keep)))
977
+ slides = [
978
+ s if i in keep or not s.takeaway else s.model_copy(update={"takeaway": ""})
979
+ for i, s in enumerate(pres.slides)
980
+ ]
981
+ # Agenda pages never carry one.
982
+ slides = [
983
+ s.model_copy(update={"takeaway": ""}) if s.layout == "agenda" else s
984
+ for s in slides
985
+ ]
986
+ return pres.model_copy(update={"slides": slides})
987
+
988
+
989
+ def _degrade_slide(
990
+ slide, theme: Theme, slide_no: int = 0, style=None
991
+ ) -> Optional[DroppedContent]:
992
+ """Truncate an over-budget slide's bullets in place until it fits.
993
+
994
+ Last resort only: the caller has already asked the model to rewrite the page
995
+ shorter (see ``_budget_feedback``), and this runs when that did not work. The
996
+ order of sacrifice goes from least to most costly:
997
+
998
+ 1. If any bullet is a ``BulletItem`` carrying children, drop the **last**
999
+ child of the last such bullet (children are finer-grained than items).
1000
+ 2. Otherwise, if more than one bullet remains, drop the last bullet.
1001
+ 3. Otherwise stop (always keep at least one bullet).
1002
+
1003
+ Everything removed is both returned to the caller and named in ``notes``, so
1004
+ it survives into the .odp itself. A slide that overruns on a non-bullet frame
1005
+ (e.g. a very long title) has no bullets to shed — it is left as-is, and the
1006
+ budget never raises.
1007
+ """
1008
+ removed: List[str] = []
1009
+ # Layouts whose schema demands more than one item keep that many: dropping
1010
+ # a dashboard to one card produced a slide its own validator rejects, and
1011
+ # the whole deck failed to generate.
1012
+ min_keep = _MIN_BULLETS.get(slide.layout, 1)
1013
+ warnings = check_budget(slide, theme, style)
1014
+ while warnings:
1015
+ before = (list(slide.bullets), warnings)
1016
+ child_idx: Optional[int] = None
1017
+ for i in range(len(slide.bullets) - 1, -1, -1):
1018
+ item = slide.bullets[i]
1019
+ if isinstance(item, BulletItem) and item.children:
1020
+ child_idx = i
1021
+ break
1022
+ if child_idx is not None:
1023
+ item = slide.bullets[child_idx]
1024
+ children = list(item.children)
1025
+ dropped = children[-1]
1026
+ slide.bullets = [
1027
+ *slide.bullets[:child_idx],
1028
+ item.model_copy(update={"children": children[:-1]}),
1029
+ *slide.bullets[child_idx + 1 :],
1030
+ ]
1031
+ elif len(slide.bullets) > min_keep:
1032
+ bullets = list(slide.bullets)
1033
+ last = bullets[-1]
1034
+ dropped = last if isinstance(last, str) else last.text
1035
+ slide.bullets = bullets[:-1]
1036
+ else:
1037
+ break
1038
+ warnings = check_budget(slide, theme, style)
1039
+ if warnings == before[1]:
1040
+ # Nothing moved — the overrun is somewhere bullets cannot fix (a
1041
+ # metric label, a timeline detail): put it back rather than shed
1042
+ # content for nothing. (A shrinking list overrun changes its
1043
+ # message — the estimate drops — so it keeps going.)
1044
+ slide.bullets = before[0]
1045
+ break
1046
+ removed.append(dropped)
1047
+ if not removed:
1048
+ return None
1049
+ removed.reverse() # back into the order they appeared on the page
1050
+ note = "(因版面限制省略:" + "、".join(removed) + ")"
1051
+ slide.notes = f"{slide.notes}\n{note}" if slide.notes else note
1052
+ return DroppedContent(slide_no=slide_no, title=slide.title, items=removed)
1053
+
1054
+
1055
+ class StructuredOutputError(RuntimeError):
1056
+ """The backend answered, but not with a payload we can use.
1057
+
1058
+ Kept distinct from every other failure because the response is *different*:
1059
+ this one is the model's mistake, so the policy layer feeds the reason back
1060
+ and retries once. A provider 403 or a CLI that will not start is not this —
1061
+ those propagate, because asking again spends another minute to print the
1062
+ same sentence.
1063
+ """
1064
+
1065
+
1066
+ # JSON Schema keywords that carry documentation, not constraints. They are
1067
+ # dropped before a schema is handed to a strict validator: `title` in
1068
+ # particular is both an annotation *and* a legal field name, and conflating the
1069
+ # two is how a schema ends up requiring a key it just deleted.
1070
+ _SCHEMA_ANNOTATIONS = frozenset({"title", "default", "examples", "$comment"})
1071
+ # Keywords whose value maps *names* to schemas. Their keys are field names, so
1072
+ # the walk must recurse into the values without filtering the keys.
1073
+ _SCHEMA_MAPS = frozenset({"properties", "$defs", "definitions", "patternProperties"})
1074
+
1075
+
1076
+ def _strict_schema(schema: object) -> object:
1077
+ """A pydantic JSON schema in OpenAI structured-output *strict* form.
1078
+
1079
+ Strict mode rejects any object that does not carry ``additionalProperties:
1080
+ false`` and list every property in ``required``. Pydantic emits neither, so
1081
+ the schema is walked and tightened rather than maintained by hand beside the
1082
+ models — a second copy would drift the first time a field is added.
1083
+
1084
+ Making every property required is safe here precisely because the models are
1085
+ the gate: an optional field arrives as ``null`` and pydantic puts the default
1086
+ back. Nothing downstream can tell the difference.
1087
+ """
1088
+ if isinstance(schema, list):
1089
+ return [_strict_schema(item) for item in schema]
1090
+ if not isinstance(schema, dict):
1091
+ return schema
1092
+ out: dict = {}
1093
+ for key, value in schema.items():
1094
+ if key in _SCHEMA_ANNOTATIONS:
1095
+ continue
1096
+ if key in _SCHEMA_MAPS and isinstance(value, dict):
1097
+ out[key] = {name: _strict_schema(sub) for name, sub in value.items()}
1098
+ else:
1099
+ out[key] = _strict_schema(value)
1100
+ if "properties" in out:
1101
+ out["type"] = "object"
1102
+ out["additionalProperties"] = False
1103
+ out["required"] = list(out["properties"])
1104
+ return out
1105
+
1106
+
1107
+ class StructuredLLMBackend:
1108
+ """Everything a backend does *except* carry the bytes to a model.
1109
+
1110
+ The four pipeline entry points below — 訪談、大綱、逐頁、單檔 IR — are policy:
1111
+ which prompt, how many retries, what gets fed back, when a bad palette may be
1112
+ stripped instead of raised, when an over-budget page is degraded instead of
1113
+ retried. None of that depends on whether the model is reached over HTTP or
1114
+ through a subprocess, so it lives here once and each transport implements
1115
+ :meth:`_structured_call`.
1116
+
1117
+ Subclasses also supply the four model names the policy picks between
1118
+ (``model`` / ``discovery_model`` / ``outline_model`` / ``slides_model``);
1119
+ a backend with one model just points all four at it.
1120
+ """
1121
+
1122
+ model: str
1123
+ discovery_model: str
1124
+ outline_model: str
1125
+ slides_model: str
1126
+
1127
+ def _structured_call(
1128
+ self,
1129
+ *,
1130
+ model: str,
1131
+ system: str,
1132
+ user: str,
1133
+ schema: dict,
1134
+ name: str,
1135
+ description: str,
1136
+ max_tokens: int,
1137
+ ) -> dict:
1138
+ """One request → the structured payload it produced, as a dict.
1139
+
1140
+ Raises :class:`StructuredOutputError` when the backend answered but the
1141
+ answer is unusable (no tool call, unreadable JSON, not an object) — the
1142
+ caller retries those. Anything else propagates untouched.
1143
+ """
1144
+ raise NotImplementedError
1145
+
1146
+ def discover_questions(
1147
+ self,
1148
+ prompt: str,
1149
+ context: str = "",
1150
+ progress: Optional[Callable[[str], None]] = None,
1151
+ ) -> DiscoveryPlan:
1152
+ """Generate a short, adaptive interview before outline generation."""
1153
+
1154
+ def report(stage: str) -> None:
1155
+ if progress is None:
1156
+ return
1157
+ try:
1158
+ progress(stage)
1159
+ except Exception:
1160
+ # Progress is observability only. A disconnected browser must
1161
+ # not invalidate an otherwise healthy model response.
1162
+ pass
1163
+
1164
+ report("preparing")
1165
+ base_content = (
1166
+ f"【使用者原始需求】\n{prompt.strip()}\n\n"
1167
+ f"【介面已有設定】\n{context.strip() or '無'}"
1168
+ )
1169
+ error_summary: Optional[str] = None
1170
+ last_exc: Optional[Exception] = None
1171
+ for _attempt in range(2):
1172
+ user_content = _with_error_feedback(base_content, error_summary)
1173
+ report("requesting" if _attempt == 0 else "retrying")
1174
+ try:
1175
+ data = self._structured_call(
1176
+ model=self.discovery_model,
1177
+ system=DISCOVERY_SYSTEM_PROMPT,
1178
+ user=user_content,
1179
+ schema=DiscoveryPlan.model_json_schema(),
1180
+ name=DISCOVERY_TOOL_NAME,
1181
+ description="輸出需求摘要、已知資訊與高價值追問",
1182
+ max_tokens=int(
1183
+ os.environ.get("ODFORGE_DISCOVERY_MAX_TOKENS", "2048")
1184
+ ),
1185
+ )
1186
+ report("validating")
1187
+ plan = DiscoveryPlan.model_validate(data)
1188
+ except (
1189
+ StructuredOutputError,
1190
+ json.JSONDecodeError,
1191
+ TypeError,
1192
+ ValidationError,
1193
+ ) as exc:
1194
+ error_summary = str(exc)
1195
+ last_exc = exc
1196
+ continue
1197
+ report("complete")
1198
+ return plan
1199
+ assert last_exc is not None
1200
+ raise last_exc
1201
+
1202
+ def generate_ir(
1203
+ self, prompt: str, doc_type: str, language: str = "zh-TW"
1204
+ ) -> Document:
1205
+ ir_cls = DOC_TYPES.get(doc_type)
1206
+ if ir_cls is None:
1207
+ raise ValueError(
1208
+ f"未知的 doc_type: {doc_type!r};可用值:{sorted(DOC_TYPES)}"
1209
+ )
1210
+
1211
+ # First attempt, then exactly one retry on failure.
1212
+ error_summary: Optional[str] = None
1213
+ last_exc: Optional[Exception] = None
1214
+ for _attempt in range(2):
1215
+ user_content = prompt
1216
+ if error_summary is not None:
1217
+ user_content = (
1218
+ f"{prompt}\n\n"
1219
+ f"[系統提示] 上一次的輸出無法通過驗證,錯誤如下,請修正後重新輸出:\n"
1220
+ f"{error_summary}"
1221
+ )
1222
+ try:
1223
+ data = self._structured_call(
1224
+ model=self.model,
1225
+ system=system_prompt_for(SYSTEM_PROMPT, language),
1226
+ user=user_content,
1227
+ schema=ir_cls.model_json_schema(),
1228
+ name=TOOL_NAME,
1229
+ description="輸出結構化文件內容",
1230
+ max_tokens=int(os.environ.get("ODFORGE_MAX_TOKENS", "8192")),
1231
+ )
1232
+ data["type"] = doc_type # guard against a missing discriminator
1233
+ return parse_ir(data)
1234
+ except (
1235
+ StructuredOutputError,
1236
+ json.JSONDecodeError,
1237
+ TypeError,
1238
+ ValidationError,
1239
+ ) as exc:
1240
+ error_summary = str(exc)
1241
+ last_exc = exc
1242
+ continue
1243
+
1244
+ assert last_exc is not None
1245
+ raise last_exc
1246
+
1247
+ def generate_outline(
1248
+ self, prompt: str, pages: int | None = None, language: str = "zh-TW"
1249
+ ) -> Outline:
1250
+ """Stage-1 of the pipeline: design + page-role outline in one call.
1251
+
1252
+ Forces a function call against ``Outline.model_json_schema()`` (same
1253
+ mechanics as :meth:`generate_ir`). Failure handling is deliberately
1254
+ asymmetric:
1255
+
1256
+ * A **design-only** failure (a palette that can't clear contrast, while
1257
+ the pages themselves are valid) is fed back and retried once; if the
1258
+ retry still can't produce a legible palette, the design is stripped
1259
+ (``design=None`` → preset fallback) and the rest of the outline is
1260
+ accepted. A bad palette never crashes generation.
1261
+ * A **pages-invalid** failure is retried once then raised, exactly like
1262
+ ``generate_ir``.
1263
+
1264
+ ``pages`` (when given) folds a target page-count instruction into the
1265
+ user prompt (「目標頁數約 N 頁…」); it is a soft target, not a schema
1266
+ constraint. ``language`` picks the deck's output language and is
1267
+ re-attached to the returned outline, so stage 2 inherits it without the
1268
+ caller having to remember.
1269
+ """
1270
+ base_prompt = prompt
1271
+ if pages is not None:
1272
+ base_prompt = (
1273
+ f"{prompt}\n\n"
1274
+ f"【目標頁數】整份簡報約 {pages} 頁(含封面與結尾,可 ±1)。"
1275
+ )
1276
+ cap = _page_cap(prompt)
1277
+ if cap is not None:
1278
+ base_prompt += (
1279
+ f"\n\n【頁數上限】使用者要求最多 {cap} 頁(含封面與結尾),不得超過。"
1280
+ )
1281
+ error_summary: Optional[str] = None
1282
+ last_exc: Optional[Exception] = None
1283
+ for attempt in range(2):
1284
+ is_last = attempt == 1
1285
+ user_content = base_prompt
1286
+ if error_summary is not None:
1287
+ user_content = (
1288
+ f"{base_prompt}\n\n"
1289
+ f"[系統提示] 上一次的輸出無法通過驗證,錯誤如下,請修正後重新輸出:\n"
1290
+ f"{error_summary}"
1291
+ )
1292
+ try:
1293
+ data = self._structured_call(
1294
+ model=self.outline_model,
1295
+ system=system_prompt_for(OUTLINE_SYSTEM_PROMPT, language),
1296
+ user=user_content,
1297
+ schema=Outline.model_json_schema(),
1298
+ name=OUTLINE_TOOL_NAME,
1299
+ description="輸出簡報的美術方向(DesignSpec)與 page-role 大綱",
1300
+ max_tokens=int(os.environ.get("ODFORGE_MAX_TOKENS", "8192")),
1301
+ )
1302
+ except (StructuredOutputError, json.JSONDecodeError, TypeError) as exc:
1303
+ error_summary = str(exc)
1304
+ last_exc = exc
1305
+ continue
1306
+
1307
+ try:
1308
+ return _cap_pages(
1309
+ _trim_structure(Outline.model_validate(data)), cap
1310
+ ).model_copy(update={"source_prompt": prompt, "language": language})
1311
+ except ValidationError as exc:
1312
+ last_exc = exc
1313
+ error_summary = str(exc)
1314
+ # Only-the-design-is-bad? Then the palette is the problem.
1315
+ if _outline_parses_without_design(data):
1316
+ if is_last:
1317
+ # Retry already spent on a bad palette: strip it and
1318
+ # accept the rest — never crash on a bad palette.
1319
+ stripped = dict(data)
1320
+ stripped.pop("design", None)
1321
+ return Outline.model_validate(stripped).model_copy(
1322
+ update={"source_prompt": prompt, "language": language}
1323
+ )
1324
+ # First design failure: feed the error back, retry once.
1325
+ continue
1326
+ # Pages are structurally invalid: retry-once-then-raise.
1327
+ continue
1328
+
1329
+ assert last_exc is not None
1330
+ raise last_exc
1331
+
1332
+ def _emit_slides(
1333
+ self,
1334
+ system: str,
1335
+ user: str,
1336
+ outline: Outline,
1337
+ ) -> tuple[Optional[Presentation], Optional[Exception]]:
1338
+ """One stage-2 round.
1339
+
1340
+ Returns ``(Presentation, None)`` when the call yields a structurally
1341
+ valid deck (outline's design re-attached, slide count + layouts aligned),
1342
+ otherwise ``(None, exc)`` whose ``str(exc)`` is fed back as the retry hint.
1343
+ """
1344
+ try:
1345
+ data = self._structured_call(
1346
+ model=self.slides_model,
1347
+ system=system,
1348
+ user=user,
1349
+ schema=Presentation.model_json_schema(),
1350
+ name=SLIDES_TOOL_NAME,
1351
+ description="輸出填好每頁內容的完整簡報(Presentation)",
1352
+ # Stage-2 fills every page, so it defaults higher than the
1353
+ # one-shot generate_ir/generate_outline paths (8192). Env
1354
+ # override still wins.
1355
+ max_tokens=int(os.environ.get("ODFORGE_MAX_TOKENS", "16384")),
1356
+ )
1357
+ except (StructuredOutputError, json.JSONDecodeError, TypeError) as exc:
1358
+ return None, exc
1359
+
1360
+ data["type"] = "presentation"
1361
+ # Art direction comes from stage 1, not from whatever the model returns.
1362
+ data["design"] = (
1363
+ outline.design.model_dump(mode="json")
1364
+ if outline.design is not None
1365
+ else None
1366
+ )
1367
+ data["style"] = outline.style
1368
+
1369
+ try:
1370
+ pres = Presentation.model_validate(data)
1371
+ except ValidationError as exc:
1372
+ return None, exc
1373
+
1374
+ structural = _slides_structure_errors(pres, outline)
1375
+ if structural is not None:
1376
+ return None, RuntimeError(structural)
1377
+ return pres, None
1378
+
1379
+ def generate_slides(
1380
+ self, outline: Outline, dropped: Optional[List[DroppedContent]] = None
1381
+ ) -> Presentation:
1382
+ """Stage-2 of the pipeline: fill every outline page into a full deck.
1383
+
1384
+ ONE LLM call fills all pages against ``Presentation.model_json_schema()``
1385
+ (chosen over a slides-only sub-schema for parity with ``generate_ir``);
1386
+ the outline's ``design`` is always re-attached so art direction comes
1387
+ from stage 1. Two gates then guard the result:
1388
+
1389
+ * **Structural consistency** — the returned slide count and each
1390
+ ``slide.layout`` must match the outline's page roles, index-for-index.
1391
+ A mismatch (or an unparseable / schema-invalid payload) is fed back and
1392
+ retried once, then raised.
1393
+ * **Layout budget** — every slide is run through :func:`check_budget`.
1394
+ Overloaded pages are fed back exactly once ("第 N 頁超載:…") asking the
1395
+ model to shorten *only* those pages and return the full deck. If any
1396
+ page is still over budget afterwards it is **auto-degraded**
1397
+ (:func:`_degrade_slide` truncates its bullets with an honesty note) —
1398
+ budget never raises.
1399
+
1400
+ The deck's output language rides along on ``outline.language`` (set by
1401
+ stage 1 / the caller), so no call site has to pass it twice.
1402
+ """
1403
+ outline = _polish_outline(outline)
1404
+ slides_system = system_prompt_for(SLIDES_SYSTEM_PROMPT, outline.language)
1405
+ base_user = _slides_user_content(outline)
1406
+
1407
+ # -- Gate 1: obtain a structurally valid deck (retry once, then raise) --
1408
+ error_summary: Optional[str] = None
1409
+ last_exc: Optional[Exception] = None
1410
+ presentation: Optional[Presentation] = None
1411
+ for _attempt in range(2):
1412
+ pres, exc = self._emit_slides(
1413
+ slides_system,
1414
+ _with_error_feedback(base_user, error_summary),
1415
+ outline,
1416
+ )
1417
+ if pres is not None:
1418
+ presentation = pres
1419
+ break
1420
+ last_exc = exc
1421
+ error_summary = str(exc)
1422
+ if presentation is None:
1423
+ assert last_exc is not None
1424
+ raise last_exc
1425
+
1426
+ # -- Gate 2: layout budget (feed back once, then auto-degrade) ----------
1427
+ presentation = _cap_takeaways(presentation)
1428
+ theme = resolve_design(presentation)
1429
+ overloads = _budget_overloads(presentation, theme)
1430
+ if not overloads:
1431
+ return presentation
1432
+
1433
+ retry_pres, _exc = self._emit_slides(
1434
+ slides_system,
1435
+ base_user
1436
+ + "\n\n"
1437
+ + _budget_feedback(overloads, presentation.model_dump_json()),
1438
+ outline,
1439
+ )
1440
+ if retry_pres is not None:
1441
+ # A structurally valid (hopefully lighter) deck. If the retry itself
1442
+ # failed structurally we keep the previous deck and degrade that.
1443
+ presentation = _cap_takeaways(retry_pres)
1444
+ # One more pass for pages still over budget: shape layouts (steps,
1445
+ # timelines, node details) cannot be degraded by dropping bullets,
1446
+ # so a second, narrower rewrite is the only way their text stops
1447
+ # shipping as 「…」.
1448
+ theme = resolve_design(presentation)
1449
+ still = [
1450
+ (n, m)
1451
+ for n, m in _budget_overloads(presentation, theme)
1452
+ if presentation.slides[n - 1].layout in _UNDEGRADABLE
1453
+ ]
1454
+ if still:
1455
+ second, _exc = self._emit_slides(
1456
+ slides_system,
1457
+ base_user
1458
+ + "\n\n"
1459
+ + _budget_feedback(still, presentation.model_dump_json()),
1460
+ outline,
1461
+ )
1462
+ if second is not None and len(
1463
+ _budget_overloads(_cap_takeaways(second), resolve_design(second))
1464
+ ) < len(_budget_overloads(presentation, theme)):
1465
+ presentation = _cap_takeaways(second)
1466
+
1467
+ theme = resolve_design(presentation)
1468
+ for n, _msgs in _budget_overloads(presentation, theme, counts=False):
1469
+ record = _degrade_slide(
1470
+ presentation.slides[n - 1], theme, slide_no=n,
1471
+ style=resolve_style(presentation),
1472
+ )
1473
+ if record is not None and dropped is not None:
1474
+ dropped.append(record)
1475
+ return presentation
1476
+
1477
+
1478
+ class OpenAICompatBackend(StructuredLLMBackend):
1479
+ """Backend for any OpenAI-compatible chat-completions endpoint."""
1480
+
1481
+ def __init__(
1482
+ self,
1483
+ base_url: str,
1484
+ api_key: str,
1485
+ model: str,
1486
+ *,
1487
+ discovery_model: str | None = None,
1488
+ outline_model: str | None = None,
1489
+ slides_model: str | None = None,
1490
+ extra_body: dict | None = None,
1491
+ ):
1492
+ self.base_url = base_url
1493
+ self.model = model
1494
+ self.outline_model = outline_model or model
1495
+ self.discovery_model = discovery_model or self.outline_model
1496
+ self.slides_model = slides_model or model
1497
+ self.extra_body = dict(extra_body or {})
1498
+ self._client = OpenAI(base_url=base_url, api_key=api_key)
1499
+
1500
+ def _structured_call(
1501
+ self,
1502
+ *,
1503
+ model: str,
1504
+ system: str,
1505
+ user: str,
1506
+ schema: dict,
1507
+ name: str,
1508
+ description: str,
1509
+ max_tokens: int,
1510
+ ) -> dict:
1511
+ """A forced function call; its ``arguments`` are the payload.
1512
+
1513
+ The schema goes over the wire exactly as pydantic emits it — no strict
1514
+ tightening. Chat-completions tool schemas are a *description* of the
1515
+ shape, not a validator the provider enforces, and every provider here
1516
+ already tolerates the pydantic dialect.
1517
+ """
1518
+ resp = self._client.chat.completions.create(
1519
+ model=model,
1520
+ messages=[
1521
+ {"role": "system", "content": system},
1522
+ {"role": "user", "content": user},
1523
+ ],
1524
+ tools=[
1525
+ {
1526
+ "type": "function",
1527
+ "function": {
1528
+ "name": name,
1529
+ "description": description,
1530
+ "parameters": schema,
1531
+ },
1532
+ }
1533
+ ],
1534
+ tool_choice={"type": "function", "function": {"name": name}},
1535
+ max_tokens=max_tokens,
1536
+ **({"extra_body": self.extra_body} if self.extra_body else {}),
1537
+ )
1538
+ tool_calls = resp.choices[0].message.tool_calls
1539
+ if not tool_calls:
1540
+ raise StructuredOutputError(
1541
+ f"模型未呼叫 {name} 工具,請務必透過該工具輸出。"
1542
+ )
1543
+ return _loads_tool_args(tool_calls[0].function.arguments)
1544
+
1545
+
1546
+ # One CLI, one model choice: the design gate imports this rather than keeping
1547
+ # its own copy (critic.py), because a text/vision split here would mean two
1548
+ # different models claiming to be "the codex backend".
1549
+ #
1550
+ # Naming a model explicitly rather than taking the CLI's own default is not
1551
+ # caution about taste — an id the installed CLI cannot drive fails with
1552
+ # "requires a newer version of Codex" (that is exactly what `gpt-5.6-terra`
1553
+ # did on codex-cli 0.142.5; it needs >= 0.147.0).
1554
+ CODEX_MODEL_DEFAULT = "gpt-5.6-terra"
1555
+ # Stage 2 fills every page of a deck in one call; 600s (the design gate's
1556
+ # budget) is not enough headroom for a long one.
1557
+ _CODEX_TIMEOUT_DEFAULT = "1800"
1558
+
1559
+
1560
+ class CodexCliBackend(StructuredLLMBackend):
1561
+ """Text generation driven through the local Codex CLI as a subprocess.
1562
+
1563
+ The sibling of :class:`odforge.critic.CodexCliVisionBackend`, and it inherits
1564
+ that class's hard-won argv: the prompt rides **stdin** (on Windows the CLI is
1565
+ ``codex.CMD``, whose cmd.exe command line caps at 8,191 characters — a
1566
+ stage-2 prompt is far past that), reasoning effort is pinned rather than
1567
+ inherited from the operator's ``~/.codex/config.toml``, and the sandbox is
1568
+ read-only because writing a deck is this process's job, not the model's.
1569
+
1570
+ ``--output-schema`` plays the part forced function calling plays on the HTTP
1571
+ backends — with one difference that matters: the CLI hands the schema to
1572
+ OpenAI's *strict* structured-output mode, which enforces it. Hence
1573
+ :func:`_strict_schema`, and hence a payload that is almost always already
1574
+ valid by the time pydantic sees it.
1575
+
1576
+ There is no API key and no per-key quota here: the CLI authenticates with the
1577
+ operator's own ChatGPT login.
1578
+ """
1579
+
1580
+ def __init__(
1581
+ self,
1582
+ model: str,
1583
+ *,
1584
+ executable: str = "codex",
1585
+ discovery_model: str | None = None,
1586
+ outline_model: str | None = None,
1587
+ slides_model: str | None = None,
1588
+ timeout: int | None = None,
1589
+ runner=subprocess.run,
1590
+ ):
1591
+ self.model = model
1592
+ self.outline_model = outline_model or model
1593
+ self.discovery_model = discovery_model or self.outline_model
1594
+ self.slides_model = slides_model or model
1595
+ # The *resolved* path, not the bare name: on Windows the CLI installs as
1596
+ # ``codex.CMD``, which ``subprocess.run(["codex", ...])`` cannot execute.
1597
+ self.executable = executable
1598
+ self.timeout = (
1599
+ timeout
1600
+ if timeout is not None
1601
+ else int(os.environ.get("ODFORGE_CODEX_TIMEOUT", _CODEX_TIMEOUT_DEFAULT))
1602
+ )
1603
+ self._run = runner
1604
+
1605
+ def _structured_call(
1606
+ self,
1607
+ *,
1608
+ model: str,
1609
+ system: str,
1610
+ user: str,
1611
+ schema: dict,
1612
+ name: str,
1613
+ description: str,
1614
+ max_tokens: int,
1615
+ ) -> dict:
1616
+ # ``max_tokens`` has no CLI equivalent — the length budget belongs to the
1617
+ # model's own configuration here. It stays in the signature because the
1618
+ # policy layer is transport-agnostic, not because this backend needs it.
1619
+ with tempfile.TemporaryDirectory(prefix="odforge-codex-") as tmp:
1620
+ work = Path(tmp)
1621
+ schema_path = work / "schema.json"
1622
+ # UTF-8 explicitly: the CLI rejects a schema file it cannot decode,
1623
+ # and Python's default encoding on Windows is not UTF-8.
1624
+ schema_path.write_text(
1625
+ json.dumps(_strict_schema(schema), ensure_ascii=False),
1626
+ encoding="utf-8",
1627
+ )
1628
+ out_path = work / "payload.json"
1629
+ argv = [
1630
+ self.executable,
1631
+ "exec",
1632
+ "-m",
1633
+ model,
1634
+ "--output-schema",
1635
+ str(schema_path),
1636
+ "-o",
1637
+ str(out_path),
1638
+ "-c",
1639
+ "model_reasoning_effort="
1640
+ + os.environ.get("ODFORGE_CODEX_REASONING_EFFORT", "medium"),
1641
+ "--sandbox",
1642
+ "read-only",
1643
+ "--skip-git-repo-check",
1644
+ # Explicit "read the prompt from stdin" marker; omitting the
1645
+ # positional is merely today's synonym for it.
1646
+ "-",
1647
+ ]
1648
+ # ``codex exec`` has no system/user split, so the system prompt
1649
+ # travels at the head of the one prompt there is.
1650
+ prompt = f"{system}\n\n{user}"
1651
+ try:
1652
+ proc = self._run(
1653
+ argv,
1654
+ input=prompt,
1655
+ capture_output=True,
1656
+ text=True,
1657
+ encoding="utf-8",
1658
+ errors="replace",
1659
+ timeout=self.timeout,
1660
+ )
1661
+ except (subprocess.TimeoutExpired, OSError, UnicodeError) as exc:
1662
+ raise RuntimeError(
1663
+ f"codex exec 無法執行:{type(exc).__name__}: {exc}"
1664
+ ) from exc
1665
+ returncode = getattr(proc, "returncode", 0)
1666
+ if returncode:
1667
+ # Not a StructuredOutputError: the CLI never got as far as
1668
+ # answering, so there is nothing to feed back and retrying just
1669
+ # spends the time again.
1670
+ detail = " ".join((getattr(proc, "stderr", "") or "").split())[-300:]
1671
+ raise RuntimeError(
1672
+ f"codex exec 結束碼 {returncode}"
1673
+ + (f":{detail}" if detail else "")
1674
+ )
1675
+ try:
1676
+ data = json.loads(out_path.read_text(encoding="utf-8"))
1677
+ except (OSError, json.JSONDecodeError) as exc:
1678
+ raise StructuredOutputError(
1679
+ f"codex exec 沒有輸出可解析的 {name} JSON:{type(exc).__name__}"
1680
+ ) from exc
1681
+ if not isinstance(data, dict):
1682
+ raise StructuredOutputError(
1683
+ f"codex exec 的 {name} 輸出不是 JSON 物件,而是 {type(data).__name__}"
1684
+ )
1685
+ return data
1686
+
1687
+
1688
+ # ---------------------------------------------------------------------------
1689
+ # Backend registry + facade
1690
+ # ---------------------------------------------------------------------------
1691
+
1692
+
1693
+ def _codex_auth_path() -> Path:
1694
+ """Where the Codex CLI keeps its OAuth credentials."""
1695
+ home = os.environ.get("CODEX_HOME")
1696
+ return (Path(home) if home else Path.home() / ".codex") / "auth.json"
1697
+
1698
+
1699
+ def _make_codex() -> LLMBackend:
1700
+ """Text backend through the local Codex CLI (subscription-authenticated).
1701
+
1702
+ Refuses on three conditions, each with a fixable message: no CLI, no login,
1703
+ and — the one that is not about convenience — a publicly-bound server.
1704
+ ODForge's web console has no authentication, and OpenAI's own guidance is not
1705
+ to expose Codex execution in untrusted environments; on a non-loopback bind
1706
+ this backend would spend the operator's ChatGPT subscription for whoever
1707
+ reaches the port. ``serve`` sets ``ODFORGE_PUBLIC_BIND`` when it binds beyond
1708
+ loopback. (The design gate's codex source refuses on the same three — see
1709
+ ``critic._make_codex``.)
1710
+ """
1711
+ executable = shutil.which("codex")
1712
+ if executable is None:
1713
+ raise RuntimeError(
1714
+ "找不到 codex CLI。請先安裝 Codex(npm i -g @openai/codex)後再使用此後端。"
1715
+ )
1716
+ if not _codex_auth_path().exists():
1717
+ raise RuntimeError(
1718
+ "Codex 尚未登入。請先執行 codex login(無瀏覽器環境用 "
1719
+ "codex login --device-auth)。"
1720
+ )
1721
+ if os.environ.get("ODFORGE_PUBLIC_BIND"):
1722
+ raise RuntimeError(
1723
+ "codex 後端僅限本機使用:此服務沒有身分驗證,對外綁定時任何人都能"
1724
+ "花用你的 ChatGPT 訂閱額度。請改用 API key 後端,或只綁定 127.0.0.1。"
1725
+ )
1726
+ return CodexCliBackend(
1727
+ os.environ.get("ODFORGE_CODEX_MODEL", CODEX_MODEL_DEFAULT),
1728
+ executable=executable,
1729
+ discovery_model=os.environ.get("ODFORGE_CODEX_DISCOVERY_MODEL"),
1730
+ outline_model=os.environ.get("ODFORGE_CODEX_OUTLINE_MODEL"),
1731
+ slides_model=os.environ.get("ODFORGE_CODEX_SLIDES_MODEL"),
1732
+ )
1733
+
1734
+
1735
+ def _custom_extra_body() -> dict | None:
1736
+ """Parse optional provider-specific OpenAI-compatible request fields."""
1737
+
1738
+ raw = os.environ.get("ODFORGE_CUSTOM_EXTRA_BODY", "").strip()
1739
+ if not raw:
1740
+ return None
1741
+ try:
1742
+ value = json.loads(raw)
1743
+ except json.JSONDecodeError as exc:
1744
+ raise RuntimeError(
1745
+ "ODFORGE_CUSTOM_EXTRA_BODY must be a valid JSON object"
1746
+ ) from exc
1747
+ if not isinstance(value, dict):
1748
+ raise RuntimeError(
1749
+ "ODFORGE_CUSTOM_EXTRA_BODY must be a JSON object"
1750
+ )
1751
+ return value
1752
+
1753
+
1754
+ # Used when neither ``--backend`` nor ``ODFORGE_BACKEND`` names one. Codex needs
1755
+ # no API key (it runs on the operator's own ChatGPT login), so it is the backend
1756
+ # a fresh checkout can use without signing up for anything.
1757
+ DEFAULT_BACKEND = "codex"
1758
+
1759
+
1760
+ BACKENDS: Dict[str, Callable[[], LLMBackend]] = {
1761
+ "codex": _make_codex,
1762
+ "ollama": lambda: OpenAICompatBackend(
1763
+ "http://localhost:11434/v1",
1764
+ "ollama",
1765
+ os.environ.get("ODFORGE_OLLAMA_MODEL", "qwen2.5"),
1766
+ discovery_model=os.environ.get("ODFORGE_OLLAMA_DISCOVERY_MODEL"),
1767
+ outline_model=os.environ.get("ODFORGE_OLLAMA_OUTLINE_MODEL"),
1768
+ slides_model=os.environ.get("ODFORGE_OLLAMA_SLIDES_MODEL"),
1769
+ ),
1770
+ "custom": lambda: OpenAICompatBackend(
1771
+ _require_env("ODFORGE_CUSTOM_BASE_URL"),
1772
+ os.environ.get("ODFORGE_CUSTOM_API_KEY", "not-needed"),
1773
+ _require_env("ODFORGE_CUSTOM_MODEL"),
1774
+ discovery_model=os.environ.get("ODFORGE_CUSTOM_DISCOVERY_MODEL"),
1775
+ outline_model=os.environ.get("ODFORGE_CUSTOM_OUTLINE_MODEL"),
1776
+ slides_model=os.environ.get("ODFORGE_CUSTOM_SLIDES_MODEL"),
1777
+ extra_body=_custom_extra_body(),
1778
+ ),
1779
+ }
1780
+
1781
+
1782
+ def get_backend(name: Optional[str] = None) -> LLMBackend:
1783
+ """Resolve and construct a backend by name.
1784
+
1785
+ ``name=None`` reads ``ODFORGE_BACKEND`` (default :data:`DEFAULT_BACKEND`). An
1786
+ unknown name raises ``ValueError`` listing the available keys.
1787
+ """
1788
+ if name is None:
1789
+ name = os.environ.get("ODFORGE_BACKEND", DEFAULT_BACKEND)
1790
+ factory = BACKENDS.get(name)
1791
+ if name == "deepseek" and factory is None:
1792
+ raise ValueError(
1793
+ "deepseek 不再是獨立後端,請改用 OpenAI 相容的 custom:"
1794
+ "ODFORGE_BACKEND=custom、ODFORGE_CUSTOM_BASE_URL=https://api.deepseek.com、"
1795
+ "ODFORGE_CUSTOM_API_KEY=<金鑰>、ODFORGE_CUSTOM_MODEL=deepseek-chat"
1796
+ )
1797
+ if factory is None:
1798
+ raise ValueError(
1799
+ f"未知的 backend: {name!r};可用值:{sorted(BACKENDS)}"
1800
+ )
1801
+ return factory()
1802
+
1803
+
1804
+ def generate_ir(
1805
+ prompt: str,
1806
+ doc_type: str,
1807
+ backend: Optional[str] = None,
1808
+ language: str = "zh-TW",
1809
+ ) -> Document:
1810
+ """Facade: resolve a backend and generate a validated Document IR."""
1811
+ return get_backend(backend).generate_ir(prompt, doc_type, language)
1812
+
1813
+
1814
+ def generate_discovery_questions(
1815
+ prompt: str,
1816
+ backend: Optional[str] = None,
1817
+ *,
1818
+ context: str = "",
1819
+ progress: Optional[Callable[[str], None]] = None,
1820
+ ) -> DiscoveryPlan:
1821
+ """Facade: ask only the missing, high-value questions for a short prompt.
1822
+
1823
+ Delivery-deadline questions are dropped on the way out (see
1824
+ :func:`_without_delivery_deadline_questions`) — the prompt forbids them, this
1825
+ is the net for when the model asks anyway.
1826
+ """
1827
+ resolved = get_backend(backend)
1828
+ if progress is None:
1829
+ plan = resolved.discover_questions(prompt, context=context)
1830
+ else:
1831
+ plan = resolved.discover_questions(
1832
+ prompt, context=context, progress=progress
1833
+ )
1834
+ return _without_delivery_deadline_questions(plan)
1835
+
1836
+
1837
+ def generate_outline(
1838
+ prompt: str,
1839
+ backend: Optional[str] = None,
1840
+ pages: int | None = None,
1841
+ language: str = "zh-TW",
1842
+ ) -> Outline:
1843
+ """Facade: resolve a backend and generate a stage-1 design + outline.
1844
+
1845
+ The chosen ``language`` is stamped onto the returned outline, so stage 2
1846
+ (``generate_slides``) inherits it without a second parameter.
1847
+ """
1848
+ return get_backend(backend).generate_outline(
1849
+ prompt, pages=pages, language=language
1850
+ )
1851
+
1852
+
1853
+ def generate_slides(
1854
+ outline: Outline,
1855
+ backend: Optional[str] = None,
1856
+ dropped: Optional[List[DroppedContent]] = None,
1857
+ ) -> Presentation:
1858
+ """Facade: resolve a backend and fill a stage-1 outline into a full deck.
1859
+
1860
+ Pass a list as ``dropped`` to be told what the layout budget had to remove.
1861
+ Callers that ignore it keep the old behaviour (the loss is still named in the
1862
+ slide's speaker notes) — but every user-facing caller should pass one:
1863
+ content vanishing with no visible trace is the failure this exists to prevent.
1864
+ """
1865
+ return get_backend(backend).generate_slides(outline, dropped)