@jungtz/wiki-router 1.0.2 → 1.0.4

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.
package/dist/index.mjs CHANGED
@@ -2,179 +2,25 @@ import fs from 'fs';
2
2
  import path from 'path';
3
3
 
4
4
  /**
5
- * 內嵌 LLM Wiki 提示詞模板
6
- * 與原始 server/prompts/ 目錄中的檔案保持同步
5
+ * LLM Wiki 提示詞 — 從 src/prompts/*.md 檔案載入
6
+ * 欲修改提示詞內容,請直接編輯對應的 .md 檔案
7
7
  */
8
8
 
9
- const SPLIT_PROMPT = `# 角色:專業文件架構師 (Documentation Architect)
10
9
 
11
- ## 任務目標
12
- 將提供的 JSON 資料完整解析並轉換為多個獨立的 Markdown \`.md\` 檔案。
13
- JSON 可能來自 CMS、API 回應、設定檔或任何結構化資料來源。
10
+ const PROMPTS_DIR = path.resolve(import.meta.dirname || __dirname, 'prompts');
14
11
 
15
- ## 原始 JSON 資料
16
- \`\`\`json
17
- {{context}}
18
- \`\`\`
19
-
20
- ## 處理規則:
21
-
22
- ### 1. 結構識別(自動語義分析)
23
- - 分析 JSON 的頂層結構(object / array / 巢狀)
24
- - 若為巢狀物件,以**第一層 key** 作為主題分群依據(如 \`data.rooms\` → 房間主題、\`data.location\` → 地點主題)
25
- - 若為頂層陣列,每個元素視為獨立條目,依內容主題分組
26
-
27
- ### 2. 完整性強制規則(最高優先)
28
- - **逐項清點**:陣列型資料必須逐一列出所有項目,先數原始 JSON 中有幾筆,輸出後再數確認數量一致
29
- - **巢狀陣列全收**:若某欄位本身是陣列(如設施清單、標籤列表),必須列出該陣列中的**每一項**
30
- - **不因長度省略**:資料再多也不能用「等」、「...」、「其他」概括
31
-
32
- ### 3. 資訊提取(語義識別)
33
- - **標題欄位**:自動識別代表名稱/標題的欄位(\`title\`、\`name\`、\`label\`、\`subject\`)
34
- - **內文欄位**:自動識別長文字欄位(\`content\`、\`description\`、\`body\`、\`intro\`、\`text\`)
35
- - **時間欄位**:自動識別時間相關欄位(\`time\`、\`date\`、\`checkin\`、\`checkout\`、\`created_at\`、\`published_at\`)
36
- - **數值欄位**:自動識別價格/數量欄位(\`price\`、\`qty\`、\`user\`、\`capacity\`、\`size\`)
37
- - **布林欄位**:自動識別開關欄位(\`enable\`、\`display\`、\`is_*\`),轉為「啟用/停用」
38
- - **巢狀物件**:遞迴展開,保留層級結構(如 \`social.{instagram_url, instagram_display}\`)
39
- - **多語言欄位**:若欄位為 \`{zh_tw, en, ja, ...}\` 結構,以 \`zh_tw\` 為主要輸出語言,不存在時依序 fallback
40
-
41
- ### 4. 格式還原
42
- - 若內容為 JSON 字串(Quill Delta 等 RTF 格式),解析後還原為純文字
43
- - 轉義換行 \`\\n\` → 真實換行、\`\\t\` → 縮排
44
- - 內嵌 HTML(\`<a href>\`, \`<img>\`, \`<br>\`)還原為對應 Markdown 語法
45
- - 內嵌 URL 保留為可點擊連結
46
-
47
- ### 5. 檔案拆分原則
48
- - 依照 JSON 的**第一層 key** 或**語義主題**拆分成獨立 \`.md\` 檔案
49
- - 每個檔案涵蓋一個獨立主題區塊
50
- - 檔名使用英文,反映主題(如 \`Rooms.md\`、\`Policies.md\`、\`Facilities.md\`)
51
-
52
- ### 6. 索引生成 (Index.md)
53
- - 彙整所有產出的檔案,生成 \`Index.md\`
54
- - 格式:\`- [顯示名稱](檔名.md):一句話摘要涵蓋的關鍵主題與具體資訊\`
55
- - 摘要必須具體,禁止只重複檔名
56
-
57
- ### 7. 輸出約束
58
- - **輸出順序**:先 \`Index.md\`,再依序輸出其他檔案
59
- - **必須標示檔名**:每個程式碼區塊正上方必須有 \`### 檔名.md\` 標題,不可省略
60
- - 每個檔案以獨立 \` \`\`\`markdown \` 程式碼區塊呈現
61
- - 所有 JSON 內容一律轉為人類可讀的 Markdown,不可保留原始 JSON 字串
62
-
63
- ## 輸出格式規範:
64
-
65
- ### Index.md
66
- \`\`\`markdown
67
- # 知識庫目錄
68
- - [顯示名稱 A](A.md):涵蓋的關鍵主題與具體資訊摘要
69
- - [顯示名稱 B](B.md):涵蓋的關鍵主題與具體資訊摘要
70
- \`\`\`
71
-
72
- ---
73
-
74
- ### 檔名.md
75
- \`\`\`markdown
76
- [還原後的 Markdown 內容]
77
- \`\`\`
78
-
79
- ---
80
-
81
- (重複上述格式直到所有檔案輸出完畢)`;
82
-
83
- const MERGE_PROMPT = `# 角色:知識庫合併架構師 (Knowledge Merge Architect)
84
-
85
- ## 任務目標
86
- 將新的內容合併到既有的知識庫檔案結構中,根據內容類型與主題智能決定「新增頁面」、「合併到既有頁面」或「更新既有頁面」。
87
-
88
- ## 既有知識庫目錄 (Index.md)
89
- \`\`\`markdown
90
- {{indexContent}}
91
- \`\`\`
92
-
93
- ## 新內容類型:{{fileType}}
94
- ## 新內容
95
- \`\`\`{{contentBlock}}
96
- {{newContent}}
97
- \`\`\`
98
-
99
- ## 處理規則:
100
-
101
- ### 1. 結構識別(依 fileType)
102
-
103
- **json**:
104
- - 分析 JSON 頂層結構,以第一層 key 或語義主題分群
105
- - 若為巢狀物件,每個第一層 key 視為一個主題區塊
106
- - 若為頂層陣列,每個元素視為獨立條目
107
-
108
- **markdown**:
109
- - 依照 \`##\` 或 \`###\` 標題拆分成獨立區塊
110
- - 每個區塊視為一個新知識條目
111
-
112
- ### 2. 合併策略判斷
113
-
114
- 對每個條目,檢查是否與既有 Index.md 中的頁面相關:
115
-
116
- - **主題全新**(目錄中無相關頁面)→ 建立**新檔案**,Index.md 追加新條目
117
- - **主題已存在**(標題或關鍵詞與既有頁面重疊)→ 將新內容**合併**到既有檔案,保留既有結構,新增內容作為補充。合併後輸出該檔案的**完整內容**
118
- - **既有檔案缺少條目**(例如列表型資料漏了某筆)→ 必須**補齊**,將缺漏條目加入對應區塊
119
- - **內容衝突**(同一主題但資訊不一致,如價格變動、規則修改)→ 以**新內容為準**更新,標記 \`> 更新於 YYYY-MM-DD\`
120
- - **內容重複**(完全相同)→ 跳過,不輸出
121
-
122
- ### 3. 完整性驗證
123
- - 陣列型資料:比對新內容的項目數與既有檔案收錄數,缺漏必須補齊
124
- - 巢狀陣列(如設施清單、標籤列表):逐一檢查是否全數收錄
125
- - 多語言欄位:以 \`zh_tw\` 為主要輸出語言,不存在時 fallback 到 \`en\`
126
- - JSON 字串內容(Quill Delta 等):\`\\n\` → 換行、\`\\t\` → 縮排、HTML → Markdown
127
-
128
- ### 4. 輸出約束
129
- - **輸出順序**:先輸出更新後的 \`Index.md\`,再依序輸出所有新增或更新過的檔案
130
- - 每個檔案前必須有 \`### 檔名.md\` 作為標題,絕對不可省略
131
- - 每個檔案以獨立 \` \`\`\`markdown \` 程式碼區塊呈現
132
- - **只輸出有變動的檔案**,未修改的既有檔案不需重複輸出
133
- - 合併的檔案必須包含**完整內容**(既有 + 新增),不可只輸出差異
134
-
135
- ## 輸出格式規範:
136
-
137
- ### Index.md
138
- \`\`\`markdown
139
- # 知識庫目錄
140
- - [顯示名稱 A](A.md):一句話摘要涵蓋的關鍵主題
141
- - [顯示名稱 B](B.md):一句話摘要涵蓋的關鍵主題
142
- \`\`\`
143
-
144
- ---
145
-
146
- ### 檔名.md
147
- \`\`\`markdown
148
- [完整內容]
149
- \`\`\`
150
-
151
- ---
152
-
153
- (重複上述格式直到所有變動檔案輸出完畢)`;
154
-
155
- const ROUTER_PROMPT = `# 角色設定
156
- 你是一個精準的「知識庫路由助手 (Router)」。
157
- 你的唯一任務是分析使用者的問題,並從提供的目錄清單中,挑選出最可能包含解答的檔案名稱。
158
-
159
- # 使用者問題
160
- {{prompt}}
161
-
162
- # 知識庫目錄
163
- {{indexContent}}
164
-
165
- # 挑選原則
166
- - 從目錄中每個檔案的**摘要**判斷相關性,不只比對檔名
167
- - 考慮同義詞與相關概念(例如:「運動」「健身」→ Facilities.md;「怎麼去」「交通」→ Location_and_Transport.md)
168
- - 若問題涉及多個主題(如「房價和退房時間」),選取所有相關檔案
169
-
170
- # 輸出嚴格規範
171
- 1. **僅輸出檔名**:從「知識庫目錄」中挑選最相關的完整檔案名稱(必須包含 \`.md\` 後綴)。
172
- 2. **多檔處理**:若有多個檔案相關,請以半形逗號 \`,\` 分隔。
173
- 3. **無相關時**:若判斷目錄中的檔案皆不相關,請直接回覆 \`NONE\`。
174
- 4. **禁止任何廢話**:**絕對禁止**輸出任何解釋文字、問候語、符號,也**禁止**使用 Markdown 標記(如代碼塊 \` \`\`\` \` \`\`\` 或清單 \`-\`)。
12
+ function readPrompt(filename) {
13
+ const filePath = path.join(PROMPTS_DIR, filename);
14
+ if (fs.existsSync(filePath)) {
15
+ return fs.readFileSync(filePath, 'utf-8')
16
+ }
17
+ console.warn(`[wiki-router] Prompt file not found: ${filePath}, using empty string`);
18
+ return ''
19
+ }
175
20
 
176
- **正確輸出範例:**
177
- Introduction.md,Policy_Info.md`;
21
+ const SPLIT_PROMPT = readPrompt('split.md');
22
+ const MERGE_PROMPT = readPrompt('merge.md');
23
+ const ROUTER_PROMPT = readPrompt('router.md');
178
24
 
179
25
  /**
180
26
  * LLM 輸出解析器
@@ -238,14 +84,76 @@ function parseWikiOutput(output) {
238
84
  return results
239
85
  }
240
86
 
87
+ /**
88
+ * 檔案系統 adapter — 將 fs 操作包裝成 Source / Store 介面
89
+ *
90
+ * 用法:
91
+ * import { fsSource, fsStore } from '@jungtz/wiki-router'
92
+ * createWikiRouter({ router, source: fsSource('./knowledge'), store: fsStore('./wiki') })
93
+ *
94
+ * 也可直接傳 knowledgeDir / outputDir 給 createWikiRouter,內部會自動包成這兩個 adapter。
95
+ */
96
+
97
+
98
+ /**
99
+ * 建立讀取本地檔案的 Source adapter
100
+ * @param {string} dir - knowledge 來源目錄
101
+ * @returns {import('../types').Source}
102
+ */
103
+ function fsSource(dir) {
104
+ const resolved = path.resolve(dir);
105
+ return {
106
+ async list() {
107
+ if (!fs.existsSync(resolved)) return []
108
+ return fs
109
+ .readdirSync(resolved)
110
+ .filter(f => f.endsWith('.json') || f.endsWith('.md'))
111
+ .sort()
112
+ },
113
+ async read(key) {
114
+ const filePath = path.join(resolved, key);
115
+ const content = fs.readFileSync(filePath, 'utf-8');
116
+ const type = key.endsWith('.json') ? 'json' : 'markdown';
117
+ return { type, content }
118
+ },
119
+ }
120
+ }
121
+
122
+ /**
123
+ * 建立讀寫本地檔案的 Store adapter
124
+ * @param {string} dir - wiki 輸出目錄
125
+ * @returns {import('../types').Store}
126
+ */
127
+ function fsStore(dir) {
128
+ const resolved = path.resolve(dir);
129
+ function ensure() {
130
+ if (!fs.existsSync(resolved)) fs.mkdirSync(resolved, { recursive: true });
131
+ }
132
+ return {
133
+ async list() {
134
+ ensure();
135
+ return fs.readdirSync(resolved).filter(f => f.endsWith('.md'))
136
+ },
137
+ async read(filename) {
138
+ const filePath = path.join(resolved, filename);
139
+ if (!fs.existsSync(filePath)) return null
140
+ return fs.readFileSync(filePath, 'utf-8')
141
+ },
142
+ async write(filename, content) {
143
+ ensure();
144
+ fs.writeFileSync(path.join(resolved, filename), content);
145
+ },
146
+ }
147
+ }
148
+
241
149
  /**
242
150
  * wiki-router - LLM Wiki 知識庫路由引擎
243
151
  *
244
- * 使用方式:
245
- * const { createWikiRouter } = require('@jungtz/wiki-router')
152
+ * 使用方式 (檔案系統):
246
153
  * const wiki = createWikiRouter({ router, knowledgeDir, outputDir })
247
- * await wiki.build()
248
- * const ctx = await wiki.getContext('user question')
154
+ *
155
+ * 使用方式 (自訂 adapter,例如 API + DB)
156
+ * const wiki = createWikiRouter({ router, source, store })
249
157
  */
250
158
 
251
159
 
@@ -260,19 +168,29 @@ function parseWikiOutput(output) {
260
168
  function createWikiRouter(config) {
261
169
  const {
262
170
  router,
171
+ source,
172
+ store,
263
173
  knowledgeDir,
264
174
  outputDir,
265
175
  modelId,
266
176
  routerModelId,
267
177
  timeout = 300000,
178
+ splitPrompt,
179
+ mergePrompt,
180
+ routerPrompt,
268
181
  } = config;
269
182
 
183
+ const activeSplitPrompt = splitPrompt || SPLIT_PROMPT;
184
+ const activeMergePrompt = mergePrompt || MERGE_PROMPT;
185
+ const activeRouterPrompt = routerPrompt || ROUTER_PROMPT;
186
+
270
187
  if (!router) throw new Error('[wiki-router] router is required')
271
- if (!knowledgeDir) throw new Error('[wiki-router] knowledgeDir is required')
272
- if (!outputDir) throw new Error('[wiki-router] outputDir is required')
273
188
 
274
- const resolvedKnowledgeDir = path.resolve(knowledgeDir);
275
- const resolvedOutputDir = path.resolve(outputDir);
189
+ const activeSource = source || (knowledgeDir ? fsSource(knowledgeDir) : null);
190
+ const activeStore = store || (outputDir ? fsStore(outputDir) : null);
191
+
192
+ if (!activeSource) throw new Error('[wiki-router] source or knowledgeDir is required')
193
+ if (!activeStore) throw new Error('[wiki-router] store or outputDir is required')
276
194
 
277
195
  let modelsFetched = false;
278
196
 
@@ -354,37 +272,28 @@ function createWikiRouter(config) {
354
272
  */
355
273
  async function build() {
356
274
  try {
357
- if (!fs.existsSync(resolvedOutputDir)) fs.mkdirSync(resolvedOutputDir, { recursive: true });
275
+ const knowledgeKeys = await activeSource.list();
358
276
 
359
- const knowledgeFiles = fs.readdirSync(resolvedKnowledgeDir)
360
- .filter(f => f.endsWith('.json') || f.endsWith('.md'))
361
- .sort();
362
-
363
- if (knowledgeFiles.length === 0) {
364
- console.warn(`[Wiki] No .json or .md files found in: ${resolvedKnowledgeDir}`);
277
+ if (knowledgeKeys.length === 0) {
278
+ console.warn('[Wiki] No knowledge entries found from source.');
365
279
  return false
366
280
  }
367
281
 
368
282
  let totalFiles = 0;
369
283
 
370
- for (const knowledgeFile of knowledgeFiles) {
371
- const existingFiles = fs.readdirSync(resolvedOutputDir).filter(f => f.endsWith('.md'));
284
+ for (const key of knowledgeKeys) {
285
+ const existingFiles = await activeStore.list();
372
286
  const isFirstTime = existingFiles.length === 0;
373
- const filePath = path.join(resolvedKnowledgeDir, knowledgeFile);
374
- const fileContent = fs.readFileSync(filePath, 'utf-8');
375
- const fileType = knowledgeFile.endsWith('.json') ? 'json' : 'markdown';
287
+ const { type: fileType, content: fileContent } = await activeSource.read(key);
376
288
 
377
- console.log(`[Wiki] Processing: ${knowledgeFile} (type: ${fileType}, mode: ${isFirstTime ? 'first' : 'merge'})`);
289
+ console.log(`[Wiki] Processing: ${key} (type: ${fileType}, mode: ${isFirstTime ? 'first' : 'merge'})`);
378
290
 
379
291
  let finalPrompt;
380
292
  if (isFirstTime && fileType === 'json') {
381
- finalPrompt = SPLIT_PROMPT.replace('{{context}}', fileContent);
293
+ finalPrompt = activeSplitPrompt.replace('{{context}}', fileContent);
382
294
  } else {
383
- const indexPath = path.join(resolvedOutputDir, 'Index.md');
384
- const indexContent = fs.existsSync(indexPath)
385
- ? fs.readFileSync(indexPath, 'utf-8')
386
- : '';
387
- finalPrompt = MERGE_PROMPT
295
+ const indexContent = (await activeStore.read('Index.md')) || '';
296
+ finalPrompt = activeMergePrompt
388
297
  .replace('{{indexContent}}', indexContent)
389
298
  .replace('{{fileType}}', fileType)
390
299
  .replace('{{contentBlock}}', fileType === 'json' ? 'json' : 'markdown')
@@ -393,18 +302,18 @@ function createWikiRouter(config) {
393
302
 
394
303
  const output = await chat([{ role: 'user', content: finalPrompt }]);
395
304
  if (!output) {
396
- console.warn(`[Wiki] No output for: ${knowledgeFile}`);
305
+ console.warn(`[Wiki] No output for: ${key}`);
397
306
  continue
398
307
  }
399
308
 
400
309
  const parsed = parseWikiOutput(output);
401
310
  if (parsed.length === 0) {
402
- console.error(`[Wiki] Failed to parse output for: ${knowledgeFile}. Raw:`, output);
311
+ console.error(`[Wiki] Failed to parse output for: ${key}. Raw:`, output);
403
312
  continue
404
313
  }
405
314
 
406
315
  for (const { filename, content } of parsed) {
407
- fs.writeFileSync(path.join(resolvedOutputDir, filename), content);
316
+ await activeStore.write(filename, content);
408
317
  console.log(`[Wiki] ${isFirstTime ? 'Generated' : 'Updated'}: ${filename}`);
409
318
  }
410
319
  totalFiles += parsed.length;
@@ -425,23 +334,20 @@ function createWikiRouter(config) {
425
334
  */
426
335
  async function getContext(prompt) {
427
336
  try {
428
- if (!fs.existsSync(resolvedOutputDir)) fs.mkdirSync(resolvedOutputDir, { recursive: true });
429
-
430
- let wikiFiles = fs.readdirSync(resolvedOutputDir).filter(f => f.endsWith('.md'));
337
+ let wikiFiles = await activeStore.list();
431
338
 
432
339
  if (wikiFiles.length === 0) {
433
340
  const success = await build();
434
341
  if (!success) return ''
435
342
  }
436
343
 
437
- const indexPath = path.join(resolvedOutputDir, 'Index.md');
438
- if (!fs.existsSync(indexPath)) {
344
+ const indexContent = await activeStore.read('Index.md');
345
+ if (!indexContent) {
439
346
  console.warn('[Wiki] Index.md not found.');
440
347
  return ''
441
348
  }
442
349
 
443
- const indexContent = fs.readFileSync(indexPath, 'utf-8');
444
- const selectionPrompt = ROUTER_PROMPT
350
+ const selectionPrompt = activeRouterPrompt
445
351
  .replace('{{prompt}}', prompt)
446
352
  .replace('{{indexContent}}', indexContent);
447
353
 
@@ -463,9 +369,9 @@ function createWikiRouter(config) {
463
369
  let loadedCount = 0;
464
370
 
465
371
  for (const file of selectedFiles) {
466
- const filePath = path.join(resolvedOutputDir, file);
467
- if (fs.existsSync(filePath)) {
468
- relevantContext += `\n--- 檔案: ${file} ---\n${fs.readFileSync(filePath, 'utf-8')}\n`;
372
+ const content = await activeStore.read(file);
373
+ if (content !== null && content !== undefined) {
374
+ relevantContext += `\n--- 檔案: ${file} ---\n${content}\n`;
469
375
  loadedCount++;
470
376
  }
471
377
  }
@@ -484,4 +390,4 @@ function createWikiRouter(config) {
484
390
  return { build, getContext }
485
391
  }
486
392
 
487
- export { MERGE_PROMPT, ROUTER_PROMPT, SPLIT_PROMPT, createWikiRouter, parseWikiOutput };
393
+ export { MERGE_PROMPT, ROUTER_PROMPT, SPLIT_PROMPT, createWikiRouter, fsSource, fsStore, parseWikiOutput };
package/dist/prompts.cjs CHANGED
@@ -1,179 +1,28 @@
1
1
  'use strict';
2
2
 
3
+ const fs = require('fs');
4
+ const path = require('path');
5
+
3
6
  /**
4
- * 內嵌 LLM Wiki 提示詞模板
5
- * 與原始 server/prompts/ 目錄中的檔案保持同步
7
+ * LLM Wiki 提示詞 — 從 src/prompts/*.md 檔案載入
8
+ * 欲修改提示詞內容,請直接編輯對應的 .md 檔案
6
9
  */
7
10
 
8
- const SPLIT_PROMPT = `# 角色:專業文件架構師 (Documentation Architect)
9
-
10
- ## 任務目標
11
- 將提供的 JSON 資料完整解析並轉換為多個獨立的 Markdown \`.md\` 檔案。
12
- JSON 可能來自 CMS、API 回應、設定檔或任何結構化資料來源。
13
-
14
- ## 原始 JSON 資料
15
- \`\`\`json
16
- {{context}}
17
- \`\`\`
18
-
19
- ## 處理規則:
20
-
21
- ### 1. 結構識別(自動語義分析)
22
- - 分析 JSON 的頂層結構(object / array / 巢狀)
23
- - 若為巢狀物件,以**第一層 key** 作為主題分群依據(如 \`data.rooms\` → 房間主題、\`data.location\` → 地點主題)
24
- - 若為頂層陣列,每個元素視為獨立條目,依內容主題分組
25
-
26
- ### 2. 完整性強制規則(最高優先)
27
- - **逐項清點**:陣列型資料必須逐一列出所有項目,先數原始 JSON 中有幾筆,輸出後再數確認數量一致
28
- - **巢狀陣列全收**:若某欄位本身是陣列(如設施清單、標籤列表),必須列出該陣列中的**每一項**
29
- - **不因長度省略**:資料再多也不能用「等」、「...」、「其他」概括
30
-
31
- ### 3. 資訊提取(語義識別)
32
- - **標題欄位**:自動識別代表名稱/標題的欄位(\`title\`、\`name\`、\`label\`、\`subject\`)
33
- - **內文欄位**:自動識別長文字欄位(\`content\`、\`description\`、\`body\`、\`intro\`、\`text\`)
34
- - **時間欄位**:自動識別時間相關欄位(\`time\`、\`date\`、\`checkin\`、\`checkout\`、\`created_at\`、\`published_at\`)
35
- - **數值欄位**:自動識別價格/數量欄位(\`price\`、\`qty\`、\`user\`、\`capacity\`、\`size\`)
36
- - **布林欄位**:自動識別開關欄位(\`enable\`、\`display\`、\`is_*\`),轉為「啟用/停用」
37
- - **巢狀物件**:遞迴展開,保留層級結構(如 \`social.{instagram_url, instagram_display}\`)
38
- - **多語言欄位**:若欄位為 \`{zh_tw, en, ja, ...}\` 結構,以 \`zh_tw\` 為主要輸出語言,不存在時依序 fallback
39
-
40
- ### 4. 格式還原
41
- - 若內容為 JSON 字串(Quill Delta 等 RTF 格式),解析後還原為純文字
42
- - 轉義換行 \`\\n\` → 真實換行、\`\\t\` → 縮排
43
- - 內嵌 HTML(\`<a href>\`, \`<img>\`, \`<br>\`)還原為對應 Markdown 語法
44
- - 內嵌 URL 保留為可點擊連結
45
-
46
- ### 5. 檔案拆分原則
47
- - 依照 JSON 的**第一層 key** 或**語義主題**拆分成獨立 \`.md\` 檔案
48
- - 每個檔案涵蓋一個獨立主題區塊
49
- - 檔名使用英文,反映主題(如 \`Rooms.md\`、\`Policies.md\`、\`Facilities.md\`)
50
-
51
- ### 6. 索引生成 (Index.md)
52
- - 彙整所有產出的檔案,生成 \`Index.md\`
53
- - 格式:\`- [顯示名稱](檔名.md):一句話摘要涵蓋的關鍵主題與具體資訊\`
54
- - 摘要必須具體,禁止只重複檔名
55
-
56
- ### 7. 輸出約束
57
- - **輸出順序**:先 \`Index.md\`,再依序輸出其他檔案
58
- - **必須標示檔名**:每個程式碼區塊正上方必須有 \`### 檔名.md\` 標題,不可省略
59
- - 每個檔案以獨立 \` \`\`\`markdown \` 程式碼區塊呈現
60
- - 所有 JSON 內容一律轉為人類可讀的 Markdown,不可保留原始 JSON 字串
61
-
62
- ## 輸出格式規範:
63
-
64
- ### Index.md
65
- \`\`\`markdown
66
- # 知識庫目錄
67
- - [顯示名稱 A](A.md):涵蓋的關鍵主題與具體資訊摘要
68
- - [顯示名稱 B](B.md):涵蓋的關鍵主題與具體資訊摘要
69
- \`\`\`
70
-
71
- ---
72
-
73
- ### 檔名.md
74
- \`\`\`markdown
75
- [還原後的 Markdown 內容]
76
- \`\`\`
77
-
78
- ---
79
-
80
- (重複上述格式直到所有檔案輸出完畢)`;
81
-
82
- const MERGE_PROMPT = `# 角色:知識庫合併架構師 (Knowledge Merge Architect)
83
-
84
- ## 任務目標
85
- 將新的內容合併到既有的知識庫檔案結構中,根據內容類型與主題智能決定「新增頁面」、「合併到既有頁面」或「更新既有頁面」。
86
-
87
- ## 既有知識庫目錄 (Index.md)
88
- \`\`\`markdown
89
- {{indexContent}}
90
- \`\`\`
91
-
92
- ## 新內容類型:{{fileType}}
93
- ## 新內容
94
- \`\`\`{{contentBlock}}
95
- {{newContent}}
96
- \`\`\`
97
-
98
- ## 處理規則:
99
-
100
- ### 1. 結構識別(依 fileType)
101
-
102
- **json**:
103
- - 分析 JSON 頂層結構,以第一層 key 或語義主題分群
104
- - 若為巢狀物件,每個第一層 key 視為一個主題區塊
105
- - 若為頂層陣列,每個元素視為獨立條目
106
-
107
- **markdown**:
108
- - 依照 \`##\` 或 \`###\` 標題拆分成獨立區塊
109
- - 每個區塊視為一個新知識條目
110
-
111
- ### 2. 合併策略判斷
112
-
113
- 對每個條目,檢查是否與既有 Index.md 中的頁面相關:
114
-
115
- - **主題全新**(目錄中無相關頁面)→ 建立**新檔案**,Index.md 追加新條目
116
- - **主題已存在**(標題或關鍵詞與既有頁面重疊)→ 將新內容**合併**到既有檔案,保留既有結構,新增內容作為補充。合併後輸出該檔案的**完整內容**
117
- - **既有檔案缺少條目**(例如列表型資料漏了某筆)→ 必須**補齊**,將缺漏條目加入對應區塊
118
- - **內容衝突**(同一主題但資訊不一致,如價格變動、規則修改)→ 以**新內容為準**更新,標記 \`> 更新於 YYYY-MM-DD\`
119
- - **內容重複**(完全相同)→ 跳過,不輸出
120
-
121
- ### 3. 完整性驗證
122
- - 陣列型資料:比對新內容的項目數與既有檔案收錄數,缺漏必須補齊
123
- - 巢狀陣列(如設施清單、標籤列表):逐一檢查是否全數收錄
124
- - 多語言欄位:以 \`zh_tw\` 為主要輸出語言,不存在時 fallback 到 \`en\`
125
- - JSON 字串內容(Quill Delta 等):\`\\n\` → 換行、\`\\t\` → 縮排、HTML → Markdown
126
-
127
- ### 4. 輸出約束
128
- - **輸出順序**:先輸出更新後的 \`Index.md\`,再依序輸出所有新增或更新過的檔案
129
- - 每個檔案前必須有 \`### 檔名.md\` 作為標題,絕對不可省略
130
- - 每個檔案以獨立 \` \`\`\`markdown \` 程式碼區塊呈現
131
- - **只輸出有變動的檔案**,未修改的既有檔案不需重複輸出
132
- - 合併的檔案必須包含**完整內容**(既有 + 新增),不可只輸出差異
133
-
134
- ## 輸出格式規範:
135
-
136
- ### Index.md
137
- \`\`\`markdown
138
- # 知識庫目錄
139
- - [顯示名稱 A](A.md):一句話摘要涵蓋的關鍵主題
140
- - [顯示名稱 B](B.md):一句話摘要涵蓋的關鍵主題
141
- \`\`\`
142
-
143
- ---
144
-
145
- ### 檔名.md
146
- \`\`\`markdown
147
- [完整內容]
148
- \`\`\`
149
-
150
- ---
151
-
152
- (重複上述格式直到所有變動檔案輸出完畢)`;
153
-
154
- const ROUTER_PROMPT = `# 角色設定
155
- 你是一個精準的「知識庫路由助手 (Router)」。
156
- 你的唯一任務是分析使用者的問題,並從提供的目錄清單中,挑選出最可能包含解答的檔案名稱。
157
-
158
- # 使用者問題
159
- {{prompt}}
160
-
161
- # 知識庫目錄
162
- {{indexContent}}
163
11
 
164
- # 挑選原則
165
- - 從目錄中每個檔案的**摘要**判斷相關性,不只比對檔名
166
- - 考慮同義詞與相關概念(例如:「運動」「健身」→ Facilities.md;「怎麼去」「交通」→ Location_and_Transport.md)
167
- - 若問題涉及多個主題(如「房價和退房時間」),選取所有相關檔案
12
+ const PROMPTS_DIR = path.resolve(undefined || __dirname, 'prompts');
168
13
 
169
- # 輸出嚴格規範
170
- 1. **僅輸出檔名**:從「知識庫目錄」中挑選最相關的完整檔案名稱(必須包含 \`.md\` 後綴)。
171
- 2. **多檔處理**:若有多個檔案相關,請以半形逗號 \`,\` 分隔。
172
- 3. **無相關時**:若判斷目錄中的檔案皆不相關,請直接回覆 \`NONE\`。
173
- 4. **禁止任何廢話**:**絕對禁止**輸出任何解釋文字、問候語、符號,也**禁止**使用 Markdown 標記(如代碼塊 \` \`\`\` \` \`\`\` 或清單 \`-\`)。
14
+ function readPrompt(filename) {
15
+ const filePath = path.join(PROMPTS_DIR, filename);
16
+ if (fs.existsSync(filePath)) {
17
+ return fs.readFileSync(filePath, 'utf-8')
18
+ }
19
+ console.warn(`[wiki-router] Prompt file not found: ${filePath}, using empty string`);
20
+ return ''
21
+ }
174
22
 
175
- **正確輸出範例:**
176
- Introduction.md,Policy_Info.md`;
23
+ const SPLIT_PROMPT = "# 角色:專業文件架構師 (Documentation Architect)\n\n## 任務目標\n將提供的 JSON 資料完整解析並轉換為多個獨立的 Markdown `.md` 檔案。\nJSON 可能來自 CMS、API 回應、設定檔或任何結構化資料來源。\n\n## 原始 JSON 資料\n```json\n{{context}}\n```\n\n## 處理規則:\n\n### 1. 結構識別(自動語義分析)\n- 分析 JSON 的頂層結構(object / array / 巢狀)\n- 若為巢狀物件,以**第一層 key** 作為主題分群依據(如 `data.rooms` → 房間主題、`data.location` → 地點主題)\n- 若為頂層陣列,每個元素視為獨立條目,依內容主題分組\n\n### 2. 完整性強制規則(最高優先)\n- **逐項清點**:陣列型資料必須逐一列出所有項目,先數原始 JSON 中有幾筆,輸出後再數確認數量一致\n- **巢狀陣列全收**:若某欄位本身是陣列(如設施清單、標籤列表),必須列出該陣列中的**每一項**\n- **不因長度省略**:資料再多也不能用「等」、「...」、「其他」概括\n\n### 3. 資訊提取(語義識別)\n- **標題欄位**:自動識別代表名稱/標題的欄位(`title`、`name`、`label`、`subject`)\n- **內文欄位**:自動識別長文字欄位(`content`、`description`、`body`、`intro`、`text`)\n- **時間欄位**:自動識別時間相關欄位(`time`、`date`、`checkin`、`checkout`、`created_at`、`published_at`)\n- **數值欄位**:自動識別價格/數量欄位(`price`、`qty`、`user`、`capacity`、`size`)\n- **布林欄位**:自動識別開關欄位(`enable`、`display`、`is_*`),轉為「啟用/停用」\n- **巢狀物件**:遞迴展開,保留層級結構(如 `social.{instagram_url, instagram_display}`)\n- **多語言欄位**:若欄位為 `{zh_tw, en, ja, ...}` 結構,以 `zh_tw` 為主要輸出語言,不存在時依序 fallback\n\n### 4. 格式還原\n- 若內容為 JSON 字串(Quill Delta 等 RTF 格式),解析後還原為純文字\n- 轉義換行 `\\n` → 真實換行、`\\t` → 縮排\n- 內嵌 HTML(`<a href>`, `<img>`, `<br>`)還原為對應 Markdown 語法\n- 內嵌 URL 保留為可點擊連結\n\n### 5. 檔案拆分原則\n- 依照 JSON 的**第一層 key** 或**語義主題**拆分成獨立 `.md` 檔案\n- 每個檔案涵蓋一個獨立主題區塊\n- 檔名使用英文,反映主題(如 `Rooms.md`、`Policies.md`、`Facilities.md`)\n\n### 6. 索引生成 (Index.md)\n- 彙整所有產出的檔案,生成 `Index.md`\n- 格式:`- [顯示名稱](檔名.md):一句話摘要涵蓋的關鍵主題與具體資訊`\n- 摘要必須具體,禁止只重複檔名\n\n### 7. 輸出約束\n- **輸出順序**:先 `Index.md`,再依序輸出其他檔案\n- **必須標示檔名**:每個程式碼區塊正上方必須有 `### 檔名.md` 標題,不可省略\n- 每個檔案以獨立 ` ```markdown ` 程式碼區塊呈現\n- 所有 JSON 內容一律轉為人類可讀的 Markdown,不可保留原始 JSON 字串\n\n## 輸出格式規範:\n\n### Index.md\n```markdown\n# 知識庫目錄\n- [顯示名稱 A](A.md):涵蓋的關鍵主題與具體資訊摘要\n- [顯示名稱 B](B.md):涵蓋的關鍵主題與具體資訊摘要\n```\n\n---\n\n### 檔名.md\n```markdown\n[還原後的 Markdown 內容]\n```\n\n---\n\n(重複上述格式直到所有檔案輸出完畢)\n";
24
+ const MERGE_PROMPT = "# 角色:知識庫合併架構師 (Knowledge Merge Architect)\n\n## 任務目標\n將新的內容合併到既有的知識庫檔案結構中,根據內容類型與主題智能決定「新增頁面」、「合併到既有頁面」或「更新既有頁面」。\n\n## 既有知識庫目錄 (Index.md)\n```markdown\n{{indexContent}}\n```\n\n## 新內容類型:{{fileType}}\n## 新內容\n```{{contentBlock}}\n{{newContent}}\n```\n\n## 處理規則:\n\n### 1. 結構識別(依 fileType)\n\n**json**:\n- 分析 JSON 頂層結構,以第一層 key 或語義主題分群\n- 若為巢狀物件,每個第一層 key 視為一個主題區塊\n- 若為頂層陣列,每個元素視為獨立條目\n\n**markdown**:\n- 依照 `##` 或 `###` 標題拆分成獨立區塊\n- 每個區塊視為一個新知識條目\n\n### 2. 合併策略判斷\n\n對每個條目,檢查是否與既有 Index.md 中的頁面相關:\n\n- **主題全新**(目錄中無相關頁面)→ 建立**新檔案**,Index.md 追加新條目\n- **主題已存在**(標題或關鍵詞與既有頁面重疊)→ 將新內容**合併**到既有檔案,保留既有結構,新增內容作為補充。合併後輸出該檔案的**完整內容**\n- **既有檔案缺少條目**(例如列表型資料漏了某筆)→ 必須**補齊**,將缺漏條目加入對應區塊\n- **內容衝突**(同一主題但資訊不一致,如價格變動、規則修改)→ 以**新內容為準**更新,標記 `> 更新於 YYYY-MM-DD`\n- **內容重複**(完全相同)→ 跳過,不輸出\n\n### 3. 完整性驗證\n- 陣列型資料:比對新內容的項目數與既有檔案收錄數,缺漏必須補齊\n- 巢狀陣列(如設施清單、標籤列表):逐一檢查是否全數收錄\n- 多語言欄位:以 `zh_tw` 為主要輸出語言,不存在時 fallback 到 `en`\n- JSON 字串內容(Quill Delta 等):`\\n` → 換行、`\\t` → 縮排、HTML → Markdown\n\n### 4. 輸出約束\n- **輸出順序**:先輸出更新後的 `Index.md`,再依序輸出所有新增或更新過的檔案\n- 每個檔案前必須有 `### 檔名.md` 作為標題,絕對不可省略\n- 每個檔案以獨立 ` ```markdown ` 程式碼區塊呈現\n- **只輸出有變動的檔案**,未修改的既有檔案不需重複輸出\n- 合併的檔案必須包含**完整內容**(既有 + 新增),不可只輸出差異\n\n## 輸出格式規範:\n\n### Index.md\n```markdown\n# 知識庫目錄\n- [顯示名稱 A](A.md):一句話摘要涵蓋的關鍵主題\n- [顯示名稱 B](B.md):一句話摘要涵蓋的關鍵主題\n```\n\n---\n\n### 檔名.md\n```markdown\n[完整內容]\n```\n\n---\n\n(重複上述格式直到所有變動檔案輸出完畢)\n";
25
+ const ROUTER_PROMPT = "# 角色設定\n你是一個精準的「知識庫路由助手 (Router)」。\n你的唯一任務是分析使用者的問題,並從提供的目錄清單中,挑選出最可能包含解答的檔案名稱。\n\n# 使用者問題\n{{prompt}}\n\n# 知識庫目錄\n{{indexContent}}\n\n# 挑選原則\n- 從目錄中每個檔案的**摘要**判斷相關性,不只比對檔名\n- 考慮同義詞與相關概念(例如:「運動」「健身」→ Facilities.md;「怎麼去」「交通」→ Location_and_Transport.md)\n- 若問題涉及多個主題(如「房價和退房時間」),選取所有相關檔案\n\n# 輸出嚴格規範\n1. **僅輸出檔名**:從「知識庫目錄」中挑選最相關的完整檔案名稱(必須包含 `.md` 後綴)。\n2. **多檔處理**:若有多個檔案相關,請以半形逗號 `,` 分隔。\n3. **無相關時**:若判斷目錄中的檔案皆不相關,請直接回覆 `NONE`。\n4. **禁止任何廢話**:**絕對禁止**輸出任何解釋文字、問候語、符號,也**禁止**使用 Markdown 標記(如代碼塊 ` ``` ` 或清單 `-`)。\n\n**正確輸出範例:**\nIntroduction.md,Policy_Info.md\n";
177
26
 
178
27
  exports.MERGE_PROMPT = MERGE_PROMPT;
179
28
  exports.ROUTER_PROMPT = ROUTER_PROMPT;