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