dsh-nvidia-models-panel 1.3.22 → 1.3.24
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/LICENSE +21 -21
- package/README.md +104 -104
- package/package.json +51 -51
- package/src/client.js +1261 -1222
- package/src/group.js +652 -652
- package/src/index.js +1253 -1253
- package/src/usage.js +285 -285
package/src/group.js
CHANGED
|
@@ -1,652 +1,652 @@
|
|
|
1
|
-
/**
|
|
2
|
-
* NVIDIA 模型组:自愈式故障转移引擎(纯逻辑,无 DSH / 无外部依赖)。
|
|
3
|
-
*
|
|
4
|
-
* 设计要点
|
|
5
|
-
* - 组内成员按健康度排序:首选模型优先 → 未冷却优先 → 失败次数少优先 → 首包快优先 → 配置顺序。
|
|
6
|
-
* - 熔断:连续失败达到阈值即进入冷却(指数退避,封顶),冷却期内直接跳过。
|
|
7
|
-
* - 流式转移只在“尚未产出任何内容”时发生;一旦已向用户吐出文本/推理/工具增量,
|
|
8
|
-
* 就不再做无痕切换(避免内容重复),而是如实返回错误。
|
|
9
|
-
* - 全部成员失败时产出合成错误 finish,交给上层(dsh-llm-retry / 会话投影)处理。
|
|
10
|
-
*
|
|
11
|
-
* 所有对外函数只依赖注入进来的 deps,便于脱离 DSH 用 node --test 单测。
|
|
12
|
-
*/
|
|
13
|
-
|
|
14
|
-
/** 虚拟「自动」成员的模型 id:不指定首选,纯按实时健康排序。 */
|
|
15
|
-
export const AUTO_MEMBER_ID = '__auto__';
|
|
16
|
-
/** 「自动」成员的展示名 / 描述。 */
|
|
17
|
-
export const AUTO_MEMBER_NAME = 'NVIDIA 模型组(自动)';
|
|
18
|
-
export const AUTO_MEMBER_DESC = '自动选择并故障转移,无需指定首选模型';
|
|
19
|
-
|
|
20
|
-
/** 判断一个模型 id 是否为「自动」虚拟成员。 */
|
|
21
|
-
export function isAutoMemberId(id) {
|
|
22
|
-
return id === AUTO_MEMBER_ID || id === 'auto';
|
|
23
|
-
}
|
|
24
|
-
|
|
25
|
-
/**
|
|
26
|
-
* 该失败是否只是「这个成员吃不消这轮请求」(例如上下文窗口不够),
|
|
27
|
-
* 而非「该模型不可用」。这类失败应当直接换下一个成员,
|
|
28
|
-
* 且不计入熔断(模型本身是好的,只是不适合这次请求)。
|
|
29
|
-
*/
|
|
30
|
-
/**
|
|
31
|
-
* 致命失败:对所有组员都一样,换模型也不会好转,因此应立即停止故障转移。
|
|
32
|
-
* 目前仅「缺 API Key / 凭据失效」属于此类。
|
|
33
|
-
*/
|
|
34
|
-
export function isFatalFailure(failure) {
|
|
35
|
-
return Boolean(failure && typeof failure === 'object' && failure.code === 'NO_API_KEY');
|
|
36
|
-
}
|
|
37
|
-
|
|
38
|
-
export function isCapabilityMismatch(failure) {
|
|
39
|
-
if (!failure || typeof failure !== 'object') return false;
|
|
40
|
-
if (failure.code === 'CONTEXT_WINDOW_EXCEEDED' || failure.code === 'MODEL_SWITCH_COMPACTION_FAILED' || failure.code === 'INVALID_REQUEST') {
|
|
41
|
-
return true; // 400 类「这次请求该模型吃不下」——换下一个即可,不熔断
|
|
42
|
-
}
|
|
43
|
-
// 上游把「多模态未启用 / 不支持图片」报成 400,也归到这一类。
|
|
44
|
-
const msg = String(failure.message || '');
|
|
45
|
-
return /multimodal|not enabled|invalid.?request|does not support image/i.test(msg);
|
|
46
|
-
}
|
|
47
|
-
|
|
48
|
-
/** 判定一个流块是否为错误/取消的 finish。 */
|
|
49
|
-
export function isErrorFinish(chunk) {
|
|
50
|
-
return Boolean(
|
|
51
|
-
chunk && chunk.type === 'finish' && chunk.reason &&
|
|
52
|
-
(chunk.reason.kind === 'error' || chunk.reason.kind === 'aborted'),
|
|
53
|
-
);
|
|
54
|
-
}
|
|
55
|
-
|
|
56
|
-
/** 判定一个流块是否携带“用户可见内容”(用于决定能否无痕转移)。 */
|
|
57
|
-
export function isContentChunk(chunk) {
|
|
58
|
-
return Boolean(
|
|
59
|
-
chunk && (chunk.type === 'text-delta' || chunk.type === 'reasoning-delta' || chunk.type === 'tool-call-delta') &&
|
|
60
|
-
chunk.text !== '' && chunk.argumentsDelta !== '',
|
|
61
|
-
);
|
|
62
|
-
}
|
|
63
|
-
|
|
64
|
-
/**
|
|
65
|
-
* 判定一个流块是否为“真正的回答产出”(用户可见的正文或工具调用)。
|
|
66
|
-
* 注意:reasoning-delta(思考过程)**不算**——模型可能把整个输出预算烧在思考上、
|
|
67
|
-
* 一个字的回答都没给出,这种情况必须能和“已给出部分回答”区分开。
|
|
68
|
-
*/
|
|
69
|
-
export function isVisibleOutputChunk(chunk) {
|
|
70
|
-
if (!chunk) return false;
|
|
71
|
-
if (chunk.type === 'text-delta') return typeof chunk.text === 'string' && chunk.text !== '';
|
|
72
|
-
if (chunk.type === 'tool-call-delta') {
|
|
73
|
-
return (typeof chunk.argumentsDelta === 'string' && chunk.argumentsDelta !== '') || Boolean(chunk.name);
|
|
74
|
-
}
|
|
75
|
-
return false;
|
|
76
|
-
}
|
|
77
|
-
|
|
78
|
-
/**
|
|
79
|
-
* 是否属于“重推理 / 思考型”模型。这类模型面对复杂任务时可能长时间只输出思考内容,
|
|
80
|
-
* 在“自动”模式下应排到普通模型之后,避免整轮对话被它的思考拖死。
|
|
81
|
-
*/
|
|
82
|
-
export function isReasoningModel(id) {
|
|
83
|
-
return /reasoning|thinking|omni|debate/i.test(String(id || ''));
|
|
84
|
-
}
|
|
85
|
-
|
|
86
|
-
/**
|
|
87
|
-
* 健康登记表 + 熔断器。默认:连续 2 次失败即冷却 20s,按 2^k 退避,封顶 5 分钟。
|
|
88
|
-
* @param {{baseCooldownMs?:number,maxCooldownMs?:number,failThreshold?:number,now?:()=>number}} [opts]
|
|
89
|
-
*/
|
|
90
|
-
export function createHealthRegistry(opts) {
|
|
91
|
-
const o = opts || {};
|
|
92
|
-
const baseCooldownMs = Number.isFinite(o.baseCooldownMs) ? o.baseCooldownMs : 20000;
|
|
93
|
-
const maxCooldownMs = Number.isFinite(o.maxCooldownMs) ? o.maxCooldownMs : 300000;
|
|
94
|
-
const failThreshold = Number.isFinite(o.failThreshold) ? o.failThreshold : 2;
|
|
95
|
-
const now = typeof o.now === 'function' ? o.now : () => Date.now();
|
|
96
|
-
const map = new Map();
|
|
97
|
-
|
|
98
|
-
function entry(id) {
|
|
99
|
-
let e = map.get(id);
|
|
100
|
-
if (!e) {
|
|
101
|
-
e = {
|
|
102
|
-
id,
|
|
103
|
-
ok: null,
|
|
104
|
-
failCount: 0,
|
|
105
|
-
successCount: 0,
|
|
106
|
-
lastError: '',
|
|
107
|
-
cooldownUntil: 0,
|
|
108
|
-
lastFirstByteMs: null,
|
|
109
|
-
lastProbeAt: null,
|
|
110
|
-
lastChangeAt: now(),
|
|
111
|
-
};
|
|
112
|
-
map.set(id, e);
|
|
113
|
-
}
|
|
114
|
-
return e;
|
|
115
|
-
}
|
|
116
|
-
|
|
117
|
-
return {
|
|
118
|
-
/** 只读快照(拷贝),用于渲染看板。 */
|
|
119
|
-
get(id) { return { ...entry(id) }; },
|
|
120
|
-
snapshot(ids) {
|
|
121
|
-
const keys = Array.isArray(ids) ? ids : [...map.keys()];
|
|
122
|
-
const out = {};
|
|
123
|
-
for (const id of keys) out[id] = this.get(id);
|
|
124
|
-
return out;
|
|
125
|
-
},
|
|
126
|
-
isCoolingDown(id) { return entry(id).cooldownUntil > now(); },
|
|
127
|
-
cooldownRemainingMs(id) { return Math.max(0, entry(id).cooldownUntil - now()); },
|
|
128
|
-
recordProbeStart(id) { const e = entry(id); e.lastProbeAt = now(); return { ...e }; },
|
|
129
|
-
recordSuccess(id, firstByteMs) {
|
|
130
|
-
const e = entry(id);
|
|
131
|
-
e.ok = true;
|
|
132
|
-
e.failCount = 0;
|
|
133
|
-
e.successCount += 1;
|
|
134
|
-
e.lastError = '';
|
|
135
|
-
e.cooldownUntil = 0;
|
|
136
|
-
if (typeof firstByteMs === 'number' && firstByteMs >= 0) e.lastFirstByteMs = Math.round(firstByteMs);
|
|
137
|
-
e.lastChangeAt = now();
|
|
138
|
-
return { ...e };
|
|
139
|
-
},
|
|
140
|
-
recordFailure(id, error) {
|
|
141
|
-
const e = entry(id);
|
|
142
|
-
e.ok = false;
|
|
143
|
-
e.failCount += 1;
|
|
144
|
-
e.lastError = describeError(error).slice(0, 240);
|
|
145
|
-
e.lastChangeAt = now();
|
|
146
|
-
if (e.failCount >= failThreshold) {
|
|
147
|
-
const k = e.failCount - failThreshold;
|
|
148
|
-
const backoff = Math.min(maxCooldownMs, baseCooldownMs * Math.pow(2, k));
|
|
149
|
-
e.cooldownUntil = now() + backoff;
|
|
150
|
-
}
|
|
151
|
-
return { ...e };
|
|
152
|
-
},
|
|
153
|
-
reset(id) {
|
|
154
|
-
if (id === undefined) map.clear();
|
|
155
|
-
else map.delete(id);
|
|
156
|
-
},
|
|
157
|
-
};
|
|
158
|
-
}
|
|
159
|
-
|
|
160
|
-
/** 把任意错误对象压成一句人类可读文本。 */
|
|
161
|
-
export function describeError(error) {
|
|
162
|
-
if (!error) return 'unknown error';
|
|
163
|
-
if (typeof error === 'string') return error;
|
|
164
|
-
if (error.message) return String(error.message);
|
|
165
|
-
if (error.code) return String(error.code);
|
|
166
|
-
try { return JSON.stringify(error); } catch { return String(error); }
|
|
167
|
-
}
|
|
168
|
-
|
|
169
|
-
/**
|
|
170
|
-
* 组内成员排序:preferredId 优先;其次未冷却;再次失败少、首包快、配置顺序。
|
|
171
|
-
* 当没有指定首选(“自动”模式)时,思考型/重推理模型整体排在普通模型之后 —— 它们
|
|
172
|
-
* 更容易把输出预算耗在思考上、迟迟不给正文,不适合作为默认首选。
|
|
173
|
-
* @param {Array<{id:string}>} members
|
|
174
|
-
* @param {any} health createHealthRegistry() 的实例(可空)
|
|
175
|
-
* @param {string} [preferredId]
|
|
176
|
-
* @param {()=>number} [clock]
|
|
177
|
-
*/
|
|
178
|
-
export function rankMembers(members, health, preferredId, clock) {
|
|
179
|
-
const nowFn = typeof clock === 'function' ? clock : () => Date.now();
|
|
180
|
-
const list = Array.isArray(members) ? members : [];
|
|
181
|
-
const scored = list.map((m, index) => {
|
|
182
|
-
const h = health && typeof health.get === 'function' ? health.get(m.id) : null;
|
|
183
|
-
const coolingDown = Boolean(h && h.cooldownUntil > nowFn());
|
|
184
|
-
const reasoning = !preferredId && isReasoningModel(m && m.id);
|
|
185
|
-
return { m, index, h, coolingDown, reasoning };
|
|
186
|
-
});
|
|
187
|
-
scored.sort((a, b) => {
|
|
188
|
-
if (preferredId) {
|
|
189
|
-
if (a.m.id === preferredId && b.m.id !== preferredId) return -1;
|
|
190
|
-
if (b.m.id === preferredId && a.m.id !== preferredId) return 1;
|
|
191
|
-
}
|
|
192
|
-
if (a.coolingDown !== b.coolingDown) return a.coolingDown ? 1 : -1;
|
|
193
|
-
if (a.reasoning !== b.reasoning) return a.reasoning ? 1 : -1;
|
|
194
|
-
const af = a.h ? a.h.failCount : 0;
|
|
195
|
-
const bf = b.h ? b.h.failCount : 0;
|
|
196
|
-
if (af !== bf) return af - bf;
|
|
197
|
-
const as = a.h && typeof a.h.lastFirstByteMs === 'number' ? a.h.lastFirstByteMs : Infinity;
|
|
198
|
-
const bs = b.h && typeof b.h.lastFirstByteMs === 'number' ? b.h.lastFirstByteMs : Infinity;
|
|
199
|
-
if (as !== bs) return as - bs;
|
|
200
|
-
return a.index - b.index;
|
|
201
|
-
});
|
|
202
|
-
return scored.map((s) => s.m);
|
|
203
|
-
}
|
|
204
|
-
|
|
205
|
-
/** 把父级 AbortSignal 链接到子控制器;返回解绑函数。 */
|
|
206
|
-
function linkSignal(parent, child) {
|
|
207
|
-
if (!parent || typeof child !== 'object') return () => {};
|
|
208
|
-
if (parent.aborted) { try { child.abort(); } catch { /* 已中止 */ } return () => {}; }
|
|
209
|
-
if (typeof parent.addEventListener === 'function') {
|
|
210
|
-
const onAbort = () => { try { child.abort(); } catch { /* 已中止 */ } };
|
|
211
|
-
parent.addEventListener('abort', onAbort, { once: true });
|
|
212
|
-
return () => { try { parent.removeEventListener('abort', onAbort); } catch { /* 忽略 */ } };
|
|
213
|
-
}
|
|
214
|
-
return () => {};
|
|
215
|
-
}
|
|
216
|
-
|
|
217
|
-
/**
|
|
218
|
-
* 故障转移主循环:依次尝试组内成员,直到某个成员产出非错误 finish。
|
|
219
|
-
* 每个成员都有「首包看门狗」:在 firstByteTimeoutMs 内一个字节都没到,就中止并切下一个,
|
|
220
|
-
* 从而把用户看到的“30 秒卡死”变成有界、快速的自动切换。
|
|
221
|
-
* @param {object} options GenerateOptions(含 provider/model/messages/signal/sessionId 等)
|
|
222
|
-
* @param {{
|
|
223
|
-
* streamChild:(childOptions:object)=>AsyncIterable<any>,
|
|
224
|
-
* health?:any,
|
|
225
|
-
* candidates:Array<{id:string,name?:string}>,
|
|
226
|
-
* childProvider?:string,
|
|
227
|
-
* skipCooling?:boolean,
|
|
228
|
-
* firstByteTimeoutMs?:number,
|
|
229
|
-
* onAttempt?:(info:{member:any,error:any,emitted:boolean,sessionId?:string})=>void,
|
|
230
|
-
* onFailover?:(info:{from:any,to?:any,error:any,sessionId?:string,exhausted?:boolean})=>void,
|
|
231
|
-
* }} deps
|
|
232
|
-
*/
|
|
233
|
-
export async function* runFailover(options, deps) {
|
|
234
|
-
const parentSignal = options && options.signal;
|
|
235
|
-
const health = deps.health;
|
|
236
|
-
const sessionId = options && options.sessionId;
|
|
237
|
-
const skipCooling = Boolean(deps.skipCooling);
|
|
238
|
-
const rawFirstByteTimeout = typeof deps.firstByteTimeoutMs === 'function' ? deps.firstByteTimeoutMs() : deps.firstByteTimeoutMs;
|
|
239
|
-
const firstByteTimeoutMs = Number.isFinite(rawFirstByteTimeout) ? rawFirstByteTimeout : 15000;
|
|
240
|
-
const rawFirstTextTimeout = typeof deps.firstTextTimeoutMs === 'function' ? deps.firstTextTimeoutMs() : deps.firstTextTimeoutMs;
|
|
241
|
-
const firstTextTimeoutMs = Number.isFinite(rawFirstTextTimeout) ? rawFirstTextTimeout : 30000;
|
|
242
|
-
// 「自动」模式(选中虚拟 AUTO 成员)不指定真实首选:preferredId 置空,才会走纯健康排序
|
|
243
|
-
// 并把思考型模型排到后面。否则 '__auto__' 作为真值会误导排序。
|
|
244
|
-
const rawPreferred = options && options.model;
|
|
245
|
-
const preferredForRank = isAutoMemberId(rawPreferred) ? '' : rawPreferred;
|
|
246
|
-
const order = rankMembers(deps.candidates, health, preferredForRank);
|
|
247
|
-
|
|
248
|
-
// 两轮尝试:
|
|
249
|
-
// 第 1 轮 —— 只试「未冷却」的成员(正常路径)。
|
|
250
|
-
// 第 2 轮 —— 若第 1 轮确实试过成员、却没有任何可见正文产出,就把「冷却中」的成员
|
|
251
|
-
// 也当最后手段补试一遍。这样即便大部分成员因首包超时被熔断、只剩一个
|
|
252
|
-
// 「只思考不出正文」的成员,也不会把空回答直接甩给用户。
|
|
253
|
-
const totalRounds = skipCooling ? 1 : 2;
|
|
254
|
-
const tried = new Set();
|
|
255
|
-
let attempted = 0;
|
|
256
|
-
let lastFailure = null;
|
|
257
|
-
let lastTriedMember = null;
|
|
258
|
-
let prevMemberId = '';
|
|
259
|
-
|
|
260
|
-
for (let round = 0; round < totalRounds; round += 1) {
|
|
261
|
-
const includeCooling = round === 1;
|
|
262
|
-
if (includeCooling && attempted === 0) break; // 第 1 轮一个都没试,谈不上“兜底重试”
|
|
263
|
-
|
|
264
|
-
for (const member of order) {
|
|
265
|
-
if (parentSignal && parentSignal.aborted) {
|
|
266
|
-
yield { type: 'finish', reason: { kind: 'aborted', failure: { code: 'ABORTED', message: '请求已取消' } } };
|
|
267
|
-
return;
|
|
268
|
-
}
|
|
269
|
-
if (tried.has(member.id)) continue;
|
|
270
|
-
const cooling = Boolean(health && typeof health.isCoolingDown === 'function' && health.isCoolingDown(member.id));
|
|
271
|
-
if (includeCooling ? !cooling : cooling) continue;
|
|
272
|
-
|
|
273
|
-
attempted += 1;
|
|
274
|
-
tried.add(member.id);
|
|
275
|
-
const wasFailover = attempted > 1;
|
|
276
|
-
const failoverFrom = wasFailover ? prevMemberId : '';
|
|
277
|
-
prevMemberId = member.id;
|
|
278
|
-
lastTriedMember = member;
|
|
279
|
-
const controller = new AbortController();
|
|
280
|
-
const unlink = linkSignal(parentSignal, controller);
|
|
281
|
-
let gotFirstByte = false;
|
|
282
|
-
let timedOut = false;
|
|
283
|
-
let textTimedOut = false;
|
|
284
|
-
const timer = firstByteTimeoutMs > 0
|
|
285
|
-
? setTimeout(() => { if (!gotFirstByte) { timedOut = true; try { controller.abort(); } catch { /* 忽略 */ } } }, firstByteTimeoutMs)
|
|
286
|
-
: null;
|
|
287
|
-
// 「首段可见正文」看门狗:模型可能首字节很快(吐思考),却长时间产不出任何正文,
|
|
288
|
-
// 把整个输出预算全烧在 reasoning 上。超过 firstTextTimeoutMs 仍无正文就中止并切换,
|
|
289
|
-
// 无论后面还有没有备份成员都要生效 —— 否则用户会干等好几分钟才看到“输出 token 上限”。
|
|
290
|
-
let textTimer = null;
|
|
291
|
-
let emitted = false; // 是否已向用户吐出过可见正文(一旦为真就不再无痕切换)
|
|
292
|
-
let failure = null;
|
|
293
|
-
let firstByteMs = 0;
|
|
294
|
-
let lastUsage = null;
|
|
295
|
-
let sawFinish = null;
|
|
296
|
-
// 在产出第一段「可见正文」之前,先把块缓存起来:若该成员最终只有思考、没有正文,
|
|
297
|
-
// 就能整段丢弃、静默切换,用户不会看到半截思考或空回答。
|
|
298
|
-
const buffer = [];
|
|
299
|
-
const childOptions = { ...options, provider: deps.childProvider || 'nvidia', model: member.id, signal: controller.signal };
|
|
300
|
-
const startedAt = Date.now();
|
|
301
|
-
|
|
302
|
-
try {
|
|
303
|
-
for await (const chunk of deps.streamChild(childOptions)) {
|
|
304
|
-
if (!gotFirstByte) {
|
|
305
|
-
gotFirstByte = true;
|
|
306
|
-
firstByteMs = Date.now() - startedAt;
|
|
307
|
-
if (timer) clearTimeout(timer);
|
|
308
|
-
if (firstTextTimeoutMs > 0) {
|
|
309
|
-
textTimer = setTimeout(() => { if (!emitted) { textTimedOut = true; try { controller.abort(); } catch { /* 忽略 */ } } }, firstTextTimeoutMs);
|
|
310
|
-
}
|
|
311
|
-
}
|
|
312
|
-
if (isErrorFinish(chunk)) {
|
|
313
|
-
failure = (chunk.reason && chunk.reason.failure) || { code: 'MEMBER_ERROR', message: '模型返回错误' };
|
|
314
|
-
break;
|
|
315
|
-
}
|
|
316
|
-
if (chunk && chunk.type === 'usage' && chunk.usage) lastUsage = chunk.usage;
|
|
317
|
-
if (chunk && chunk.type === 'finish') sawFinish = chunk;
|
|
318
|
-
|
|
319
|
-
if (!emitted) {
|
|
320
|
-
if (isVisibleOutputChunk(chunk)) {
|
|
321
|
-
// 第一段正文到达:把之前缓存的块按顺序补发,然后转入实时直通。
|
|
322
|
-
emitted = true;
|
|
323
|
-
if (textTimer) { clearTimeout(textTimer); textTimer = null; }
|
|
324
|
-
for (const b of buffer) yield b;
|
|
325
|
-
buffer.length = 0;
|
|
326
|
-
yield chunk;
|
|
327
|
-
} else {
|
|
328
|
-
buffer.push(chunk);
|
|
329
|
-
}
|
|
330
|
-
} else {
|
|
331
|
-
yield chunk;
|
|
332
|
-
}
|
|
333
|
-
if (sawFinish) break;
|
|
334
|
-
}
|
|
335
|
-
} catch (error) {
|
|
336
|
-
failure = timedOut
|
|
337
|
-
? { code: 'FIRST_BYTE_TIMEOUT', message: '首包超时(' + firstByteTimeoutMs + 'ms 内无响应),已自动切换' }
|
|
338
|
-
: { code: 'MEMBER_THROW', message: describeError(error) };
|
|
339
|
-
} finally {
|
|
340
|
-
if (timer) clearTimeout(timer);
|
|
341
|
-
if (textTimer) clearTimeout(textTimer);
|
|
342
|
-
unlink();
|
|
343
|
-
}
|
|
344
|
-
|
|
345
|
-
// 看门狗主动中止时,子流往往报成 “network aborted”,诊断信息不清晰;
|
|
346
|
-
// 这里以看门狗为准,统一记为「首包超时 / 首段正文超时」,原始错误码留在 cause 里。
|
|
347
|
-
if (timedOut) {
|
|
348
|
-
failure = {
|
|
349
|
-
code: 'FIRST_BYTE_TIMEOUT',
|
|
350
|
-
message: '首包超时(' + firstByteTimeoutMs + 'ms 内无响应),已自动切换',
|
|
351
|
-
cause: failure || undefined,
|
|
352
|
-
};
|
|
353
|
-
} else if (textTimedOut && !emitted) {
|
|
354
|
-
failure = {
|
|
355
|
-
code: 'FIRST_TEXT_TIMEOUT',
|
|
356
|
-
message: '首段正文超时(' + firstTextTimeoutMs + 'ms 内无输出正文),已自动切换',
|
|
357
|
-
cause: failure || undefined,
|
|
358
|
-
};
|
|
359
|
-
}
|
|
360
|
-
|
|
361
|
-
// 没有产出任何可见正文(典型是“把输出预算全烧在思考上、正文为空”)——
|
|
362
|
-
// 无论后面还有没有备份成员,都判为 EMPTY_ANSWER:绝不能把空的/纯思考的结果
|
|
363
|
-
// 静默当成正常回答交给用户(那正是“没有输出内容 + 已达到输出 token 上限”的成因)。
|
|
364
|
-
if (!emitted && !failure) {
|
|
365
|
-
const inner = (sawFinish && sawFinish.reason) || null;
|
|
366
|
-
const reasonNote = inner && inner.kind === 'max-tokens' ? '(输出预算耗尽在思考内容上,未产出正文)' : '(未产出任何正文)';
|
|
367
|
-
failure = {
|
|
368
|
-
code: 'EMPTY_ANSWER',
|
|
369
|
-
message: '模型未产出正文' + reasonNote + ',已自动切换',
|
|
370
|
-
};
|
|
371
|
-
}
|
|
372
|
-
|
|
373
|
-
if (!failure) {
|
|
374
|
-
// 走到这里一定已经产出过可见正文(否则上面已判 EMPTY_ANSWER)。
|
|
375
|
-
if (health && typeof health.recordSuccess === 'function') health.recordSuccess(member.id, firstByteMs);
|
|
376
|
-
if (typeof deps.onAttempt === 'function') {
|
|
377
|
-
try { deps.onAttempt({ member, error: null, emitted, sessionId, firstByteMs, elapsedMs: Date.now() - startedAt, usage: lastUsage, failover: wasFailover, failoverFrom }); } catch { /* 观测失败不影响主流程 */ }
|
|
378
|
-
}
|
|
379
|
-
if (!sawFinish) yield { type: 'finish', reason: { kind: 'stop' } };
|
|
380
|
-
return;
|
|
381
|
-
}
|
|
382
|
-
|
|
383
|
-
lastFailure = failure;
|
|
384
|
-
// 致命错误(如缺 API Key):对所有成员都一样,换模型无用——立即停止,如实把友好提示交给用户。
|
|
385
|
-
if (isFatalFailure(failure)) {
|
|
386
|
-
if (typeof deps.onAttempt === 'function') {
|
|
387
|
-
try { deps.onAttempt({ member, error: failure, emitted, sessionId, firstByteMs, elapsedMs: Date.now() - startedAt, usage: null, fatal: true }); } catch { /* 忽略 */ }
|
|
388
|
-
}
|
|
389
|
-
yield { type: 'finish', reason: { kind: 'error', failure: toFailure(failure) } };
|
|
390
|
-
return;
|
|
391
|
-
}
|
|
392
|
-
// 「能力不符 / 空回答 / 首段正文超时」不是模型“坏了”,而是这次请求不称职:不记熔断,直接换下一个成员。
|
|
393
|
-
const capability = isCapabilityMismatch(failure) || failure.code === 'EMPTY_ANSWER' || failure.code === 'FIRST_TEXT_TIMEOUT';
|
|
394
|
-
if (!capability && health && typeof health.recordFailure === 'function') health.recordFailure(member.id, failure);
|
|
395
|
-
if (typeof deps.onAttempt === 'function') {
|
|
396
|
-
try { deps.onAttempt({ member, error: failure, emitted, sessionId, firstByteMs, elapsedMs: Date.now() - startedAt, usage: null, failover: wasFailover, failoverFrom, capability }); } catch { /* 观测失败不影响主流程 */ }
|
|
397
|
-
}
|
|
398
|
-
|
|
399
|
-
if (emitted) {
|
|
400
|
-
// 已向用户产出内容,无法无痕切换,如实返回错误。
|
|
401
|
-
yield { type: 'finish', reason: { kind: 'error', failure: toFailure(lastFailure) } };
|
|
402
|
-
return;
|
|
403
|
-
}
|
|
404
|
-
if (typeof deps.onFailover === 'function') {
|
|
405
|
-
try { deps.onFailover({ from: member, to: null, error: failure, sessionId, capability, exhausted: false }); } catch { /* 忽略 */ }
|
|
406
|
-
}
|
|
407
|
-
}
|
|
408
|
-
}
|
|
409
|
-
|
|
410
|
-
if (attempted === 0) {
|
|
411
|
-
yield {
|
|
412
|
-
type: 'finish',
|
|
413
|
-
reason: { kind: 'error', failure: { code: 'ALL_MEMBERS_COOLING', message: '模型组内所有模型都在熔断冷却中,请稍后重试或手动探测恢复' } },
|
|
414
|
-
};
|
|
415
|
-
return;
|
|
416
|
-
}
|
|
417
|
-
const finalFailure = toFailure(lastFailure || { code: 'ALL_MEMBERS_FAILED', message: '模型组内所有模型均调用失败' });
|
|
418
|
-
if (lastFailure && lastFailure.code === 'EMPTY_ANSWER') {
|
|
419
|
-
// 最后一个失败是“只思考没正文”:给出明确、可操作的提示,而不是含糊的“模型组均失败”。
|
|
420
|
-
finalFailure.code = 'EMPTY_ANSWER';
|
|
421
|
-
finalFailure.message = '组内所有模型都没有产出正文(重推理模型把输出预算耗在思考上),请重试、增大 maxTokens 或改用非推理模型';
|
|
422
|
-
}
|
|
423
|
-
if (typeof deps.onFailover === 'function') {
|
|
424
|
-
try { deps.onFailover({ from: lastTriedMember, to: null, error: finalFailure, sessionId, exhausted: true }); } catch { /* 忽略 */ }
|
|
425
|
-
}
|
|
426
|
-
yield { type: 'finish', reason: { kind: 'error', failure: finalFailure } };
|
|
427
|
-
}
|
|
428
|
-
|
|
429
|
-
function toFailure(failure) {
|
|
430
|
-
const message = describeError(failure);
|
|
431
|
-
const code = (failure && failure.code) || 'ALL_MEMBERS_FAILED';
|
|
432
|
-
return { code, message };
|
|
433
|
-
}
|
|
434
|
-
|
|
435
|
-
/** 判断一次请求是否含有图片输入(据此只路由到多模态成员)。 */
|
|
436
|
-
export function requestHasImage(options) {
|
|
437
|
-
const messages = (options && options.messages) || [];
|
|
438
|
-
for (const msg of messages) {
|
|
439
|
-
const content = msg && msg.content;
|
|
440
|
-
if (!content) continue;
|
|
441
|
-
if (Array.isArray(content)) {
|
|
442
|
-
for (const part of content) {
|
|
443
|
-
if (part && (part.type === 'image' || part.type === 'image-url' || part.type === 'input-image')) return true;
|
|
444
|
-
}
|
|
445
|
-
}
|
|
446
|
-
}
|
|
447
|
-
return false;
|
|
448
|
-
}
|
|
449
|
-
|
|
450
|
-
/** 成员是否具备视觉/图片输入能力。 */
|
|
451
|
-
export function memberSupportsImage(member) {
|
|
452
|
-
const mods = (member && member.inputModalities) || [];
|
|
453
|
-
if (mods.includes('image')) return true;
|
|
454
|
-
// 防御:未标注模态时按 id 名称兜底推断。
|
|
455
|
-
return /vision|vl\b|omni|diffusion|image/i.test(String((member && member.id) || ''));
|
|
456
|
-
}
|
|
457
|
-
|
|
458
|
-
/**
|
|
459
|
-
* 构造一个 DSH LlmAdapter 形态的“模型组”适配器。deps 全部注入,便于测试。
|
|
460
|
-
* @param {{
|
|
461
|
-
* groupId?:string, groupName?:string,
|
|
462
|
-
* getMembers:()=>Promise<Array<{id:string,name?:string,description?:string,inputModalities?:string[]}>>,
|
|
463
|
-
* streamChild:(childOptions:object)=>AsyncIterable<any>,
|
|
464
|
-
* health:any, childProvider?:string, firstByteTimeoutMs?:number,
|
|
465
|
-
* onAttempt?:Function, onFailover?:Function,
|
|
466
|
-
* }} deps
|
|
467
|
-
*/
|
|
468
|
-
export function createGroupAdapter(deps) {
|
|
469
|
-
const groupName = deps.groupName || 'NVIDIA 模型组';
|
|
470
|
-
const getMembers = deps.getMembers;
|
|
471
|
-
const adapter = {
|
|
472
|
-
providerInfo(provider) { return { id: provider, name: groupName }; },
|
|
473
|
-
providerRetryPolicy() { return undefined; },
|
|
474
|
-
async listModels(provider) {
|
|
475
|
-
const members = await getMembers();
|
|
476
|
-
// 虚拟「自动」成员放在第一位:用户选择它即表示「不指定首选、纯按实时健康排序」。
|
|
477
|
-
const auto = { provider, id: AUTO_MEMBER_ID, name: AUTO_MEMBER_NAME, description: AUTO_MEMBER_DESC };
|
|
478
|
-
return [auto, ...members.map((m) => {
|
|
479
|
-
const out = { provider, id: m.id, name: m.name || m.id };
|
|
480
|
-
if (m.description) out.description = m.description;
|
|
481
|
-
if (Array.isArray(m.inputModalities) && m.inputModalities.length) out.inputModalities = m.inputModalities;
|
|
482
|
-
return out;
|
|
483
|
-
})];
|
|
484
|
-
},
|
|
485
|
-
async resolveModel(provider, model) {
|
|
486
|
-
const members = await getMembers();
|
|
487
|
-
if (isAutoMemberId(model)) {
|
|
488
|
-
// 「自动」是个虚拟成员:取组内上报的最大上下文窗口,绝不虚假声明成 128K
|
|
489
|
-
// (声明过小会让 pi-ai 在本会话这种长上下文下误判为溢出)。
|
|
490
|
-
let maxCtx = 0;
|
|
491
|
-
for (const m of members) {
|
|
492
|
-
if (Number.isFinite(m.contextWindow) && m.contextWindow > maxCtx) maxCtx = m.contextWindow;
|
|
493
|
-
}
|
|
494
|
-
const autoCtx = maxCtx > 0 ? maxCtx : 1048576;
|
|
495
|
-
return {
|
|
496
|
-
provider,
|
|
497
|
-
id: model,
|
|
498
|
-
name: AUTO_MEMBER_NAME,
|
|
499
|
-
description: AUTO_MEMBER_DESC,
|
|
500
|
-
context: { contextWindow: autoCtx },
|
|
501
|
-
defaultMaxTokens: 8192,
|
|
502
|
-
};
|
|
503
|
-
}
|
|
504
|
-
const hit = members.find((m) => m.id === model) || {};
|
|
505
|
-
const info = { provider, id: model, name: hit.name || model };
|
|
506
|
-
if (hit.description) info.description = hit.description;
|
|
507
|
-
if (Array.isArray(hit.inputModalities) && hit.inputModalities.length) info.inputModalities = hit.inputModalities;
|
|
508
|
-
if (Number.isFinite(hit.contextWindow) && hit.contextWindow > 0) info.context = { contextWindow: Math.round(hit.contextWindow) };
|
|
509
|
-
if (Number.isFinite(hit.maxTokens) && hit.maxTokens > 0) info.defaultMaxTokens = Math.round(hit.maxTokens);
|
|
510
|
-
return info;
|
|
511
|
-
},
|
|
512
|
-
async prepareCall(provider, model) {
|
|
513
|
-
const resolved = await adapter.resolveModel(provider, model);
|
|
514
|
-
return { model: resolved, stream: (options) => adapter.stream(options) };
|
|
515
|
-
},
|
|
516
|
-
stream(options) {
|
|
517
|
-
const sessionId = options && options.sessionId;
|
|
518
|
-
return (async function* () {
|
|
519
|
-
let members = [];
|
|
520
|
-
try {
|
|
521
|
-
members = await getMembers();
|
|
522
|
-
} catch {
|
|
523
|
-
members = [];
|
|
524
|
-
}
|
|
525
|
-
if (!members.length) {
|
|
526
|
-
yield {
|
|
527
|
-
type: 'finish',
|
|
528
|
-
reason: { kind: 'error', failure: { code: 'EMPTY_GROUP', message: 'NVIDIA 模型组当前没有可用成员,请先在面板中检测并配置模型' } },
|
|
529
|
-
};
|
|
530
|
-
return;
|
|
531
|
-
}
|
|
532
|
-
const pickAuto = isAutoMemberId(options && options.model);
|
|
533
|
-
const current = pickAuto ? null : members.find((m) => m.id === (options && options.model));
|
|
534
|
-
// 手动选中具体模型 = 锁定该模型:候选只保留它本身,不做任何自动故障转移。
|
|
535
|
-
// 这样失败就如实报错,不会悄悄切到别的成员、也不会在面板"自动切换"里计数。
|
|
536
|
-
// 只有选「模型组(自动)」时才把全部成员交给故障转移引擎轮询。
|
|
537
|
-
let candidates = current ? [current] : members;
|
|
538
|
-
// 能力感知路由(软过滤):含图片的请求**优先**把多模态成员排到前面,
|
|
539
|
-
// 但保留全部成员作为后备。绝不把组员砍到只剩"看起来支持图片"的那几个——
|
|
540
|
-
// id 正则判断并不可靠(如 muse-glimmer 实为多模态却被判为纯文本),
|
|
541
|
-
// 一旦把其余成员剔除,组里常常只剩 1~2 人,一个抖动就整轮失败。
|
|
542
|
-
// 纯文本成员若真的收到图片,会由上游报 400,isCapabilityMismatch 归为
|
|
543
|
-
// INVALID_REQUEST 类 → 直接换下一个且不熔断,代价可控。
|
|
544
|
-
if (requestHasImage(options)) {
|
|
545
|
-
const visionCapable = candidates.filter((m) => memberSupportsImage(m));
|
|
546
|
-
const rest = candidates.filter((m) => !memberSupportsImage(m));
|
|
547
|
-
if (visionCapable.length) candidates = [...visionCapable, ...rest];
|
|
548
|
-
}
|
|
549
|
-
const onAttempt = deps.onAttempt
|
|
550
|
-
? (info) => deps.onAttempt({ ...info, sessionId })
|
|
551
|
-
: undefined;
|
|
552
|
-
const onFailover = deps.onFailover
|
|
553
|
-
? (info) => deps.onFailover({ ...info, sessionId })
|
|
554
|
-
: undefined;
|
|
555
|
-
yield* runFailover(options, {
|
|
556
|
-
streamChild: deps.streamChild,
|
|
557
|
-
health: deps.health,
|
|
558
|
-
candidates,
|
|
559
|
-
childProvider: deps.childProvider || 'nvidia',
|
|
560
|
-
firstByteTimeoutMs: deps.firstByteTimeoutMs,
|
|
561
|
-
firstTextTimeoutMs: deps.firstTextTimeoutMs,
|
|
562
|
-
onAttempt,
|
|
563
|
-
onFailover,
|
|
564
|
-
});
|
|
565
|
-
})();
|
|
566
|
-
},
|
|
567
|
-
};
|
|
568
|
-
return adapter;
|
|
569
|
-
}
|
|
570
|
-
|
|
571
|
-
/* ───────────────────────── 会话投影状态(无 zod,自带校验) ───────────────────────── */
|
|
572
|
-
|
|
573
|
-
/** 空投影状态。 */
|
|
574
|
-
export function createGroupState() {
|
|
575
|
-
return { members: {}, timeline: [] };
|
|
576
|
-
}
|
|
577
|
-
|
|
578
|
-
/** 手工校验/规整投影状态:只容许预期形状,异常输入回落到空状态。 */
|
|
579
|
-
export function parseGroupState(value) {
|
|
580
|
-
if (!value || typeof value !== 'object') return createGroupState();
|
|
581
|
-
const members = {};
|
|
582
|
-
const rawMembers = value.members && typeof value.members === 'object' ? value.members : {};
|
|
583
|
-
for (const id of Object.keys(rawMembers)) {
|
|
584
|
-
const e = rawMembers[id];
|
|
585
|
-
if (!e || typeof e !== 'object') continue;
|
|
586
|
-
members[id] = {
|
|
587
|
-
status: typeof e.status === 'string' ? e.status : 'unknown',
|
|
588
|
-
failCount: Number.isFinite(e.failCount) ? e.failCount : 0,
|
|
589
|
-
lastError: typeof e.lastError === 'string' ? e.lastError : '',
|
|
590
|
-
cooldownUntil: Number.isFinite(e.cooldownUntil) ? e.cooldownUntil : 0,
|
|
591
|
-
lastSuccessAt: Number.isFinite(e.lastSuccessAt) ? e.lastSuccessAt : null,
|
|
592
|
-
};
|
|
593
|
-
}
|
|
594
|
-
const timeline = Array.isArray(value.timeline)
|
|
595
|
-
? value.timeline.filter((t) => t && typeof t === 'object').slice(-30).map((t) => ({
|
|
596
|
-
at: Number.isFinite(t.at) ? t.at : 0,
|
|
597
|
-
type: typeof t.type === 'string' ? t.type : 'event',
|
|
598
|
-
member: typeof t.member === 'string' ? t.member : '',
|
|
599
|
-
to: typeof t.to === 'string' ? t.to : '',
|
|
600
|
-
error: typeof t.error === 'string' ? t.error : '',
|
|
601
|
-
}))
|
|
602
|
-
: [];
|
|
603
|
-
return { members, timeline };
|
|
604
|
-
}
|
|
605
|
-
|
|
606
|
-
/** 一个满足 `.parse()` 契约的极简 schema(避免引入 zod 依赖)。 */
|
|
607
|
-
export function makeSchema() {
|
|
608
|
-
return { parse: (value) => parseGroupState(value) };
|
|
609
|
-
}
|
|
610
|
-
|
|
611
|
-
// 事件类型名:新版走 harness 官方 plugin record(plugin: 命名空间 + 自动
|
|
612
|
-
// ignorable),旧版遗留 nvidia-group/* 仍需识别以便回放历史会话。
|
|
613
|
-
const PROBE_TYPES = new Set(['nvidia-group/probe', 'plugin:dsh-nvidia-models-panel/probe']);
|
|
614
|
-
const FAILOVER_TYPES = new Set(['nvidia-group/failover', 'plugin:dsh-nvidia-models-panel/failover']);
|
|
615
|
-
|
|
616
|
-
/** 把一条组事件(新旧类型名)折进投影状态。 */
|
|
617
|
-
export function foldGroupEvent(state, event) {
|
|
618
|
-
const s = parseGroupState(state);
|
|
619
|
-
const type = event && event.type;
|
|
620
|
-
const data = (event && event.data) || {};
|
|
621
|
-
const at = Number.isFinite(event && event.time) ? event.time : Date.now();
|
|
622
|
-
if (FAILOVER_TYPES.has(type)) {
|
|
623
|
-
const from = String(data.from || '');
|
|
624
|
-
const to = String(data.to || '');
|
|
625
|
-
const members = { ...s.members };
|
|
626
|
-
if (from) {
|
|
627
|
-
const prev = members[from] || { status: 'unknown', failCount: 0, lastError: '', cooldownUntil: 0, lastSuccessAt: null };
|
|
628
|
-
members[from] = { ...prev, status: 'failed', failCount: (prev.failCount || 0) + 1, lastError: String(data.error || prev.lastError || '') };
|
|
629
|
-
}
|
|
630
|
-
if (to) {
|
|
631
|
-
const prev = members[to] || { status: 'unknown', failCount: 0, lastError: '', cooldownUntil: 0, lastSuccessAt: null };
|
|
632
|
-
members[to] = { ...prev, status: 'ok', failCount: 0, lastSuccessAt: at };
|
|
633
|
-
}
|
|
634
|
-
const timeline = s.timeline.concat([{ at, type: 'failover', member: from, to, error: String(data.error || '') }]).slice(-30);
|
|
635
|
-
return { members, timeline };
|
|
636
|
-
}
|
|
637
|
-
if (PROBE_TYPES.has(type)) {
|
|
638
|
-
const id = String(data.member || '');
|
|
639
|
-
if (!id) return s;
|
|
640
|
-
const members = { ...s.members };
|
|
641
|
-
const prev = members[id] || { status: 'unknown', failCount: 0, lastError: '', cooldownUntil: 0, lastSuccessAt: null };
|
|
642
|
-
members[id] = {
|
|
643
|
-
...prev,
|
|
644
|
-
status: data.status === 'ok' ? 'ok' : (data.status === 'fail' ? 'failed' : prev.status),
|
|
645
|
-
lastError: data.status === 'fail' ? String(data.error || prev.lastError || '') : (data.status === 'ok' ? '' : prev.lastError),
|
|
646
|
-
lastSuccessAt: data.status === 'ok' ? at : prev.lastSuccessAt,
|
|
647
|
-
};
|
|
648
|
-
return { members, timeline: s.timeline };
|
|
649
|
-
}
|
|
650
|
-
if (type === 'nvidia-group/reset') return createGroupState();
|
|
651
|
-
return s;
|
|
652
|
-
}
|
|
1
|
+
/**
|
|
2
|
+
* NVIDIA 模型组:自愈式故障转移引擎(纯逻辑,无 DSH / 无外部依赖)。
|
|
3
|
+
*
|
|
4
|
+
* 设计要点
|
|
5
|
+
* - 组内成员按健康度排序:首选模型优先 → 未冷却优先 → 失败次数少优先 → 首包快优先 → 配置顺序。
|
|
6
|
+
* - 熔断:连续失败达到阈值即进入冷却(指数退避,封顶),冷却期内直接跳过。
|
|
7
|
+
* - 流式转移只在“尚未产出任何内容”时发生;一旦已向用户吐出文本/推理/工具增量,
|
|
8
|
+
* 就不再做无痕切换(避免内容重复),而是如实返回错误。
|
|
9
|
+
* - 全部成员失败时产出合成错误 finish,交给上层(dsh-llm-retry / 会话投影)处理。
|
|
10
|
+
*
|
|
11
|
+
* 所有对外函数只依赖注入进来的 deps,便于脱离 DSH 用 node --test 单测。
|
|
12
|
+
*/
|
|
13
|
+
|
|
14
|
+
/** 虚拟「自动」成员的模型 id:不指定首选,纯按实时健康排序。 */
|
|
15
|
+
export const AUTO_MEMBER_ID = '__auto__';
|
|
16
|
+
/** 「自动」成员的展示名 / 描述。 */
|
|
17
|
+
export const AUTO_MEMBER_NAME = 'NVIDIA 模型组(自动)';
|
|
18
|
+
export const AUTO_MEMBER_DESC = '自动选择并故障转移,无需指定首选模型';
|
|
19
|
+
|
|
20
|
+
/** 判断一个模型 id 是否为「自动」虚拟成员。 */
|
|
21
|
+
export function isAutoMemberId(id) {
|
|
22
|
+
return id === AUTO_MEMBER_ID || id === 'auto';
|
|
23
|
+
}
|
|
24
|
+
|
|
25
|
+
/**
|
|
26
|
+
* 该失败是否只是「这个成员吃不消这轮请求」(例如上下文窗口不够),
|
|
27
|
+
* 而非「该模型不可用」。这类失败应当直接换下一个成员,
|
|
28
|
+
* 且不计入熔断(模型本身是好的,只是不适合这次请求)。
|
|
29
|
+
*/
|
|
30
|
+
/**
|
|
31
|
+
* 致命失败:对所有组员都一样,换模型也不会好转,因此应立即停止故障转移。
|
|
32
|
+
* 目前仅「缺 API Key / 凭据失效」属于此类。
|
|
33
|
+
*/
|
|
34
|
+
export function isFatalFailure(failure) {
|
|
35
|
+
return Boolean(failure && typeof failure === 'object' && failure.code === 'NO_API_KEY');
|
|
36
|
+
}
|
|
37
|
+
|
|
38
|
+
export function isCapabilityMismatch(failure) {
|
|
39
|
+
if (!failure || typeof failure !== 'object') return false;
|
|
40
|
+
if (failure.code === 'CONTEXT_WINDOW_EXCEEDED' || failure.code === 'MODEL_SWITCH_COMPACTION_FAILED' || failure.code === 'INVALID_REQUEST') {
|
|
41
|
+
return true; // 400 类「这次请求该模型吃不下」——换下一个即可,不熔断
|
|
42
|
+
}
|
|
43
|
+
// 上游把「多模态未启用 / 不支持图片」报成 400,也归到这一类。
|
|
44
|
+
const msg = String(failure.message || '');
|
|
45
|
+
return /multimodal|not enabled|invalid.?request|does not support image/i.test(msg);
|
|
46
|
+
}
|
|
47
|
+
|
|
48
|
+
/** 判定一个流块是否为错误/取消的 finish。 */
|
|
49
|
+
export function isErrorFinish(chunk) {
|
|
50
|
+
return Boolean(
|
|
51
|
+
chunk && chunk.type === 'finish' && chunk.reason &&
|
|
52
|
+
(chunk.reason.kind === 'error' || chunk.reason.kind === 'aborted'),
|
|
53
|
+
);
|
|
54
|
+
}
|
|
55
|
+
|
|
56
|
+
/** 判定一个流块是否携带“用户可见内容”(用于决定能否无痕转移)。 */
|
|
57
|
+
export function isContentChunk(chunk) {
|
|
58
|
+
return Boolean(
|
|
59
|
+
chunk && (chunk.type === 'text-delta' || chunk.type === 'reasoning-delta' || chunk.type === 'tool-call-delta') &&
|
|
60
|
+
chunk.text !== '' && chunk.argumentsDelta !== '',
|
|
61
|
+
);
|
|
62
|
+
}
|
|
63
|
+
|
|
64
|
+
/**
|
|
65
|
+
* 判定一个流块是否为“真正的回答产出”(用户可见的正文或工具调用)。
|
|
66
|
+
* 注意:reasoning-delta(思考过程)**不算**——模型可能把整个输出预算烧在思考上、
|
|
67
|
+
* 一个字的回答都没给出,这种情况必须能和“已给出部分回答”区分开。
|
|
68
|
+
*/
|
|
69
|
+
export function isVisibleOutputChunk(chunk) {
|
|
70
|
+
if (!chunk) return false;
|
|
71
|
+
if (chunk.type === 'text-delta') return typeof chunk.text === 'string' && chunk.text !== '';
|
|
72
|
+
if (chunk.type === 'tool-call-delta') {
|
|
73
|
+
return (typeof chunk.argumentsDelta === 'string' && chunk.argumentsDelta !== '') || Boolean(chunk.name);
|
|
74
|
+
}
|
|
75
|
+
return false;
|
|
76
|
+
}
|
|
77
|
+
|
|
78
|
+
/**
|
|
79
|
+
* 是否属于“重推理 / 思考型”模型。这类模型面对复杂任务时可能长时间只输出思考内容,
|
|
80
|
+
* 在“自动”模式下应排到普通模型之后,避免整轮对话被它的思考拖死。
|
|
81
|
+
*/
|
|
82
|
+
export function isReasoningModel(id) {
|
|
83
|
+
return /reasoning|thinking|omni|debate/i.test(String(id || ''));
|
|
84
|
+
}
|
|
85
|
+
|
|
86
|
+
/**
|
|
87
|
+
* 健康登记表 + 熔断器。默认:连续 2 次失败即冷却 20s,按 2^k 退避,封顶 5 分钟。
|
|
88
|
+
* @param {{baseCooldownMs?:number,maxCooldownMs?:number,failThreshold?:number,now?:()=>number}} [opts]
|
|
89
|
+
*/
|
|
90
|
+
export function createHealthRegistry(opts) {
|
|
91
|
+
const o = opts || {};
|
|
92
|
+
const baseCooldownMs = Number.isFinite(o.baseCooldownMs) ? o.baseCooldownMs : 20000;
|
|
93
|
+
const maxCooldownMs = Number.isFinite(o.maxCooldownMs) ? o.maxCooldownMs : 300000;
|
|
94
|
+
const failThreshold = Number.isFinite(o.failThreshold) ? o.failThreshold : 2;
|
|
95
|
+
const now = typeof o.now === 'function' ? o.now : () => Date.now();
|
|
96
|
+
const map = new Map();
|
|
97
|
+
|
|
98
|
+
function entry(id) {
|
|
99
|
+
let e = map.get(id);
|
|
100
|
+
if (!e) {
|
|
101
|
+
e = {
|
|
102
|
+
id,
|
|
103
|
+
ok: null,
|
|
104
|
+
failCount: 0,
|
|
105
|
+
successCount: 0,
|
|
106
|
+
lastError: '',
|
|
107
|
+
cooldownUntil: 0,
|
|
108
|
+
lastFirstByteMs: null,
|
|
109
|
+
lastProbeAt: null,
|
|
110
|
+
lastChangeAt: now(),
|
|
111
|
+
};
|
|
112
|
+
map.set(id, e);
|
|
113
|
+
}
|
|
114
|
+
return e;
|
|
115
|
+
}
|
|
116
|
+
|
|
117
|
+
return {
|
|
118
|
+
/** 只读快照(拷贝),用于渲染看板。 */
|
|
119
|
+
get(id) { return { ...entry(id) }; },
|
|
120
|
+
snapshot(ids) {
|
|
121
|
+
const keys = Array.isArray(ids) ? ids : [...map.keys()];
|
|
122
|
+
const out = {};
|
|
123
|
+
for (const id of keys) out[id] = this.get(id);
|
|
124
|
+
return out;
|
|
125
|
+
},
|
|
126
|
+
isCoolingDown(id) { return entry(id).cooldownUntil > now(); },
|
|
127
|
+
cooldownRemainingMs(id) { return Math.max(0, entry(id).cooldownUntil - now()); },
|
|
128
|
+
recordProbeStart(id) { const e = entry(id); e.lastProbeAt = now(); return { ...e }; },
|
|
129
|
+
recordSuccess(id, firstByteMs) {
|
|
130
|
+
const e = entry(id);
|
|
131
|
+
e.ok = true;
|
|
132
|
+
e.failCount = 0;
|
|
133
|
+
e.successCount += 1;
|
|
134
|
+
e.lastError = '';
|
|
135
|
+
e.cooldownUntil = 0;
|
|
136
|
+
if (typeof firstByteMs === 'number' && firstByteMs >= 0) e.lastFirstByteMs = Math.round(firstByteMs);
|
|
137
|
+
e.lastChangeAt = now();
|
|
138
|
+
return { ...e };
|
|
139
|
+
},
|
|
140
|
+
recordFailure(id, error) {
|
|
141
|
+
const e = entry(id);
|
|
142
|
+
e.ok = false;
|
|
143
|
+
e.failCount += 1;
|
|
144
|
+
e.lastError = describeError(error).slice(0, 240);
|
|
145
|
+
e.lastChangeAt = now();
|
|
146
|
+
if (e.failCount >= failThreshold) {
|
|
147
|
+
const k = e.failCount - failThreshold;
|
|
148
|
+
const backoff = Math.min(maxCooldownMs, baseCooldownMs * Math.pow(2, k));
|
|
149
|
+
e.cooldownUntil = now() + backoff;
|
|
150
|
+
}
|
|
151
|
+
return { ...e };
|
|
152
|
+
},
|
|
153
|
+
reset(id) {
|
|
154
|
+
if (id === undefined) map.clear();
|
|
155
|
+
else map.delete(id);
|
|
156
|
+
},
|
|
157
|
+
};
|
|
158
|
+
}
|
|
159
|
+
|
|
160
|
+
/** 把任意错误对象压成一句人类可读文本。 */
|
|
161
|
+
export function describeError(error) {
|
|
162
|
+
if (!error) return 'unknown error';
|
|
163
|
+
if (typeof error === 'string') return error;
|
|
164
|
+
if (error.message) return String(error.message);
|
|
165
|
+
if (error.code) return String(error.code);
|
|
166
|
+
try { return JSON.stringify(error); } catch { return String(error); }
|
|
167
|
+
}
|
|
168
|
+
|
|
169
|
+
/**
|
|
170
|
+
* 组内成员排序:preferredId 优先;其次未冷却;再次失败少、首包快、配置顺序。
|
|
171
|
+
* 当没有指定首选(“自动”模式)时,思考型/重推理模型整体排在普通模型之后 —— 它们
|
|
172
|
+
* 更容易把输出预算耗在思考上、迟迟不给正文,不适合作为默认首选。
|
|
173
|
+
* @param {Array<{id:string}>} members
|
|
174
|
+
* @param {any} health createHealthRegistry() 的实例(可空)
|
|
175
|
+
* @param {string} [preferredId]
|
|
176
|
+
* @param {()=>number} [clock]
|
|
177
|
+
*/
|
|
178
|
+
export function rankMembers(members, health, preferredId, clock) {
|
|
179
|
+
const nowFn = typeof clock === 'function' ? clock : () => Date.now();
|
|
180
|
+
const list = Array.isArray(members) ? members : [];
|
|
181
|
+
const scored = list.map((m, index) => {
|
|
182
|
+
const h = health && typeof health.get === 'function' ? health.get(m.id) : null;
|
|
183
|
+
const coolingDown = Boolean(h && h.cooldownUntil > nowFn());
|
|
184
|
+
const reasoning = !preferredId && isReasoningModel(m && m.id);
|
|
185
|
+
return { m, index, h, coolingDown, reasoning };
|
|
186
|
+
});
|
|
187
|
+
scored.sort((a, b) => {
|
|
188
|
+
if (preferredId) {
|
|
189
|
+
if (a.m.id === preferredId && b.m.id !== preferredId) return -1;
|
|
190
|
+
if (b.m.id === preferredId && a.m.id !== preferredId) return 1;
|
|
191
|
+
}
|
|
192
|
+
if (a.coolingDown !== b.coolingDown) return a.coolingDown ? 1 : -1;
|
|
193
|
+
if (a.reasoning !== b.reasoning) return a.reasoning ? 1 : -1;
|
|
194
|
+
const af = a.h ? a.h.failCount : 0;
|
|
195
|
+
const bf = b.h ? b.h.failCount : 0;
|
|
196
|
+
if (af !== bf) return af - bf;
|
|
197
|
+
const as = a.h && typeof a.h.lastFirstByteMs === 'number' ? a.h.lastFirstByteMs : Infinity;
|
|
198
|
+
const bs = b.h && typeof b.h.lastFirstByteMs === 'number' ? b.h.lastFirstByteMs : Infinity;
|
|
199
|
+
if (as !== bs) return as - bs;
|
|
200
|
+
return a.index - b.index;
|
|
201
|
+
});
|
|
202
|
+
return scored.map((s) => s.m);
|
|
203
|
+
}
|
|
204
|
+
|
|
205
|
+
/** 把父级 AbortSignal 链接到子控制器;返回解绑函数。 */
|
|
206
|
+
function linkSignal(parent, child) {
|
|
207
|
+
if (!parent || typeof child !== 'object') return () => {};
|
|
208
|
+
if (parent.aborted) { try { child.abort(); } catch { /* 已中止 */ } return () => {}; }
|
|
209
|
+
if (typeof parent.addEventListener === 'function') {
|
|
210
|
+
const onAbort = () => { try { child.abort(); } catch { /* 已中止 */ } };
|
|
211
|
+
parent.addEventListener('abort', onAbort, { once: true });
|
|
212
|
+
return () => { try { parent.removeEventListener('abort', onAbort); } catch { /* 忽略 */ } };
|
|
213
|
+
}
|
|
214
|
+
return () => {};
|
|
215
|
+
}
|
|
216
|
+
|
|
217
|
+
/**
|
|
218
|
+
* 故障转移主循环:依次尝试组内成员,直到某个成员产出非错误 finish。
|
|
219
|
+
* 每个成员都有「首包看门狗」:在 firstByteTimeoutMs 内一个字节都没到,就中止并切下一个,
|
|
220
|
+
* 从而把用户看到的“30 秒卡死”变成有界、快速的自动切换。
|
|
221
|
+
* @param {object} options GenerateOptions(含 provider/model/messages/signal/sessionId 等)
|
|
222
|
+
* @param {{
|
|
223
|
+
* streamChild:(childOptions:object)=>AsyncIterable<any>,
|
|
224
|
+
* health?:any,
|
|
225
|
+
* candidates:Array<{id:string,name?:string}>,
|
|
226
|
+
* childProvider?:string,
|
|
227
|
+
* skipCooling?:boolean,
|
|
228
|
+
* firstByteTimeoutMs?:number,
|
|
229
|
+
* onAttempt?:(info:{member:any,error:any,emitted:boolean,sessionId?:string})=>void,
|
|
230
|
+
* onFailover?:(info:{from:any,to?:any,error:any,sessionId?:string,exhausted?:boolean})=>void,
|
|
231
|
+
* }} deps
|
|
232
|
+
*/
|
|
233
|
+
export async function* runFailover(options, deps) {
|
|
234
|
+
const parentSignal = options && options.signal;
|
|
235
|
+
const health = deps.health;
|
|
236
|
+
const sessionId = options && options.sessionId;
|
|
237
|
+
const skipCooling = Boolean(deps.skipCooling);
|
|
238
|
+
const rawFirstByteTimeout = typeof deps.firstByteTimeoutMs === 'function' ? deps.firstByteTimeoutMs() : deps.firstByteTimeoutMs;
|
|
239
|
+
const firstByteTimeoutMs = Number.isFinite(rawFirstByteTimeout) ? rawFirstByteTimeout : 15000;
|
|
240
|
+
const rawFirstTextTimeout = typeof deps.firstTextTimeoutMs === 'function' ? deps.firstTextTimeoutMs() : deps.firstTextTimeoutMs;
|
|
241
|
+
const firstTextTimeoutMs = Number.isFinite(rawFirstTextTimeout) ? rawFirstTextTimeout : 30000;
|
|
242
|
+
// 「自动」模式(选中虚拟 AUTO 成员)不指定真实首选:preferredId 置空,才会走纯健康排序
|
|
243
|
+
// 并把思考型模型排到后面。否则 '__auto__' 作为真值会误导排序。
|
|
244
|
+
const rawPreferred = options && options.model;
|
|
245
|
+
const preferredForRank = isAutoMemberId(rawPreferred) ? '' : rawPreferred;
|
|
246
|
+
const order = rankMembers(deps.candidates, health, preferredForRank);
|
|
247
|
+
|
|
248
|
+
// 两轮尝试:
|
|
249
|
+
// 第 1 轮 —— 只试「未冷却」的成员(正常路径)。
|
|
250
|
+
// 第 2 轮 —— 若第 1 轮确实试过成员、却没有任何可见正文产出,就把「冷却中」的成员
|
|
251
|
+
// 也当最后手段补试一遍。这样即便大部分成员因首包超时被熔断、只剩一个
|
|
252
|
+
// 「只思考不出正文」的成员,也不会把空回答直接甩给用户。
|
|
253
|
+
const totalRounds = skipCooling ? 1 : 2;
|
|
254
|
+
const tried = new Set();
|
|
255
|
+
let attempted = 0;
|
|
256
|
+
let lastFailure = null;
|
|
257
|
+
let lastTriedMember = null;
|
|
258
|
+
let prevMemberId = '';
|
|
259
|
+
|
|
260
|
+
for (let round = 0; round < totalRounds; round += 1) {
|
|
261
|
+
const includeCooling = round === 1;
|
|
262
|
+
if (includeCooling && attempted === 0) break; // 第 1 轮一个都没试,谈不上“兜底重试”
|
|
263
|
+
|
|
264
|
+
for (const member of order) {
|
|
265
|
+
if (parentSignal && parentSignal.aborted) {
|
|
266
|
+
yield { type: 'finish', reason: { kind: 'aborted', failure: { code: 'ABORTED', message: '请求已取消' } } };
|
|
267
|
+
return;
|
|
268
|
+
}
|
|
269
|
+
if (tried.has(member.id)) continue;
|
|
270
|
+
const cooling = Boolean(health && typeof health.isCoolingDown === 'function' && health.isCoolingDown(member.id));
|
|
271
|
+
if (includeCooling ? !cooling : cooling) continue;
|
|
272
|
+
|
|
273
|
+
attempted += 1;
|
|
274
|
+
tried.add(member.id);
|
|
275
|
+
const wasFailover = attempted > 1;
|
|
276
|
+
const failoverFrom = wasFailover ? prevMemberId : '';
|
|
277
|
+
prevMemberId = member.id;
|
|
278
|
+
lastTriedMember = member;
|
|
279
|
+
const controller = new AbortController();
|
|
280
|
+
const unlink = linkSignal(parentSignal, controller);
|
|
281
|
+
let gotFirstByte = false;
|
|
282
|
+
let timedOut = false;
|
|
283
|
+
let textTimedOut = false;
|
|
284
|
+
const timer = firstByteTimeoutMs > 0
|
|
285
|
+
? setTimeout(() => { if (!gotFirstByte) { timedOut = true; try { controller.abort(); } catch { /* 忽略 */ } } }, firstByteTimeoutMs)
|
|
286
|
+
: null;
|
|
287
|
+
// 「首段可见正文」看门狗:模型可能首字节很快(吐思考),却长时间产不出任何正文,
|
|
288
|
+
// 把整个输出预算全烧在 reasoning 上。超过 firstTextTimeoutMs 仍无正文就中止并切换,
|
|
289
|
+
// 无论后面还有没有备份成员都要生效 —— 否则用户会干等好几分钟才看到“输出 token 上限”。
|
|
290
|
+
let textTimer = null;
|
|
291
|
+
let emitted = false; // 是否已向用户吐出过可见正文(一旦为真就不再无痕切换)
|
|
292
|
+
let failure = null;
|
|
293
|
+
let firstByteMs = 0;
|
|
294
|
+
let lastUsage = null;
|
|
295
|
+
let sawFinish = null;
|
|
296
|
+
// 在产出第一段「可见正文」之前,先把块缓存起来:若该成员最终只有思考、没有正文,
|
|
297
|
+
// 就能整段丢弃、静默切换,用户不会看到半截思考或空回答。
|
|
298
|
+
const buffer = [];
|
|
299
|
+
const childOptions = { ...options, provider: deps.childProvider || 'nvidia', model: member.id, signal: controller.signal };
|
|
300
|
+
const startedAt = Date.now();
|
|
301
|
+
|
|
302
|
+
try {
|
|
303
|
+
for await (const chunk of deps.streamChild(childOptions)) {
|
|
304
|
+
if (!gotFirstByte) {
|
|
305
|
+
gotFirstByte = true;
|
|
306
|
+
firstByteMs = Date.now() - startedAt;
|
|
307
|
+
if (timer) clearTimeout(timer);
|
|
308
|
+
if (firstTextTimeoutMs > 0) {
|
|
309
|
+
textTimer = setTimeout(() => { if (!emitted) { textTimedOut = true; try { controller.abort(); } catch { /* 忽略 */ } } }, firstTextTimeoutMs);
|
|
310
|
+
}
|
|
311
|
+
}
|
|
312
|
+
if (isErrorFinish(chunk)) {
|
|
313
|
+
failure = (chunk.reason && chunk.reason.failure) || { code: 'MEMBER_ERROR', message: '模型返回错误' };
|
|
314
|
+
break;
|
|
315
|
+
}
|
|
316
|
+
if (chunk && chunk.type === 'usage' && chunk.usage) lastUsage = chunk.usage;
|
|
317
|
+
if (chunk && chunk.type === 'finish') sawFinish = chunk;
|
|
318
|
+
|
|
319
|
+
if (!emitted) {
|
|
320
|
+
if (isVisibleOutputChunk(chunk)) {
|
|
321
|
+
// 第一段正文到达:把之前缓存的块按顺序补发,然后转入实时直通。
|
|
322
|
+
emitted = true;
|
|
323
|
+
if (textTimer) { clearTimeout(textTimer); textTimer = null; }
|
|
324
|
+
for (const b of buffer) yield b;
|
|
325
|
+
buffer.length = 0;
|
|
326
|
+
yield chunk;
|
|
327
|
+
} else {
|
|
328
|
+
buffer.push(chunk);
|
|
329
|
+
}
|
|
330
|
+
} else {
|
|
331
|
+
yield chunk;
|
|
332
|
+
}
|
|
333
|
+
if (sawFinish) break;
|
|
334
|
+
}
|
|
335
|
+
} catch (error) {
|
|
336
|
+
failure = timedOut
|
|
337
|
+
? { code: 'FIRST_BYTE_TIMEOUT', message: '首包超时(' + firstByteTimeoutMs + 'ms 内无响应),已自动切换' }
|
|
338
|
+
: { code: 'MEMBER_THROW', message: describeError(error) };
|
|
339
|
+
} finally {
|
|
340
|
+
if (timer) clearTimeout(timer);
|
|
341
|
+
if (textTimer) clearTimeout(textTimer);
|
|
342
|
+
unlink();
|
|
343
|
+
}
|
|
344
|
+
|
|
345
|
+
// 看门狗主动中止时,子流往往报成 “network aborted”,诊断信息不清晰;
|
|
346
|
+
// 这里以看门狗为准,统一记为「首包超时 / 首段正文超时」,原始错误码留在 cause 里。
|
|
347
|
+
if (timedOut) {
|
|
348
|
+
failure = {
|
|
349
|
+
code: 'FIRST_BYTE_TIMEOUT',
|
|
350
|
+
message: '首包超时(' + firstByteTimeoutMs + 'ms 内无响应),已自动切换',
|
|
351
|
+
cause: failure || undefined,
|
|
352
|
+
};
|
|
353
|
+
} else if (textTimedOut && !emitted) {
|
|
354
|
+
failure = {
|
|
355
|
+
code: 'FIRST_TEXT_TIMEOUT',
|
|
356
|
+
message: '首段正文超时(' + firstTextTimeoutMs + 'ms 内无输出正文),已自动切换',
|
|
357
|
+
cause: failure || undefined,
|
|
358
|
+
};
|
|
359
|
+
}
|
|
360
|
+
|
|
361
|
+
// 没有产出任何可见正文(典型是“把输出预算全烧在思考上、正文为空”)——
|
|
362
|
+
// 无论后面还有没有备份成员,都判为 EMPTY_ANSWER:绝不能把空的/纯思考的结果
|
|
363
|
+
// 静默当成正常回答交给用户(那正是“没有输出内容 + 已达到输出 token 上限”的成因)。
|
|
364
|
+
if (!emitted && !failure) {
|
|
365
|
+
const inner = (sawFinish && sawFinish.reason) || null;
|
|
366
|
+
const reasonNote = inner && inner.kind === 'max-tokens' ? '(输出预算耗尽在思考内容上,未产出正文)' : '(未产出任何正文)';
|
|
367
|
+
failure = {
|
|
368
|
+
code: 'EMPTY_ANSWER',
|
|
369
|
+
message: '模型未产出正文' + reasonNote + ',已自动切换',
|
|
370
|
+
};
|
|
371
|
+
}
|
|
372
|
+
|
|
373
|
+
if (!failure) {
|
|
374
|
+
// 走到这里一定已经产出过可见正文(否则上面已判 EMPTY_ANSWER)。
|
|
375
|
+
if (health && typeof health.recordSuccess === 'function') health.recordSuccess(member.id, firstByteMs);
|
|
376
|
+
if (typeof deps.onAttempt === 'function') {
|
|
377
|
+
try { deps.onAttempt({ member, error: null, emitted, sessionId, firstByteMs, elapsedMs: Date.now() - startedAt, usage: lastUsage, failover: wasFailover, failoverFrom }); } catch { /* 观测失败不影响主流程 */ }
|
|
378
|
+
}
|
|
379
|
+
if (!sawFinish) yield { type: 'finish', reason: { kind: 'stop' } };
|
|
380
|
+
return;
|
|
381
|
+
}
|
|
382
|
+
|
|
383
|
+
lastFailure = failure;
|
|
384
|
+
// 致命错误(如缺 API Key):对所有成员都一样,换模型无用——立即停止,如实把友好提示交给用户。
|
|
385
|
+
if (isFatalFailure(failure)) {
|
|
386
|
+
if (typeof deps.onAttempt === 'function') {
|
|
387
|
+
try { deps.onAttempt({ member, error: failure, emitted, sessionId, firstByteMs, elapsedMs: Date.now() - startedAt, usage: null, fatal: true }); } catch { /* 忽略 */ }
|
|
388
|
+
}
|
|
389
|
+
yield { type: 'finish', reason: { kind: 'error', failure: toFailure(failure) } };
|
|
390
|
+
return;
|
|
391
|
+
}
|
|
392
|
+
// 「能力不符 / 空回答 / 首段正文超时」不是模型“坏了”,而是这次请求不称职:不记熔断,直接换下一个成员。
|
|
393
|
+
const capability = isCapabilityMismatch(failure) || failure.code === 'EMPTY_ANSWER' || failure.code === 'FIRST_TEXT_TIMEOUT';
|
|
394
|
+
if (!capability && health && typeof health.recordFailure === 'function') health.recordFailure(member.id, failure);
|
|
395
|
+
if (typeof deps.onAttempt === 'function') {
|
|
396
|
+
try { deps.onAttempt({ member, error: failure, emitted, sessionId, firstByteMs, elapsedMs: Date.now() - startedAt, usage: null, failover: wasFailover, failoverFrom, capability }); } catch { /* 观测失败不影响主流程 */ }
|
|
397
|
+
}
|
|
398
|
+
|
|
399
|
+
if (emitted) {
|
|
400
|
+
// 已向用户产出内容,无法无痕切换,如实返回错误。
|
|
401
|
+
yield { type: 'finish', reason: { kind: 'error', failure: toFailure(lastFailure) } };
|
|
402
|
+
return;
|
|
403
|
+
}
|
|
404
|
+
if (typeof deps.onFailover === 'function') {
|
|
405
|
+
try { deps.onFailover({ from: member, to: null, error: failure, sessionId, capability, exhausted: false }); } catch { /* 忽略 */ }
|
|
406
|
+
}
|
|
407
|
+
}
|
|
408
|
+
}
|
|
409
|
+
|
|
410
|
+
if (attempted === 0) {
|
|
411
|
+
yield {
|
|
412
|
+
type: 'finish',
|
|
413
|
+
reason: { kind: 'error', failure: { code: 'ALL_MEMBERS_COOLING', message: '模型组内所有模型都在熔断冷却中,请稍后重试或手动探测恢复' } },
|
|
414
|
+
};
|
|
415
|
+
return;
|
|
416
|
+
}
|
|
417
|
+
const finalFailure = toFailure(lastFailure || { code: 'ALL_MEMBERS_FAILED', message: '模型组内所有模型均调用失败' });
|
|
418
|
+
if (lastFailure && lastFailure.code === 'EMPTY_ANSWER') {
|
|
419
|
+
// 最后一个失败是“只思考没正文”:给出明确、可操作的提示,而不是含糊的“模型组均失败”。
|
|
420
|
+
finalFailure.code = 'EMPTY_ANSWER';
|
|
421
|
+
finalFailure.message = '组内所有模型都没有产出正文(重推理模型把输出预算耗在思考上),请重试、增大 maxTokens 或改用非推理模型';
|
|
422
|
+
}
|
|
423
|
+
if (typeof deps.onFailover === 'function') {
|
|
424
|
+
try { deps.onFailover({ from: lastTriedMember, to: null, error: finalFailure, sessionId, exhausted: true }); } catch { /* 忽略 */ }
|
|
425
|
+
}
|
|
426
|
+
yield { type: 'finish', reason: { kind: 'error', failure: finalFailure } };
|
|
427
|
+
}
|
|
428
|
+
|
|
429
|
+
function toFailure(failure) {
|
|
430
|
+
const message = describeError(failure);
|
|
431
|
+
const code = (failure && failure.code) || 'ALL_MEMBERS_FAILED';
|
|
432
|
+
return { code, message };
|
|
433
|
+
}
|
|
434
|
+
|
|
435
|
+
/** 判断一次请求是否含有图片输入(据此只路由到多模态成员)。 */
|
|
436
|
+
export function requestHasImage(options) {
|
|
437
|
+
const messages = (options && options.messages) || [];
|
|
438
|
+
for (const msg of messages) {
|
|
439
|
+
const content = msg && msg.content;
|
|
440
|
+
if (!content) continue;
|
|
441
|
+
if (Array.isArray(content)) {
|
|
442
|
+
for (const part of content) {
|
|
443
|
+
if (part && (part.type === 'image' || part.type === 'image-url' || part.type === 'input-image')) return true;
|
|
444
|
+
}
|
|
445
|
+
}
|
|
446
|
+
}
|
|
447
|
+
return false;
|
|
448
|
+
}
|
|
449
|
+
|
|
450
|
+
/** 成员是否具备视觉/图片输入能力。 */
|
|
451
|
+
export function memberSupportsImage(member) {
|
|
452
|
+
const mods = (member && member.inputModalities) || [];
|
|
453
|
+
if (mods.includes('image')) return true;
|
|
454
|
+
// 防御:未标注模态时按 id 名称兜底推断。
|
|
455
|
+
return /vision|vl\b|omni|diffusion|image/i.test(String((member && member.id) || ''));
|
|
456
|
+
}
|
|
457
|
+
|
|
458
|
+
/**
|
|
459
|
+
* 构造一个 DSH LlmAdapter 形态的“模型组”适配器。deps 全部注入,便于测试。
|
|
460
|
+
* @param {{
|
|
461
|
+
* groupId?:string, groupName?:string,
|
|
462
|
+
* getMembers:()=>Promise<Array<{id:string,name?:string,description?:string,inputModalities?:string[]}>>,
|
|
463
|
+
* streamChild:(childOptions:object)=>AsyncIterable<any>,
|
|
464
|
+
* health:any, childProvider?:string, firstByteTimeoutMs?:number,
|
|
465
|
+
* onAttempt?:Function, onFailover?:Function,
|
|
466
|
+
* }} deps
|
|
467
|
+
*/
|
|
468
|
+
export function createGroupAdapter(deps) {
|
|
469
|
+
const groupName = deps.groupName || 'NVIDIA 模型组';
|
|
470
|
+
const getMembers = deps.getMembers;
|
|
471
|
+
const adapter = {
|
|
472
|
+
providerInfo(provider) { return { id: provider, name: groupName }; },
|
|
473
|
+
providerRetryPolicy() { return undefined; },
|
|
474
|
+
async listModels(provider) {
|
|
475
|
+
const members = await getMembers();
|
|
476
|
+
// 虚拟「自动」成员放在第一位:用户选择它即表示「不指定首选、纯按实时健康排序」。
|
|
477
|
+
const auto = { provider, id: AUTO_MEMBER_ID, name: AUTO_MEMBER_NAME, description: AUTO_MEMBER_DESC };
|
|
478
|
+
return [auto, ...members.map((m) => {
|
|
479
|
+
const out = { provider, id: m.id, name: m.name || m.id };
|
|
480
|
+
if (m.description) out.description = m.description;
|
|
481
|
+
if (Array.isArray(m.inputModalities) && m.inputModalities.length) out.inputModalities = m.inputModalities;
|
|
482
|
+
return out;
|
|
483
|
+
})];
|
|
484
|
+
},
|
|
485
|
+
async resolveModel(provider, model) {
|
|
486
|
+
const members = await getMembers();
|
|
487
|
+
if (isAutoMemberId(model)) {
|
|
488
|
+
// 「自动」是个虚拟成员:取组内上报的最大上下文窗口,绝不虚假声明成 128K
|
|
489
|
+
// (声明过小会让 pi-ai 在本会话这种长上下文下误判为溢出)。
|
|
490
|
+
let maxCtx = 0;
|
|
491
|
+
for (const m of members) {
|
|
492
|
+
if (Number.isFinite(m.contextWindow) && m.contextWindow > maxCtx) maxCtx = m.contextWindow;
|
|
493
|
+
}
|
|
494
|
+
const autoCtx = maxCtx > 0 ? maxCtx : 1048576;
|
|
495
|
+
return {
|
|
496
|
+
provider,
|
|
497
|
+
id: model,
|
|
498
|
+
name: AUTO_MEMBER_NAME,
|
|
499
|
+
description: AUTO_MEMBER_DESC,
|
|
500
|
+
context: { contextWindow: autoCtx },
|
|
501
|
+
defaultMaxTokens: 8192,
|
|
502
|
+
};
|
|
503
|
+
}
|
|
504
|
+
const hit = members.find((m) => m.id === model) || {};
|
|
505
|
+
const info = { provider, id: model, name: hit.name || model };
|
|
506
|
+
if (hit.description) info.description = hit.description;
|
|
507
|
+
if (Array.isArray(hit.inputModalities) && hit.inputModalities.length) info.inputModalities = hit.inputModalities;
|
|
508
|
+
if (Number.isFinite(hit.contextWindow) && hit.contextWindow > 0) info.context = { contextWindow: Math.round(hit.contextWindow) };
|
|
509
|
+
if (Number.isFinite(hit.maxTokens) && hit.maxTokens > 0) info.defaultMaxTokens = Math.round(hit.maxTokens);
|
|
510
|
+
return info;
|
|
511
|
+
},
|
|
512
|
+
async prepareCall(provider, model) {
|
|
513
|
+
const resolved = await adapter.resolveModel(provider, model);
|
|
514
|
+
return { model: resolved, stream: (options) => adapter.stream(options) };
|
|
515
|
+
},
|
|
516
|
+
stream(options) {
|
|
517
|
+
const sessionId = options && options.sessionId;
|
|
518
|
+
return (async function* () {
|
|
519
|
+
let members = [];
|
|
520
|
+
try {
|
|
521
|
+
members = await getMembers();
|
|
522
|
+
} catch {
|
|
523
|
+
members = [];
|
|
524
|
+
}
|
|
525
|
+
if (!members.length) {
|
|
526
|
+
yield {
|
|
527
|
+
type: 'finish',
|
|
528
|
+
reason: { kind: 'error', failure: { code: 'EMPTY_GROUP', message: 'NVIDIA 模型组当前没有可用成员,请先在面板中检测并配置模型' } },
|
|
529
|
+
};
|
|
530
|
+
return;
|
|
531
|
+
}
|
|
532
|
+
const pickAuto = isAutoMemberId(options && options.model);
|
|
533
|
+
const current = pickAuto ? null : members.find((m) => m.id === (options && options.model));
|
|
534
|
+
// 手动选中具体模型 = 锁定该模型:候选只保留它本身,不做任何自动故障转移。
|
|
535
|
+
// 这样失败就如实报错,不会悄悄切到别的成员、也不会在面板"自动切换"里计数。
|
|
536
|
+
// 只有选「模型组(自动)」时才把全部成员交给故障转移引擎轮询。
|
|
537
|
+
let candidates = current ? [current] : members;
|
|
538
|
+
// 能力感知路由(软过滤):含图片的请求**优先**把多模态成员排到前面,
|
|
539
|
+
// 但保留全部成员作为后备。绝不把组员砍到只剩"看起来支持图片"的那几个——
|
|
540
|
+
// id 正则判断并不可靠(如 muse-glimmer 实为多模态却被判为纯文本),
|
|
541
|
+
// 一旦把其余成员剔除,组里常常只剩 1~2 人,一个抖动就整轮失败。
|
|
542
|
+
// 纯文本成员若真的收到图片,会由上游报 400,isCapabilityMismatch 归为
|
|
543
|
+
// INVALID_REQUEST 类 → 直接换下一个且不熔断,代价可控。
|
|
544
|
+
if (requestHasImage(options)) {
|
|
545
|
+
const visionCapable = candidates.filter((m) => memberSupportsImage(m));
|
|
546
|
+
const rest = candidates.filter((m) => !memberSupportsImage(m));
|
|
547
|
+
if (visionCapable.length) candidates = [...visionCapable, ...rest];
|
|
548
|
+
}
|
|
549
|
+
const onAttempt = deps.onAttempt
|
|
550
|
+
? (info) => deps.onAttempt({ ...info, sessionId })
|
|
551
|
+
: undefined;
|
|
552
|
+
const onFailover = deps.onFailover
|
|
553
|
+
? (info) => deps.onFailover({ ...info, sessionId })
|
|
554
|
+
: undefined;
|
|
555
|
+
yield* runFailover(options, {
|
|
556
|
+
streamChild: deps.streamChild,
|
|
557
|
+
health: deps.health,
|
|
558
|
+
candidates,
|
|
559
|
+
childProvider: deps.childProvider || 'nvidia',
|
|
560
|
+
firstByteTimeoutMs: deps.firstByteTimeoutMs,
|
|
561
|
+
firstTextTimeoutMs: deps.firstTextTimeoutMs,
|
|
562
|
+
onAttempt,
|
|
563
|
+
onFailover,
|
|
564
|
+
});
|
|
565
|
+
})();
|
|
566
|
+
},
|
|
567
|
+
};
|
|
568
|
+
return adapter;
|
|
569
|
+
}
|
|
570
|
+
|
|
571
|
+
/* ───────────────────────── 会话投影状态(无 zod,自带校验) ───────────────────────── */
|
|
572
|
+
|
|
573
|
+
/** 空投影状态。 */
|
|
574
|
+
export function createGroupState() {
|
|
575
|
+
return { members: {}, timeline: [] };
|
|
576
|
+
}
|
|
577
|
+
|
|
578
|
+
/** 手工校验/规整投影状态:只容许预期形状,异常输入回落到空状态。 */
|
|
579
|
+
export function parseGroupState(value) {
|
|
580
|
+
if (!value || typeof value !== 'object') return createGroupState();
|
|
581
|
+
const members = {};
|
|
582
|
+
const rawMembers = value.members && typeof value.members === 'object' ? value.members : {};
|
|
583
|
+
for (const id of Object.keys(rawMembers)) {
|
|
584
|
+
const e = rawMembers[id];
|
|
585
|
+
if (!e || typeof e !== 'object') continue;
|
|
586
|
+
members[id] = {
|
|
587
|
+
status: typeof e.status === 'string' ? e.status : 'unknown',
|
|
588
|
+
failCount: Number.isFinite(e.failCount) ? e.failCount : 0,
|
|
589
|
+
lastError: typeof e.lastError === 'string' ? e.lastError : '',
|
|
590
|
+
cooldownUntil: Number.isFinite(e.cooldownUntil) ? e.cooldownUntil : 0,
|
|
591
|
+
lastSuccessAt: Number.isFinite(e.lastSuccessAt) ? e.lastSuccessAt : null,
|
|
592
|
+
};
|
|
593
|
+
}
|
|
594
|
+
const timeline = Array.isArray(value.timeline)
|
|
595
|
+
? value.timeline.filter((t) => t && typeof t === 'object').slice(-30).map((t) => ({
|
|
596
|
+
at: Number.isFinite(t.at) ? t.at : 0,
|
|
597
|
+
type: typeof t.type === 'string' ? t.type : 'event',
|
|
598
|
+
member: typeof t.member === 'string' ? t.member : '',
|
|
599
|
+
to: typeof t.to === 'string' ? t.to : '',
|
|
600
|
+
error: typeof t.error === 'string' ? t.error : '',
|
|
601
|
+
}))
|
|
602
|
+
: [];
|
|
603
|
+
return { members, timeline };
|
|
604
|
+
}
|
|
605
|
+
|
|
606
|
+
/** 一个满足 `.parse()` 契约的极简 schema(避免引入 zod 依赖)。 */
|
|
607
|
+
export function makeSchema() {
|
|
608
|
+
return { parse: (value) => parseGroupState(value) };
|
|
609
|
+
}
|
|
610
|
+
|
|
611
|
+
// 事件类型名:新版走 harness 官方 plugin record(plugin: 命名空间 + 自动
|
|
612
|
+
// ignorable),旧版遗留 nvidia-group/* 仍需识别以便回放历史会话。
|
|
613
|
+
const PROBE_TYPES = new Set(['nvidia-group/probe', 'plugin:dsh-nvidia-models-panel/probe']);
|
|
614
|
+
const FAILOVER_TYPES = new Set(['nvidia-group/failover', 'plugin:dsh-nvidia-models-panel/failover']);
|
|
615
|
+
|
|
616
|
+
/** 把一条组事件(新旧类型名)折进投影状态。 */
|
|
617
|
+
export function foldGroupEvent(state, event) {
|
|
618
|
+
const s = parseGroupState(state);
|
|
619
|
+
const type = event && event.type;
|
|
620
|
+
const data = (event && event.data) || {};
|
|
621
|
+
const at = Number.isFinite(event && event.time) ? event.time : Date.now();
|
|
622
|
+
if (FAILOVER_TYPES.has(type)) {
|
|
623
|
+
const from = String(data.from || '');
|
|
624
|
+
const to = String(data.to || '');
|
|
625
|
+
const members = { ...s.members };
|
|
626
|
+
if (from) {
|
|
627
|
+
const prev = members[from] || { status: 'unknown', failCount: 0, lastError: '', cooldownUntil: 0, lastSuccessAt: null };
|
|
628
|
+
members[from] = { ...prev, status: 'failed', failCount: (prev.failCount || 0) + 1, lastError: String(data.error || prev.lastError || '') };
|
|
629
|
+
}
|
|
630
|
+
if (to) {
|
|
631
|
+
const prev = members[to] || { status: 'unknown', failCount: 0, lastError: '', cooldownUntil: 0, lastSuccessAt: null };
|
|
632
|
+
members[to] = { ...prev, status: 'ok', failCount: 0, lastSuccessAt: at };
|
|
633
|
+
}
|
|
634
|
+
const timeline = s.timeline.concat([{ at, type: 'failover', member: from, to, error: String(data.error || '') }]).slice(-30);
|
|
635
|
+
return { members, timeline };
|
|
636
|
+
}
|
|
637
|
+
if (PROBE_TYPES.has(type)) {
|
|
638
|
+
const id = String(data.member || '');
|
|
639
|
+
if (!id) return s;
|
|
640
|
+
const members = { ...s.members };
|
|
641
|
+
const prev = members[id] || { status: 'unknown', failCount: 0, lastError: '', cooldownUntil: 0, lastSuccessAt: null };
|
|
642
|
+
members[id] = {
|
|
643
|
+
...prev,
|
|
644
|
+
status: data.status === 'ok' ? 'ok' : (data.status === 'fail' ? 'failed' : prev.status),
|
|
645
|
+
lastError: data.status === 'fail' ? String(data.error || prev.lastError || '') : (data.status === 'ok' ? '' : prev.lastError),
|
|
646
|
+
lastSuccessAt: data.status === 'ok' ? at : prev.lastSuccessAt,
|
|
647
|
+
};
|
|
648
|
+
return { members, timeline: s.timeline };
|
|
649
|
+
}
|
|
650
|
+
if (type === 'nvidia-group/reset') return createGroupState();
|
|
651
|
+
return s;
|
|
652
|
+
}
|