omnitrix 0.0.0-stage → 0.5.0

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.
@@ -0,0 +1,76 @@
1
+ // Ollama's own API knows what each local model can do. The OpenAI-style model list does not say.
2
+ import { spawnSync } from 'node:child_process';
3
+ import path from 'node:path';
4
+ import { makeModel } from '../models.js';
5
+ import { resolveCommand } from './cli.js';
6
+ import { getJson, postJson } from './http.js';
7
+ /** Each local model's size in bytes, as Ollama reports it; empty when the server does not answer. */
8
+ export async function modelSizes(baseUrl) {
9
+ const root = baseUrl.replace(/\/+$/, '').replace(/\/v1$/, '');
10
+ try {
11
+ const list = await getJson(`${root}/api/tags`, {}, 5000);
12
+ const out = {};
13
+ for (const t of Array.isArray(list?.models) ? list.models : []) {
14
+ if (typeof t.name === 'string' && typeof t.size === 'number' && t.size > 0)
15
+ out[t.name] = t.size;
16
+ }
17
+ return out;
18
+ }
19
+ catch {
20
+ return {};
21
+ }
22
+ }
23
+ let gpuCache;
24
+ /**
25
+ * The memory of the largest NVIDIA graphics card, read once with nvidia-smi, or undefined without one.
26
+ * A local model larger than this runs mostly on the processor, which is many times slower. Other cards
27
+ * and Apple's shared memory are not read, so nothing changes for them.
28
+ */
29
+ export function gpuMemoryBytes() {
30
+ if (gpuCache)
31
+ return gpuCache.bytes;
32
+ gpuCache = { bytes: undefined };
33
+ // resolveCommand skips the current folder on Windows, so a project cannot plant its own nvidia-smi
34
+ const found = resolveCommand('nvidia-smi');
35
+ if (!found || !path.isAbsolute(found.file) || found.shell)
36
+ return undefined;
37
+ const r = spawnSync(found.file, ['--query-gpu=memory.total', '--format=csv,noheader,nounits'], { encoding: 'utf8', timeout: 5000, windowsHide: true });
38
+ if (r.status === 0)
39
+ gpuCache.bytes = parseGpuMemory(r.stdout ?? '');
40
+ return gpuCache.bytes;
41
+ }
42
+ /** nvidia-smi prints one line per card with its memory in MiB, such as "4096"; the largest card counts. */
43
+ export function parseGpuMemory(stdout) {
44
+ const mib = stdout.split(/\r?\n/).map((l) => Number(l.trim())).filter((n) => Number.isFinite(n) && n > 0);
45
+ return mib.length ? Math.max(...mib) * 1024 * 1024 : undefined;
46
+ }
47
+ /** The given models with capabilities, size and version from Ollama; a model it cannot describe gets plain local scores. */
48
+ export async function localModels(baseUrl, ids) {
49
+ const root = baseUrl.replace(/\/+$/, '').replace(/\/v1$/, '');
50
+ let tags = [];
51
+ try {
52
+ const list = await getJson(`${root}/api/tags`, {}, 5000);
53
+ if (Array.isArray(list?.models))
54
+ tags = list.models;
55
+ }
56
+ catch {
57
+ // not an Ollama server, or it is not running
58
+ }
59
+ const byName = new Map(tags.filter((t) => typeof t.name === 'string').map((t) => [t.name, t]));
60
+ return Promise.all(ids.map(async (id) => {
61
+ const tag = byName.get(id);
62
+ if (!tag)
63
+ return makeModel(id, {}, { local: true });
64
+ let capabilities;
65
+ try {
66
+ const shown = (await postJson(`${root}/api/show`, {}, { model: id }, 10_000)).json;
67
+ if (Array.isArray(shown?.capabilities))
68
+ capabilities = shown.capabilities.filter((c) => typeof c === 'string');
69
+ }
70
+ catch {
71
+ // older Ollama versions do not report capabilities; vision then stays unclaimed
72
+ }
73
+ const digest = typeof tag.digest === 'string' && /^[0-9a-f]{12,}$/i.test(tag.digest) ? tag.digest : undefined;
74
+ return makeModel(id, digest ? { digest } : {}, { local: true, capabilities, parameterSize: tag.details?.parameter_size });
75
+ }));
76
+ }
@@ -0,0 +1,64 @@
1
+ import { resolveKey } from '../store.js';
2
+ import { DriverError } from '../types.js';
3
+ import { getJson, joinUrl, missingKey, postJson, readRateHeaders } from './http.js';
4
+ function authHeaders(account) {
5
+ const key = resolveKey(account);
6
+ if (!key && !account.local)
7
+ throw new DriverError(missingKey(account), 'auth');
8
+ const h = key ? { authorization: `Bearer ${key}` } : {};
9
+ if (account.provider === 'openrouter') {
10
+ h['x-title'] = 'omnitrix';
11
+ }
12
+ return h;
13
+ }
14
+ /**
15
+ * The answer without a thinking block that some models put before it, such as Gemma 4's
16
+ * "<thought>...</thought>" or DeepSeek R1's "<think>...</think>". Only a closed block at the very start
17
+ * goes; a block later on is part of the answer, and an answer that is only thinking is kept whole.
18
+ */
19
+ export function withoutThinking(text) {
20
+ const m = /^\s*<(think|thought|thinking)>[\s\S]*?<\/\1>\s*/i.exec(text);
21
+ return m && m[0].length < text.length ? text.slice(m[0].length) : text;
22
+ }
23
+ /** Chat Completions: the format almost every provider and local runtime speaks. */
24
+ export async function runOpenAI(req) {
25
+ const { account } = req;
26
+ if (!account.baseUrl)
27
+ throw new DriverError(`account ${account.id} has no base URL`, 'bad_request');
28
+ const messages = [];
29
+ if (req.system)
30
+ messages.push({ role: 'system', content: req.system });
31
+ messages.push({
32
+ role: 'user',
33
+ content: req.images?.length
34
+ ? [{ type: 'text', text: req.prompt }, ...req.images.map((i) => ({ type: 'image_url', image_url: { url: `data:${i.mime};base64,${i.data}` } }))]
35
+ : req.prompt,
36
+ });
37
+ const body = { model: req.model, messages, stream: false };
38
+ if (req.maxOutputTokens)
39
+ body.max_tokens = req.maxOutputTokens;
40
+ // OpenAI, Gemini and other compatible APIs read this; it is sent only when a task asks for it
41
+ if (req.effort)
42
+ body.reasoning_effort = req.effort;
43
+ const { json, headers } = await postJson(joinUrl(account.baseUrl, 'chat/completions'), authHeaders(account), body, req.timeoutMs, req.signal);
44
+ const choice = json?.choices?.[0];
45
+ const content = choice?.message?.content;
46
+ const text = withoutThinking(typeof content === 'string' ? content : Array.isArray(content) ? content.map((p) => p?.text ?? '').join('') : '');
47
+ if (!text && !choice)
48
+ throw new DriverError(`unexpected response: ${JSON.stringify(json).slice(0, 200)}`, 'server');
49
+ const usage = json?.usage ?? {};
50
+ return {
51
+ text,
52
+ inputTokens: Number(usage.prompt_tokens ?? usage.input_tokens ?? 0),
53
+ outputTokens: Number(usage.completion_tokens ?? usage.output_tokens ?? 0),
54
+ costUsd: typeof usage.cost === 'number' ? usage.cost : undefined, // OpenRouter reports this
55
+ rate: readRateHeaders(headers),
56
+ };
57
+ }
58
+ export async function listOpenAIModels(account) {
59
+ if (!account.baseUrl)
60
+ return [];
61
+ const json = await getJson(joinUrl(account.baseUrl, 'models'), authHeaders(account));
62
+ const list = Array.isArray(json?.data) ? json.data : Array.isArray(json?.models) ? json.models : [];
63
+ return list.map((m) => String(m.id ?? m.name ?? '')).filter(Boolean);
64
+ }