dsh-qqbot-muu 0.1.15 → 0.1.21
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/CHANGELOG.md +168 -85
- package/client/qqbot-settings.js +13401 -12024
- package/config/modules.json +212 -0
- package/dist/channel-tools.js +21 -10
- package/dist/config.d.ts +14 -0
- package/dist/config.js +573 -449
- package/dist/features/contextless-store.js +247 -247
- package/dist/features/contextless-trim.js +455 -34
- package/dist/features/four-source.js +338 -336
- package/dist/features/group-join-request.js +289 -287
- package/dist/features/local-models.js +1494 -0
- package/dist/features/rotate-summarizer.js +438 -0
- package/dist/features/scenario-detect.js +321 -0
- package/dist/features/scheduler.js +8 -1
- package/dist/features/session-rotate.js +499 -0
- package/dist/features/session-title.js +199 -0
- package/dist/features/style-layer.js +501 -0
- package/dist/features/thinking-log.js +71 -69
- package/dist/gateway/bootstrap.js +1704 -1388
- package/dist/gateway/data-root.js +77 -3
- package/dist/gateway/middleware-setup.js +6 -3
- package/dist/index.js +4 -2
- package/dist/model/settings-reader.js +193 -102
- package/dist/session/session-manager.js +1730 -1587
- package/dist/shared/paths.js +128 -0
- package/dist/shared/settings-io.js +79 -0
- package/dist/transport/inbound.js +20 -1
- package/dist/transport/outbound.js +56 -4
- package/docs/RELEASE_CHECKLIST.md +24 -2
- package/dshqqbot/.qqbot-extensions/hooks/interview-panel.mjs +41 -1
- package/dshqqbot/.qqbot-extensions/inbound/00-vision.mjs +111 -0
- package/dshqqbot/.qqbot-extensions/inbound/aa-memory-recall.mjs +802 -689
- package/dshqqbot/.qqbot-extensions/inbound/ac-image-see.mjs +1 -1
- package/dshqqbot/.qqbot-extensions/inbound/az-feedback.mjs +113 -115
- package/dshqqbot/.qqbot-extensions/inbound/local-answer.mjs +689 -568
- package/dshqqbot/.qqbot-extensions/lib/.pet-form.json +1 -1
- package/dshqqbot/.qqbot-extensions/lib/draw-core.mjs +238 -7
- package/dshqqbot/.qqbot-extensions/lib/local-llm.mjs +455 -394
- package/dshqqbot/.qqbot-extensions/lib/memory-agent.mjs +930 -928
- package/dshqqbot/.qqbot-extensions/lib/memory-core.mjs +537 -537
- package/dshqqbot/.qqbot-extensions/lib/memory-db.mjs +2476 -2245
- package/dshqqbot/.qqbot-extensions/lib/memory-hippo.mjs +18 -0
- package/dshqqbot/.qqbot-extensions/lib/memory.mjs +191 -186
- package/dshqqbot/.qqbot-extensions/lib/plugin-dir.mjs +14 -4
- package/dshqqbot/.qqbot-extensions/lib/scope-util.mjs +84 -0
- package/dshqqbot/.qqbot-extensions/lib/vision.mjs +1 -1
- package/dshqqbot/.qqbot-extensions/outbound/aa-sanitize.mjs +158 -154
- package/dshqqbot/.qqbot-extensions/outbound/ac-media-fix.mjs +5 -1
- package/dshqqbot/.qqbot-extensions/outbound/memory-agent.mjs +121 -130
- package/dshqqbot/.qqbot-extensions/outbound/split-reply.mjs +18 -2
- package/dshqqbot/.qqbot-extensions/outbound/turn-memory.mjs +92 -101
- package/dshqqbot/.qqbot-extensions/tools/draw.mjs +22 -1
- package/dshqqbot/.qqbot-extensions/tools/memory.mjs +178 -120
- package/dshqqbot/.qqbot-extensions/tools/pet_card.mjs +3 -2
- package/dshqqbot/.qqbot-extensions/tools/storyboard.mjs +3 -1
- package/dshqqbot/.qqbot-extensions/vendor/abogus/test-abogus.mjs +128 -126
- package/package.json +119 -111
- package/scripts/__pycache__/fan-mode.cpython-311.pyc +0 -0
- package/scripts/__pycache__/memory-audit.cpython-311.pyc +0 -0
- package/scripts/__pycache__/qq-ip-sync.cpython-311.pyc +0 -0
- package/scripts/__pycache__/qq-whitelist.cpython-311.pyc +0 -0
- package/scripts/_add_maintenance_cfg.py +20 -0
- package/scripts/_bench_keeplease.sh +10 -0
- package/scripts/_dbg_purge.py +15 -0
- package/scripts/_elev.sh +6 -0
- package/scripts/_fix_all_admin.cmd +16 -0
- package/scripts/_livecheck-image.mjs +33 -0
- package/scripts/_livecheck-llm.mjs +34 -0
- package/scripts/_livecheck-tts.mjs +37 -0
- package/scripts/_patch_curve.py +88 -0
- package/scripts/_patch_fan_thermal.py +24 -0
- package/scripts/_tag_tmp.py +13 -0
- package/scripts/adb-broker-client.mjs +87 -0
- package/scripts/adb-broker.mjs +205 -0
- package/scripts/ai-mode.cmd +6 -0
- package/scripts/ai-mode.py +387 -0
- package/scripts/ai-toolkit.py +607 -0
- package/scripts/apply-fan-gpu45.py +51 -0
- package/scripts/bench-fans.py +515 -0
- package/scripts/bench-load-direct.py +63 -0
- package/scripts/boot-tasks-hidden.vbs +20 -0
- package/scripts/boot-tasks.cmd +277 -0
- package/scripts/chat-archive/__pycache__/build-sft-v4.cpython-311.pyc +0 -0
- package/scripts/chat-archive/__pycache__/build-sft.cpython-311.pyc +0 -0
- package/scripts/chat-archive/build-sft-v4.py +566 -0
- package/scripts/chat-archive/build-sft.py +390 -0
- package/scripts/chat-archive/eval-sft.py +155 -0
- package/scripts/chat-archive/extract-memory.py +143 -0
- package/scripts/chat-archive/inventory.py +182 -0
- package/scripts/chat-archive/merge-sft.py +114 -0
- package/scripts/chat-archive/qce-pull.py +217 -0
- package/scripts/chat-archive/qqheader.py +110 -0
- package/scripts/chat-archive/qqkey2.py +113 -0
- package/scripts/chat-archive/qqprobe.py +153 -0
- package/scripts/chat-archive/screen-collect.py +163 -0
- package/scripts/chat-archive/sqlcipher_probe.py +444 -0
- package/scripts/comfy_gen.py +209 -0
- package/scripts/compose-video.py +168 -0
- package/scripts/dl_models.py +45 -0
- package/scripts/draw-now.cmd +18 -0
- package/scripts/dsh-instance-guard.mjs +20 -2
- package/scripts/elev-extra.cmd +25 -0
- package/scripts/episode.py +529 -0
- package/scripts/fan-curve.py +218 -0
- package/scripts/fan-guard.cmd +8 -0
- package/scripts/fan-mode.py +380 -0
- package/scripts/fan_manual_safe.py +33 -0
- package/scripts/fan_restore_manual.py +46 -0
- package/scripts/fc_curves.py +359 -0
- package/scripts/fix-fan-and-timers.cmd +39 -0
- package/scripts/fix_admin_all.py +94 -0
- package/scripts/flows.mjs +224 -0
- package/scripts/gateway.cmd +126 -0
- package/scripts/gen-image.py +420 -0
- package/scripts/gen-video.py +186 -0
- package/scripts/git-askpass.cmd +2 -2
- package/scripts/gpu-mode.py +195 -0
- package/scripts/hw-profile.py +175 -0
- package/scripts/install-schedule.cmd +37 -0
- package/scripts/install-watch.cmd +29 -0
- package/scripts/matte-cutout.py +106 -0
- package/scripts/media-enhance.py +402 -0
- package/scripts/memory-audit.py +581 -0
- package/scripts/migrate-scope.mjs +140 -139
- package/scripts/model-registry.py +519 -0
- package/scripts/openid-audit.mjs +219 -0
- package/scripts/pull-gguf.py +127 -0
- package/scripts/purge-standby.py +151 -0
- package/scripts/qq-connect-login.py +133 -0
- package/scripts/qq-ip-sync-hidden.vbs +5 -0
- package/scripts/qq-ip-sync.py +300 -0
- package/scripts/qq-login-once.cmd +20 -0
- package/scripts/qq-login-qr.py +72 -0
- package/scripts/qq-whitelist-fix.cmd +27 -0
- package/scripts/qq-whitelist-login.cmd +26 -0
- package/scripts/qq-whitelist.cmd +12 -0
- package/scripts/qq-whitelist.py +1452 -0
- package/scripts/quality-compare.py +134 -0
- package/scripts/release-all.mjs +636 -430
- package/scripts/release-check.mjs +244 -226
- package/scripts/resume-coder.cmd +38 -0
- package/scripts/secure-room/index.html +334 -0
- package/scripts/secure-room/server.py +582 -0
- package/scripts/security-check.mjs +164 -0
- package/scripts/selftest-local-llm.mjs +20 -0
- package/scripts/selftest-local-models.mjs +754 -0
- package/scripts/selftest-rotate-style.mjs +308 -0
- package/scripts/shutdown-s5-optional.cmd +21 -0
- package/scripts/sleep-2325.cmd +75 -0
- package/scripts/start-comfyui.cmd +5 -0
- package/scripts/start-strata.cmd +17 -0
- package/scripts/start-strata.vbs +11 -0
- package/scripts/start-watch-hidden.vbs +3 -0
- package/scripts/stickers/auto-tag.mjs +161 -0
- package/scripts/storage.mjs +236 -0
- package/scripts/sync-plugin-copies.mjs +98 -23
- package/scripts/tests/test-qq-whitelist.py +192 -0
- package/scripts/train/__pycache__/train-lora.cpython-311.pyc +0 -0
- package/scripts/train/gguf-quantize.py +92 -0
- package/scripts/train/gguf-to-hf.py +112 -0
- package/scripts/train/merge-lora.py +51 -0
- package/scripts/train/probe-mirrors.sh +12 -0
- package/scripts/train/probe-mirrors2.sh +20 -0
- package/scripts/train/setup-wsl.sh +23 -0
- package/scripts/train/setup-wsl2.sh +25 -0
- package/scripts/train/setup-wsl3.sh +22 -0
- package/scripts/train/setup-wsl4.sh +22 -0
- package/scripts/train/train-lora.py +319 -0
- package/scripts/vram-free.py +104 -0
- package/scripts/wechat-full-pull.mjs +1 -1
- package/settings-host.js +1047 -12
|
@@ -1,394 +1,455 @@
|
|
|
1
|
-
import { existsSync as __existsSync } from 'node:fs'
|
|
2
|
-
const __repoRoot = (() => {
|
|
3
|
-
let cached = ''
|
|
4
|
-
const norm = (p) => String(p || '').split(String.fromCharCode(92)).join('/')
|
|
5
|
-
return () => {
|
|
6
|
-
if (cached) return cached
|
|
7
|
-
const cands = []
|
|
8
|
-
const env = String(process.env.QQBOT_ROOT || process.env.QQBOT_REPO_ROOT || '').trim()
|
|
9
|
-
if (env) cands.push(norm(env))
|
|
10
|
-
try {
|
|
11
|
-
let here = decodeURIComponent(new URL('.', import.meta.url).pathname)
|
|
12
|
-
if (here[0] === '/' && here[2] === ':') here = here.slice(1)
|
|
13
|
-
here = norm(here).replace(/\/+$/, '')
|
|
14
|
-
let d = here
|
|
15
|
-
for (let i = 0; i < 6; i += 1) {
|
|
16
|
-
if (!d) break
|
|
17
|
-
cands.push(d)
|
|
18
|
-
const k = d.lastIndexOf('/')
|
|
19
|
-
d = k > 0 ? d.slice(0, k) : ''
|
|
20
|
-
}
|
|
21
|
-
} catch { /* noop */ }
|
|
22
|
-
try { cands.push(norm(process.cwd())) } catch { /* noop */ }
|
|
23
|
-
for (const c of cands) {
|
|
24
|
-
try {
|
|
25
|
-
if (c && (__existsSync(c + '/qqbot-mod/muu-shared.mjs') || __existsSync(c + '/dshqqbot'))) { cached = c; return cached }
|
|
26
|
-
} catch { /* noop */ }
|
|
27
|
-
}
|
|
28
|
-
cached = norm(cands.find(Boolean) || '.')
|
|
29
|
-
return cached
|
|
30
|
-
}
|
|
31
|
-
})()
|
|
32
|
-
/**
|
|
33
|
-
* local-llm.mjs — 本地小模型(Ollama)客户端
|
|
34
|
-
*
|
|
35
|
-
* 为什么要有这一层:
|
|
36
|
-
* "哈哈哈"、"在吗"、"鲸鲸" 这种消息走云端大模型是纯浪费(一次几百~上千 token)。
|
|
37
|
-
* 本机跑一个 0.5B 的小模型,这类消息直接本地出话,**云端 token = 0**,
|
|
38
|
-
* 而且延迟 200~600ms,比等云快得多。
|
|
39
|
-
*
|
|
40
|
-
* 设计原则(和记忆库一致):
|
|
41
|
-
* · 永不抛异常,失败一律返回 { ok:false, error },调用方照常走云端;
|
|
42
|
-
* · 服务没起来 / 模型没拉 / 超时 —— 全部静默降级,不影响正常聊天;
|
|
43
|
-
* · 只要 HTTP,不需要装任何 npm 依赖(Node 24 自带 fetch)。
|
|
44
|
-
*
|
|
45
|
-
* 配置:{dataRoot}/.qqbot-extensions/local-llm-config.json
|
|
46
|
-
*/
|
|
47
|
-
|
|
48
|
-
import { existsSync, readFileSync, mkdirSync, writeFileSync } from 'node:fs';
|
|
49
|
-
import { join, dirname } from 'node:path';
|
|
50
|
-
import { keepAliveFor, noteUse, ensureWatcher, snapshot as policySnapshot } from './model-policy.mjs';
|
|
51
|
-
|
|
52
|
-
export const CONFIG_NAME = 'local-llm-config.json';
|
|
53
|
-
|
|
54
|
-
export const DEFAULTS = {
|
|
55
|
-
enabled: true,
|
|
56
|
-
//
|
|
57
|
-
baseUrl
|
|
58
|
-
|
|
59
|
-
//
|
|
60
|
-
|
|
61
|
-
//
|
|
62
|
-
|
|
63
|
-
|
|
64
|
-
//
|
|
65
|
-
|
|
66
|
-
//
|
|
67
|
-
|
|
68
|
-
|
|
69
|
-
|
|
70
|
-
residency
|
|
71
|
-
|
|
72
|
-
|
|
73
|
-
|
|
74
|
-
|
|
75
|
-
|
|
76
|
-
|
|
77
|
-
|
|
78
|
-
|
|
79
|
-
|
|
80
|
-
|
|
81
|
-
|
|
82
|
-
|
|
83
|
-
|
|
84
|
-
|
|
85
|
-
|
|
86
|
-
|
|
87
|
-
|
|
88
|
-
*
|
|
89
|
-
|
|
90
|
-
|
|
91
|
-
|
|
92
|
-
|
|
93
|
-
|
|
94
|
-
|
|
95
|
-
|
|
96
|
-
|
|
97
|
-
|
|
98
|
-
|
|
99
|
-
|
|
100
|
-
|
|
101
|
-
|
|
102
|
-
|
|
103
|
-
|
|
104
|
-
|
|
105
|
-
|
|
106
|
-
|
|
107
|
-
|
|
108
|
-
|
|
109
|
-
*
|
|
110
|
-
|
|
111
|
-
|
|
112
|
-
|
|
113
|
-
|
|
114
|
-
|
|
115
|
-
|
|
116
|
-
|
|
117
|
-
|
|
118
|
-
|
|
119
|
-
|
|
120
|
-
|
|
121
|
-
|
|
122
|
-
|
|
123
|
-
|
|
124
|
-
|
|
125
|
-
|
|
126
|
-
|
|
127
|
-
|
|
128
|
-
|
|
129
|
-
export function
|
|
130
|
-
|
|
131
|
-
|
|
132
|
-
|
|
133
|
-
|
|
134
|
-
|
|
135
|
-
|
|
136
|
-
|
|
137
|
-
|
|
138
|
-
|
|
139
|
-
const
|
|
140
|
-
|
|
141
|
-
|
|
142
|
-
|
|
143
|
-
|
|
144
|
-
|
|
145
|
-
|
|
146
|
-
|
|
147
|
-
|
|
148
|
-
|
|
149
|
-
|
|
150
|
-
|
|
151
|
-
|
|
152
|
-
|
|
153
|
-
|
|
154
|
-
|
|
155
|
-
|
|
156
|
-
|
|
157
|
-
|
|
158
|
-
|
|
159
|
-
|
|
160
|
-
|
|
161
|
-
|
|
162
|
-
|
|
163
|
-
|
|
164
|
-
|
|
165
|
-
}
|
|
166
|
-
|
|
167
|
-
|
|
168
|
-
|
|
169
|
-
|
|
170
|
-
|
|
171
|
-
|
|
172
|
-
|
|
173
|
-
|
|
174
|
-
|
|
175
|
-
|
|
176
|
-
|
|
177
|
-
|
|
178
|
-
|
|
179
|
-
|
|
180
|
-
|
|
181
|
-
|
|
182
|
-
|
|
183
|
-
|
|
184
|
-
|
|
185
|
-
|
|
186
|
-
|
|
187
|
-
|
|
188
|
-
|
|
189
|
-
|
|
190
|
-
|
|
191
|
-
|
|
192
|
-
|
|
193
|
-
|
|
194
|
-
|
|
195
|
-
|
|
196
|
-
|
|
197
|
-
|
|
198
|
-
|
|
199
|
-
|
|
200
|
-
|
|
201
|
-
|
|
202
|
-
|
|
203
|
-
|
|
204
|
-
|
|
205
|
-
|
|
206
|
-
|
|
207
|
-
|
|
208
|
-
|
|
209
|
-
|
|
210
|
-
|
|
211
|
-
|
|
212
|
-
|
|
213
|
-
|
|
214
|
-
|
|
215
|
-
|
|
216
|
-
|
|
217
|
-
|
|
218
|
-
|
|
219
|
-
|
|
220
|
-
|
|
221
|
-
|
|
222
|
-
|
|
223
|
-
|
|
224
|
-
}
|
|
225
|
-
}
|
|
226
|
-
|
|
227
|
-
|
|
228
|
-
|
|
229
|
-
|
|
230
|
-
|
|
231
|
-
|
|
232
|
-
|
|
233
|
-
|
|
234
|
-
|
|
235
|
-
|
|
236
|
-
|
|
237
|
-
|
|
238
|
-
|
|
239
|
-
|
|
240
|
-
|
|
241
|
-
|
|
242
|
-
|
|
243
|
-
|
|
244
|
-
|
|
245
|
-
|
|
246
|
-
|
|
247
|
-
|
|
248
|
-
|
|
249
|
-
|
|
250
|
-
|
|
251
|
-
|
|
252
|
-
|
|
253
|
-
|
|
254
|
-
|
|
255
|
-
|
|
256
|
-
|
|
257
|
-
|
|
258
|
-
|
|
259
|
-
|
|
260
|
-
|
|
261
|
-
|
|
262
|
-
|
|
263
|
-
|
|
264
|
-
|
|
265
|
-
}
|
|
266
|
-
|
|
267
|
-
|
|
268
|
-
|
|
269
|
-
|
|
270
|
-
|
|
271
|
-
|
|
272
|
-
|
|
273
|
-
|
|
274
|
-
|
|
275
|
-
|
|
276
|
-
|
|
277
|
-
|
|
278
|
-
|
|
279
|
-
|
|
280
|
-
|
|
281
|
-
|
|
282
|
-
|
|
283
|
-
|
|
284
|
-
|
|
285
|
-
|
|
286
|
-
|
|
287
|
-
|
|
288
|
-
|
|
289
|
-
|
|
290
|
-
|
|
291
|
-
|
|
292
|
-
|
|
293
|
-
|
|
294
|
-
|
|
295
|
-
|
|
296
|
-
|
|
297
|
-
|
|
298
|
-
|
|
299
|
-
|
|
300
|
-
|
|
301
|
-
|
|
302
|
-
|
|
303
|
-
|
|
304
|
-
|
|
305
|
-
|
|
306
|
-
|
|
307
|
-
|
|
308
|
-
|
|
309
|
-
|
|
310
|
-
|
|
311
|
-
|
|
312
|
-
|
|
313
|
-
|
|
314
|
-
|
|
315
|
-
|
|
316
|
-
|
|
317
|
-
|
|
318
|
-
const
|
|
319
|
-
|
|
320
|
-
|
|
321
|
-
|
|
322
|
-
|
|
323
|
-
|
|
324
|
-
|
|
325
|
-
|
|
326
|
-
|
|
327
|
-
|
|
328
|
-
|
|
329
|
-
|
|
330
|
-
|
|
331
|
-
|
|
332
|
-
|
|
333
|
-
|
|
334
|
-
|
|
335
|
-
|
|
336
|
-
|
|
337
|
-
|
|
338
|
-
|
|
339
|
-
|
|
340
|
-
|
|
341
|
-
|
|
342
|
-
|
|
343
|
-
|
|
344
|
-
|
|
345
|
-
|
|
346
|
-
|
|
347
|
-
|
|
348
|
-
|
|
349
|
-
|
|
350
|
-
|
|
351
|
-
|
|
352
|
-
|
|
353
|
-
|
|
354
|
-
|
|
355
|
-
|
|
356
|
-
|
|
357
|
-
|
|
358
|
-
|
|
359
|
-
|
|
360
|
-
|
|
361
|
-
|
|
362
|
-
|
|
363
|
-
|
|
364
|
-
|
|
365
|
-
|
|
366
|
-
|
|
367
|
-
|
|
368
|
-
|
|
369
|
-
|
|
370
|
-
|
|
371
|
-
|
|
372
|
-
|
|
373
|
-
|
|
374
|
-
|
|
375
|
-
|
|
376
|
-
|
|
377
|
-
|
|
378
|
-
|
|
379
|
-
|
|
380
|
-
|
|
381
|
-
|
|
382
|
-
|
|
383
|
-
|
|
384
|
-
|
|
385
|
-
|
|
386
|
-
|
|
387
|
-
|
|
388
|
-
|
|
389
|
-
|
|
390
|
-
|
|
391
|
-
|
|
392
|
-
|
|
393
|
-
};
|
|
394
|
-
}
|
|
1
|
+
import { existsSync as __existsSync } from 'node:fs'
|
|
2
|
+
const __repoRoot = (() => {
|
|
3
|
+
let cached = ''
|
|
4
|
+
const norm = (p) => String(p || '').split(String.fromCharCode(92)).join('/')
|
|
5
|
+
return () => {
|
|
6
|
+
if (cached) return cached
|
|
7
|
+
const cands = []
|
|
8
|
+
const env = String(process.env.QQBOT_ROOT || process.env.QQBOT_REPO_ROOT || '').trim()
|
|
9
|
+
if (env) cands.push(norm(env))
|
|
10
|
+
try {
|
|
11
|
+
let here = decodeURIComponent(new URL('.', import.meta.url).pathname)
|
|
12
|
+
if (here[0] === '/' && here[2] === ':') here = here.slice(1)
|
|
13
|
+
here = norm(here).replace(/\/+$/, '')
|
|
14
|
+
let d = here
|
|
15
|
+
for (let i = 0; i < 6; i += 1) {
|
|
16
|
+
if (!d) break
|
|
17
|
+
cands.push(d)
|
|
18
|
+
const k = d.lastIndexOf('/')
|
|
19
|
+
d = k > 0 ? d.slice(0, k) : ''
|
|
20
|
+
}
|
|
21
|
+
} catch { /* noop */ }
|
|
22
|
+
try { cands.push(norm(process.cwd())) } catch { /* noop */ }
|
|
23
|
+
for (const c of cands) {
|
|
24
|
+
try {
|
|
25
|
+
if (c && (__existsSync(c + '/qqbot-mod/muu-shared.mjs') || __existsSync(c + '/dshqqbot'))) { cached = c; return cached }
|
|
26
|
+
} catch { /* noop */ }
|
|
27
|
+
}
|
|
28
|
+
cached = norm(cands.find(Boolean) || '.')
|
|
29
|
+
return cached
|
|
30
|
+
}
|
|
31
|
+
})()
|
|
32
|
+
/**
|
|
33
|
+
* local-llm.mjs — 本地小模型(Ollama)客户端
|
|
34
|
+
*
|
|
35
|
+
* 为什么要有这一层:
|
|
36
|
+
* "哈哈哈"、"在吗"、"鲸鲸" 这种消息走云端大模型是纯浪费(一次几百~上千 token)。
|
|
37
|
+
* 本机跑一个 0.5B 的小模型,这类消息直接本地出话,**云端 token = 0**,
|
|
38
|
+
* 而且延迟 200~600ms,比等云快得多。
|
|
39
|
+
*
|
|
40
|
+
* 设计原则(和记忆库一致):
|
|
41
|
+
* · 永不抛异常,失败一律返回 { ok:false, error },调用方照常走云端;
|
|
42
|
+
* · 服务没起来 / 模型没拉 / 超时 —— 全部静默降级,不影响正常聊天;
|
|
43
|
+
* · 只要 HTTP,不需要装任何 npm 依赖(Node 24 自带 fetch)。
|
|
44
|
+
*
|
|
45
|
+
* 配置:{dataRoot}/.qqbot-extensions/local-llm-config.json
|
|
46
|
+
*/
|
|
47
|
+
|
|
48
|
+
import { existsSync, readFileSync, mkdirSync, writeFileSync } from 'node:fs';
|
|
49
|
+
import { join, dirname } from 'node:path';
|
|
50
|
+
import { keepAliveFor, noteUse, ensureWatcher, snapshot as policySnapshot } from './model-policy.mjs';
|
|
51
|
+
|
|
52
|
+
export const CONFIG_NAME = 'local-llm-config.json';
|
|
53
|
+
|
|
54
|
+
export const DEFAULTS = {
|
|
55
|
+
enabled: true,
|
|
56
|
+
// provider:ollama(默认,/api/chat)| openai(任意 OpenAI 兼容 /v1/chat/completions:
|
|
57
|
+
// Strata 8080 / vLLM / LM Studio / 云端中转都算)。留空 = 看 baseUrl 自动判断。
|
|
58
|
+
provider: 'ollama',
|
|
59
|
+
// Ollama 默认监听;若用户改了 OLLAMA_HOST 需要同步改这里
|
|
60
|
+
baseUrl: 'http://127.0.0.1:11434',
|
|
61
|
+
// provider=openai 时如果端点要 key,填这里(本地 Strata 留空即可)
|
|
62
|
+
apiKey: '',
|
|
63
|
+
model: 'dolphin3:8b',
|
|
64
|
+
// 单次生成超时(实测 qwen2.5:7b 热态 0.27s、冷启 7.3s,留足余量)
|
|
65
|
+
timeoutMs: 12000,
|
|
66
|
+
// 生成上限:小蓝的回复本来就 ≤50 字,48 token 够了(中文约 1 字 ≈ 1 token)
|
|
67
|
+
maxTokens: 48,
|
|
68
|
+
// 模型常驻时长(Ollama keep_alive)。
|
|
69
|
+
// 2026-10-26 改口:主人要求"不要常驻,有需求再唤醒" ⇒ 这里只是兜底,
|
|
70
|
+
// 真正的取值走 residency(见下)与 lib/model-policy.mjs:
|
|
71
|
+
// 没有被 pin(游戏/配音)时 = '0'(这一轮生成完就离开显存)
|
|
72
|
+
// 被 pin 时 = '10m'(多轮之间不冷启)
|
|
73
|
+
keepAlive: '0',
|
|
74
|
+
/** 显存/常驻策略(详见 lib/model-policy.mjs) */
|
|
75
|
+
residency: {
|
|
76
|
+
enabled: true,
|
|
77
|
+
idleUnloadSec: 60, // 没 pin 且 60 秒没人用就全卸
|
|
78
|
+
pinnedKeepAlive: '10m', // 游戏/配音期间钉住
|
|
79
|
+
looseKeepAlive: '0', // 平时生成完即卸
|
|
80
|
+
watchMs: 20000,
|
|
81
|
+
},
|
|
82
|
+
temperature: 0.7,
|
|
83
|
+
topP: 0.9,
|
|
84
|
+
// 健康检查结果缓存多久(避免每条消息都探测一次)
|
|
85
|
+
healthTtlMs: 5000,
|
|
86
|
+
// ── 下面这些是「入站代答」的策略参数(local-answer 用)──
|
|
87
|
+
/**
|
|
88
|
+
* 谁来回这条消息(★ 面板里那个下拉就是它):
|
|
89
|
+
* off 全交云端(本地只当语义检索用)
|
|
90
|
+
* simple 只有"简单消息"本地答(默认;碎句/打招呼/表情)
|
|
91
|
+
* chat 简单 + 闲聊也本地答(更省 token,废话精度略降)
|
|
92
|
+
* all 尽量本地(除任务型/长文,全本地)
|
|
93
|
+
* 判据见 local-answer.mjs 的 worthLocal()。
|
|
94
|
+
*/
|
|
95
|
+
whoAnswers: 'simple',
|
|
96
|
+
maxInputChars: 80, // 超过这么多字就不给本地模型(长文它会胡说)
|
|
97
|
+
maxReplyChars: 60, // 本地回复截断上限(人设 ≤50 字/3 句,留余量)
|
|
98
|
+
shortChatChars: 12, // ≤ 这个字数的非任务句也算"简单消息"
|
|
99
|
+
minIntervalMs: 6000, // 两次本地代答的最小间隔
|
|
100
|
+
maxPerWindow: 6, // 每窗口最多几条
|
|
101
|
+
windowMs: 60000,
|
|
102
|
+
allowUnmentioned: false, // 群里没 @ 她要不要也抢答
|
|
103
|
+
unmentionedProb: 0.25, // allowUnmentioned=true 时,没 @ 她的消息按这个概率接
|
|
104
|
+
ownerToo: true, // 主人的消息要不要也本地代答(只限简单话;复杂活照样交云端)
|
|
105
|
+
/**
|
|
106
|
+
* "简单话本地先接"的开关(2026-10-23 晚改口):
|
|
107
|
+
* 主人实测"私聊里一句你好也调大模型太浪费" ⇒ 私聊 / 被 @ 的**简单话**也归本地,
|
|
108
|
+
* 摘得掉(annihilate 成功,含 ownerAck)就省下一整轮云 token,摘不掉自动回落云端。
|
|
109
|
+
* c2cLocal=false / onlyUnmentioned=true 仍然可用,含义变成"连简单话也不许本地抢"。
|
|
110
|
+
*/
|
|
111
|
+
onlyUnmentioned: false,
|
|
112
|
+
c2cLocal: true,
|
|
113
|
+
/**
|
|
114
|
+
* 单脑仲裁窗口(毫秒):云端在这个窗口内被放行过 / 刚说完,本地就不插嘴。
|
|
115
|
+
* 0 = 关闭仲裁(想复现"左右脑互搏"时用)。
|
|
116
|
+
* 12 秒的依据:云端一回合(含工具调用)通常 3~10 秒,窗口盖住一个回合即可。
|
|
117
|
+
*/
|
|
118
|
+
brainHoldMs: 12000,
|
|
119
|
+
systemPrompt: '', // 空 = 用 local-answer 内置人设
|
|
120
|
+
};
|
|
121
|
+
|
|
122
|
+
/** 解析数据根(环境变量优先,便于测试隔离) */
|
|
123
|
+
export function dataRootOf(cfg) {
|
|
124
|
+
const env = String(process.env.QQBOT_MEMORY_DATA_ROOT || '').trim();
|
|
125
|
+
if (env) return env;
|
|
126
|
+
return (cfg && cfg.dataRoot) || __repoRoot() + "/dshqqbot";
|
|
127
|
+
}
|
|
128
|
+
|
|
129
|
+
export function configPath(dataRoot) {
|
|
130
|
+
return join(String(dataRoot || '.'), '.qqbot-extensions', CONFIG_NAME);
|
|
131
|
+
}
|
|
132
|
+
|
|
133
|
+
/** 读配置:文件不存在就用默认值(不写盘),字段缺失用默认值补齐 */
|
|
134
|
+
export function loadConfig(dataRoot) {
|
|
135
|
+
const def = { ...DEFAULTS, dataRoot };
|
|
136
|
+
try {
|
|
137
|
+
const p = configPath(dataRoot);
|
|
138
|
+
if (!existsSync(p)) return def;
|
|
139
|
+
const raw = JSON.parse(readFileSync(p, 'utf8'));
|
|
140
|
+
if (!raw || typeof raw !== 'object') return def;
|
|
141
|
+
// ★ 这里踩过坑:原来只拷贝 DEFAULTS 里有的键 ⇒ 配置文件里那些"策略参数"
|
|
142
|
+
// (minIntervalMs / maxPerWindow / allowUnmentioned / systemPrompt …)
|
|
143
|
+
// 被静默丢掉,改配置等于没改。现在反过来:文件里的键**全部生效**。
|
|
144
|
+
const out = { ...def, ...raw };
|
|
145
|
+
out.dataRoot = dataRoot;
|
|
146
|
+
return out;
|
|
147
|
+
} catch {
|
|
148
|
+
return def;
|
|
149
|
+
}
|
|
150
|
+
}
|
|
151
|
+
|
|
152
|
+
/** 写配置(给脚本/工具用) */
|
|
153
|
+
export function saveConfig(dataRoot, patch) {
|
|
154
|
+
const p = configPath(dataRoot);
|
|
155
|
+
try {
|
|
156
|
+
const cur = existsSync(p) ? JSON.parse(readFileSync(p, 'utf8')) : {};
|
|
157
|
+
const next = { ...DEFAULTS, ...(cur && typeof cur === 'object' ? cur : {}), ...(patch || {}) };
|
|
158
|
+
delete next.dataRoot;
|
|
159
|
+
mkdirSync(dirname(p), { recursive: true });
|
|
160
|
+
writeFileSync(p, JSON.stringify(next, null, 2), 'utf8');
|
|
161
|
+
return { ok: true, path: p, config: next };
|
|
162
|
+
} catch (e) {
|
|
163
|
+
return { ok: false, error: e instanceof Error ? e.message : String(e) };
|
|
164
|
+
}
|
|
165
|
+
}
|
|
166
|
+
|
|
167
|
+
function urlOf(cfg, path) {
|
|
168
|
+
const base = String(cfg.baseUrl || DEFAULTS.baseUrl).replace(/\/+$/, '');
|
|
169
|
+
return base + path;
|
|
170
|
+
}
|
|
171
|
+
|
|
172
|
+
/**
|
|
173
|
+
* 走 OpenAI 兼容协议吗?
|
|
174
|
+
* provider 显式写了就听它的;没写就看 baseUrl 是不是以 /v1 结尾
|
|
175
|
+
* (Strata 8080/v1、LM Studio 1234/v1、各种中转都是这个形状)。
|
|
176
|
+
*/
|
|
177
|
+
export function useOpenAI(cfg) {
|
|
178
|
+
const p = String((cfg && cfg.provider) || '').toLowerCase();
|
|
179
|
+
if (p === 'openai') return true;
|
|
180
|
+
if (p === 'ollama') return false;
|
|
181
|
+
return /\/v1$/.test(String((cfg && cfg.baseUrl) || '').replace(/\/+$/, ''));
|
|
182
|
+
}
|
|
183
|
+
|
|
184
|
+
function authHeaders(cfg) {
|
|
185
|
+
const k = String((cfg && cfg.apiKey) || '').trim();
|
|
186
|
+
return k ? { authorization: 'Bearer ' + k } : {};
|
|
187
|
+
}
|
|
188
|
+
|
|
189
|
+
// ── 判定日志(面板要靠它显示"这条是谁答的")─────────────────────
|
|
190
|
+
/**
|
|
191
|
+
* 为什么要有日志:本地代答不生效时,界面上**什么都看不出来**(用户实测反馈
|
|
192
|
+
* "本地小模型似乎没有生效")。把每次判定写进 jsonl,面板就能显示
|
|
193
|
+
* "最近 8 条:本地 took=1 / 云端 why=tier:task",一眼看出是被哪道门挡了。
|
|
194
|
+
*/
|
|
195
|
+
const LOG_MAX_BYTES = 2 * 1024 * 1024;
|
|
196
|
+
|
|
197
|
+
export function logFile(dataRoot) {
|
|
198
|
+
return join(String(dataRoot || '.'), '.qqbot', 'local-answer-log.jsonl');
|
|
199
|
+
}
|
|
200
|
+
|
|
201
|
+
export function appendLog(dataRoot, rec) {
|
|
202
|
+
try {
|
|
203
|
+
const p = logFile(dataRoot);
|
|
204
|
+
mkdirSync(dirname(p), { recursive: true });
|
|
205
|
+
try {
|
|
206
|
+
// 轮转:太大就先截掉一半(只留最近的行)
|
|
207
|
+
const st = readFileSync(p, 'utf8');
|
|
208
|
+
if (st.length > LOG_MAX_BYTES) {
|
|
209
|
+
const lines = st.split('\n').filter(Boolean);
|
|
210
|
+
writeFileSync(p, lines.slice(Math.floor(lines.length / 2)).join('\n') + '\n', 'utf8');
|
|
211
|
+
}
|
|
212
|
+
} catch { /* 文件不存在 → 直接追加 */ }
|
|
213
|
+
writeFileSync(p, JSON.stringify({
|
|
214
|
+
ts: Date.now(),
|
|
215
|
+
by: String(rec.by || 'cloud'),
|
|
216
|
+
why: String(rec.why || ''),
|
|
217
|
+
model: String(rec.model || ''),
|
|
218
|
+
ms: Number(rec.ms || 0),
|
|
219
|
+
scope: String(rec.scope || ''),
|
|
220
|
+
text: String(rec.text || '').slice(0, 120),
|
|
221
|
+
reply: String(rec.reply || '').slice(0, 120),
|
|
222
|
+
}) + '\n', { encoding: 'utf8', flag: 'a' });
|
|
223
|
+
return true;
|
|
224
|
+
} catch { return false; }
|
|
225
|
+
}
|
|
226
|
+
|
|
227
|
+
/** 读最近 N 条判定(面板用;新的在后面) */
|
|
228
|
+
export function readLog(dataRoot, limit = 10) {
|
|
229
|
+
try {
|
|
230
|
+
const p = logFile(dataRoot);
|
|
231
|
+
if (!existsSync(p)) return [];
|
|
232
|
+
const lines = readFileSync(p, 'utf8').split('\n').filter(Boolean);
|
|
233
|
+
const n = Math.max(1, Math.min(200, Number(limit) || 10));
|
|
234
|
+
return lines.slice(-n).map((l) => { try { return JSON.parse(l); } catch { return null; } }).filter(Boolean);
|
|
235
|
+
} catch { return []; }
|
|
236
|
+
}
|
|
237
|
+
|
|
238
|
+
/** 带超时的 fetch(Node 自带 AbortController) */
|
|
239
|
+
async function timedFetch(url, opts = {}, timeoutMs = 6000) {
|
|
240
|
+
const ac = new AbortController();
|
|
241
|
+
const t = setTimeout(() => { try { ac.abort(); } catch { /* ignore */ } }, Math.max(500, timeoutMs));
|
|
242
|
+
try {
|
|
243
|
+
return await fetch(url, { ...opts, signal: ac.signal });
|
|
244
|
+
} finally {
|
|
245
|
+
clearTimeout(t);
|
|
246
|
+
}
|
|
247
|
+
}
|
|
248
|
+
|
|
249
|
+
// ── 健康检查(带缓存) ─────────────────────────────────────────────
|
|
250
|
+
// 缓存按 **baseUrl** 分桶(2026-10-23 修:原来只有一个全局槽,测过一个坏地址之后
|
|
251
|
+
// 好地址的检查结果会被那次的失败污染 5 秒,表现为"模型明明起着却说离线")。
|
|
252
|
+
let _health = { key: '', at: 0, ok: false, models: [], error: null };
|
|
253
|
+
|
|
254
|
+
/**
|
|
255
|
+
* 探测 Ollama 是否活着、模型是否已拉下来。
|
|
256
|
+
* @returns {{ok:boolean, models:string[], hasModel:boolean, error:string|null}}
|
|
257
|
+
*/
|
|
258
|
+
export async function health(cfg, force = false) {
|
|
259
|
+
const now = Date.now();
|
|
260
|
+
const ttl = Number(cfg && cfg.healthTtlMs) || DEFAULTS.healthTtlMs;
|
|
261
|
+
const oa = useOpenAI(cfg);
|
|
262
|
+
const key = String(urlOf(cfg, oa ? '/models' : '/api/tags'));
|
|
263
|
+
if (!force && _health.at && _health.key === key && now - _health.at < ttl) {
|
|
264
|
+
return { ..._health, hasModel: _health.models.includes(String(cfg?.model || DEFAULTS.model)) };
|
|
265
|
+
}
|
|
266
|
+
let ok = false;
|
|
267
|
+
let models = [];
|
|
268
|
+
let error = null;
|
|
269
|
+
try {
|
|
270
|
+
const res = await timedFetch(key, { method: 'GET', headers: authHeaders(cfg) }, 2500);
|
|
271
|
+
if (!res.ok) {
|
|
272
|
+
error = 'HTTP ' + res.status;
|
|
273
|
+
} else {
|
|
274
|
+
const j = await res.json();
|
|
275
|
+
models = oa
|
|
276
|
+
? (Array.isArray(j?.data) ? j.data.map((m) => String(m?.id || '')).filter(Boolean) : [])
|
|
277
|
+
: (Array.isArray(j?.models) ? j.models.map((m) => String(m?.name || '')).filter(Boolean) : []);
|
|
278
|
+
ok = true;
|
|
279
|
+
}
|
|
280
|
+
} catch (e) {
|
|
281
|
+
error = e instanceof Error ? e.message : String(e);
|
|
282
|
+
}
|
|
283
|
+
_health = { key, at: now, ok, models, error };
|
|
284
|
+
return { ok, models, error, hasModel: models.includes(String(cfg?.model || DEFAULTS.model)) };
|
|
285
|
+
}
|
|
286
|
+
|
|
287
|
+
/** 测试用:清空健康缓存 */
|
|
288
|
+
export function resetHealthCache() {
|
|
289
|
+
_health = { key: '', at: 0, ok: false, models: [], error: null };
|
|
290
|
+
}
|
|
291
|
+
|
|
292
|
+
/**
|
|
293
|
+
* 调 /api/chat(非流式)。
|
|
294
|
+
* @param {object} p
|
|
295
|
+
* @param {Array<{role:string,content:string}>} p.messages
|
|
296
|
+
* @param {object} [p.cfg]
|
|
297
|
+
* @returns {Promise<{ok:boolean, text?:string, ms?:number, model?:string, error?:string}>}
|
|
298
|
+
*/
|
|
299
|
+
export async function chat({ messages, cfg, model, timeoutMs, maxTokens, temperature, format } = {}) {
|
|
300
|
+
const c = cfg || loadConfig(dataRootOf());
|
|
301
|
+
const started = Date.now();
|
|
302
|
+
// [qqbot-mod] ollama-prefix 2026-10-27:配置里允许写 'ollama:qwen2.5:7b'(说明自己也是这么写的),
|
|
303
|
+
// 但 ollama API 不认这个前缀 —— digest 历史切片就因此 404 秒失败(10-24 后切片再没长过)。
|
|
304
|
+
// 统一在入口剥掉,写不写前缀都通。
|
|
305
|
+
const wantModel = String(model || c.model || DEFAULTS.model).replace(/^ollama:/, '');
|
|
306
|
+
// 常驻策略:默认 0(生成完即离开显存);游戏/配音期间被 pin 住才给 10m
|
|
307
|
+
ensureWatcher(() => c.residency || DEFAULTS.residency);
|
|
308
|
+
const keepAlive = keepAliveFor({ residency: { ...DEFAULTS.residency, ...(c.residency || {}) } });
|
|
309
|
+
try {
|
|
310
|
+
const oa = useOpenAI(c);
|
|
311
|
+
const msgs = Array.isArray(messages) ? messages : [];
|
|
312
|
+
const temp = typeof temperature === 'number' ? temperature : c.temperature;
|
|
313
|
+
const cap = typeof maxTokens === 'number' ? maxTokens : c.maxTokens;
|
|
314
|
+
// ★ 2026-12-02 修(本地代答"永远空回复"):Strata/qwen3.6 默认开思考,
|
|
315
|
+
// 48 token 全被 reasoning 吃掉 → content 空 → local-answer 判 'empty' 回落云端。
|
|
316
|
+
// 本机端点(127.0.0.1/localhost)一律显式关思考;云端点不加这两个字段(严格的服务会 400)。
|
|
317
|
+
const localEndpoint = /^https?:\/\/(127\.0\.0\.1|localhost|\[::1\])(:|\/)/i.test(String(c.baseUrl || ''));
|
|
318
|
+
const noThink = localEndpoint ? { enable_thinking: false, chat_template_kwargs: { enable_thinking: false } } : {};
|
|
319
|
+
// OpenAI 兼容端(Strata 8080 / vLLM / LM Studio / 中转)走 /v1/chat/completions;
|
|
320
|
+
// 老的 Ollama 路径保持原样,两边字段名不同但都只依赖 Node 自带 fetch。
|
|
321
|
+
const body = oa
|
|
322
|
+
? {
|
|
323
|
+
model: wantModel,
|
|
324
|
+
messages: msgs,
|
|
325
|
+
stream: false,
|
|
326
|
+
temperature: temp,
|
|
327
|
+
top_p: c.topP,
|
|
328
|
+
max_tokens: cap,
|
|
329
|
+
...noThink,
|
|
330
|
+
...(format === 'json' ? { response_format: { type: 'json_object' } } : {}),
|
|
331
|
+
}
|
|
332
|
+
: {
|
|
333
|
+
model: wantModel,
|
|
334
|
+
messages: msgs,
|
|
335
|
+
stream: false,
|
|
336
|
+
// ★ 2026-12-03(换默认本地模型那天踩的):qwen3 系(含 huihui abliterated)
|
|
337
|
+
// 默认先"想"一大段,48 token 全被 thinking 吃光 → content 空 → 本地代答永远
|
|
338
|
+
// 判 empty 回落云端。Ollama 认 think:false,但对 llama 系模型传它会报错,
|
|
339
|
+
// 所以只对会思考的模型开。
|
|
340
|
+
...(/qwen3|qwq|huihui|deepseek|r1/i.test(wantModel) ? { think: false } : {}),
|
|
341
|
+
// Ollama 的结构化输出:写脚本时传 'json',解析成功率明显高
|
|
342
|
+
...(format ? { format } : {}),
|
|
343
|
+
// ★ 2026-10-26:不再无条件常驻。没被 pin → '0'(显存立刻释放),
|
|
344
|
+
// 被游戏/配音 pin 住 → '10m'(多轮不冷启)。见 lib/model-policy.mjs
|
|
345
|
+
keep_alive: keepAlive,
|
|
346
|
+
options: {
|
|
347
|
+
temperature: temp,
|
|
348
|
+
top_p: c.topP,
|
|
349
|
+
top_k: 40,
|
|
350
|
+
min_p: 0.05,
|
|
351
|
+
num_predict: cap,
|
|
352
|
+
// 小模型容易发散,压低重复惩罚让它更像人说话
|
|
353
|
+
repeat_penalty: 1.15,
|
|
354
|
+
},
|
|
355
|
+
};
|
|
356
|
+
const res = await timedFetch(urlOf(c, oa ? '/chat/completions' : '/api/chat'), {
|
|
357
|
+
method: 'POST',
|
|
358
|
+
headers: { 'content-type': 'application/json', ...authHeaders(c) },
|
|
359
|
+
body: JSON.stringify(body),
|
|
360
|
+
}, typeof timeoutMs === 'number' ? timeoutMs : c.timeoutMs);
|
|
361
|
+
if (!res.ok) {
|
|
362
|
+
const hint = res.status === 404
|
|
363
|
+
? (oa ? '模型不存在(端点没这个模型: ' + wantModel + ')' : '模型不存在(需要 ollama pull ' + wantModel + ')')
|
|
364
|
+
: 'HTTP ' + res.status;
|
|
365
|
+
noteUse('chat', wantModel);
|
|
366
|
+
return { ok: false, error: hint, ms: Date.now() - started, model: wantModel };
|
|
367
|
+
}
|
|
368
|
+
const j = await res.json();
|
|
369
|
+
noteUse('chat', wantModel);
|
|
370
|
+
const text = String(oa ? (j?.choices?.[0]?.message?.content || '') : (j?.message?.content || '')).trim();
|
|
371
|
+
// 两边都回真实 token 数:Ollama 用 prompt_eval_count/eval_count,OpenAI 用 usage.*
|
|
372
|
+
const usage = oa
|
|
373
|
+
? {
|
|
374
|
+
promptTokens: Number(j?.usage?.prompt_tokens) || 0,
|
|
375
|
+
completionTokens: Number(j?.usage?.completion_tokens) || 0,
|
|
376
|
+
}
|
|
377
|
+
: {
|
|
378
|
+
promptTokens: Number(j?.prompt_eval_count) || 0,
|
|
379
|
+
completionTokens: Number(j?.eval_count) || 0,
|
|
380
|
+
};
|
|
381
|
+
if (!text) return { ok: false, error: 'empty', ms: Date.now() - started, model: wantModel, usage };
|
|
382
|
+
return { ok: true, text, ms: Date.now() - started, model: wantModel, usage };
|
|
383
|
+
} catch (e) {
|
|
384
|
+
const msg = e instanceof Error ? e.message : String(e);
|
|
385
|
+
const friendly = /abort/i.test(msg) ? 'timeout' : msg;
|
|
386
|
+
return { ok: false, error: friendly, ms: Date.now() - started, model: wantModel };
|
|
387
|
+
}
|
|
388
|
+
}
|
|
389
|
+
|
|
390
|
+
/** 一句话问答的便捷封装(单轮) */
|
|
391
|
+
export async function ask(prompt, { system, cfg, model, timeoutMs, maxTokens } = {}) {
|
|
392
|
+
const messages = [];
|
|
393
|
+
if (system) messages.push({ role: 'system', content: String(system) });
|
|
394
|
+
messages.push({ role: 'user', content: String(prompt || '') });
|
|
395
|
+
return chat({ messages, cfg, model, timeoutMs, maxTokens });
|
|
396
|
+
}
|
|
397
|
+
|
|
398
|
+
/** 预热:把模型加载进内存(避免第一条消息等 3~5 秒加载) */
|
|
399
|
+
export async function warmup(cfg, model) {
|
|
400
|
+
const started = Date.now();
|
|
401
|
+
const r = await chat({
|
|
402
|
+
messages: [{ role: 'user', content: '咕' }],
|
|
403
|
+
cfg,
|
|
404
|
+
model,
|
|
405
|
+
maxTokens: 4,
|
|
406
|
+
timeoutMs: 60000,
|
|
407
|
+
});
|
|
408
|
+
return { ok: r.ok, ms: Date.now() - started, error: r.error || null };
|
|
409
|
+
}
|
|
410
|
+
|
|
411
|
+
/**
|
|
412
|
+
* 把模型从显存里卸掉(keep_alive=0)。
|
|
413
|
+
*
|
|
414
|
+
* 为什么需要:RTX 3060 只有 6GB,qwen2.5:7b 量化占 ~5GB、sd-turbo 占 ~4GB,
|
|
415
|
+
* 两个一起挂在显存里必然 `CUDA out of memory`。
|
|
416
|
+
* 出图前先把它请出去,画完下一次对话它会自己冷启动回来(~7 秒,只付一次)。
|
|
417
|
+
*/
|
|
418
|
+
export async function unload(cfg, model) {
|
|
419
|
+
try {
|
|
420
|
+
const c = cfg || loadConfig(dataRootOf());
|
|
421
|
+
// OpenAI 兼容端没有「卸载模型」的概念(Strata/vLLM 自己管显存),直接跳过
|
|
422
|
+
if (useOpenAI(c)) return { ok: false, error: 'not-supported-by-provider' };
|
|
423
|
+
const m = String(model || c.model || '').trim();
|
|
424
|
+
if (!m) return { ok: false, error: 'no-model' };
|
|
425
|
+
const ac = new AbortController();
|
|
426
|
+
const t = setTimeout(() => ac.abort(), 4000);
|
|
427
|
+
const r = await fetch(urlOf(c, '/api/generate'), {
|
|
428
|
+
method: 'POST',
|
|
429
|
+
headers: { 'content-type': 'application/json' },
|
|
430
|
+
body: JSON.stringify({ model: m, keep_alive: 0 }),
|
|
431
|
+
signal: ac.signal,
|
|
432
|
+
});
|
|
433
|
+
clearTimeout(t);
|
|
434
|
+
return { ok: r.ok };
|
|
435
|
+
} catch (e) {
|
|
436
|
+
return { ok: false, error: e instanceof Error ? e.message : String(e) };
|
|
437
|
+
}
|
|
438
|
+
}
|
|
439
|
+
|
|
440
|
+
/** 状态汇总(给面板/脚本用) */
|
|
441
|
+
export async function status(cfg, force = false) {
|
|
442
|
+
const c = cfg || loadConfig(dataRootOf());
|
|
443
|
+
const h = await health(c, force);
|
|
444
|
+
return {
|
|
445
|
+
enabled: c.enabled !== false,
|
|
446
|
+
baseUrl: c.baseUrl,
|
|
447
|
+
model: c.model,
|
|
448
|
+
timeoutMs: c.timeoutMs,
|
|
449
|
+
serverUp: h.ok,
|
|
450
|
+
models: h.models,
|
|
451
|
+
hasModel: h.hasModel,
|
|
452
|
+
error: h.error,
|
|
453
|
+
residency: await policySnapshot(c.baseUrl),
|
|
454
|
+
};
|
|
455
|
+
}
|