odant-work 1.0.36 → 1.0.38
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/#system/package-manifest.json +31 -31
- package/$server/$folder/$file/$task/handlers/pages/form/file/$handler/file.js +18 -2
- package/$server/$folder/$file/$task/handlers/pages/form/file/$handler/ui/docs.js +15 -0
- package/$server/$folder/$file/$task/handlers/pages/form/file/$handler/ui/feed.js +7 -3
- package/$server/$folder/handlers/pages/form/$handler/form.js +1 -1
- package/$server/$folder/lib/consultant/consultant.js +18 -45
- package/$server/$folder/lib/prompt-bar/prompt-bar.js +7 -5
- package/MODELS/$ai/$folder/$class/$ai/class.js +135 -10
- package/MODELS/$ai/$folder/$class/$ai/handlers/pages/form/trainer/$handler/trainer.js +183 -10
- package/MODELS/$ai/$folder/$class/$ai/methods/chat/$method/class.js +19 -0
- package/MODELS/$ai/$folder/$class/$provider/handlers/pages/form/trainer/$handler/trainer.js +91 -0
- package/oda/components/containers/popover/popover.js +225 -212
- package/oda/core/shared.js +1 -1
- package/oda/oda.js +4 -2
- package/package.json +1 -1
- package/sources/data/progress.md +11 -0
- package/sources/modules/agent/index.js +47 -3
- package/sources/modules/agent/loop.js +6 -0
- package/sources/modules/agent/session.js +2 -2
- package/sources/modules/agent/voice.js +29 -1
- package/sources/modules/rag/config.js +75 -75
- package/sources/modules/rag/embedder.js +118 -81
- package/sources/modules/rag/search.js +31 -5
- package/sources/modules/rag/store.js +3 -1
- package/sources/modules/trainer/index.js +210 -0
- package/sources/modules/trainer/local-engine.js +244 -1
- package/sources/modules/trainer/worker/local_infer_worker.py +319 -1
- package/sources/server/class.js +6 -0
|
@@ -320,6 +320,11 @@ export default {
|
|
|
320
320
|
|
|
321
321
|
// Вызовы инструментов копятся по index (параллельные tool_calls), отдаются одним событием в конце.
|
|
322
322
|
const calls = [];
|
|
323
|
+
const tStart = Date.now();
|
|
324
|
+
let tFirstToken = 0;
|
|
325
|
+
let lastToolProgressAt = 0;
|
|
326
|
+
let streamedChars = 0;
|
|
327
|
+
let emittedUsage = false;
|
|
323
328
|
const noteCall = (idx, id, name, args) => {
|
|
324
329
|
const e = calls[idx] ??= { id: '', name: '', args: '' };
|
|
325
330
|
if (id)
|
|
@@ -328,6 +333,24 @@ export default {
|
|
|
328
333
|
e.name = name;
|
|
329
334
|
if (args != null)
|
|
330
335
|
e.args = appendFunctionArgs(e.args, args);
|
|
336
|
+
return e;
|
|
337
|
+
};
|
|
338
|
+
const buildSpeedMeta = (completionTokens, timings) => {
|
|
339
|
+
const now = Date.now();
|
|
340
|
+
const ttftMs = tFirstToken ? Math.max(1, tFirstToken - tStart) : Math.max(1, now - tStart);
|
|
341
|
+
const decodeMs = tFirstToken ? Math.max(1, now - tFirstToken) : ttftMs;
|
|
342
|
+
const predPerSec = Number(timings?.predicted_per_second) || 0;
|
|
343
|
+
const promptPerSec = Number(timings?.prompt_per_second) || 0;
|
|
344
|
+
const estTok = completionTokens > 0 ? completionTokens : Math.round(streamedChars / 4);
|
|
345
|
+
const tokPerSec = predPerSec > 0
|
|
346
|
+
? +predPerSec.toFixed(1)
|
|
347
|
+
: (estTok > 0 && decodeMs > 0 ? +((estTok * 1000) / decodeMs).toFixed(1) : 0);
|
|
348
|
+
return {
|
|
349
|
+
ttftMs,
|
|
350
|
+
decodeMs,
|
|
351
|
+
...(tokPerSec > 0 ? { tokPerSec } : {}),
|
|
352
|
+
...(promptPerSec > 0 ? { promptTokPerSec: +promptPerSec.toFixed(1) } : {}),
|
|
353
|
+
};
|
|
331
354
|
};
|
|
332
355
|
// Конец ответа: finish_reason и/или [DONE]; без обоих — поток оборвался (цикл агента повторит ход).
|
|
333
356
|
let finishReason = null;
|
|
@@ -359,16 +382,49 @@ export default {
|
|
|
359
382
|
finishReason = String(json.choices[0].finish_reason);
|
|
360
383
|
const delta = json.choices?.[0]?.delta || json.choices?.[0]?.message || {};
|
|
361
384
|
const reasoning = delta.reasoning ?? delta.reasoning_content;
|
|
362
|
-
if (reasoning)
|
|
385
|
+
if (reasoning) {
|
|
386
|
+
tFirstToken ||= Date.now();
|
|
387
|
+
streamedChars += String(reasoning).length;
|
|
363
388
|
yield { type: 'reasoning', content: String(reasoning) };
|
|
389
|
+
}
|
|
364
390
|
const content = delta.content || delta.text;
|
|
365
|
-
if (content)
|
|
391
|
+
if (content) {
|
|
392
|
+
tFirstToken ||= Date.now();
|
|
393
|
+
streamedChars += String(content).length;
|
|
366
394
|
yield String(content);
|
|
367
|
-
|
|
368
|
-
|
|
369
|
-
|
|
370
|
-
|
|
371
|
-
|
|
395
|
+
}
|
|
396
|
+
let activeTool = null;
|
|
397
|
+
if (Array.isArray(delta.tool_calls)) {
|
|
398
|
+
tFirstToken ||= Date.now();
|
|
399
|
+
for (const tc of delta.tool_calls) {
|
|
400
|
+
const entry = noteCall(tc.index ?? 0, tc.id, tc.function?.name, tc.function?.arguments);
|
|
401
|
+
if (tc.function?.arguments)
|
|
402
|
+
streamedChars += String(tc.function.arguments).length;
|
|
403
|
+
if (entry?.name)
|
|
404
|
+
activeTool = { index: tc.index ?? 0, entry, freshName: Boolean(tc.function?.name) };
|
|
405
|
+
}
|
|
406
|
+
}
|
|
407
|
+
if (delta.function_call) {
|
|
408
|
+
tFirstToken ||= Date.now();
|
|
409
|
+
const entry = noteCall(0, null, delta.function_call.name, delta.function_call.arguments);
|
|
410
|
+
if (delta.function_call.arguments)
|
|
411
|
+
streamedChars += String(delta.function_call.arguments).length;
|
|
412
|
+
if (entry?.name)
|
|
413
|
+
activeTool = { index: 0, entry, freshName: Boolean(delta.function_call.name) };
|
|
414
|
+
}
|
|
415
|
+
if (activeTool) {
|
|
416
|
+
const now = Date.now();
|
|
417
|
+
if (activeTool.freshName || now - lastToolProgressAt >= 200) {
|
|
418
|
+
lastToolProgressAt = now;
|
|
419
|
+
yield {
|
|
420
|
+
type: 'tool_progress',
|
|
421
|
+
index: activeTool.index,
|
|
422
|
+
name: activeTool.entry.name,
|
|
423
|
+
target: extractToolTarget(activeTool.entry.args),
|
|
424
|
+
chars: activeTool.entry.args.length,
|
|
425
|
+
};
|
|
426
|
+
}
|
|
427
|
+
}
|
|
372
428
|
if (json.usage) {
|
|
373
429
|
const u = json.usage;
|
|
374
430
|
const timings = json.timings || lastTimings || null;
|
|
@@ -382,12 +438,14 @@ export default {
|
|
|
382
438
|
promptTokens = (Number(u.input_tokens) || 0) + cached + cacheWrite;
|
|
383
439
|
const completionTokens = Number(u.completion_tokens ?? u.completionTokens ?? u.output_tokens ?? 0) || 0;
|
|
384
440
|
const totalTokens = Number(u.total_tokens ?? u.totalTokens ?? (promptTokens + completionTokens)) || 0;
|
|
441
|
+
emittedUsage = true;
|
|
385
442
|
yield {
|
|
386
443
|
type: 'usage',
|
|
387
444
|
prompt_tokens: promptTokens,
|
|
388
445
|
completion_tokens: completionTokens,
|
|
389
446
|
total_tokens: totalTokens,
|
|
390
447
|
cached_tokens: cached,
|
|
448
|
+
...buildSpeedMeta(completionTokens, timings),
|
|
391
449
|
...(u.completion_tokens_details ? { completion_tokens_details: u.completion_tokens_details } : {}),
|
|
392
450
|
...(timings ? { timings } : {}),
|
|
393
451
|
...(halogenFromHeader ? { halogen_from: halogenFromHeader } : {}),
|
|
@@ -413,6 +471,21 @@ export default {
|
|
|
413
471
|
if (String(buf || '').trim())
|
|
414
472
|
yield* parseLine(buf.trim());
|
|
415
473
|
|
|
474
|
+
if (!emittedUsage && (lastTimings || tFirstToken || streamedChars > 0)) {
|
|
475
|
+
const predCount = Number(lastTimings?.predicted_n) || Math.round(streamedChars / 4);
|
|
476
|
+
const promptCount = Number(lastTimings?.prompt_n) || 0;
|
|
477
|
+
yield {
|
|
478
|
+
type: 'usage',
|
|
479
|
+
prompt_tokens: promptCount,
|
|
480
|
+
completion_tokens: predCount,
|
|
481
|
+
total_tokens: promptCount + predCount,
|
|
482
|
+
cached_tokens: Number(lastTimings?.cache_n) || 0,
|
|
483
|
+
...buildSpeedMeta(predCount, lastTimings),
|
|
484
|
+
...(lastTimings ? { timings: lastTimings } : {}),
|
|
485
|
+
...(halogenFromHeader ? { halogen_from: halogenFromHeader } : {}),
|
|
486
|
+
};
|
|
487
|
+
}
|
|
488
|
+
|
|
416
489
|
// reasoning не подменяем content: silent-меню иначе получает абзац «think»
|
|
417
490
|
const done = calls.filter(c => c && c.name);
|
|
418
491
|
if (done.length)
|
|
@@ -438,6 +511,8 @@ export default {
|
|
|
438
511
|
const ai = params.$ai || this;
|
|
439
512
|
if (!hasCap(ai, 'image'))
|
|
440
513
|
throw new Error('generateImage: у модели нет capabilities image');
|
|
514
|
+
if (isLocalDirectModel(ai) && typeof WORK?.localEngine?.generateImage === 'function')
|
|
515
|
+
return WORK.localEngine.generateImage(ai, params);
|
|
441
516
|
const prompt = String(params.prompt || params.post || '').trim();
|
|
442
517
|
if (!prompt)
|
|
443
518
|
throw new Error('generateImage: пустой prompt');
|
|
@@ -501,6 +576,8 @@ export default {
|
|
|
501
576
|
const ai = params.$ai || this;
|
|
502
577
|
if (!hasCap(ai, 'tts'))
|
|
503
578
|
throw new Error('speak: у модели нет capabilities tts');
|
|
579
|
+
if (isLocalDirectModel(ai) && typeof WORK?.localEngine?.speak === 'function')
|
|
580
|
+
return WORK.localEngine.speak(ai, params);
|
|
504
581
|
const text = String(params.text ?? params.post ?? '').trim().slice(0, 1500);
|
|
505
582
|
if (!text)
|
|
506
583
|
throw new Error('speak: пустой текст');
|
|
@@ -583,6 +660,8 @@ export default {
|
|
|
583
660
|
const ai = params.$ai || this;
|
|
584
661
|
if (!hasCap(ai, 'stt'))
|
|
585
662
|
throw new Error('transcribe: у модели нет capabilities stt');
|
|
663
|
+
if (isLocalDirectModel(ai) && typeof WORK?.localEngine?.transcribe === 'function')
|
|
664
|
+
return WORK.localEngine.transcribe(ai, params);
|
|
586
665
|
const audio = Buffer.isBuffer(params.audio) ? params.audio : null;
|
|
587
666
|
if (!audio?.length)
|
|
588
667
|
throw new Error('transcribe: нет аудио');
|
|
@@ -627,6 +706,8 @@ export default {
|
|
|
627
706
|
*/
|
|
628
707
|
async embed(params = {}) {
|
|
629
708
|
const ai = params.$ai || this;
|
|
709
|
+
if (isLocalDirectModel(ai) && typeof WORK?.localEngine?.embed === 'function')
|
|
710
|
+
return WORK.localEngine.embed(ai, params);
|
|
630
711
|
const tag = String(params.model || ai.model || 'qwen3-embedding-0.6b').trim();
|
|
631
712
|
const input = params.input ?? params.text ?? params.post ?? '';
|
|
632
713
|
const origin = speechOrigin(params, ai, 'embed');
|
|
@@ -660,6 +741,8 @@ export default {
|
|
|
660
741
|
*/
|
|
661
742
|
async rerank(params = {}) {
|
|
662
743
|
const ai = params.$ai || this;
|
|
744
|
+
if (isLocalDirectModel(ai) && typeof WORK?.localEngine?.rerank === 'function')
|
|
745
|
+
return WORK.localEngine.rerank(ai, params);
|
|
663
746
|
const tag = String(params.model || ai.model || 'qwen3-reranker-0.6b').trim();
|
|
664
747
|
const query = String(params.query || '').trim();
|
|
665
748
|
const documents = Array.isArray(params.documents) ? params.documents : [];
|
|
@@ -695,6 +778,8 @@ export default {
|
|
|
695
778
|
*/
|
|
696
779
|
async decide(params = {}) {
|
|
697
780
|
const ai = params.$ai || this;
|
|
781
|
+
if (isLocalDirectModel(ai) && typeof WORK?.localEngine?.decide === 'function')
|
|
782
|
+
return WORK.localEngine.decide(ai, params);
|
|
698
783
|
const tag = String(params.model || ai.model || 'decider-0.8b').trim();
|
|
699
784
|
const origin = speechOrigin(params, ai, 'decide');
|
|
700
785
|
const headers = await getAuthHeaders(ai);
|
|
@@ -728,6 +813,13 @@ function isHalogenModel(ai) {
|
|
|
728
813
|
|| (p.startsWith('/MODELS/Local/') && b.includes(':8731'));
|
|
729
814
|
}
|
|
730
815
|
|
|
816
|
+
function isLocalDirectModel(ai) {
|
|
817
|
+
const p = String(ai?.path || ai?.short || '');
|
|
818
|
+
const b = String(ai?.baseUrl || ai?.DATA?.baseUrl || '').trim();
|
|
819
|
+
return ai?.protocol === 'local'
|
|
820
|
+
|| (p.startsWith('/MODELS/Local/') && !b && ai?.protocol !== 'halogen');
|
|
821
|
+
}
|
|
822
|
+
|
|
731
823
|
function speechOrigin(params, ai, who) {
|
|
732
824
|
const base = String(ai.baseUrl || ai.DATA?.baseUrl || '').trim();
|
|
733
825
|
if (!base)
|
|
@@ -1392,6 +1484,9 @@ const ANTHROPIC_STOP = { end_turn: 'stop', stop_sequence: 'stop', tool_use: 'too
|
|
|
1392
1484
|
export function createAnthropicParser(model = '') {
|
|
1393
1485
|
const blocks = [];
|
|
1394
1486
|
const usage = { input: 0, cacheRead: 0, cacheWrite: 0, output: 0 };
|
|
1487
|
+
const tStart = Date.now();
|
|
1488
|
+
let tFirstToken = 0;
|
|
1489
|
+
let lastToolProgressAt = 0;
|
|
1395
1490
|
let stop = null;
|
|
1396
1491
|
let done = false;
|
|
1397
1492
|
const takeUsage = u => {
|
|
@@ -1412,18 +1507,35 @@ export function createAnthropicParser(model = '') {
|
|
|
1412
1507
|
case 'content_block_start': {
|
|
1413
1508
|
const cb = ev.content_block || {};
|
|
1414
1509
|
blocks[ev.index] = { type: cb.type, id: cb.id, name: cb.name, args: '', thinking: cb.thinking || '', signature: cb.signature || '', data: cb.data };
|
|
1415
|
-
if (cb.type === 'text' && cb.text)
|
|
1510
|
+
if (cb.type === 'text' && cb.text) {
|
|
1511
|
+
tFirstToken ||= Date.now();
|
|
1416
1512
|
out.push(String(cb.text));
|
|
1513
|
+
}
|
|
1514
|
+
else if (cb.type === 'tool_use' && cb.name) {
|
|
1515
|
+
tFirstToken ||= Date.now();
|
|
1516
|
+
lastToolProgressAt = Date.now();
|
|
1517
|
+
out.push({ type: 'tool_progress', index: ev.index, name: cb.name, target: '', chars: 0 });
|
|
1518
|
+
}
|
|
1417
1519
|
break;
|
|
1418
1520
|
}
|
|
1419
1521
|
case 'content_block_delta': {
|
|
1420
1522
|
const d = ev.delta || {};
|
|
1421
1523
|
const b = blocks[ev.index] ??= { type: d.type === 'input_json_delta' ? 'tool_use' : 'text', args: '', thinking: '', signature: '' };
|
|
1422
|
-
if (d.type === 'text_delta' && d.text)
|
|
1524
|
+
if (d.type === 'text_delta' && d.text) {
|
|
1525
|
+
tFirstToken ||= Date.now();
|
|
1423
1526
|
out.push(String(d.text));
|
|
1424
|
-
|
|
1527
|
+
}
|
|
1528
|
+
else if (d.type === 'input_json_delta') {
|
|
1529
|
+
tFirstToken ||= Date.now();
|
|
1425
1530
|
b.args += d.partial_json || '';
|
|
1531
|
+
const now = Date.now();
|
|
1532
|
+
if (b.name && now - lastToolProgressAt >= 200) {
|
|
1533
|
+
lastToolProgressAt = now;
|
|
1534
|
+
out.push({ type: 'tool_progress', index: ev.index, name: b.name, target: extractToolTarget(b.args), chars: b.args.length });
|
|
1535
|
+
}
|
|
1536
|
+
}
|
|
1426
1537
|
else if (d.type === 'thinking_delta' && d.thinking) {
|
|
1538
|
+
tFirstToken ||= Date.now();
|
|
1427
1539
|
b.thinking += d.thinking;
|
|
1428
1540
|
out.push({ type: 'reasoning', content: String(d.thinking) });
|
|
1429
1541
|
}
|
|
@@ -1455,9 +1567,14 @@ export function createAnthropicParser(model = '') {
|
|
|
1455
1567
|
if (calls.length)
|
|
1456
1568
|
out.push({ type: 'tool_calls', calls });
|
|
1457
1569
|
const prompt = usage.input + usage.cacheRead + usage.cacheWrite;
|
|
1570
|
+
const now = Date.now();
|
|
1571
|
+
const ttftMs = tFirstToken ? Math.max(1, tFirstToken - tStart) : Math.max(1, now - tStart);
|
|
1572
|
+
const decodeMs = tFirstToken ? Math.max(1, now - tFirstToken) : ttftMs;
|
|
1573
|
+
const tokPerSec = usage.output > 0 && decodeMs > 0 ? +((usage.output * 1000) / decodeMs).toFixed(1) : 0;
|
|
1458
1574
|
out.push({
|
|
1459
1575
|
type: 'usage', prompt_tokens: prompt, completion_tokens: usage.output, total_tokens: prompt + usage.output,
|
|
1460
1576
|
cached_tokens: usage.cacheRead, cache_creation_tokens: usage.cacheWrite,
|
|
1577
|
+
ttftMs, decodeMs, ...(tokPerSec > 0 ? { tokPerSec } : {}),
|
|
1461
1578
|
});
|
|
1462
1579
|
out.push({ type: 'finish', reason: stop ? (ANTHROPIC_STOP[stop] || stop) : null, done });
|
|
1463
1580
|
return out;
|
|
@@ -1465,6 +1582,14 @@ export function createAnthropicParser(model = '') {
|
|
|
1465
1582
|
};
|
|
1466
1583
|
}
|
|
1467
1584
|
|
|
1585
|
+
function extractToolTarget(rawArgs) {
|
|
1586
|
+
const s = String(rawArgs || '');
|
|
1587
|
+
const m = /"(?:path|filePath|file|target|command|cmd|query|url|name)"\s*:\s*"((?:[^"\\]|\\.)*)/i.exec(s);
|
|
1588
|
+
if (!m)
|
|
1589
|
+
return '';
|
|
1590
|
+
return m[1].replace(/\\"/g, '"').replace(/\\\\/g, '\\').slice(0, 80);
|
|
1591
|
+
}
|
|
1592
|
+
|
|
1468
1593
|
/** SSE-поток Messages API (res — ответ HTTP) → события адаптера. Строки `event:` не нужны: тип есть в каждом data. */
|
|
1469
1594
|
async function* anthropicStream(res, model) {
|
|
1470
1595
|
const parser = createAnthropicParser(model);
|
|
@@ -268,25 +268,104 @@ export default {
|
|
|
268
268
|
</div>
|
|
269
269
|
|
|
270
270
|
<div class="card">
|
|
271
|
-
<div class="section-title">Быстрая проверка
|
|
272
|
-
<
|
|
271
|
+
<div class="section-title">Быстрая проверка ({{testModalityLabel}})</div>
|
|
272
|
+
<div class="vertical" style="gap:8px;" ~if="testModality === 'llm'">
|
|
273
|
+
<textarea rows="3" :value="testPrompt" placeholder="Введите тестовый вопрос к модели…" @input="testPrompt = $this.value"></textarea>
|
|
274
|
+
</div>
|
|
275
|
+
<div class="vertical" style="gap:8px;" ~if="testModality === 'tts'">
|
|
276
|
+
<textarea rows="2" :value="testTtsText" placeholder="Текст для озвучивания…" @input="testTtsText = $this.value"></textarea>
|
|
277
|
+
</div>
|
|
278
|
+
<div class="vertical" style="gap:8px;" ~if="testModality === 'stt'">
|
|
279
|
+
<div style="font-size:12px;opacity:0.8;">Можно загрузить WAV-файл или запустить автоматическую проверку встроенным тестовым аудиосигналом.</div>
|
|
280
|
+
<input type="file" accept="audio/wav,.wav" @change="onSttFileChange($event)">
|
|
281
|
+
</div>
|
|
282
|
+
<div class="vertical" style="gap:8px;" ~if="testModality === 'image'">
|
|
283
|
+
<textarea rows="2" :value="testImagePrompt" placeholder="Опишите изображение…" @input="testImagePrompt = $this.value"></textarea>
|
|
284
|
+
</div>
|
|
285
|
+
<div class="vertical" style="gap:8px;" ~if="testModality === 'embed'">
|
|
286
|
+
<textarea rows="3" :value="testEmbedInput" placeholder="Строки для векторизации (по одной в строке)…" @input="testEmbedInput = $this.value"></textarea>
|
|
287
|
+
</div>
|
|
288
|
+
<div class="vertical" style="gap:8px;" ~if="testModality === 'rerank'">
|
|
289
|
+
<textarea rows="2" :value="testRerankQuery" placeholder="Поисковый запрос…" @input="testRerankQuery = $this.value"></textarea>
|
|
290
|
+
<textarea rows="3" :value="testRerankDocs" placeholder="Документы (по одному в строке)…" @input="testRerankDocs = $this.value"></textarea>
|
|
291
|
+
</div>
|
|
273
292
|
<div class="toolbar">
|
|
274
293
|
<button type="button" class="btn primary" :disabled="testing" @tap="runTestPrompt()">
|
|
275
|
-
{{testing ? '
|
|
294
|
+
{{testing ? 'Выполняю…' : testButtonLabel}}
|
|
276
295
|
</button>
|
|
277
296
|
</div>
|
|
297
|
+
<div class="msg warn" ~if="testMissingDeps.length">
|
|
298
|
+
<span>Не хватает Python-библиотек: <code>{{testMissingDeps.join(', ')}}</code></span>
|
|
299
|
+
<button type="button" class="btn primary" :disabled="installingDeps" @tap="installMissingDeps()">
|
|
300
|
+
{{installingDeps ? 'Установка…' : 'Доустановить зависимости'}}
|
|
301
|
+
</button>
|
|
302
|
+
</div>
|
|
303
|
+
<div class="toolbar" ~if="testMetricsLine" style="font-size:12px;opacity:0.85;">
|
|
304
|
+
<span class="pill">{{testMetricsLine}}</span>
|
|
305
|
+
</div>
|
|
278
306
|
<div class="reply-box" ~if="testReply">{{testReply}}</div>
|
|
307
|
+
<audio controls ~if="testAudioUrl" :src="testAudioUrl" style="width:100%;"></audio>
|
|
308
|
+
<img ~if="testImageUrl" :src="testImageUrl" style="max-width:100%;max-height:360px;object-fit:contain;border-radius:6px;border:1px solid var(--border-color, #cbd5e1);">
|
|
279
309
|
</div>
|
|
280
310
|
</div>
|
|
281
311
|
`,
|
|
282
312
|
info: null,
|
|
283
313
|
modelEnabled: true,
|
|
284
314
|
testPrompt: 'Привет! Представься коротко в одном предложении.',
|
|
315
|
+
testTtsText: 'Привет! Локальный синтез речи платформы WORK работает.',
|
|
316
|
+
testImagePrompt: 'Минималистичная светлая 3D-иконка офисного здания в стиле современного UI',
|
|
317
|
+
testEmbedInput: 'Учётная система WORK\nОборотно-сальдовая ведомость',
|
|
318
|
+
testRerankQuery: 'остатки на расчётном счёте 51',
|
|
319
|
+
testRerankDocs: 'Счёт 51 «Расчётные счета»: обороты и остатки денежных средств\nДоговор аренды офиса и коммунальные услуги',
|
|
320
|
+
testSttBase64: '',
|
|
285
321
|
testReply: '',
|
|
322
|
+
testAudioUrl: '',
|
|
323
|
+
testImageUrl: '',
|
|
324
|
+
testMetricsLine: '',
|
|
325
|
+
testMissingDeps: [],
|
|
286
326
|
testing: false,
|
|
327
|
+
installingDeps: false,
|
|
287
328
|
busyAction: false,
|
|
288
329
|
notice: '',
|
|
289
330
|
error: '',
|
|
331
|
+
get testModality() {
|
|
332
|
+
const mod = String(this.info?.modality || this.info?.DATA?.modality || '').toLowerCase();
|
|
333
|
+
const caps = (this.capabilities || []).map(c => String(c).toLowerCase());
|
|
334
|
+
const id = String(this.info?.id || this.resolvedModelId || '').toLowerCase();
|
|
335
|
+
if (caps.includes('tts') || mod === 'tts' || mod === 'voice')
|
|
336
|
+
return 'tts';
|
|
337
|
+
if (caps.includes('stt') || caps.includes('asr') || mod === 'stt' || mod === 'asr')
|
|
338
|
+
return 'stt';
|
|
339
|
+
if (caps.includes('image') || caps.includes('text-to-image') || mod === 'image')
|
|
340
|
+
return 'image';
|
|
341
|
+
if (caps.includes('rerank') || mod === 'rerank' || id.includes('rerank'))
|
|
342
|
+
return 'rerank';
|
|
343
|
+
if (caps.includes('embeddings') || caps.includes('rag') || mod === 'embed' || mod === 'embedding')
|
|
344
|
+
return 'embed';
|
|
345
|
+
return 'llm';
|
|
346
|
+
},
|
|
347
|
+
get testModalityLabel() {
|
|
348
|
+
const map = {
|
|
349
|
+
llm: 'Чат / LLM',
|
|
350
|
+
tts: 'Синтез речи (TTS)',
|
|
351
|
+
stt: 'Распознавание речи (STT)',
|
|
352
|
+
image: 'Генерация изображений',
|
|
353
|
+
embed: 'Эмбеддинги (RAG)',
|
|
354
|
+
rerank: 'Реранкинг (RAG)',
|
|
355
|
+
};
|
|
356
|
+
return map[this.testModality] || 'Модель';
|
|
357
|
+
},
|
|
358
|
+
get testButtonLabel() {
|
|
359
|
+
const map = {
|
|
360
|
+
llm: 'Отправить запрос',
|
|
361
|
+
tts: 'Озвучить фразу',
|
|
362
|
+
stt: 'Проверить распознавание',
|
|
363
|
+
image: 'Сгенерировать картинку',
|
|
364
|
+
embed: 'Проверить эмбеддинги',
|
|
365
|
+
rerank: 'Проверить реранкинг',
|
|
366
|
+
};
|
|
367
|
+
return map[this.testModality] || 'Проверить';
|
|
368
|
+
},
|
|
290
369
|
get providerName() {
|
|
291
370
|
const parts = String(this.info?.path || this.$item?.path || '').split('/').filter(Boolean);
|
|
292
371
|
return parts[1] || 'MODELS';
|
|
@@ -422,19 +501,113 @@ export default {
|
|
|
422
501
|
this.error = String(e?.message || e);
|
|
423
502
|
}
|
|
424
503
|
},
|
|
504
|
+
onSttFileChange(e) {
|
|
505
|
+
const f = e?.target?.files?.[0];
|
|
506
|
+
if (!f) {
|
|
507
|
+
this.testSttBase64 = '';
|
|
508
|
+
return;
|
|
509
|
+
}
|
|
510
|
+
const reader = new FileReader();
|
|
511
|
+
reader.onload = () => {
|
|
512
|
+
const res = String(reader.result || '');
|
|
513
|
+
this.testSttBase64 = res.includes(',') ? res.split(',')[1] : '';
|
|
514
|
+
};
|
|
515
|
+
reader.readAsDataURL(f);
|
|
516
|
+
},
|
|
517
|
+
async installMissingDeps() {
|
|
518
|
+
if (!this.$item || !this.testMissingDeps.length)
|
|
519
|
+
return;
|
|
520
|
+
this.installingDeps = true;
|
|
521
|
+
this.error = '';
|
|
522
|
+
this.notice = '';
|
|
523
|
+
try {
|
|
524
|
+
const res = await this.$item.fetch('trainer_install_python_deps', {}, { packages: this.testMissingDeps });
|
|
525
|
+
if (res?.ok) {
|
|
526
|
+
this.testMissingDeps = [];
|
|
527
|
+
this.notice = 'Пакеты установлены: ' + (res.packages || []).join(', ') + '. Повторяем проверку…';
|
|
528
|
+
await this.runTestPrompt();
|
|
529
|
+
}
|
|
530
|
+
else {
|
|
531
|
+
this.error = res?.error || 'Не удалось установить Python-пакеты.';
|
|
532
|
+
}
|
|
533
|
+
}
|
|
534
|
+
catch (e) {
|
|
535
|
+
this.error = String(e?.message || e);
|
|
536
|
+
}
|
|
537
|
+
finally {
|
|
538
|
+
this.installingDeps = false;
|
|
539
|
+
}
|
|
540
|
+
},
|
|
425
541
|
async runTestPrompt() {
|
|
426
|
-
if (!this.$item
|
|
542
|
+
if (!this.$item)
|
|
543
|
+
return;
|
|
544
|
+
const m = this.testModality;
|
|
545
|
+
if (m === 'llm' && !this.testPrompt.trim())
|
|
427
546
|
return;
|
|
428
547
|
this.testing = true;
|
|
429
548
|
this.error = '';
|
|
549
|
+
this.notice = '';
|
|
430
550
|
this.testReply = '';
|
|
551
|
+
this.testAudioUrl = '';
|
|
552
|
+
this.testImageUrl = '';
|
|
553
|
+
this.testMetricsLine = '';
|
|
554
|
+
this.testMissingDeps = [];
|
|
431
555
|
try {
|
|
432
|
-
const
|
|
433
|
-
|
|
434
|
-
|
|
435
|
-
|
|
436
|
-
|
|
437
|
-
|
|
556
|
+
const body = { modality: m };
|
|
557
|
+
if (m === 'llm')
|
|
558
|
+
body.messages = [{ role: 'user', content: this.testPrompt.trim() }];
|
|
559
|
+
else if (m === 'tts')
|
|
560
|
+
body.text = this.testTtsText.trim();
|
|
561
|
+
else if (m === 'stt' && this.testSttBase64)
|
|
562
|
+
body.audioBase64 = this.testSttBase64;
|
|
563
|
+
else if (m === 'image')
|
|
564
|
+
body.prompt = this.testImagePrompt.trim();
|
|
565
|
+
else if (m === 'embed')
|
|
566
|
+
body.input = this.testEmbedInput.split(/\r?\n/).map(s => s.trim()).filter(Boolean);
|
|
567
|
+
else if (m === 'rerank') {
|
|
568
|
+
body.query = this.testRerankQuery.trim();
|
|
569
|
+
body.documents = this.testRerankDocs.split(/\r?\n/).map(s => s.trim()).filter(Boolean);
|
|
570
|
+
}
|
|
571
|
+
|
|
572
|
+
const res = await this.$item.fetch('trainer_test_model', {}, body);
|
|
573
|
+
if (!res?.ok) {
|
|
574
|
+
this.error = res?.error || 'Ошибка проверки модели.';
|
|
575
|
+
if (Array.isArray(res?.missingDeps))
|
|
576
|
+
this.testMissingDeps = res.missingDeps;
|
|
577
|
+
return;
|
|
578
|
+
}
|
|
579
|
+
const parts = [];
|
|
580
|
+
if (res.durationMs)
|
|
581
|
+
parts.push(`Время: ${(res.durationMs / 1000).toFixed(2)} с`);
|
|
582
|
+
if (res.ttftMs)
|
|
583
|
+
parts.push(`TTFT: ${(res.ttftMs / 1000).toFixed(2)} с`);
|
|
584
|
+
if (res.tokPerSec)
|
|
585
|
+
parts.push(`Скорость: ${res.tokPerSec} tok/s`);
|
|
586
|
+
if (res.promptTokPerSec)
|
|
587
|
+
parts.push(`Prefill: ${res.promptTokPerSec} tok/s`);
|
|
588
|
+
if (res.usage?.completion_tokens)
|
|
589
|
+
parts.push(`Токенов: ${res.usage.prompt_tokens || 0} → ${res.usage.completion_tokens}`);
|
|
590
|
+
if (res.summary && m !== 'llm')
|
|
591
|
+
parts.push(res.summary);
|
|
592
|
+
this.testMetricsLine = parts.join(' · ');
|
|
593
|
+
|
|
594
|
+
if (m === 'tts' && res.audioBase64) {
|
|
595
|
+
this.testAudioUrl = 'data:audio/wav;base64,' + res.audioBase64;
|
|
596
|
+
}
|
|
597
|
+
else if (m === 'image' && res.base64) {
|
|
598
|
+
this.testImageUrl = `data:${res.mime || 'image/png'};base64,${res.base64}`;
|
|
599
|
+
}
|
|
600
|
+
else if (m === 'embed') {
|
|
601
|
+
this.testReply = `Получено векторов: ${res.count}, размерность: ${res.dimensions}`;
|
|
602
|
+
}
|
|
603
|
+
else if (m === 'rerank') {
|
|
604
|
+
this.testReply = (res.results || [])
|
|
605
|
+
.map((r, i) => `${i + 1}. [${((r.relevance_score ?? 0) * 100).toFixed(1)}%] ${r.document || ''}`)
|
|
606
|
+
.join('\n');
|
|
607
|
+
}
|
|
608
|
+
else {
|
|
609
|
+
this.testReply = String(res.text ?? '');
|
|
610
|
+
}
|
|
438
611
|
}
|
|
439
612
|
catch (e) {
|
|
440
613
|
this.error = String(e?.message || e);
|
|
@@ -1,10 +1,29 @@
|
|
|
1
1
|
export default {
|
|
2
2
|
async execute(params = {}, post) {
|
|
3
|
+
const t0 = Date.now();
|
|
3
4
|
const gen = this.$context.streamChat(params, post);
|
|
4
5
|
let result = '';
|
|
6
|
+
let usage = null;
|
|
5
7
|
for await (const token of gen) {
|
|
6
8
|
if (typeof token === 'string')
|
|
7
9
|
result += token;
|
|
10
|
+
else if (token?.type === 'usage')
|
|
11
|
+
usage = token;
|
|
12
|
+
}
|
|
13
|
+
if (params?.metrics || post?.metrics) {
|
|
14
|
+
const durationMs = Math.max(1, Date.now() - t0);
|
|
15
|
+
const ttftMs = Number(usage?.ttftMs) || 0;
|
|
16
|
+
const completionTokens = Number(usage?.completion_tokens) || 0;
|
|
17
|
+
const tokPerSec = Number(usage?.tokPerSec)
|
|
18
|
+
|| (completionTokens > 0 ? +((completionTokens * 1000) / Math.max(1, durationMs - ttftMs)).toFixed(1) : 0);
|
|
19
|
+
return {
|
|
20
|
+
text: result,
|
|
21
|
+
durationMs,
|
|
22
|
+
ttftMs,
|
|
23
|
+
tokPerSec,
|
|
24
|
+
promptTokPerSec: Number(usage?.promptTokPerSec) || 0,
|
|
25
|
+
usage,
|
|
26
|
+
};
|
|
8
27
|
}
|
|
9
28
|
return result;
|
|
10
29
|
},
|
|
@@ -389,6 +389,10 @@ export default {
|
|
|
389
389
|
Локальные модели (/MODELS/Local) · установлено: {{localModels.length}}
|
|
390
390
|
</div>
|
|
391
391
|
<div class="toolbar">
|
|
392
|
+
<button type="button" class="btn primary" :disabled="checkingAll" @tap="checkAllModels()">
|
|
393
|
+
<oda-icon icon="carbon:checkmark-outline" icon-size="15"></oda-icon>
|
|
394
|
+
<span>{{checkingAll ? 'Проверяю модели…' : 'Проверить все модели'}}</span>
|
|
395
|
+
</button>
|
|
392
396
|
<button type="button" class="btn" @tap="toggleNetworkPanel()">
|
|
393
397
|
<oda-icon icon="carbon:network-4" icon-size="15"></oda-icon>
|
|
394
398
|
<span>Сеть: {{networkSummary}}</span>
|
|
@@ -404,6 +408,30 @@ export default {
|
|
|
404
408
|
</div>
|
|
405
409
|
</div>
|
|
406
410
|
|
|
411
|
+
<!-- Панель диагностики всех локальных моделей и Python-окружения -->
|
|
412
|
+
<div class="bios-box" ~if="checkAllResult" style="margin-bottom:8px;">
|
|
413
|
+
<div class="model-main" style="margin-bottom:6px;">
|
|
414
|
+
<strong>Диагностика локальных моделей (/MODELS/Local)</strong>
|
|
415
|
+
<div class="toolbar">
|
|
416
|
+
<span class="status-chip ok" ~if="checkAllResult.pythonDeps?.deviceName">Python: {{checkAllResult.pythonDeps.deviceName}}</span>
|
|
417
|
+
<button type="button" class="btn primary" ~if="missingPythonPkgs.length" :disabled="installingPythonDeps" @tap="installMissingPythonDeps()">
|
|
418
|
+
{{installingPythonDeps ? 'Установка…' : ('Доустановить пакеты (' + missingPythonPkgs.join(', ') + ')')}}
|
|
419
|
+
</button>
|
|
420
|
+
</div>
|
|
421
|
+
</div>
|
|
422
|
+
<div class="model-row" ~for="checkAllResult.results || []" style="padding:6px 0;">
|
|
423
|
+
<div class="model-main">
|
|
424
|
+
<div>
|
|
425
|
+
<div class="model-name">{{$for.item.label}} <span style="opacity:0.65;font-weight:normal;">({{$for.item.modality}})</span></div>
|
|
426
|
+
<div class="model-desc">{{$for.item.ok ? $for.item.summary : ($for.item.error || $for.item.summary)}}</div>
|
|
427
|
+
</div>
|
|
428
|
+
<span class="status-chip" ~class="$for.item.ok ? 'ok' : ($for.item.skipped ? 'warn' : 'err')">
|
|
429
|
+
{{$for.item.ok ? 'Работает' : ($for.item.skipped ? 'Пропущена' : 'Ошибка')}}
|
|
430
|
+
</span>
|
|
431
|
+
</div>
|
|
432
|
+
</div>
|
|
433
|
+
</div>
|
|
434
|
+
|
|
407
435
|
<!-- Панель настроек источника (зеркало), потоков и точечного прокси (только для загрузок моделей) -->
|
|
408
436
|
<div id="networkPanel" class="bios-box" ~if="networkOpen">
|
|
409
437
|
<div class="model-main" style="margin-bottom:8px;">
|
|
@@ -719,8 +747,28 @@ export default {
|
|
|
719
747
|
netClearToken: false,
|
|
720
748
|
netBusy: false,
|
|
721
749
|
halogenPrepareState: null,
|
|
750
|
+
checkingAll: false,
|
|
751
|
+
installingPythonDeps: false,
|
|
752
|
+
checkAllResult: null,
|
|
722
753
|
_pollTimer: null,
|
|
723
754
|
|
|
755
|
+
get missingPythonPkgs() {
|
|
756
|
+
const res = this.checkAllResult;
|
|
757
|
+
if (!res)
|
|
758
|
+
return [];
|
|
759
|
+
const set = new Set();
|
|
760
|
+
const pkgs = res.pythonDeps?.packages || {};
|
|
761
|
+
for (const [k, ok] of Object.entries(pkgs)) {
|
|
762
|
+
if (!ok)
|
|
763
|
+
set.add(k);
|
|
764
|
+
}
|
|
765
|
+
for (const r of (res.results || [])) {
|
|
766
|
+
for (const dep of (r.missingDeps || []))
|
|
767
|
+
set.add(dep);
|
|
768
|
+
}
|
|
769
|
+
return [...set];
|
|
770
|
+
},
|
|
771
|
+
|
|
724
772
|
get hasNetworkChanges() {
|
|
725
773
|
const n = this.network || {};
|
|
726
774
|
const savedPreset = n.sourcePreset || 'official';
|
|
@@ -1027,6 +1075,49 @@ export default {
|
|
|
1027
1075
|
return null;
|
|
1028
1076
|
}
|
|
1029
1077
|
},
|
|
1078
|
+
async checkAllModels() {
|
|
1079
|
+
if (!this.$item)
|
|
1080
|
+
return;
|
|
1081
|
+
this.checkingAll = true;
|
|
1082
|
+
this.error = '';
|
|
1083
|
+
this.notice = '';
|
|
1084
|
+
try {
|
|
1085
|
+
const res = await this.$item.fetch('trainer_check_all_models');
|
|
1086
|
+
this.checkAllResult = res;
|
|
1087
|
+
const total = (res?.results || []).filter(r => !r.skipped).length;
|
|
1088
|
+
const passed = (res?.results || []).filter(r => r.ok).length;
|
|
1089
|
+
this.notice = `Проверка завершена: работает ${passed} из ${total} активных моделей.`;
|
|
1090
|
+
}
|
|
1091
|
+
catch (e) {
|
|
1092
|
+
this.error = String(e?.message || e);
|
|
1093
|
+
}
|
|
1094
|
+
finally {
|
|
1095
|
+
this.checkingAll = false;
|
|
1096
|
+
}
|
|
1097
|
+
},
|
|
1098
|
+
async installMissingPythonDeps() {
|
|
1099
|
+
if (!this.$item || !this.missingPythonPkgs.length)
|
|
1100
|
+
return;
|
|
1101
|
+
this.installingPythonDeps = true;
|
|
1102
|
+
this.error = '';
|
|
1103
|
+
this.notice = '';
|
|
1104
|
+
try {
|
|
1105
|
+
const res = await this.$item.fetch('trainer_install_python_deps', {}, { packages: this.missingPythonPkgs });
|
|
1106
|
+
if (res?.ok) {
|
|
1107
|
+
this.notice = 'Пакеты установлены: ' + (res.packages || []).join(', ') + '. Повторяем проверку…';
|
|
1108
|
+
await this.checkAllModels();
|
|
1109
|
+
}
|
|
1110
|
+
else {
|
|
1111
|
+
this.error = res?.error || 'Не удалось установить Python-пакеты.';
|
|
1112
|
+
}
|
|
1113
|
+
}
|
|
1114
|
+
catch (e) {
|
|
1115
|
+
this.error = String(e?.message || e);
|
|
1116
|
+
}
|
|
1117
|
+
finally {
|
|
1118
|
+
this.installingPythonDeps = false;
|
|
1119
|
+
}
|
|
1120
|
+
},
|
|
1030
1121
|
_invalidateClientModelsTree() {
|
|
1031
1122
|
for (const w of [window, window.parent, window.top]) {
|
|
1032
1123
|
try {
|