@mizchi/vlmkit-ai 0.6.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,501 @@
1
+ /**
2
+ * VLM (Vision Language Model) client
3
+ *
4
+ * Multi-provider support:
5
+ * - OpenRouter (100+ vision models)
6
+ * - Google AI (Gemini direct)
7
+ *
8
+ * Model list is fetched dynamically from the API.
9
+ */
10
+ import { readFile } from "node:fs/promises";
11
+ import { VrtConfigError } from "./errors.ts";
12
+
13
+ // ---- Types ----
14
+
15
+ export interface VlmModel {
16
+ id: string;
17
+ name: string;
18
+ promptCostPer1k: number;
19
+ completionCostPer1k: number;
20
+ contextLength: number;
21
+ modality: string;
22
+ }
23
+
24
+ export interface VlmResponse {
25
+ content: string;
26
+ model: string;
27
+ promptTokens: number;
28
+ completionTokens: number;
29
+ totalTokens: number;
30
+ costUsd: number;
31
+ latencyMs: number;
32
+ }
33
+
34
+ export interface VlmClient {
35
+ model: VlmModel;
36
+ analyzeImage(imageBase64: string, prompt: string, options?: { maxTokens?: number }): Promise<VlmResponse>;
37
+ analyzeImageFile(imagePath: string, prompt: string, options?: { maxTokens?: number }): Promise<VlmResponse>;
38
+ analyzeDiff(baselineBase64: string, currentBase64: string, prompt: string, options?: { maxTokens?: number }): Promise<VlmResponse>;
39
+ }
40
+
41
+ // ---- Model discovery from OpenRouter API ----
42
+
43
+ let _cachedModels: VlmModel[] | null = null;
44
+
45
+ export async function fetchVisionModels(): Promise<VlmModel[]> {
46
+ if (_cachedModels) return _cachedModels;
47
+
48
+ const res = await fetch("https://openrouter.ai/api/v1/models");
49
+ if (!res.ok) throw new Error(`OpenRouter API error: ${res.status}`);
50
+ const data = await res.json() as { data: any[] };
51
+
52
+ _cachedModels = data.data
53
+ .filter((m: any) => {
54
+ const inputMods = m.architecture?.input_modalities ?? [];
55
+ return inputMods.includes("image");
56
+ })
57
+ .map((m: any) => ({
58
+ id: m.id,
59
+ name: m.name ?? m.id,
60
+ promptCostPer1k: parseFloat(m.pricing?.prompt ?? "999"),
61
+ completionCostPer1k: parseFloat(m.pricing?.completion ?? "999"),
62
+ contextLength: m.context_length ?? 0,
63
+ modality: m.architecture?.modality ?? "",
64
+ }))
65
+ .sort((a: VlmModel, b: VlmModel) => a.promptCostPer1k - b.promptCostPer1k);
66
+
67
+ return _cachedModels;
68
+ }
69
+
70
+ export async function listModels(options?: { maxCost?: number; limit?: number; includeGemini?: boolean; includeClaude?: boolean }): Promise<VlmModel[]> {
71
+ const openRouterModels = await fetchVisionModels();
72
+ const direct: VlmModel[] = [];
73
+ if (options?.includeGemini !== false) direct.push(...GOOGLE_MODELS);
74
+ if (options?.includeClaude !== false) direct.push(...CLAUDE_MODELS);
75
+ const models = [...direct, ...openRouterModels];
76
+ // Sort by cost
77
+ models.sort((a, b) => a.promptCostPer1k - b.promptCostPer1k);
78
+ let filtered = models;
79
+ if (options?.maxCost !== undefined) {
80
+ filtered = filtered.filter((m) => m.promptCostPer1k <= options.maxCost!);
81
+ }
82
+ if (options?.limit) {
83
+ filtered = filtered.slice(0, options.limit);
84
+ }
85
+ return filtered;
86
+ }
87
+
88
+ export async function resolveModel(idOrIndex: string): Promise<VlmModel> {
89
+ // Check direct providers first
90
+ const geminiModel = resolveGeminiModel(idOrIndex);
91
+ if (geminiModel) return geminiModel;
92
+
93
+ const claudeModel = resolveClaudeModel(idOrIndex);
94
+ if (claudeModel) return claudeModel;
95
+
96
+ const models = await fetchVisionModels();
97
+
98
+ // Exact ID match
99
+ const exact = models.find((m) => m.id === idOrIndex);
100
+ if (exact) return exact;
101
+
102
+ // Partial match — prefer exact substring, then fuzzy
103
+ const partial = models.filter((m) => m.id.includes(idOrIndex));
104
+ if (partial.length === 1) return partial[0];
105
+ if (partial.length > 1) {
106
+ // Prefer shortest match (most specific)
107
+ const sorted = partial.sort((a, b) => a.id.length - b.id.length);
108
+ // If the shortest is a clear prefix match, use it
109
+ if (sorted[0].id.endsWith(idOrIndex) || sorted[0].id.includes(`/${idOrIndex}`)) {
110
+ return sorted[0];
111
+ }
112
+ throw new VrtConfigError(
113
+ "MULTIPLE_MATCHES",
114
+ `Ambiguous model "${idOrIndex}". Matches: ${partial.slice(0, 5).map((m) => m.id).join(", ")}\nTip: use more specific ID, e.g. "${partial[0].id}"`,
115
+ );
116
+ }
117
+
118
+ // Numeric index
119
+ const idx = parseInt(idOrIndex, 10);
120
+ if (!isNaN(idx) && idx >= 0 && idx < models.length) return models[idx];
121
+
122
+ throw new VrtConfigError(
123
+ "INVALID_MODEL",
124
+ `Model not found: "${idOrIndex}". Use --list to see available models.`,
125
+ );
126
+ }
127
+
128
+ // ---- Google AI (Gemini direct) ----
129
+
130
+ const GOOGLE_MODELS: VlmModel[] = [
131
+ { id: "gemini:gemini-2.5-flash-preview-05-20", name: "Gemini 2.5 Flash (direct)", promptCostPer1k: 1.5e-7, completionCostPer1k: 6e-7, contextLength: 1048576, modality: "text+image->text" },
132
+ { id: "gemini:gemini-2.0-flash", name: "Gemini 2.0 Flash (direct)", promptCostPer1k: 1e-7, completionCostPer1k: 4e-7, contextLength: 1048576, modality: "text+image->text" },
133
+ { id: "gemini:gemini-2.0-flash-lite", name: "Gemini 2.0 Flash Lite (direct)", promptCostPer1k: 7.5e-8, completionCostPer1k: 3e-7, contextLength: 1048576, modality: "text+image->text" },
134
+ ];
135
+
136
+ export function isGeminiDirectModel(id: string): boolean {
137
+ return id.startsWith("gemini:");
138
+ }
139
+
140
+ export function resolveGeminiModel(id: string): VlmModel | undefined {
141
+ return GOOGLE_MODELS.find((m) => m.id === id || m.id === `gemini:${id}`);
142
+ }
143
+
144
+ export function listGeminiModels(): VlmModel[] {
145
+ return [...GOOGLE_MODELS];
146
+ }
147
+
148
+ // ---- Anthropic (Claude direct) ----
149
+ //
150
+ // Per-token USD prices follow the OpenRouter convention used elsewhere
151
+ // in this file (`promptCostPer1k` is actually "per token"; the runtime
152
+ // cost expression `(tokens/1000) * promptCostPer1k` is consistent
153
+ // within this tool's reporting and comparable across providers).
154
+ //
155
+ // 2026 Anthropic list pricing (input / output per million tokens):
156
+ // - Haiku 4.5: $1.00 / $5.00
157
+ // - Sonnet 4.6: $3.00 / $15.00
158
+ // - Opus 4.7: $15.00 / $75.00
159
+
160
+ const CLAUDE_MODELS: VlmModel[] = [
161
+ { id: "claude:claude-haiku-4-5-20251001", name: "Claude Haiku 4.5 (direct)", promptCostPer1k: 1e-6, completionCostPer1k: 5e-6, contextLength: 200000, modality: "text+image->text" },
162
+ { id: "claude:claude-sonnet-4-6", name: "Claude Sonnet 4.6 (direct)", promptCostPer1k: 3e-6, completionCostPer1k: 1.5e-5, contextLength: 200000, modality: "text+image->text" },
163
+ { id: "claude:claude-opus-4-7", name: "Claude Opus 4.7 (direct)", promptCostPer1k: 1.5e-5, completionCostPer1k: 7.5e-5, contextLength: 200000, modality: "text+image->text" },
164
+ ];
165
+
166
+ export function isClaudeDirectModel(id: string): boolean {
167
+ return id.startsWith("claude:");
168
+ }
169
+
170
+ export function resolveClaudeModel(id: string): VlmModel | undefined {
171
+ return CLAUDE_MODELS.find((m) => m.id === id || m.id === `claude:${id}`);
172
+ }
173
+
174
+ export function listClaudeModels(): VlmModel[] {
175
+ return [...CLAUDE_MODELS];
176
+ }
177
+
178
+ async function createClaudeClient(model: VlmModel, apiKey: string): Promise<VlmClient> {
179
+ const claudeModelId = model.id.replace("claude:", "");
180
+
181
+ type ClaudeContentBlock =
182
+ | { type: "text"; text: string }
183
+ | { type: "image"; source: { type: "base64"; media_type: "image/png" | "image/jpeg" | "image/webp" | "image/gif"; data: string } };
184
+
185
+ async function callClaude(
186
+ content: ClaudeContentBlock[],
187
+ maxTokens: number,
188
+ ): Promise<VlmResponse> {
189
+ const start = Date.now();
190
+ const res = await fetch("https://api.anthropic.com/v1/messages", {
191
+ method: "POST",
192
+ headers: {
193
+ "Content-Type": "application/json",
194
+ "x-api-key": apiKey,
195
+ "anthropic-version": "2023-06-01",
196
+ },
197
+ body: JSON.stringify({
198
+ model: claudeModelId,
199
+ max_tokens: maxTokens,
200
+ messages: [{ role: "user", content }],
201
+ }),
202
+ });
203
+
204
+ if (!res.ok) {
205
+ const text = await res.text();
206
+ throw new Error(`Anthropic API error: ${res.status} ${text.slice(0, 200)}`);
207
+ }
208
+
209
+ const data = await res.json() as {
210
+ content: Array<{ type: string; text?: string }>;
211
+ usage?: { input_tokens: number; output_tokens: number };
212
+ };
213
+
214
+ const latencyMs = Date.now() - start;
215
+ const textOut = data.content
216
+ .filter((b) => b.type === "text" && typeof b.text === "string")
217
+ .map((b) => b.text as string)
218
+ .join("");
219
+ const usage = data.usage ?? { input_tokens: 0, output_tokens: 0 };
220
+ const costUsd = (usage.input_tokens / 1000) * model.promptCostPer1k +
221
+ (usage.output_tokens / 1000) * model.completionCostPer1k;
222
+
223
+ return {
224
+ content: textOut,
225
+ model: model.id,
226
+ promptTokens: usage.input_tokens,
227
+ completionTokens: usage.output_tokens,
228
+ totalTokens: usage.input_tokens + usage.output_tokens,
229
+ costUsd,
230
+ latencyMs,
231
+ };
232
+ }
233
+
234
+ const client: VlmClient = {
235
+ model,
236
+ async analyzeImage(imageBase64, prompt, options) {
237
+ return callClaude([
238
+ { type: "image", source: { type: "base64", media_type: "image/png", data: imageBase64 } },
239
+ { type: "text", text: prompt },
240
+ ], options?.maxTokens ?? 1024);
241
+ },
242
+ async analyzeImageFile(imagePath, prompt, options) {
243
+ const buf = await readFile(imagePath);
244
+ return client.analyzeImage(buf.toString("base64"), prompt, options);
245
+ },
246
+ async analyzeDiff(baselineBase64, currentBase64, prompt, options) {
247
+ return callClaude([
248
+ { type: "text", text: "Baseline screenshot:" },
249
+ { type: "image", source: { type: "base64", media_type: "image/png", data: baselineBase64 } },
250
+ { type: "text", text: "Current screenshot:" },
251
+ { type: "image", source: { type: "base64", media_type: "image/png", data: currentBase64 } },
252
+ { type: "text", text: prompt },
253
+ ], options?.maxTokens ?? 1024);
254
+ },
255
+ };
256
+ return client;
257
+ }
258
+
259
+ async function createGeminiClient(model: VlmModel, apiKey: string): Promise<VlmClient> {
260
+ const geminiModelId = model.id.replace("gemini:", "");
261
+ let GoogleGenerativeAI: any;
262
+ try {
263
+ ({ GoogleGenerativeAI } = await import("@google/generative-ai"));
264
+ } catch (e) {
265
+ throw new VrtConfigError(
266
+ "MISSING_DEPENDENCY",
267
+ `@google/generative-ai is not installed. Run: pnpm add @google/generative-ai`,
268
+ );
269
+ }
270
+ const genAI = new GoogleGenerativeAI(apiKey);
271
+ const genModel = genAI.getGenerativeModel({ model: geminiModelId });
272
+
273
+ async function callGemini(
274
+ imageBase64: string,
275
+ textPrompt: string,
276
+ maxTokens: number,
277
+ ): Promise<VlmResponse> {
278
+
279
+ const start = Date.now();
280
+ const result = await genModel.generateContent({
281
+ contents: [{
282
+ role: "user",
283
+ parts: [
284
+ { inlineData: { mimeType: "image/png", data: imageBase64 } },
285
+ { text: textPrompt },
286
+ ],
287
+ }],
288
+ generationConfig: { maxOutputTokens: maxTokens },
289
+ });
290
+
291
+ const latencyMs = Date.now() - start;
292
+ const response = result.response;
293
+ const content = response.text();
294
+ const usage = response.usageMetadata;
295
+ const promptTokens = usage?.promptTokenCount ?? 0;
296
+ const completionTokens = usage?.candidatesTokenCount ?? 0;
297
+ const costUsd = (promptTokens / 1000) * model.promptCostPer1k +
298
+ (completionTokens / 1000) * model.completionCostPer1k;
299
+
300
+ return {
301
+ content,
302
+ model: model.id,
303
+ promptTokens,
304
+ completionTokens,
305
+ totalTokens: promptTokens + completionTokens,
306
+ costUsd,
307
+ latencyMs,
308
+ };
309
+ }
310
+
311
+ const client: VlmClient = {
312
+ model,
313
+ async analyzeImage(imageBase64, prompt, options) {
314
+ return callGemini(imageBase64, prompt, options?.maxTokens ?? 1024);
315
+ },
316
+ async analyzeImageFile(imagePath, prompt, options) {
317
+ const buf = await readFile(imagePath);
318
+ return client.analyzeImage(buf.toString("base64"), prompt, options);
319
+ },
320
+ async analyzeDiff(baselineBase64, currentBase64, prompt, options) {
321
+ const start = Date.now();
322
+ const result = await genModel.generateContent({
323
+ contents: [{
324
+ role: "user",
325
+ parts: [
326
+ { text: "Baseline screenshot:" },
327
+ { inlineData: { mimeType: "image/png", data: baselineBase64 } },
328
+ { text: "Current screenshot:" },
329
+ { inlineData: { mimeType: "image/png", data: currentBase64 } },
330
+ { text: prompt },
331
+ ],
332
+ }],
333
+ generationConfig: { maxOutputTokens: options?.maxTokens ?? 1024 },
334
+ });
335
+
336
+ const latencyMs = Date.now() - start;
337
+ const response = result.response;
338
+ const usage = response.usageMetadata;
339
+ const promptTokens = usage?.promptTokenCount ?? 0;
340
+ const completionTokens = usage?.candidatesTokenCount ?? 0;
341
+
342
+ return {
343
+ content: response.text(),
344
+ model: model.id,
345
+ promptTokens,
346
+ completionTokens,
347
+ totalTokens: promptTokens + completionTokens,
348
+ costUsd: (promptTokens / 1000) * model.promptCostPer1k +
349
+ (completionTokens / 1000) * model.completionCostPer1k,
350
+ latencyMs,
351
+ };
352
+ },
353
+ };
354
+ return client;
355
+ }
356
+
357
+ // ---- Client factory ----
358
+
359
+ export interface CreateVlmClientOptions {
360
+ /** Override `OPENROUTER_API_KEY` / `GEMINI_API_KEY` lookup. */
361
+ apiKey?: string;
362
+ /**
363
+ * When `false`, return `null` instead of throwing `VrtConfigError`
364
+ * if the required API key is missing. Default: `true`.
365
+ */
366
+ throwIfMissing?: boolean;
367
+ }
368
+
369
+ /**
370
+ * Construct a VLM client for the given model.
371
+ *
372
+ * Throws `VrtConfigError` (`code: "MISSING_KEY"`) when the model's
373
+ * required API key isn't set in the environment. Pass
374
+ * `{ throwIfMissing: false }` for the legacy `T | null` return.
375
+ */
376
+ export async function createVlmClient(
377
+ model: VlmModel,
378
+ options?: CreateVlmClientOptions,
379
+ ): Promise<VlmClient | null> {
380
+ const throwIfMissing = options?.throwIfMissing ?? true;
381
+ // Gemini direct
382
+ if (isGeminiDirectModel(model.id)) {
383
+ const key = options?.apiKey ?? process.env.GEMINI_API_KEY ?? process.env.GOOGLE_AI_API_KEY;
384
+ if (!key) {
385
+ if (throwIfMissing) {
386
+ throw new VrtConfigError(
387
+ "MISSING_KEY",
388
+ `GEMINI_API_KEY (or GOOGLE_AI_API_KEY) is required for ${model.id}`,
389
+ );
390
+ }
391
+ return null;
392
+ }
393
+ return createGeminiClient(model, key);
394
+ }
395
+
396
+ // Anthropic (Claude) direct
397
+ if (isClaudeDirectModel(model.id)) {
398
+ const key = options?.apiKey ?? process.env.ANTHROPIC_API_KEY;
399
+ if (!key) {
400
+ if (throwIfMissing) {
401
+ throw new VrtConfigError(
402
+ "MISSING_KEY",
403
+ `ANTHROPIC_API_KEY is required for ${model.id}`,
404
+ );
405
+ }
406
+ return null;
407
+ }
408
+ return createClaudeClient(model, key);
409
+ }
410
+
411
+ // OpenRouter
412
+ const key = options?.apiKey ?? process.env.OPENROUTER_API_KEY;
413
+ if (!key) {
414
+ if (throwIfMissing) {
415
+ throw new VrtConfigError(
416
+ "MISSING_KEY",
417
+ `OPENROUTER_API_KEY is required for ${model.id}`,
418
+ );
419
+ }
420
+ return null;
421
+ }
422
+
423
+ async function callOpenRouter(
424
+ messages: Array<{ role: string; content: any }>,
425
+ maxTokens: number,
426
+ ): Promise<VlmResponse> {
427
+ const start = Date.now();
428
+ const res = await fetch("https://openrouter.ai/api/v1/chat/completions", {
429
+ method: "POST",
430
+ headers: {
431
+ "Content-Type": "application/json",
432
+ "Authorization": `Bearer ${key}`,
433
+ "HTTP-Referer": "https://github.com/mizchi/vrt",
434
+ "X-Title": "vrt",
435
+ },
436
+ body: JSON.stringify({
437
+ model: model.id,
438
+ max_tokens: maxTokens,
439
+ messages,
440
+ }),
441
+ });
442
+
443
+ if (!res.ok) {
444
+ const text = await res.text();
445
+ throw new Error(`OpenRouter API error: ${res.status} ${text.slice(0, 200)}`);
446
+ }
447
+
448
+ const data = await res.json() as {
449
+ choices: Array<{ message: { content: string } }>;
450
+ usage?: { prompt_tokens: number; completion_tokens: number; total_tokens: number };
451
+ };
452
+
453
+ const latencyMs = Date.now() - start;
454
+ const usage = data.usage ?? { prompt_tokens: 0, completion_tokens: 0, total_tokens: 0 };
455
+ const costUsd = (usage.prompt_tokens / 1000) * model.promptCostPer1k +
456
+ (usage.completion_tokens / 1000) * model.completionCostPer1k;
457
+
458
+ return {
459
+ content: data.choices[0]?.message?.content ?? "",
460
+ model: model.id,
461
+ promptTokens: usage.prompt_tokens,
462
+ completionTokens: usage.completion_tokens,
463
+ totalTokens: usage.total_tokens,
464
+ costUsd,
465
+ latencyMs,
466
+ };
467
+ }
468
+
469
+ const orClient: VlmClient = {
470
+ model,
471
+
472
+ async analyzeImage(imageBase64, prompt, options) {
473
+ return callOpenRouter([{
474
+ role: "user",
475
+ content: [
476
+ { type: "image_url", image_url: { url: `data:image/png;base64,${imageBase64}` } },
477
+ { type: "text", text: prompt },
478
+ ],
479
+ }], options?.maxTokens ?? 1024);
480
+ },
481
+
482
+ async analyzeImageFile(imagePath, prompt, options) {
483
+ const buf = await readFile(imagePath);
484
+ return orClient.analyzeImage(buf.toString("base64"), prompt, options);
485
+ },
486
+
487
+ async analyzeDiff(baselineBase64, currentBase64, prompt, options) {
488
+ return callOpenRouter([{
489
+ role: "user",
490
+ content: [
491
+ { type: "text", text: "Baseline screenshot:" },
492
+ { type: "image_url", image_url: { url: `data:image/png;base64,${baselineBase64}` } },
493
+ { type: "text", text: "Current screenshot:" },
494
+ { type: "image_url", image_url: { url: `data:image/png;base64,${currentBase64}` } },
495
+ { type: "text", text: prompt },
496
+ ],
497
+ }], options?.maxTokens ?? 1024);
498
+ },
499
+ };
500
+ return orClient;
501
+ }