@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,421 @@
1
+ /**
2
+ * Unified LLM client
3
+ *
4
+ * Supports both text and image. Provider priority:
5
+ * 1. Anthropic (ANTHROPIC_API_KEY) -- text + vision
6
+ * 2. Gemini (GEMINI_API_KEY) -- text + vision
7
+ * 3. OpenRouter (OPENROUTER_API_KEY) -- text + vision
8
+ *
9
+ * Backwards-compatible with the existing LLMProvider interface.
10
+ */
11
+ import type { LLMProvider } from "./intent.ts";
12
+ import { VrtConfigError } from "./errors.ts";
13
+
14
+ // ---- Types ----
15
+
16
+ export interface LLMClientOptions {
17
+ /** Whether vision support is needed */
18
+ vision?: boolean;
19
+ /** Max tokens */
20
+ maxTokens?: number;
21
+ /** Specific provider */
22
+ provider?: "anthropic" | "gemini" | "openrouter";
23
+ /** Specific model */
24
+ model?: string;
25
+ /**
26
+ * When `false`, factories return `null` instead of throwing
27
+ * `VrtConfigError` if the required API key is missing. Default: `true`.
28
+ */
29
+ throwIfMissing?: boolean;
30
+ }
31
+
32
+ export interface ImageContent {
33
+ type: "image";
34
+ base64: string;
35
+ mimeType?: string;
36
+ }
37
+
38
+ export interface TextContent {
39
+ type: "text";
40
+ text: string;
41
+ }
42
+
43
+ export type MessageContent = string | Array<TextContent | ImageContent>;
44
+
45
+ export interface LLMResponse {
46
+ content: string;
47
+ model: string;
48
+ provider: string;
49
+ promptTokens: number;
50
+ completionTokens: number;
51
+ costUsd: number;
52
+ latencyMs: number;
53
+ }
54
+
55
+ export interface UnifiedLLMClient {
56
+ /** Text only (backwards-compatible) */
57
+ complete(prompt: string): Promise<string>;
58
+ /** Text + images */
59
+ completeWithImages(content: MessageContent, options?: { maxTokens?: number }): Promise<LLMResponse>;
60
+ /** VRT diff analysis: pass heatmap + text report together */
61
+ analyzeDiff(options: {
62
+ heatmapBase64?: string;
63
+ baselineBase64?: string;
64
+ currentBase64?: string;
65
+ textReport: string;
66
+ prompt?: string;
67
+ maxTokens?: number;
68
+ }): Promise<LLMResponse>;
69
+
70
+ provider: string;
71
+ model: string;
72
+ }
73
+
74
+ // ---- Anthropic ----
75
+
76
+ function createAnthropicClient(apiKey: string, model?: string): UnifiedLLMClient {
77
+ const modelId = model ?? "claude-sonnet-4-20250514";
78
+
79
+ async function call(content: MessageContent, maxTokens: number): Promise<LLMResponse> {
80
+ const start = Date.now();
81
+
82
+ type AnthropicBlock =
83
+ | { type: "text"; text: string }
84
+ | { type: "image"; source: { type: "base64"; media_type: string; data: string } };
85
+
86
+ const messageContent: string | AnthropicBlock[] =
87
+ typeof content === "string"
88
+ ? content
89
+ : content.map((c): AnthropicBlock => {
90
+ if (c.type === "text") return { type: "text", text: c.text };
91
+ return {
92
+ type: "image",
93
+ source: { type: "base64", media_type: c.mimeType ?? "image/png", data: c.base64 },
94
+ };
95
+ });
96
+
97
+ const res = await fetch("https://api.anthropic.com/v1/messages", {
98
+ method: "POST",
99
+ headers: {
100
+ "content-type": "application/json",
101
+ "x-api-key": apiKey,
102
+ "anthropic-version": "2023-06-01",
103
+ },
104
+ body: JSON.stringify({
105
+ model: modelId,
106
+ max_tokens: maxTokens,
107
+ messages: [{ role: "user", content: messageContent }],
108
+ }),
109
+ });
110
+
111
+ if (!res.ok) {
112
+ const body = (await res.text()).slice(0, 200);
113
+ throw new Error(`Anthropic API error: ${res.status} ${body}`);
114
+ }
115
+
116
+ const data = await res.json() as {
117
+ content: Array<{ type: string; text: string }>;
118
+ usage?: { input_tokens: number; output_tokens: number };
119
+ };
120
+
121
+ const latencyMs = Date.now() - start;
122
+ const text = data.content.filter((c) => c.type === "text").map((c) => c.text).join("");
123
+ const promptTokens = data.usage?.input_tokens ?? 0;
124
+ const completionTokens = data.usage?.output_tokens ?? 0;
125
+
126
+ return {
127
+ content: text,
128
+ model: modelId,
129
+ provider: "anthropic",
130
+ promptTokens,
131
+ completionTokens,
132
+ costUsd: 0, // Anthropic pricing varies, skip for now
133
+ latencyMs,
134
+ };
135
+ }
136
+
137
+ return {
138
+ provider: "anthropic",
139
+ model: modelId,
140
+ async complete(prompt) { return (await call(prompt, 1024)).content; },
141
+ async completeWithImages(content, options) { return call(content, options?.maxTokens ?? 1024); },
142
+ async analyzeDiff(options) { return call(buildDiffContent(options), options.maxTokens ?? 1024); },
143
+ };
144
+ }
145
+
146
+ // ---- Gemini ----
147
+
148
+ function createGeminiLLMClient(apiKey: string, model?: string): UnifiedLLMClient {
149
+ const modelId = model ?? "gemini-2.5-flash-preview-05-20";
150
+
151
+ async function call(content: MessageContent, maxTokens: number): Promise<LLMResponse> {
152
+ const { GoogleGenerativeAI } = await import("@google/generative-ai");
153
+ const genAI = new GoogleGenerativeAI(apiKey);
154
+ const genModel = genAI.getGenerativeModel({ model: modelId });
155
+ const start = Date.now();
156
+
157
+ type GeminiPart =
158
+ | { text: string }
159
+ | { inlineData: { mimeType: string; data: string } };
160
+
161
+ const parts: GeminiPart[] =
162
+ typeof content === "string"
163
+ ? [{ text: content }]
164
+ : content.map((c): GeminiPart => {
165
+ if (c.type === "text") return { text: c.text };
166
+ return { inlineData: { mimeType: c.mimeType ?? "image/png", data: c.base64 } };
167
+ });
168
+
169
+ const result = await genModel.generateContent({
170
+ contents: [{ role: "user", parts }],
171
+ generationConfig: { maxOutputTokens: maxTokens },
172
+ });
173
+
174
+ const latencyMs = Date.now() - start;
175
+ const response = result.response;
176
+ const usage = response.usageMetadata;
177
+
178
+ return {
179
+ content: response.text(),
180
+ model: modelId,
181
+ provider: "gemini",
182
+ promptTokens: usage?.promptTokenCount ?? 0,
183
+ completionTokens: usage?.candidatesTokenCount ?? 0,
184
+ costUsd: 0,
185
+ latencyMs,
186
+ };
187
+ }
188
+
189
+ return {
190
+ provider: "gemini",
191
+ model: modelId,
192
+ async complete(prompt) { return (await call(prompt, 1024)).content; },
193
+ async completeWithImages(content, options) { return call(content, options?.maxTokens ?? 1024); },
194
+ async analyzeDiff(options) { return call(buildDiffContent(options), options.maxTokens ?? 1024); },
195
+ };
196
+ }
197
+
198
+ // ---- OpenRouter ----
199
+
200
+ function createOpenRouterLLMClient(apiKey: string, model?: string): UnifiedLLMClient {
201
+ const modelId = model ?? "qwen/qwen3-vl-8b-instruct";
202
+
203
+ async function call(content: MessageContent, maxTokens: number): Promise<LLMResponse> {
204
+ const start = Date.now();
205
+
206
+ type OpenRouterBlock =
207
+ | { type: "text"; text: string }
208
+ | { type: "image_url"; image_url: { url: string } };
209
+
210
+ const messageContent: string | OpenRouterBlock[] =
211
+ typeof content === "string"
212
+ ? content
213
+ : content.map((c): OpenRouterBlock => {
214
+ if (c.type === "text") return { type: "text", text: c.text };
215
+ return { type: "image_url", image_url: { url: `data:${c.mimeType ?? "image/png"};base64,${c.base64}` } };
216
+ });
217
+
218
+ const res = await fetch("https://openrouter.ai/api/v1/chat/completions", {
219
+ method: "POST",
220
+ headers: {
221
+ "Content-Type": "application/json",
222
+ "Authorization": `Bearer ${apiKey}`,
223
+ "HTTP-Referer": "https://github.com/mizchi/vrt",
224
+ },
225
+ body: JSON.stringify({
226
+ model: modelId,
227
+ max_tokens: maxTokens,
228
+ messages: [{ role: "user", content: messageContent }],
229
+ }),
230
+ });
231
+
232
+ if (!res.ok) throw new Error(`OpenRouter API error: ${res.status} ${(await res.text()).slice(0, 200)}`);
233
+
234
+ const data = await res.json() as {
235
+ choices: Array<{ message: { content: string } }>;
236
+ usage?: { prompt_tokens: number; completion_tokens: number };
237
+ };
238
+
239
+ const latencyMs = Date.now() - start;
240
+ return {
241
+ content: data.choices[0]?.message?.content ?? "",
242
+ model: modelId,
243
+ provider: "openrouter",
244
+ promptTokens: data.usage?.prompt_tokens ?? 0,
245
+ completionTokens: data.usage?.completion_tokens ?? 0,
246
+ costUsd: 0,
247
+ latencyMs,
248
+ };
249
+ }
250
+
251
+ return {
252
+ provider: "openrouter",
253
+ model: modelId,
254
+ async complete(prompt) { return (await call(prompt, 1024)).content; },
255
+ async completeWithImages(content, options) { return call(content, options?.maxTokens ?? 1024); },
256
+ async analyzeDiff(options) { return call(buildDiffContent(options), options.maxTokens ?? 1024); },
257
+ };
258
+ }
259
+
260
+ // ---- Diff content builder ----
261
+
262
+ function buildDiffContent(options: {
263
+ heatmapBase64?: string;
264
+ baselineBase64?: string;
265
+ currentBase64?: string;
266
+ textReport: string;
267
+ prompt?: string;
268
+ }): MessageContent {
269
+ const parts: Array<TextContent | ImageContent> = [];
270
+
271
+ if (options.baselineBase64) {
272
+ parts.push({ type: "text", text: "Baseline screenshot:" });
273
+ parts.push({ type: "image", base64: options.baselineBase64 });
274
+ }
275
+ if (options.currentBase64) {
276
+ parts.push({ type: "text", text: "Current screenshot:" });
277
+ parts.push({ type: "image", base64: options.currentBase64 });
278
+ }
279
+ if (options.heatmapBase64) {
280
+ parts.push({ type: "text", text: "Diff heatmap (red = changed pixels):" });
281
+ parts.push({ type: "image", base64: options.heatmapBase64 });
282
+ }
283
+
284
+ parts.push({ type: "text", text: options.textReport });
285
+
286
+ if (options.prompt) {
287
+ parts.push({ type: "text", text: options.prompt });
288
+ }
289
+
290
+ return parts;
291
+ }
292
+
293
+ // ---- Factory ----
294
+
295
+ export type LLMProviderName = "gemini" | "anthropic" | "openrouter";
296
+
297
+ const VALID_PROVIDERS: ReadonlySet<LLMProviderName> = new Set([
298
+ "gemini",
299
+ "anthropic",
300
+ "openrouter",
301
+ ]);
302
+
303
+ /**
304
+ * Resolve provider and key from environment variables.
305
+ *
306
+ * VRT_LLM_PROVIDER: gemini (default) | anthropic | openrouter
307
+ * VRT_LLM_MODEL: model ID (defaults to provider's default)
308
+ *
309
+ * Returns a config, or describes why no config was available. The
310
+ * factory decides whether to throw based on `throwIfMissing`.
311
+ */
312
+ function resolveProviderConfig(options?: LLMClientOptions):
313
+ | { ok: true; provider: LLMProviderName; key: string; model?: string }
314
+ | { ok: false; code: "INVALID_PROVIDER" | "MISSING_KEY"; message: string }
315
+ {
316
+ const rawProvider = options?.provider
317
+ ?? process.env.VRT_LLM_PROVIDER
318
+ ?? "gemini";
319
+
320
+ if (!VALID_PROVIDERS.has(rawProvider as LLMProviderName)) {
321
+ return {
322
+ ok: false,
323
+ code: "INVALID_PROVIDER",
324
+ message: `Unknown VRT_LLM_PROVIDER "${rawProvider}". Expected: gemini | anthropic | openrouter.`,
325
+ };
326
+ }
327
+ const provider = rawProvider as LLMProviderName;
328
+
329
+ const model = options?.model ?? process.env.VRT_LLM_MODEL ?? undefined;
330
+
331
+ const keyMap: Record<LLMProviderName, string | undefined> = {
332
+ gemini: process.env.GEMINI_API_KEY ?? process.env.GOOGLE_AI_API_KEY,
333
+ anthropic: process.env.ANTHROPIC_API_KEY,
334
+ openrouter: process.env.OPENROUTER_API_KEY,
335
+ };
336
+ const envVarName: Record<LLMProviderName, string> = {
337
+ gemini: "GEMINI_API_KEY (or GOOGLE_AI_API_KEY)",
338
+ anthropic: "ANTHROPIC_API_KEY",
339
+ openrouter: "OPENROUTER_API_KEY",
340
+ };
341
+
342
+ const key = keyMap[provider];
343
+ if (!key) {
344
+ return {
345
+ ok: false,
346
+ code: "MISSING_KEY",
347
+ message: `${envVarName[provider]} is required for provider "${provider}".`,
348
+ };
349
+ }
350
+
351
+ return { ok: true, provider, key, model };
352
+ }
353
+
354
+ /**
355
+ * Create a unified LLM client.
356
+ *
357
+ * Provider is set via `VRT_LLM_PROVIDER` env var (default: `gemini`).
358
+ *
359
+ * Throws `VrtConfigError` when the resolved provider has no API key
360
+ * (`code: "MISSING_KEY"`) or the provider value is unknown
361
+ * (`code: "INVALID_PROVIDER"`). Pass `{ throwIfMissing: false }` for
362
+ * legacy `T | null` return.
363
+ */
364
+ export function createUnifiedLLMClient(options?: LLMClientOptions): UnifiedLLMClient | null {
365
+ const throwIfMissing = options?.throwIfMissing ?? true;
366
+ const config = resolveProviderConfig(options);
367
+ if (!config.ok) {
368
+ if (throwIfMissing) {
369
+ throw new VrtConfigError(config.code, config.message);
370
+ }
371
+ return null;
372
+ }
373
+
374
+ switch (config.provider) {
375
+ case "anthropic":
376
+ return createAnthropicClient(config.key, config.model);
377
+ case "gemini":
378
+ return createGeminiLLMClient(config.key, config.model);
379
+ case "openrouter":
380
+ return createOpenRouterLLMClient(config.key, config.model);
381
+ }
382
+ }
383
+
384
+ export interface CreateLLMProviderOptions {
385
+ /**
386
+ * When `false`, returns `null` instead of throwing `VrtConfigError`
387
+ * if no provider has an API key. Default: `true`.
388
+ */
389
+ throwIfMissing?: boolean;
390
+ }
391
+
392
+ /**
393
+ * Backwards-compatible: returns the existing `LLMProvider` interface.
394
+ * Uses the provider specified by `VRT_LLM_PROVIDER`. Falls back to
395
+ * other providers if the requested key is missing.
396
+ *
397
+ * Throws `VrtConfigError` (`code: "NO_PROVIDER_AVAILABLE"`) when no
398
+ * provider in the fallback chain has an API key. Pass
399
+ * `{ throwIfMissing: false }` for the legacy `T | null` return.
400
+ */
401
+ export function createLLMProvider(options?: CreateLLMProviderOptions): LLMProvider | null {
402
+ const throwIfMissing = options?.throwIfMissing ?? true;
403
+ // Try requested/default provider first without throwing — we'll fall back.
404
+ const client = createUnifiedLLMClient({ throwIfMissing: false });
405
+ if (client) return { complete: (prompt: string) => client.complete(prompt) };
406
+
407
+ // Fallback: use any available key
408
+ const fallbackOrder: LLMProviderName[] = ["gemini", "anthropic", "openrouter"];
409
+ for (const provider of fallbackOrder) {
410
+ const fb = createUnifiedLLMClient({ provider, throwIfMissing: false });
411
+ if (fb) return { complete: (prompt: string) => fb.complete(prompt) };
412
+ }
413
+
414
+ if (throwIfMissing) {
415
+ throw new VrtConfigError(
416
+ "NO_PROVIDER_AVAILABLE",
417
+ "No LLM provider available. Set one of: GEMINI_API_KEY, ANTHROPIC_API_KEY, OPENROUTER_API_KEY.",
418
+ );
419
+ }
420
+ return null;
421
+ }
package/src/nlp.ts ADDED
@@ -0,0 +1,27 @@
1
+ /**
2
+ * Text-matching helpers shared between expectation matching and reasoning.
3
+ */
4
+
5
+ export const STOP_WORDS = new Set([
6
+ "gets", "from", "with", "that", "this", "should",
7
+ "have", "the", "for", "and", "all", "proper",
8
+ ]);
9
+
10
+ export const SYNONYMS: Record<string, string[]> = {
11
+ input: ["textbox", "searchbox", "combobox"],
12
+ textbox: ["input", "searchbox"],
13
+ searchbox: ["input", "textbox", "search"],
14
+ label: ["name", "accessible"],
15
+ name: ["label"],
16
+ button: ["btn"],
17
+ nav: ["navigation"],
18
+ navigation: ["nav"],
19
+ search: ["searchbox"],
20
+ tab: ["tablist", "tabpanel"],
21
+ tablist: ["tab", "tabs"],
22
+ tabpanel: ["tab", "panel", "content"],
23
+ panel: ["tabpanel"],
24
+ table: ["grid"],
25
+ column: ["columnheader", "header"],
26
+ header: ["columnheader", "column"],
27
+ };