@mizchi/vlmkit-ai 0.9.1 → 0.11.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.
@@ -224,16 +224,39 @@ const VALID_PROVIDERS = new Set([
224
224
  *
225
225
  * Returns a config, or describes why no config was available. The
226
226
  * factory decides whether to throw based on `throwIfMissing`.
227
+ *
228
+ * ## An unrequested provider is chosen from the keys you have
229
+ *
230
+ * This used to be `options?.provider ?? readEnv("LLM_PROVIDER") ?? "gemini"` with no
231
+ * regard for which keys existed, so a caller that expressed no preference got gemini and
232
+ * then a `MISSING_KEY` naming a key it did not need. Measured with exactly one key set:
233
+ *
234
+ * ANTHROPIC_API_KEY only → MISSING_KEY: GEMINI_API_KEY (or GOOGLE_AI_API_KEY) is required
235
+ * OPENROUTER_API_KEY only → MISSING_KEY: GEMINI_API_KEY (or GOOGLE_AI_API_KEY) is required
236
+ *
237
+ * while `createLLMProvider`, twenty lines further down this same file, returned a working
238
+ * client for both. Being told to obtain a key you do not need, while the one you have is
239
+ * ignored, sends the reader to the wrong fix.
240
+ *
241
+ * Every caller had already worked around it, in four different ways, which is what made
242
+ * this worth changing rather than leaving: `createLLMProvider` and
243
+ * `reasoning-pipeline.ts` each carry a byte-identical `["gemini", "anthropic",
244
+ * "openrouter"]` retry loop, and `vlmkit-plan` and `vlmkit-generate` each carry a
245
+ * byte-identical `resolveDefaultProvider` that picks by key presence before calling in.
246
+ * Four workarounds for one missing behaviour is the shared function being wrong, and the
247
+ * fifth caller is the one that pays for it — the same shape as eight modules hand-rolling
248
+ * `isUrlSource`.
249
+ *
250
+ * **An explicit request is still honoured exactly.** `{ provider: "gemini" }` or
251
+ * `VLMKIT_LLM_PROVIDER=gemini` with no Gemini key is a `MISSING_KEY` for *gemini*, not a
252
+ * silent substitution — asking for a specific provider and quietly getting another is its
253
+ * own kind of wrong answer. `createLLMProvider` deliberately does substitute, which is
254
+ * why its retry loop survives this change and is not redundant.
255
+ *
256
+ * The documented default is unchanged: gemini is first in the preference order, so a
257
+ * Gemini key present still means gemini.
227
258
  */
228
259
  function resolveProviderConfig(options) {
229
- const rawProvider = options?.provider ?? readEnv("LLM_PROVIDER") ?? "gemini";
230
- if (!VALID_PROVIDERS.has(rawProvider)) return {
231
- ok: false,
232
- code: "INVALID_PROVIDER",
233
- message: `Unknown VLMKIT_LLM_PROVIDER "${rawProvider}". Expected: gemini | anthropic | openrouter.`
234
- };
235
- const provider = rawProvider;
236
- const model = options?.model ?? readEnv("LLM_MODEL") ?? void 0;
237
260
  const keyMap = {
238
261
  gemini: process.env.GEMINI_API_KEY ?? process.env.GOOGLE_AI_API_KEY,
239
262
  anthropic: process.env.ANTHROPIC_API_KEY,
@@ -244,6 +267,34 @@ function resolveProviderConfig(options) {
244
267
  anthropic: "ANTHROPIC_API_KEY",
245
268
  openrouter: "OPENROUTER_API_KEY"
246
269
  };
270
+ /** Gemini first, so the documented default wins whenever its key is present. */
271
+ const PREFERENCE = [
272
+ "gemini",
273
+ "anthropic",
274
+ "openrouter"
275
+ ];
276
+ const requested = options?.provider ?? readEnv("LLM_PROVIDER");
277
+ const model = options?.model ?? readEnv("LLM_MODEL") ?? void 0;
278
+ if (requested === void 0) {
279
+ const provider = PREFERENCE.find((p) => keyMap[p]);
280
+ if (!provider) return {
281
+ ok: false,
282
+ code: "MISSING_KEY",
283
+ message: `No LLM API key found. Set one of: ${PREFERENCE.map((p) => envVarName[p]).join(", ")} — or pick a provider explicitly with VLMKIT_LLM_PROVIDER.`
284
+ };
285
+ return {
286
+ ok: true,
287
+ provider,
288
+ key: keyMap[provider],
289
+ model
290
+ };
291
+ }
292
+ if (!VALID_PROVIDERS.has(requested)) return {
293
+ ok: false,
294
+ code: "INVALID_PROVIDER",
295
+ message: `Unknown VLMKIT_LLM_PROVIDER "${requested}". Expected: gemini | anthropic | openrouter.`
296
+ };
297
+ const provider = requested;
247
298
  const key = keyMap[provider];
248
299
  if (!key) return {
249
300
  ok: false,
@@ -28,6 +28,15 @@ interface VlmClient {
28
28
  maxTokens?: number;
29
29
  }): Promise<VlmResponse>;
30
30
  }
31
+ /**
32
+ * Drop the cached OpenRouter model list.
33
+ *
34
+ * The cache is process-wide and had no way out, which matters beyond tests: the API server
35
+ * (`src/api/`) and a `--loop` run are long-lived, so a model added or repriced upstream is
36
+ * invisible to them until restart. Named after `resetGateRegistryCache`, which exists for the
37
+ * same reason on the same kind of lazily-built module state.
38
+ */
39
+ declare function resetVisionModelCache(): void;
31
40
  declare function fetchVisionModels(): Promise<VlmModel[]>;
32
41
  declare function listModels(options?: {
33
42
  maxCost?: number;
@@ -60,4 +69,4 @@ interface CreateVlmClientOptions {
60
69
  */
61
70
  declare function createVlmClient(model: VlmModel, options?: CreateVlmClientOptions): Promise<VlmClient | null>;
62
71
  //#endregion
63
- export { CreateVlmClientOptions, VlmClient, VlmModel, VlmResponse, createVlmClient, fetchVisionModels, isClaudeDirectModel, isGeminiDirectModel, listClaudeModels, listGeminiModels, listModels, resolveClaudeModel, resolveGeminiModel, resolveModel };
72
+ export { CreateVlmClientOptions, VlmClient, VlmModel, VlmResponse, createVlmClient, fetchVisionModels, isClaudeDirectModel, isGeminiDirectModel, listClaudeModels, listGeminiModels, listModels, resetVisionModelCache, resolveClaudeModel, resolveGeminiModel, resolveModel };
@@ -11,6 +11,17 @@ import { readFile } from "node:fs/promises";
11
11
  * Model list is fetched dynamically from the API.
12
12
  */
13
13
  let _cachedModels = null;
14
+ /**
15
+ * Drop the cached OpenRouter model list.
16
+ *
17
+ * The cache is process-wide and had no way out, which matters beyond tests: the API server
18
+ * (`src/api/`) and a `--loop` run are long-lived, so a model added or repriced upstream is
19
+ * invisible to them until restart. Named after `resetGateRegistryCache`, which exists for the
20
+ * same reason on the same kind of lazily-built module state.
21
+ */
22
+ function resetVisionModelCache() {
23
+ _cachedModels = null;
24
+ }
14
25
  async function fetchVisionModels() {
15
26
  if (_cachedModels) return _cachedModels;
16
27
  const res = await fetch("https://openrouter.ai/api/v1/models");
@@ -50,9 +61,9 @@ async function resolveModel(idOrIndex) {
50
61
  const partial = models.filter((m) => m.id.includes(idOrIndex));
51
62
  if (partial.length === 1) return partial[0];
52
63
  if (partial.length > 1) {
53
- const sorted = partial.sort((a, b) => a.id.length - b.id.length);
54
- if (sorted[0].id.endsWith(idOrIndex) || sorted[0].id.includes(`/${idOrIndex}`)) return sorted[0];
55
- throw new VrtConfigError("MULTIPLE_MATCHES", `Ambiguous model "${idOrIndex}". Matches: ${partial.slice(0, 5).map((m) => m.id).join(", ")}\nTip: use more specific ID, e.g. "${partial[0].id}"`);
64
+ const segmentMatches = partial.filter((m) => m.id.split("/").includes(idOrIndex));
65
+ if (segmentMatches.length === 1) return segmentMatches[0];
66
+ throw new VrtConfigError("MULTIPLE_MATCHES", `Ambiguous model "${idOrIndex}". Matches: ${(segmentMatches.length > 1 ? segmentMatches : partial).slice(0, 5).map((m) => m.id).join(", ")}\nTip: use more specific ID, e.g. "${(segmentMatches[0] ?? partial[0]).id}"`);
56
67
  }
57
68
  const idx = parseInt(idOrIndex, 10);
58
69
  if (!isNaN(idx) && idx >= 0 && idx < models.length) return models[idx];
@@ -364,8 +375,7 @@ async function createVlmClient(model, options) {
364
375
  const latencyMs = Date.now() - start;
365
376
  const usage = data.usage ?? {
366
377
  prompt_tokens: 0,
367
- completion_tokens: 0,
368
- total_tokens: 0
378
+ completion_tokens: 0
369
379
  };
370
380
  const costUsd = usage.prompt_tokens / 1e3 * model.promptCostPer1k + usage.completion_tokens / 1e3 * model.completionCostPer1k;
371
381
  return {
@@ -373,7 +383,7 @@ async function createVlmClient(model, options) {
373
383
  model: model.id,
374
384
  promptTokens: usage.prompt_tokens,
375
385
  completionTokens: usage.completion_tokens,
376
- totalTokens: usage.total_tokens,
386
+ totalTokens: usage.total_tokens ?? usage.prompt_tokens + usage.completion_tokens,
377
387
  costUsd,
378
388
  latencyMs
379
389
  };
@@ -427,4 +437,4 @@ async function createVlmClient(model, options) {
427
437
  return orClient;
428
438
  }
429
439
  //#endregion
430
- export { createVlmClient, fetchVisionModels, isClaudeDirectModel, isGeminiDirectModel, listClaudeModels, listGeminiModels, listModels, resolveClaudeModel, resolveGeminiModel, resolveModel };
440
+ export { createVlmClient, fetchVisionModels, isClaudeDirectModel, isGeminiDirectModel, listClaudeModels, listGeminiModels, listModels, resetVisionModelCache, resolveClaudeModel, resolveGeminiModel, resolveModel };
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@mizchi/vlmkit-ai",
3
- "version": "0.9.1",
3
+ "version": "0.11.0",
4
4
  "description": "VLM / LLM clients, reasoning pipeline, and NLP helpers used by VRT to interpret diff images and natural-language intent.",
5
5
  "license": "MIT",
6
6
  "author": "mizchi",
@@ -37,10 +37,10 @@
37
37
  },
38
38
  "dependencies": {
39
39
  "@google/generative-ai": "^0.24.1",
40
- "@mizchi/vlmkit-core": "0.9.1"
40
+ "@mizchi/vlmkit-core": "0.11.0"
41
41
  },
42
42
  "scripts": {
43
43
  "build": "pnpm --dir ../.. exec tsdown --config tsdown.packages.config.ts --filter @mizchi/vlmkit-ai",
44
- "test": "node --test 'src/**/*.test.ts'"
44
+ "test": "pnpm --dir ../.. exec vitest run packages/vlmkit-ai/src"
45
45
  }
46
46
  }