@jungtz/wiki-router 1.0.1 → 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,27 +168,68 @@ 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,
177
+ timeout = 300000,
178
+ splitPrompt,
179
+ mergePrompt,
180
+ routerPrompt,
267
181
  } = config;
268
182
 
183
+ const activeSplitPrompt = splitPrompt || SPLIT_PROMPT;
184
+ const activeMergePrompt = mergePrompt || MERGE_PROMPT;
185
+ const activeRouterPrompt = routerPrompt || ROUTER_PROMPT;
186
+
269
187
  if (!router) throw new Error('[wiki-router] router is required')
270
- if (!knowledgeDir) throw new Error('[wiki-router] knowledgeDir is required')
271
- if (!outputDir) throw new Error('[wiki-router] outputDir is required')
272
188
 
273
- const resolvedKnowledgeDir = path.resolve(knowledgeDir);
274
- 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')
194
+
195
+ let modelsFetched = false;
196
+
197
+ /**
198
+ * 預先獲取本地模型清單(仿照 models.js 的 getModelsList 邏輯)
199
+ * 確保 switchModel 能識別動態發現的 local 模型
200
+ */
201
+ async function ensureModels() {
202
+ if (modelsFetched) return
203
+ try {
204
+ const { models } = await router.getModels();
205
+ const localProviders = Object.keys(router.config.providers).filter(
206
+ p => router.config.providers[p].type === 'local'
207
+ );
208
+ localProviders.forEach(pName => {
209
+ const pModels = models.filter(m => m.provider === pName);
210
+ if (pModels.length > 0) {
211
+ router.config.providers[pName].models = pModels.map(m => ({
212
+ model: m.model,
213
+ description: m.description
214
+ }));
215
+ }
216
+ });
217
+ modelsFetched = true;
218
+ } catch (e) {
219
+ console.warn('[Wiki] Failed to fetch models:', e.message);
220
+ }
221
+ }
275
222
 
276
223
  /**
277
224
  * 向 LLM 發送對話並取得完整回應
278
225
  * @param {{ role: string, content: string }[]} messages
279
226
  * @param {string} [overrideModelId]
227
+ * @param {number} [overrideTimeout]
280
228
  * @returns {Promise<string|null>}
281
229
  */
282
- async function chat(messages, overrideModelId) {
230
+ async function chat(messages, overrideModelId, overrideTimeout) {
283
231
  const wikiModelId = overrideModelId || modelId || process.env.WIKI_MODEL || 'ollama-local/gemma4:31b';
232
+ const effectiveTimeout = overrideTimeout || timeout;
284
233
 
285
234
  try {
286
235
  let provider;
@@ -294,10 +243,17 @@ function createWikiRouter(config) {
294
243
 
295
244
  // 使用 AI Router 進行對話
296
245
  if (router && provider) {
246
+ await ensureModels();
297
247
  await router.switchModel(provider, modelName);
298
248
  let content = '';
299
249
  const stream = router.chat(messages);
250
+
251
+ const deadline = Date.now() + effectiveTimeout;
300
252
  for await (const chunk of stream) {
253
+ if (Date.now() > deadline) {
254
+ console.warn(`[Wiki Chat] Timeout after ${effectiveTimeout}ms`);
255
+ break
256
+ }
301
257
  if (chunk.type === 'content') content += chunk.content;
302
258
  }
303
259
  return content
@@ -316,37 +272,28 @@ function createWikiRouter(config) {
316
272
  */
317
273
  async function build() {
318
274
  try {
319
- if (!fs.existsSync(resolvedOutputDir)) fs.mkdirSync(resolvedOutputDir, { recursive: true });
320
-
321
- const knowledgeFiles = fs.readdirSync(resolvedKnowledgeDir)
322
- .filter(f => f.endsWith('.json') || f.endsWith('.md'))
323
- .sort();
275
+ const knowledgeKeys = await activeSource.list();
324
276
 
325
- if (knowledgeFiles.length === 0) {
326
- 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.');
327
279
  return false
328
280
  }
329
281
 
330
282
  let totalFiles = 0;
331
283
 
332
- for (const knowledgeFile of knowledgeFiles) {
333
- const existingFiles = fs.readdirSync(resolvedOutputDir).filter(f => f.endsWith('.md'));
284
+ for (const key of knowledgeKeys) {
285
+ const existingFiles = await activeStore.list();
334
286
  const isFirstTime = existingFiles.length === 0;
335
- const filePath = path.join(resolvedKnowledgeDir, knowledgeFile);
336
- const fileContent = fs.readFileSync(filePath, 'utf-8');
337
- const fileType = knowledgeFile.endsWith('.json') ? 'json' : 'markdown';
287
+ const { type: fileType, content: fileContent } = await activeSource.read(key);
338
288
 
339
- console.log(`[Wiki] Processing: ${knowledgeFile} (type: ${fileType}, mode: ${isFirstTime ? 'first' : 'merge'})`);
289
+ console.log(`[Wiki] Processing: ${key} (type: ${fileType}, mode: ${isFirstTime ? 'first' : 'merge'})`);
340
290
 
341
291
  let finalPrompt;
342
292
  if (isFirstTime && fileType === 'json') {
343
- finalPrompt = SPLIT_PROMPT.replace('{{context}}', fileContent);
293
+ finalPrompt = activeSplitPrompt.replace('{{context}}', fileContent);
344
294
  } else {
345
- const indexPath = path.join(resolvedOutputDir, 'Index.md');
346
- const indexContent = fs.existsSync(indexPath)
347
- ? fs.readFileSync(indexPath, 'utf-8')
348
- : '';
349
- finalPrompt = MERGE_PROMPT
295
+ const indexContent = (await activeStore.read('Index.md')) || '';
296
+ finalPrompt = activeMergePrompt
350
297
  .replace('{{indexContent}}', indexContent)
351
298
  .replace('{{fileType}}', fileType)
352
299
  .replace('{{contentBlock}}', fileType === 'json' ? 'json' : 'markdown')
@@ -355,18 +302,18 @@ function createWikiRouter(config) {
355
302
 
356
303
  const output = await chat([{ role: 'user', content: finalPrompt }]);
357
304
  if (!output) {
358
- console.warn(`[Wiki] No output for: ${knowledgeFile}`);
305
+ console.warn(`[Wiki] No output for: ${key}`);
359
306
  continue
360
307
  }
361
308
 
362
309
  const parsed = parseWikiOutput(output);
363
310
  if (parsed.length === 0) {
364
- console.error(`[Wiki] Failed to parse output for: ${knowledgeFile}. Raw:`, output);
311
+ console.error(`[Wiki] Failed to parse output for: ${key}. Raw:`, output);
365
312
  continue
366
313
  }
367
314
 
368
315
  for (const { filename, content } of parsed) {
369
- fs.writeFileSync(path.join(resolvedOutputDir, filename), content);
316
+ await activeStore.write(filename, content);
370
317
  console.log(`[Wiki] ${isFirstTime ? 'Generated' : 'Updated'}: ${filename}`);
371
318
  }
372
319
  totalFiles += parsed.length;
@@ -387,23 +334,20 @@ function createWikiRouter(config) {
387
334
  */
388
335
  async function getContext(prompt) {
389
336
  try {
390
- if (!fs.existsSync(resolvedOutputDir)) fs.mkdirSync(resolvedOutputDir, { recursive: true });
391
-
392
- let wikiFiles = fs.readdirSync(resolvedOutputDir).filter(f => f.endsWith('.md'));
337
+ let wikiFiles = await activeStore.list();
393
338
 
394
339
  if (wikiFiles.length === 0) {
395
340
  const success = await build();
396
341
  if (!success) return ''
397
342
  }
398
343
 
399
- const indexPath = path.join(resolvedOutputDir, 'Index.md');
400
- if (!fs.existsSync(indexPath)) {
344
+ const indexContent = await activeStore.read('Index.md');
345
+ if (!indexContent) {
401
346
  console.warn('[Wiki] Index.md not found.');
402
347
  return ''
403
348
  }
404
349
 
405
- const indexContent = fs.readFileSync(indexPath, 'utf-8');
406
- const selectionPrompt = ROUTER_PROMPT
350
+ const selectionPrompt = activeRouterPrompt
407
351
  .replace('{{prompt}}', prompt)
408
352
  .replace('{{indexContent}}', indexContent);
409
353
 
@@ -425,9 +369,9 @@ function createWikiRouter(config) {
425
369
  let loadedCount = 0;
426
370
 
427
371
  for (const file of selectedFiles) {
428
- const filePath = path.join(resolvedOutputDir, file);
429
- if (fs.existsSync(filePath)) {
430
- 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`;
431
375
  loadedCount++;
432
376
  }
433
377
  }
@@ -446,4 +390,4 @@ function createWikiRouter(config) {
446
390
  return { build, getContext }
447
391
  }
448
392
 
449
- export { MERGE_PROMPT, ROUTER_PROMPT, SPLIT_PROMPT, createWikiRouter, parseWikiOutput };
393
+ export { MERGE_PROMPT, ROUTER_PROMPT, SPLIT_PROMPT, createWikiRouter, fsSource, fsStore, parseWikiOutput };