odant-work 1.0.37 → 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.
@@ -44,6 +44,7 @@ import {
44
44
  } from './runner.js';
45
45
  import {
46
46
  localStreamChat,
47
+ localEngine,
47
48
  getLocalEngineStatus,
48
49
  releaseLocalEngineMemory,
49
50
  touchLocalEngineActivity,
@@ -147,6 +148,7 @@ export const halogenFallback = Object.freeze({
147
148
 
148
149
  export {
149
150
  localStreamChat,
151
+ localEngine,
150
152
  SOURCE_PRESETS,
151
153
  THREAD_OPTIONS,
152
154
  loadTrainerNetworkSettings,
@@ -324,6 +326,147 @@ function stripInventoryFiles(inv) {
324
326
  /**
325
327
  * Методы `trainer_*`, подключаемые к узлам `$class` (в `/MODELS/Local` и локальных `$ai`) и в шлюз `gateway.js`.
326
328
  */
329
+ function inferTestModality(ai) {
330
+ const d = ai?.DATA || {};
331
+ const mod = String(ai?.modality || d.modality || '').toLowerCase();
332
+ const rawCaps = ai?.capabilities ?? d.capabilities ?? [];
333
+ const caps = (Array.isArray(rawCaps) ? rawCaps : String(rawCaps || '').split(/[\s,]+/))
334
+ .map(s => String(s).trim().toLowerCase()).filter(Boolean);
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' || /rerank/i.test(String(ai?.id || ai?.model || '')))
342
+ return 'rerank';
343
+ if (caps.includes('embeddings') || caps.includes('rag') || mod === 'embed' || mod === 'embedding')
344
+ return 'embed';
345
+ return 'llm';
346
+ }
347
+
348
+ async function runSingleModelSmokeTest(ai, p = {}) {
349
+ await ai?.init?.catch?.(() => {});
350
+ const modality = String(p.modality || inferTestModality(ai));
351
+ const t0 = Date.now();
352
+ try {
353
+ if (modality === 'tts') {
354
+ const text = String(p.text || p.prompt || 'Привет! Проверка локального синтеза речи WORK.').trim();
355
+ const buf = await ai.speak({ text, language: p.language, instructions: p.instructions });
356
+ const durationMs = Math.max(1, Date.now() - t0);
357
+ return {
358
+ ok: true,
359
+ modality,
360
+ durationMs,
361
+ bytes: buf.length,
362
+ audioBase64: buf.toString('base64'),
363
+ summary: `WAV ${(buf.length / 1024).toFixed(1)} КБ за ${(durationMs / 1000).toFixed(2)} с`,
364
+ };
365
+ }
366
+ if (modality === 'stt') {
367
+ let audio = null;
368
+ if (p.audioBase64)
369
+ audio = Buffer.from(String(p.audioBase64), 'base64');
370
+ else
371
+ audio = synthesizeFallbackWav('проверка');
372
+ const res = await ai.transcribe({ audio, language: p.language || 'ru' });
373
+ const durationMs = Math.max(1, Date.now() - t0);
374
+ return {
375
+ ok: true,
376
+ modality,
377
+ durationMs,
378
+ text: res?.text || '',
379
+ summary: res?.text ? `«${res.text.slice(0, 60)}» (${durationMs} мс)` : `Обработано за ${durationMs} мс`,
380
+ };
381
+ }
382
+ if (modality === 'image') {
383
+ const prompt = String(p.prompt || 'Минималистичная 3D-иконка офисного здания на светлом фоне').trim();
384
+ const pic = await ai.generateImage({ prompt, size: p.size || '512x512', steps: p.steps ? Number(p.steps) : undefined });
385
+ const durationMs = Math.max(1, Date.now() - t0);
386
+ return {
387
+ ok: true,
388
+ modality,
389
+ durationMs,
390
+ mime: pic?.mime || 'image/png',
391
+ base64: pic?.base64 || '',
392
+ summary: `Картинка ${pic?.mime || 'image/png'} за ${(durationMs / 1000).toFixed(1)} с`,
393
+ };
394
+ }
395
+ if (modality === 'embed') {
396
+ const input = Array.isArray(p.input) && p.input.length
397
+ ? p.input
398
+ : String(p.prompt || 'Учётная система WORK\nОборотно-сальдовая ведомость').split(/\r?\n/).filter(Boolean);
399
+ const res = await ai.embed({ input });
400
+ const durationMs = Math.max(1, Date.now() - t0);
401
+ const list = res?.data || [];
402
+ const dims = list[0]?.embedding?.length || res?.dimensions || 0;
403
+ return {
404
+ ok: true,
405
+ modality,
406
+ durationMs,
407
+ count: list.length,
408
+ dimensions: dims,
409
+ summary: `${list.length} вект. × ${dims}d за ${durationMs} мс`,
410
+ };
411
+ }
412
+ if (modality === 'rerank') {
413
+ const query = String(p.query || p.prompt || 'остатки на расчётном счёте 51').trim();
414
+ const documents = Array.isArray(p.documents) && p.documents.length
415
+ ? p.documents
416
+ : ['Счёт 51 «Расчётные счета»: обороты и остатки денежных средств', 'Договор аренды офиса и коммунальные услуги'];
417
+ const res = await ai.rerank({ query, documents, top_n: documents.length });
418
+ const durationMs = Math.max(1, Date.now() - t0);
419
+ const top = res?.results?.[0];
420
+ return {
421
+ ok: true,
422
+ modality,
423
+ durationMs,
424
+ results: res?.results || [],
425
+ summary: `Топ #${(top?.index ?? 0) + 1} (${((top?.relevance_score ?? 0) * 100).toFixed(1)}%) за ${durationMs} мс`,
426
+ };
427
+ }
428
+ const messages = Array.isArray(p.messages) && p.messages.length
429
+ ? p.messages
430
+ : [{ role: 'user', content: String(p.prompt || 'Привет! Представься коротко в одном предложении.') }];
431
+ let text = '';
432
+ let usage = null;
433
+ for await (const chunk of ai.streamChat({ messages, max_tokens: Number(p.maxTokens) || 192 }, {})) {
434
+ if (typeof chunk === 'string')
435
+ text += chunk;
436
+ else if (chunk?.type === 'usage')
437
+ usage = chunk;
438
+ }
439
+ const durationMs = Math.max(1, Date.now() - t0);
440
+ const ttftMs = Number(usage?.ttftMs) || 0;
441
+ const tokPerSec = Number(usage?.tokPerSec) || 0;
442
+ const promptTokPerSec = Number(usage?.promptTokPerSec) || 0;
443
+ return {
444
+ ok: true,
445
+ modality: 'llm',
446
+ text: text.trim(),
447
+ durationMs,
448
+ ttftMs,
449
+ tokPerSec,
450
+ promptTokPerSec,
451
+ usage,
452
+ summary: [
453
+ tokPerSec > 0 ? `${tokPerSec} tok/s` : `${durationMs} мс`,
454
+ ttftMs > 0 ? `TTFT ${(ttftMs / 1000).toFixed(2)} с` : '',
455
+ ].filter(Boolean).join(' · '),
456
+ };
457
+ }
458
+ catch (e) {
459
+ const durationMs = Math.max(1, Date.now() - t0);
460
+ return {
461
+ ok: false,
462
+ modality,
463
+ durationMs,
464
+ error: String(e?.message || e),
465
+ ...(Array.isArray(e?.missingDeps) && e.missingDeps.length ? { missingDeps: e.missingDeps } : {}),
466
+ };
467
+ }
468
+ }
469
+
327
470
  export const TRAINER_METHODS = Object.freeze({
328
471
  trainer_status: {
329
472
  level: 'read',
@@ -1088,6 +1231,73 @@ export const TRAINER_METHODS = Object.freeze({
1088
1231
  });
1089
1232
  },
1090
1233
  },
1234
+ trainer_test_model: {
1235
+ level: 'call',
1236
+ fn: async function (p = {}) {
1237
+ const args = mergeTrainerArgs(p);
1238
+ let target = this;
1239
+ if (args.nodePath || args.path) {
1240
+ const found = await globalThis.WORK?.get_item?.(args.nodePath || args.path).catch(() => null);
1241
+ if (found)
1242
+ target = found;
1243
+ }
1244
+ return runSingleModelSmokeTest(target, args);
1245
+ },
1246
+ },
1247
+ trainer_check_all_models: {
1248
+ level: 'call',
1249
+ fn: async function () {
1250
+ const pythonDeps = await localEngine.checkDeps();
1251
+ const localNode = await globalThis.WORK?.get_item?.('/MODELS/Local').catch(() => null);
1252
+ const items = (await localNode?.items) || [];
1253
+ const results = [];
1254
+ for (const m of items) {
1255
+ if (!m || Array.isArray(m))
1256
+ continue;
1257
+ await m.init?.catch?.(() => {});
1258
+ const act = evaluateAiNodeActivitySync(m);
1259
+ const modality = inferTestModality(m);
1260
+ if (!act.active) {
1261
+ results.push({
1262
+ id: m.id,
1263
+ path: m.path,
1264
+ label: m.label || m.DATA?.label || m.id,
1265
+ modality,
1266
+ active: false,
1267
+ ok: false,
1268
+ skipped: true,
1269
+ summary: act.reason || 'Неактивна',
1270
+ });
1271
+ continue;
1272
+ }
1273
+ const res = await runSingleModelSmokeTest(m, {
1274
+ prompt: modality === 'llm' ? 'Ответь одним словом: Готов.' : undefined,
1275
+ });
1276
+ results.push({
1277
+ id: m.id,
1278
+ path: m.path,
1279
+ label: m.label || m.DATA?.label || m.id,
1280
+ active: true,
1281
+ ...res,
1282
+ });
1283
+ }
1284
+ return {
1285
+ ok: results.every(r => r.skipped || r.ok),
1286
+ pythonDeps,
1287
+ results,
1288
+ };
1289
+ },
1290
+ },
1291
+ trainer_install_python_deps: {
1292
+ level: 'admin',
1293
+ fn: async function (p = {}) {
1294
+ const args = mergeTrainerArgs(p);
1295
+ const list = Array.isArray(args.packages)
1296
+ ? args.packages
1297
+ : String(args.packages || '').split(/[\s,]+/).filter(Boolean);
1298
+ return localEngine.installDeps(list);
1299
+ },
1300
+ },
1091
1301
  });
1092
1302
 
1093
1303
  export function attachTrainerMethods($class) {
@@ -133,12 +133,31 @@ async function getTokenizer(weightsDir) {
133
133
  return tok;
134
134
  }
135
135
 
136
+ function resolvePythonCommand(rootDir = process.cwd()) {
137
+ const candidates = os.platform() === 'win32'
138
+ ? [
139
+ path.resolve(rootDir, '.venv/Scripts/python.exe'),
140
+ path.resolve(rootDir, 'venv/Scripts/python.exe'),
141
+ path.resolve(rootDir, 'MODELS/Local/.venv/Scripts/python.exe'),
142
+ ]
143
+ : [
144
+ path.resolve(rootDir, '.venv/bin/python'),
145
+ path.resolve(rootDir, 'venv/bin/python'),
146
+ path.resolve(rootDir, 'MODELS/Local/.venv/bin/python'),
147
+ ];
148
+ for (const c of candidates) {
149
+ if (fs.existsSync(c))
150
+ return c;
151
+ }
152
+ return 'python';
153
+ }
154
+
136
155
  function ensureInferWorker() {
137
156
  if (_workerProc && !_workerProc.killed)
138
157
  return _workerProc;
139
158
 
140
159
  const scriptPath = path.resolve(import.meta.dirname, './worker/local_infer_worker.py');
141
- const proc = spawn('python', [scriptPath], {
160
+ const proc = spawn(resolvePythonCommand(), [scriptPath], {
142
161
  windowsHide: true,
143
162
  stdio: ['pipe', 'pipe', 'pipe'],
144
163
  });
@@ -335,6 +354,8 @@ export async function* localStreamChat(ai, body = {}, options = {}) {
335
354
 
336
355
  proc.stdin.write(payload);
337
356
 
357
+ const tStart = Date.now();
358
+ let tFirstToken = 0;
338
359
  const generatedIds = [];
339
360
  let prevDecoded = '';
340
361
 
@@ -344,6 +365,7 @@ export async function* localStreamChat(ai, body = {}, options = {}) {
344
365
  await new Promise(resolve => { notify = resolve; });
345
366
  }
346
367
  while (queue.length > 0) {
368
+ tFirstToken ||= Date.now();
347
369
  const tokId = queue.shift();
348
370
  generatedIds.push(tokId);
349
371
  const fullDecoded = tokenizer.decode(generatedIds, { skip_special_tokens: true });
@@ -377,6 +399,10 @@ export async function* localStreamChat(ai, body = {}, options = {}) {
377
399
  tokens: inputIds.length,
378
400
  });
379
401
  const cachedTokens = sessionRes.cachedTokens ? Math.min(inputIds.length, sessionRes.cachedTokens) : 0;
402
+ const now = Date.now();
403
+ const ttftMs = tFirstToken ? Math.max(1, tFirstToken - tStart) : Math.max(1, now - tStart);
404
+ const decodeMs = tFirstToken ? Math.max(1, now - tFirstToken) : ttftMs;
405
+ const tokPerSec = generatedIds.length > 0 && decodeMs > 0 ? +((generatedIds.length * 1000) / decodeMs).toFixed(1) : 0;
380
406
 
381
407
  yield {
382
408
  type: 'usage',
@@ -384,6 +410,9 @@ export async function* localStreamChat(ai, body = {}, options = {}) {
384
410
  completion_tokens: generatedIds.length,
385
411
  total_tokens: inputIds.length + generatedIds.length,
386
412
  cached_tokens: cachedTokens,
413
+ ttftMs,
414
+ decodeMs,
415
+ ...(tokPerSec > 0 ? { tokPerSec } : {}),
387
416
  ...(sessionRes.fromStatus ? { halogen_from: sessionRes.fromStatus } : {}),
388
417
  };
389
418
  yield {
@@ -420,3 +449,217 @@ export async function* localStreamChat(ai, body = {}, options = {}) {
420
449
 
421
450
  throw new Error('Файлы весов модели ещё не скачаны в $ai/#weights (откройте /MODELS/Local для установки).');
422
451
  }
452
+
453
+ function runWorkerOp(payload, timeoutMs = 120000) {
454
+ touchLocalEngineActivity();
455
+ const proc = ensureInferWorker();
456
+ proc.stdout?.ref?.();
457
+ const reqId = 'op_' + crypto.randomUUID().slice(0, 8);
458
+ return new Promise((resolve, reject) => {
459
+ const timer = setTimeout(() => {
460
+ _pendingRequests.delete(reqId);
461
+ if (_pendingRequests.size === 0)
462
+ proc.stdout?.unref?.();
463
+ reject(new Error(`Локальный движок (${payload.op}): таймаут ${Math.round(timeoutMs / 1000)}с`));
464
+ }, timeoutMs);
465
+ _pendingRequests.set(reqId, {
466
+ onMessage(msg) {
467
+ if (msg.event === 'result') {
468
+ clearTimeout(timer);
469
+ _pendingRequests.delete(reqId);
470
+ if (_pendingRequests.size === 0)
471
+ proc.stdout?.unref?.();
472
+ resolve(msg.data || {});
473
+ }
474
+ else if (msg.event === 'error') {
475
+ clearTimeout(timer);
476
+ _pendingRequests.delete(reqId);
477
+ if (_pendingRequests.size === 0)
478
+ proc.stdout?.unref?.();
479
+ const err = new Error(msg.error || 'Ошибка локального движка');
480
+ if (Array.isArray(msg.missingDeps))
481
+ err.missingDeps = msg.missingDeps;
482
+ reject(err);
483
+ }
484
+ },
485
+ });
486
+ proc.stdin.write(JSON.stringify({ id: reqId, ...payload }) + '\n');
487
+ });
488
+ }
489
+
490
+ function assertLocalWeightsReady(ai) {
491
+ const weightsDir = resolveWeightsDir(ai);
492
+ const wInsp = inspectWeightsDirectorySync(weightsDir);
493
+ if (wInsp.incompatibleOnPlatform)
494
+ throw new Error(wInsp.incompatibleReason);
495
+ if (!wInsp.exists || (!wInsp.hasSafetensors && !wInsp.hasConfig))
496
+ throw new Error('Файлы весов модели ещё не скачаны в $ai/#weights.');
497
+ return weightsDir;
498
+ }
499
+
500
+ export async function localEmbed(ai, params = {}) {
501
+ const weightsDir = assertLocalWeightsReady(ai);
502
+ const raw = params.input ?? params.text ?? params.post ?? '';
503
+ const input = Array.isArray(raw) ? raw.map(String) : [String(raw)];
504
+ const res = await runWorkerOp({ op: 'embed', weightsDir, input }, 60000);
505
+ return {
506
+ object: 'list',
507
+ model: String(ai?.model || ai?.id || 'local-embed'),
508
+ data: (res.embeddings || []).map((embedding, index) => ({ object: 'embedding', index, embedding })),
509
+ dimensions: res.dimensions || 0,
510
+ durationMs: res.durationMs || 0,
511
+ };
512
+ }
513
+
514
+ export async function localRerank(ai, params = {}) {
515
+ const weightsDir = assertLocalWeightsReady(ai);
516
+ const query = String(params.query || '').trim();
517
+ const documents = Array.isArray(params.documents) ? params.documents : [];
518
+ const res = await runWorkerOp({
519
+ op: 'rerank',
520
+ weightsDir,
521
+ query,
522
+ documents,
523
+ topN: Number(params.top_n || params.topN) || 0,
524
+ }, 60000);
525
+ return {
526
+ model: String(ai?.model || ai?.id || 'local-rerank'),
527
+ results: res.results || [],
528
+ durationMs: res.durationMs || 0,
529
+ };
530
+ }
531
+
532
+ export async function localGenerateImage(ai, params = {}) {
533
+ const weightsDir = assertLocalWeightsReady(ai);
534
+ const prompt = String(params.prompt || params.post || '').trim();
535
+ if (!prompt)
536
+ throw new Error('generateImage: пустой prompt');
537
+ const res = await runWorkerOp({
538
+ op: 'image',
539
+ weightsDir,
540
+ prompt,
541
+ size: String(params.size || '512x512'),
542
+ steps: Number(params.steps) || 8,
543
+ seed: params.seed != null ? Number(params.seed) : 42,
544
+ }, 240000);
545
+ return {
546
+ mime: res.mime || 'image/png',
547
+ base64: res.base64,
548
+ model: String(ai?.model || ai?.id || 'local-image'),
549
+ durationMs: res.durationMs || 0,
550
+ };
551
+ }
552
+
553
+ export async function localSpeak(ai, params = {}) {
554
+ const weightsDir = assertLocalWeightsReady(ai);
555
+ const text = String(params.text ?? params.post ?? '').trim().slice(0, 1500);
556
+ if (!text)
557
+ throw new Error('speak: пустой текст');
558
+ const res = await runWorkerOp({
559
+ op: 'tts',
560
+ weightsDir,
561
+ text,
562
+ language: String(params.language || ai?.language || 'Russian'),
563
+ instructions: String(params.instructions || ai?.instructions || '').trim(),
564
+ voice: String(params.voice || ai?.voice || 'serena'),
565
+ }, 120000);
566
+ return Buffer.from(res.audioBase64 || '', 'base64');
567
+ }
568
+
569
+ export async function localTranscribe(ai, params = {}) {
570
+ const weightsDir = assertLocalWeightsReady(ai);
571
+ const audio = Buffer.isBuffer(params.audio) ? params.audio : null;
572
+ if (!audio?.length)
573
+ throw new Error('transcribe: нет аудио');
574
+ const res = await runWorkerOp({
575
+ op: 'stt',
576
+ weightsDir,
577
+ audioBase64: audio.toString('base64'),
578
+ language: String(params.language || ai?.language || 'Russian'),
579
+ }, 120000);
580
+ return {
581
+ text: String(res.text || '').trim(),
582
+ model: String(ai?.model || ai?.id || 'local-stt'),
583
+ durationMs: res.durationMs || 0,
584
+ };
585
+ }
586
+
587
+ export async function localDecide(ai, params = {}) {
588
+ const state = String(params.state ?? '').trim();
589
+ const questions = params.questions && typeof params.questions === 'object' ? params.questions : {};
590
+ const prompt = `Ответь строго в JSON по схеме ключей ${JSON.stringify(Object.keys(questions))}.\nВопросы: ${JSON.stringify(questions)}\nКонтекст: ${state}`;
591
+ let out = '';
592
+ for await (const ch of localStreamChat(ai, { messages: [{ role: 'user', content: prompt }], max_tokens: 160, temperature: 0.1 }, { effort: 'off' })) {
593
+ if (typeof ch === 'string')
594
+ out += ch;
595
+ }
596
+ try {
597
+ const m = /\{[\s\S]*\}/.exec(out);
598
+ return { answers: m ? JSON.parse(m[0]) : {}, raw: out.trim(), model: String(ai?.model || ai?.id || 'local-decide') };
599
+ }
600
+ catch {
601
+ return { answers: {}, raw: out.trim(), model: String(ai?.model || ai?.id || 'local-decide') };
602
+ }
603
+ }
604
+
605
+ export async function checkLocalPythonDeps() {
606
+ try {
607
+ return await runWorkerOp({ op: 'check_deps' }, 15000);
608
+ }
609
+ catch (e) {
610
+ return { error: String(e?.message || e), packages: {}, cuda: false, deviceName: 'CPU' };
611
+ }
612
+ }
613
+
614
+ const ALLOWED_PYTHON_DEPS = new Set([
615
+ 'transformers',
616
+ 'diffusers',
617
+ 'accelerate',
618
+ 'pillow',
619
+ 'soundfile',
620
+ 'qwen-tts',
621
+ 'qwen-asr',
622
+ 'sentencepiece',
623
+ 'safetensors',
624
+ ]);
625
+
626
+ export function installLocalPythonDeps(packages = []) {
627
+ const clean = [...new Set((Array.isArray(packages) ? packages : [packages])
628
+ .map(s => String(s || '').trim().toLowerCase())
629
+ .filter(p => ALLOWED_PYTHON_DEPS.has(p)))];
630
+ if (!clean.length)
631
+ return Promise.resolve({ ok: false, error: 'Не указаны разрешённые Python-пакеты.' });
632
+ const py = resolvePythonCommand();
633
+ return new Promise((resolve) => {
634
+ const proc = spawn(py, ['-m', 'pip', 'install', '--upgrade', ...clean], {
635
+ windowsHide: true,
636
+ stdio: ['ignore', 'pipe', 'pipe'],
637
+ });
638
+ let out = '';
639
+ let err = '';
640
+ proc.stdout.on('data', d => { out += String(d); if (out.length > 8000) out = out.slice(-8000); });
641
+ proc.stderr.on('data', d => { err += String(d); if (err.length > 8000) err = err.slice(-8000); });
642
+ proc.on('error', e => resolve({ ok: false, error: String(e?.message || e) }));
643
+ proc.on('close', code => {
644
+ if (code === 0) {
645
+ closeInferWorker();
646
+ resolve({ ok: true, packages: clean, log: out.trim() });
647
+ }
648
+ else {
649
+ resolve({ ok: false, packages: clean, error: (err || out || `pip завершился с кодом ${code}`).trim() });
650
+ }
651
+ });
652
+ });
653
+ }
654
+
655
+ export const localEngine = Object.freeze({
656
+ streamChat: localStreamChat,
657
+ embed: localEmbed,
658
+ rerank: localRerank,
659
+ generateImage: localGenerateImage,
660
+ speak: localSpeak,
661
+ transcribe: localTranscribe,
662
+ decide: localDecide,
663
+ checkDeps: checkLocalPythonDeps,
664
+ installDeps: installLocalPythonDeps,
665
+ });