@mizchi/vlmkit-ai 0.22.0 → 0.23.1
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.
- package/dist/image-gen-client.d.mts +41 -3
- package/dist/image-gen-client.mjs +63 -15
- package/dist/index.d.mts +6 -2
- package/dist/index.mjs +6 -2
- package/dist/llm-client.d.mts +4 -4
- package/dist/llm-client.mjs +4 -4
- package/dist/zoom-drivers.d.mts +33 -0
- package/dist/zoom-drivers.mjs +316 -0
- package/dist/zoom-geometry.d.mts +85 -0
- package/dist/zoom-geometry.mjs +103 -0
- package/dist/zoom-image.d.mts +42 -0
- package/dist/zoom-image.mjs +147 -0
- package/dist/zoom-loop.d.mts +129 -0
- package/dist/zoom-loop.mjs +314 -0
- package/dist/zoom.d.mts +29 -0
- package/dist/zoom.mjs +61 -0
- package/package.json +3 -2
|
@@ -3,9 +3,12 @@ type ImageGenSize = "1024x1024" | "1024x1536" | "1536x1024" | "auto";
|
|
|
3
3
|
type ImageGenQuality = "low" | "medium" | "high" | "auto";
|
|
4
4
|
type ImageGenOutputFormat = "png" | "jpeg" | "webp";
|
|
5
5
|
type ImageGenBackground = "opaque" | "transparent" | "auto";
|
|
6
|
+
/** The figure bench's choice: 3/3 on its briefs at the lowest price measured (2026-09-30). */
|
|
7
|
+
declare const IMAGE_GEN_DEFAULT_MODEL = "openai/gpt-image-2.5-flare";
|
|
6
8
|
interface ImageGenModel {
|
|
7
9
|
id: string;
|
|
8
|
-
|
|
10
|
+
/** `openai`: api.openai.com + OPENAI_API_KEY. `openrouter`: openrouter.ai + OPENROUTER_API_KEY. */
|
|
11
|
+
provider: "openai" | "openrouter";
|
|
9
12
|
/** USD per 1M tokens (matches OpenAI's published pricing table). */
|
|
10
13
|
costPer1MInputTextTokens: number;
|
|
11
14
|
costPer1MInputImageTokens: number;
|
|
@@ -18,6 +21,14 @@ interface ImageGenRequest {
|
|
|
18
21
|
n?: number;
|
|
19
22
|
outputFormat?: ImageGenOutputFormat;
|
|
20
23
|
background?: ImageGenBackground;
|
|
24
|
+
/** OpenRouter only (e.g. `16:9`); the OpenAI route takes `size`. */
|
|
25
|
+
aspectRatio?: string;
|
|
26
|
+
/**
|
|
27
|
+
* OpenRouter only: images the model draws from — a style to match, a subject to edit. URLs or
|
|
28
|
+
* `data:` URLs. Sent as `input_references`, which takes chat-style `image_url` parts (a bare
|
|
29
|
+
* string or `{ url }` is a 400).
|
|
30
|
+
*/
|
|
31
|
+
inputReferences?: string[];
|
|
21
32
|
}
|
|
22
33
|
interface ImageGenUsage {
|
|
23
34
|
inputTextTokens: number;
|
|
@@ -27,10 +38,26 @@ interface ImageGenUsage {
|
|
|
27
38
|
interface ImageGenResponse {
|
|
28
39
|
model: string;
|
|
29
40
|
images: Uint8Array[];
|
|
41
|
+
/** One per image when the API names it (`image/png`, `image/svg+xml`, …). */
|
|
42
|
+
mediaTypes: (string | null)[];
|
|
30
43
|
usage: ImageGenUsage | null;
|
|
31
44
|
costUsd: number;
|
|
32
45
|
latencyMs: number;
|
|
33
46
|
}
|
|
47
|
+
interface OpenRouterImageBody {
|
|
48
|
+
model: string;
|
|
49
|
+
prompt: string;
|
|
50
|
+
n: number;
|
|
51
|
+
aspect_ratio?: string;
|
|
52
|
+
quality?: ImageGenQuality;
|
|
53
|
+
background?: ImageGenBackground;
|
|
54
|
+
input_references?: {
|
|
55
|
+
type: "image_url";
|
|
56
|
+
image_url: {
|
|
57
|
+
url: string;
|
|
58
|
+
};
|
|
59
|
+
}[];
|
|
60
|
+
}
|
|
34
61
|
interface ImageGenRequestBody {
|
|
35
62
|
model: string;
|
|
36
63
|
prompt: string;
|
|
@@ -46,13 +73,20 @@ interface ImageGenClient {
|
|
|
46
73
|
}
|
|
47
74
|
declare function listImageGenModels(): ImageGenModel[];
|
|
48
75
|
declare function resolveImageGenModel(id: string): ImageGenModel;
|
|
76
|
+
/** `VLMKIT_IMAGE_MODEL`, else the bench's default. */
|
|
77
|
+
declare function defaultImageGenModelId(env?: Record<string, string | undefined>): string;
|
|
49
78
|
declare function buildGenerationBody(model: ImageGenModel, req: ImageGenRequest): ImageGenRequestBody;
|
|
79
|
+
declare function buildOpenRouterBody(model: ImageGenModel, req: ImageGenRequest): OpenRouterImageBody;
|
|
50
80
|
interface RawGenerationResponse {
|
|
51
81
|
data?: Array<{
|
|
52
82
|
b64_json?: string;
|
|
53
83
|
url?: string;
|
|
84
|
+
media_type?: string;
|
|
54
85
|
}>;
|
|
55
86
|
usage?: {
|
|
87
|
+
/** OpenRouter: what the call was billed, in USD. */cost?: number;
|
|
88
|
+
prompt_tokens?: number;
|
|
89
|
+
completion_tokens?: number;
|
|
56
90
|
input_tokens?: number;
|
|
57
91
|
output_tokens?: number;
|
|
58
92
|
total_tokens?: number;
|
|
@@ -64,7 +98,10 @@ interface RawGenerationResponse {
|
|
|
64
98
|
}
|
|
65
99
|
interface ParsedGeneration {
|
|
66
100
|
images: Uint8Array[];
|
|
101
|
+
mediaTypes: (string | null)[];
|
|
67
102
|
usage: ImageGenUsage | null;
|
|
103
|
+
/** The provider's own figure (OpenRouter `usage.cost`), when it gives one. */
|
|
104
|
+
reportedCostUsd: number | null;
|
|
68
105
|
}
|
|
69
106
|
declare function parseGenerationResponse(json: RawGenerationResponse): ParsedGeneration;
|
|
70
107
|
declare function estimateImageGenCost(model: ImageGenModel, usage: ImageGenUsage | null): number;
|
|
@@ -74,6 +111,7 @@ interface CreateImageGenClientOptions {
|
|
|
74
111
|
/** Override the API base URL (for tests / proxies). */
|
|
75
112
|
baseUrl?: string;
|
|
76
113
|
}
|
|
77
|
-
|
|
114
|
+
/** With no model: `VLMKIT_IMAGE_MODEL`, else `IMAGE_GEN_DEFAULT_MODEL`. */
|
|
115
|
+
declare function createImageGenClient(modelOrId?: ImageGenModel | string, options?: CreateImageGenClientOptions): ImageGenClient;
|
|
78
116
|
//#endregion
|
|
79
|
-
export { CreateImageGenClientOptions, ImageGenBackground, ImageGenClient, ImageGenModel, ImageGenOutputFormat, ImageGenQuality, ImageGenRequest, ImageGenRequestBody, ImageGenResponse, ImageGenSize, ImageGenUsage, ParsedGeneration, buildGenerationBody, createImageGenClient, estimateImageGenCost, listImageGenModels, parseGenerationResponse, resolveImageGenModel };
|
|
117
|
+
export { CreateImageGenClientOptions, IMAGE_GEN_DEFAULT_MODEL, ImageGenBackground, ImageGenClient, ImageGenModel, ImageGenOutputFormat, ImageGenQuality, ImageGenRequest, ImageGenRequestBody, ImageGenResponse, ImageGenSize, ImageGenUsage, OpenRouterImageBody, ParsedGeneration, buildGenerationBody, buildOpenRouterBody, createImageGenClient, defaultImageGenModelId, estimateImageGenCost, listImageGenModels, parseGenerationResponse, resolveImageGenModel };
|
|
@@ -1,7 +1,14 @@
|
|
|
1
1
|
import { VrtConfigError } from "./errors.mjs";
|
|
2
2
|
//#region src/image-gen-client.ts
|
|
3
3
|
/**
|
|
4
|
-
* Image generation client (OpenAI
|
|
4
|
+
* Image generation client: OpenRouter's Images API (the default route) or the OpenAI Images API.
|
|
5
|
+
*
|
|
6
|
+
* `IMAGE_GEN_DEFAULT_MODEL` is the model the figure bench chose
|
|
7
|
+
* (`src/experiments/benchmark/image-gen/`, evaluation saved under
|
|
8
|
+
* `docs/reports/data/2026-09-30-image-gen/`); `VLMKIT_IMAGE_MODEL` overrides it. Any
|
|
9
|
+
* `vendor/model` id is an OpenRouter model and needs `OPENROUTER_API_KEY`; its cost is the one
|
|
10
|
+
* OpenRouter reports in `usage.cost`. The two bare ids in the registry (`gpt-image-2`, the dated
|
|
11
|
+
* snapshot) call `api.openai.com` directly with `OPENAI_API_KEY`.
|
|
5
12
|
*
|
|
6
13
|
* Mirrors the vlm-client / llm-client split: a small registry of known
|
|
7
14
|
* models, pure builders + parsers that can be unit-tested without a network
|
|
@@ -18,6 +25,8 @@ import { VrtConfigError } from "./errors.mjs";
|
|
|
18
25
|
* `/v1/images/edits`) are intentionally out of scope here; add a separate
|
|
19
26
|
* `editImage` method if/when a caller needs it.
|
|
20
27
|
*/
|
|
28
|
+
/** The figure bench's choice: 3/3 on its briefs at the lowest price measured (2026-09-30). */
|
|
29
|
+
const IMAGE_GEN_DEFAULT_MODEL = "openai/gpt-image-2.5-flare";
|
|
21
30
|
const IMAGE_GEN_MODELS = [{
|
|
22
31
|
id: "gpt-image-2",
|
|
23
32
|
provider: "openai",
|
|
@@ -56,10 +65,22 @@ const VALID_BACKGROUNDS = new Set([
|
|
|
56
65
|
function listImageGenModels() {
|
|
57
66
|
return IMAGE_GEN_MODELS.map((m) => ({ ...m }));
|
|
58
67
|
}
|
|
68
|
+
const OPENROUTER_ID = /^[a-z0-9][a-z0-9-]*\/[a-z0-9][a-z0-9.:\-]*$/;
|
|
59
69
|
function resolveImageGenModel(id) {
|
|
60
70
|
const hit = IMAGE_GEN_MODELS.find((m) => m.id === id);
|
|
61
|
-
if (
|
|
62
|
-
return {
|
|
71
|
+
if (hit) return { ...hit };
|
|
72
|
+
if (OPENROUTER_ID.test(id)) return {
|
|
73
|
+
id,
|
|
74
|
+
provider: "openrouter",
|
|
75
|
+
costPer1MInputTextTokens: 0,
|
|
76
|
+
costPer1MInputImageTokens: 0,
|
|
77
|
+
costPer1MOutputImageTokens: 0
|
|
78
|
+
};
|
|
79
|
+
throw new VrtConfigError("INVALID_MODEL", `Unknown image generation model: "${id}". Known: ${IMAGE_GEN_MODELS.map((m) => m.id).join(", ")}, or any OpenRouter id (vendor/model)`);
|
|
80
|
+
}
|
|
81
|
+
/** `VLMKIT_IMAGE_MODEL`, else the bench's default. */
|
|
82
|
+
function defaultImageGenModelId(env = process.env) {
|
|
83
|
+
return env.VLMKIT_IMAGE_MODEL?.trim() || "openai/gpt-image-2.5-flare";
|
|
63
84
|
}
|
|
64
85
|
function buildGenerationBody(model, req) {
|
|
65
86
|
if (!req.prompt || !req.prompt.trim()) throw new VrtConfigError("INVALID_REQUEST", "image-gen: prompt must be a non-empty string");
|
|
@@ -83,20 +104,41 @@ function buildGenerationBody(model, req) {
|
|
|
83
104
|
background
|
|
84
105
|
};
|
|
85
106
|
}
|
|
107
|
+
function buildOpenRouterBody(model, req) {
|
|
108
|
+
if (!req.prompt || !req.prompt.trim()) throw new VrtConfigError("INVALID_REQUEST", "image-gen: prompt must be a non-empty string");
|
|
109
|
+
const n = req.n ?? 1;
|
|
110
|
+
if (!Number.isInteger(n) || n <= 0) throw new VrtConfigError("INVALID_REQUEST", `image-gen: n must be a positive integer, got ${n}`);
|
|
111
|
+
return {
|
|
112
|
+
model: model.id,
|
|
113
|
+
prompt: req.prompt,
|
|
114
|
+
n,
|
|
115
|
+
...req.aspectRatio ? { aspect_ratio: req.aspectRatio } : {},
|
|
116
|
+
...req.quality ? { quality: req.quality } : {},
|
|
117
|
+
...req.background ? { background: req.background } : {},
|
|
118
|
+
...req.inputReferences?.length ? { input_references: req.inputReferences.map((url) => ({
|
|
119
|
+
type: "image_url",
|
|
120
|
+
image_url: { url }
|
|
121
|
+
})) } : {}
|
|
122
|
+
};
|
|
123
|
+
}
|
|
86
124
|
function parseGenerationResponse(json) {
|
|
87
125
|
const images = [];
|
|
126
|
+
const mediaTypes = [];
|
|
88
127
|
for (const entry of json.data ?? []) {
|
|
89
128
|
if (!entry || typeof entry.b64_json !== "string") continue;
|
|
90
129
|
images.push(new Uint8Array(Buffer.from(entry.b64_json, "base64")));
|
|
130
|
+
mediaTypes.push(entry.media_type ?? null);
|
|
91
131
|
}
|
|
92
132
|
const u = json.usage;
|
|
93
133
|
return {
|
|
94
134
|
images,
|
|
135
|
+
mediaTypes,
|
|
95
136
|
usage: u ? {
|
|
96
|
-
inputTextTokens: u.input_tokens_details?.text_tokens ?? u.input_tokens ?? 0,
|
|
137
|
+
inputTextTokens: u.input_tokens_details?.text_tokens ?? u.input_tokens ?? u.prompt_tokens ?? 0,
|
|
97
138
|
inputImageTokens: u.input_tokens_details?.image_tokens ?? 0,
|
|
98
|
-
outputTokens: u.output_tokens ?? 0
|
|
99
|
-
} : null
|
|
139
|
+
outputTokens: u.output_tokens ?? u.completion_tokens ?? 0
|
|
140
|
+
} : null,
|
|
141
|
+
reportedCostUsd: typeof u?.cost === "number" ? u.cost : null
|
|
100
142
|
};
|
|
101
143
|
}
|
|
102
144
|
function estimateImageGenCost(model, usage) {
|
|
@@ -104,18 +146,23 @@ function estimateImageGenCost(model, usage) {
|
|
|
104
146
|
const cost = (usage.inputTextTokens * model.costPer1MInputTextTokens + usage.inputImageTokens * model.costPer1MInputImageTokens + usage.outputTokens * model.costPer1MOutputImageTokens) / 1e6;
|
|
105
147
|
return Math.round(cost * 1e6) / 1e6;
|
|
106
148
|
}
|
|
107
|
-
|
|
149
|
+
/** With no model: `VLMKIT_IMAGE_MODEL`, else `IMAGE_GEN_DEFAULT_MODEL`. */
|
|
150
|
+
function createImageGenClient(modelOrId = defaultImageGenModelId(), options) {
|
|
108
151
|
const model = typeof modelOrId === "string" ? resolveImageGenModel(modelOrId) : modelOrId;
|
|
152
|
+
const openRouter = model.provider === "openrouter";
|
|
153
|
+
const keyName = openRouter ? "OPENROUTER_API_KEY" : "OPENAI_API_KEY";
|
|
109
154
|
const throwIfMissing = options?.throwIfMissing ?? true;
|
|
110
|
-
const apiKey = options?.apiKey ?? process.env
|
|
111
|
-
if (!apiKey && throwIfMissing) throw new VrtConfigError("MISSING_KEY",
|
|
112
|
-
const baseUrl = options?.baseUrl ?? "https://api.openai.com";
|
|
155
|
+
const apiKey = options?.apiKey ?? process.env[keyName];
|
|
156
|
+
if (!apiKey && throwIfMissing) throw new VrtConfigError("MISSING_KEY", `${keyName} is required for ${model.id}`);
|
|
157
|
+
const baseUrl = options?.baseUrl ?? (openRouter ? "https://openrouter.ai" : "https://api.openai.com");
|
|
158
|
+
const path = openRouter ? "/api/v1/images" : "/v1/images/generations";
|
|
159
|
+
const provider = openRouter ? "OpenRouter" : "OpenAI";
|
|
113
160
|
return {
|
|
114
161
|
model,
|
|
115
162
|
async generate(req) {
|
|
116
|
-
const body = buildGenerationBody(model, req);
|
|
163
|
+
const body = openRouter ? buildOpenRouterBody(model, req) : buildGenerationBody(model, req);
|
|
117
164
|
const started = Date.now();
|
|
118
|
-
const res = await fetch(`${baseUrl}
|
|
165
|
+
const res = await fetch(`${baseUrl}${path}`, {
|
|
119
166
|
method: "POST",
|
|
120
167
|
headers: {
|
|
121
168
|
Authorization: `Bearer ${apiKey ?? ""}`,
|
|
@@ -128,7 +175,7 @@ function createImageGenClient(modelOrId, options) {
|
|
|
128
175
|
try {
|
|
129
176
|
json = JSON.parse(text);
|
|
130
177
|
} catch {
|
|
131
|
-
throw new Error(`image-gen: non-JSON response from
|
|
178
|
+
throw new Error(`image-gen: non-JSON response from ${provider} (status ${res.status}): ${text.slice(0, 200)}`);
|
|
132
179
|
}
|
|
133
180
|
if (!res.ok) {
|
|
134
181
|
const message = json.error?.message ?? text.slice(0, 200);
|
|
@@ -138,12 +185,13 @@ function createImageGenClient(modelOrId, options) {
|
|
|
138
185
|
return {
|
|
139
186
|
model: model.id,
|
|
140
187
|
images: parsed.images,
|
|
188
|
+
mediaTypes: parsed.mediaTypes,
|
|
141
189
|
usage: parsed.usage,
|
|
142
|
-
costUsd: estimateImageGenCost(model, parsed.usage),
|
|
190
|
+
costUsd: parsed.reportedCostUsd ?? estimateImageGenCost(model, parsed.usage),
|
|
143
191
|
latencyMs: Date.now() - started
|
|
144
192
|
};
|
|
145
193
|
}
|
|
146
194
|
};
|
|
147
195
|
}
|
|
148
196
|
//#endregion
|
|
149
|
-
export { buildGenerationBody, createImageGenClient, estimateImageGenCost, listImageGenModels, parseGenerationResponse, resolveImageGenModel };
|
|
197
|
+
export { IMAGE_GEN_DEFAULT_MODEL, buildGenerationBody, buildOpenRouterBody, createImageGenClient, defaultImageGenModelId, estimateImageGenCost, listImageGenModels, parseGenerationResponse, resolveImageGenModel };
|
package/dist/index.d.mts
CHANGED
|
@@ -1,8 +1,12 @@
|
|
|
1
1
|
import { VrtConfigError, VrtConfigErrorCode } from "./errors.mjs";
|
|
2
|
-
import { CreateImageGenClientOptions, ImageGenBackground, ImageGenClient, ImageGenModel, ImageGenOutputFormat, ImageGenQuality, ImageGenRequest, ImageGenRequestBody, ImageGenResponse, ImageGenSize, ImageGenUsage, ParsedGeneration, buildGenerationBody, createImageGenClient, estimateImageGenCost, listImageGenModels, parseGenerationResponse, resolveImageGenModel } from "./image-gen-client.mjs";
|
|
2
|
+
import { CreateImageGenClientOptions, IMAGE_GEN_DEFAULT_MODEL, ImageGenBackground, ImageGenClient, ImageGenModel, ImageGenOutputFormat, ImageGenQuality, ImageGenRequest, ImageGenRequestBody, ImageGenResponse, ImageGenSize, ImageGenUsage, OpenRouterImageBody, ParsedGeneration, buildGenerationBody, buildOpenRouterBody, createImageGenClient, defaultImageGenModelId, estimateImageGenCost, listImageGenModels, parseGenerationResponse, resolveImageGenModel } from "./image-gen-client.mjs";
|
|
3
3
|
import { LLMProvider, buildIntent, buildIntentWithLLM, buildReasoningPrompt, extractDiffSemantics, parseDiff } from "./intent.mjs";
|
|
4
4
|
import { CreateLLMProviderOptions, ImageContent, LLMClientOptions, LLMProviderName, LLMResponse, MessageContent, OPENAI_DEFAULT_MODEL, TextContent, UnifiedLLMClient, createLLMProvider, createUnifiedLLMClient } from "./llm-client.mjs";
|
|
5
5
|
import { CreateVlmClientOptions, VlmClient, VlmModel, VlmResponse, createVlmClient, fetchVisionModels, isGeminiDirectModel, listGeminiModels, listModels, resolveGeminiModel, resolveModel } from "./vlm-client.mjs";
|
|
6
6
|
import { AnalyzeOptions, CssFix, FixSuggestion, PipelineConfig, ReasoningPipeline, StructuredDiffReport, VisualChange, createReasoningPipeline } from "./reasoning-pipeline.mjs";
|
|
7
7
|
import { ActualChange, ExpectationMapping, ReasoningChain, reasonAboutChanges } from "./reasoning.mjs";
|
|
8
|
-
|
|
8
|
+
import { DEFAULT_IMAGE_BUDGET, ImageBudget, ZoomCoordinates } from "./zoom-geometry.mjs";
|
|
9
|
+
import { SingleLookResult, VisionChatDriver, ZoomLoopOptions, ZoomLoopResult, parseZoomRequests, runSingleLook, runZoomLoop } from "./zoom-loop.mjs";
|
|
10
|
+
import { anthropicDriver, geminiDriver, openAiCompatibleDriver } from "./zoom-drivers.mjs";
|
|
11
|
+
import { ZoomAnalysis, analyzeWithZoom, createZoomDriver } from "./zoom.mjs";
|
|
12
|
+
export { type ActualChange, type AnalyzeOptions, type CreateImageGenClientOptions, type CreateLLMProviderOptions, type CreateVlmClientOptions, type CssFix, DEFAULT_IMAGE_BUDGET, type ExpectationMapping, type FixSuggestion, IMAGE_GEN_DEFAULT_MODEL, type ImageBudget, type ImageContent, type ImageGenBackground, type ImageGenClient, type ImageGenModel, type ImageGenOutputFormat, type ImageGenQuality, type ImageGenRequest, type ImageGenRequestBody, type ImageGenResponse, type ImageGenSize, type ImageGenUsage, type LLMClientOptions, type LLMProvider, type LLMProviderName, type LLMResponse, type MessageContent, OPENAI_DEFAULT_MODEL, type OpenRouterImageBody, type ParsedGeneration, type PipelineConfig, type ReasoningChain, type ReasoningPipeline, type SingleLookResult, type StructuredDiffReport, type TextContent, type UnifiedLLMClient, type VisionChatDriver, type VisualChange, type VlmClient, type VlmModel, type VlmResponse, VrtConfigError, type VrtConfigErrorCode, type ZoomAnalysis, type ZoomCoordinates, type ZoomLoopOptions, type ZoomLoopResult, analyzeWithZoom, anthropicDriver, buildGenerationBody, buildIntent, buildIntentWithLLM, buildOpenRouterBody, buildReasoningPrompt, createImageGenClient, createLLMProvider, createReasoningPipeline, createUnifiedLLMClient, createVlmClient, createZoomDriver, defaultImageGenModelId, estimateImageGenCost, extractDiffSemantics, fetchVisionModels, geminiDriver, isGeminiDirectModel, listGeminiModels, listImageGenModels, listModels, openAiCompatibleDriver, parseDiff, parseGenerationResponse, parseZoomRequests, reasonAboutChanges, resolveGeminiModel, resolveImageGenModel, resolveModel, runSingleLook, runZoomLoop };
|
package/dist/index.mjs
CHANGED
|
@@ -1,8 +1,12 @@
|
|
|
1
1
|
import { VrtConfigError } from "./errors.mjs";
|
|
2
|
-
import { buildGenerationBody, createImageGenClient, estimateImageGenCost, listImageGenModels, parseGenerationResponse, resolveImageGenModel } from "./image-gen-client.mjs";
|
|
2
|
+
import { IMAGE_GEN_DEFAULT_MODEL, buildGenerationBody, buildOpenRouterBody, createImageGenClient, defaultImageGenModelId, estimateImageGenCost, listImageGenModels, parseGenerationResponse, resolveImageGenModel } from "./image-gen-client.mjs";
|
|
3
3
|
import { OPENAI_DEFAULT_MODEL, createLLMProvider, createUnifiedLLMClient } from "./llm-client.mjs";
|
|
4
4
|
import { createVlmClient, fetchVisionModels, isGeminiDirectModel, listGeminiModels, listModels, resolveGeminiModel, resolveModel } from "./vlm-client.mjs";
|
|
5
5
|
import { createReasoningPipeline } from "./reasoning-pipeline.mjs";
|
|
6
6
|
import { reasonAboutChanges } from "./reasoning.mjs";
|
|
7
7
|
import { buildIntent, buildIntentWithLLM, buildReasoningPrompt, extractDiffSemantics, parseDiff } from "./intent.mjs";
|
|
8
|
-
|
|
8
|
+
import { DEFAULT_IMAGE_BUDGET } from "./zoom-geometry.mjs";
|
|
9
|
+
import { parseZoomRequests, runSingleLook, runZoomLoop } from "./zoom-loop.mjs";
|
|
10
|
+
import { anthropicDriver, geminiDriver, openAiCompatibleDriver } from "./zoom-drivers.mjs";
|
|
11
|
+
import { analyzeWithZoom, createZoomDriver } from "./zoom.mjs";
|
|
12
|
+
export { DEFAULT_IMAGE_BUDGET, IMAGE_GEN_DEFAULT_MODEL, OPENAI_DEFAULT_MODEL, VrtConfigError, analyzeWithZoom, anthropicDriver, buildGenerationBody, buildIntent, buildIntentWithLLM, buildOpenRouterBody, buildReasoningPrompt, createImageGenClient, createLLMProvider, createReasoningPipeline, createUnifiedLLMClient, createVlmClient, createZoomDriver, defaultImageGenModelId, estimateImageGenCost, extractDiffSemantics, fetchVisionModels, geminiDriver, isGeminiDirectModel, listGeminiModels, listImageGenModels, listModels, openAiCompatibleDriver, parseDiff, parseGenerationResponse, parseZoomRequests, reasonAboutChanges, resolveGeminiModel, resolveImageGenModel, resolveModel, runSingleLook, runZoomLoop };
|
package/dist/llm-client.d.mts
CHANGED
|
@@ -58,10 +58,10 @@ type LLMProviderName = "gemini" | "anthropic" | "openrouter";
|
|
|
58
58
|
/**
|
|
59
59
|
* The OpenAI model this project reaches for by default, and the one place its id is written.
|
|
60
60
|
*
|
|
61
|
-
* OpenAI is **not**
|
|
62
|
-
*
|
|
63
|
-
*
|
|
64
|
-
*
|
|
61
|
+
* OpenAI is **not** an LLM provider name here. This client serves its OpenAI models through
|
|
62
|
+
* OpenRouter, which is why the id carries the `openai/` prefix: that string is an OpenRouter
|
|
63
|
+
* catalogue id. The separate image-generation client calls `api.openai.com` and reads
|
|
64
|
+
* `OPENAI_API_KEY`.
|
|
65
65
|
*
|
|
66
66
|
* Exported so the docs can be pinned to it. `tests/agent-model-defaults.test.mjs` asserts that
|
|
67
67
|
* `AGENTS.md`, `.claude/CLAUDE.md` and `docs/configuration.md` all name this exact model, because
|
package/dist/llm-client.mjs
CHANGED
|
@@ -219,10 +219,10 @@ const VALID_PROVIDERS = new Set([
|
|
|
219
219
|
/**
|
|
220
220
|
* The OpenAI model this project reaches for by default, and the one place its id is written.
|
|
221
221
|
*
|
|
222
|
-
* OpenAI is **not**
|
|
223
|
-
*
|
|
224
|
-
*
|
|
225
|
-
*
|
|
222
|
+
* OpenAI is **not** an LLM provider name here. This client serves its OpenAI models through
|
|
223
|
+
* OpenRouter, which is why the id carries the `openai/` prefix: that string is an OpenRouter
|
|
224
|
+
* catalogue id. The separate image-generation client calls `api.openai.com` and reads
|
|
225
|
+
* `OPENAI_API_KEY`.
|
|
226
226
|
*
|
|
227
227
|
* Exported so the docs can be pinned to it. `tests/agent-model-defaults.test.mjs` asserts that
|
|
228
228
|
* `AGENTS.md`, `.claude/CLAUDE.md` and `docs/configuration.md` all name this exact model, because
|
|
@@ -0,0 +1,33 @@
|
|
|
1
|
+
import { VisionChatDriver, ZoomToolSpec } from "./zoom-loop.mjs";
|
|
2
|
+
|
|
3
|
+
//#region src/zoom-drivers.d.ts
|
|
4
|
+
type Fetch = typeof fetch;
|
|
5
|
+
interface OpenAiCompatibleDriverOptions {
|
|
6
|
+
model: string;
|
|
7
|
+
apiKey?: string;
|
|
8
|
+
/** Chat Completions URL (default OpenRouter's). */
|
|
9
|
+
url?: string;
|
|
10
|
+
headers?: Record<string, string>;
|
|
11
|
+
/** False for a server without function calling: the loop then uses the text protocol. */
|
|
12
|
+
nativeTools?: boolean;
|
|
13
|
+
fetch?: Fetch;
|
|
14
|
+
}
|
|
15
|
+
declare function openAiCompatibleDriver(options: OpenAiCompatibleDriverOptions): VisionChatDriver;
|
|
16
|
+
interface AnthropicDriverOptions {
|
|
17
|
+
model: string;
|
|
18
|
+
apiKey: string;
|
|
19
|
+
/** Default https://api.anthropic.com (or ANTHROPIC_BASE_URL when the caller passes it). */
|
|
20
|
+
baseUrl?: string;
|
|
21
|
+
fetch?: Fetch;
|
|
22
|
+
}
|
|
23
|
+
declare function anthropicDriver(options: AnthropicDriverOptions): VisionChatDriver;
|
|
24
|
+
interface GeminiDriverOptions {
|
|
25
|
+
/** e.g. `gemini-2.5-flash` (no `gemini:` prefix). */
|
|
26
|
+
model: string;
|
|
27
|
+
apiKey: string;
|
|
28
|
+
baseUrl?: string;
|
|
29
|
+
fetch?: Fetch;
|
|
30
|
+
}
|
|
31
|
+
declare function geminiDriver(options: GeminiDriverOptions): VisionChatDriver;
|
|
32
|
+
//#endregion
|
|
33
|
+
export { AnthropicDriverOptions, GeminiDriverOptions, OpenAiCompatibleDriverOptions, type ZoomToolSpec, anthropicDriver, geminiDriver, openAiCompatibleDriver };
|
|
@@ -0,0 +1,316 @@
|
|
|
1
|
+
import { zoomCallFromArgs } from "./zoom-loop.mjs";
|
|
2
|
+
//#region src/zoom-drivers.ts
|
|
3
|
+
async function postJson(fetcher, url, headers, body, provider) {
|
|
4
|
+
const res = await fetcher(url, {
|
|
5
|
+
method: "POST",
|
|
6
|
+
headers: {
|
|
7
|
+
"Content-Type": "application/json",
|
|
8
|
+
...headers
|
|
9
|
+
},
|
|
10
|
+
body: JSON.stringify(body)
|
|
11
|
+
});
|
|
12
|
+
if (!res.ok) {
|
|
13
|
+
const text = await res.text();
|
|
14
|
+
throw new Error(`${provider} API error: ${res.status} ${text.slice(0, 300)}`);
|
|
15
|
+
}
|
|
16
|
+
return await res.json();
|
|
17
|
+
}
|
|
18
|
+
/** A call the provider made whose arguments did not parse still needs an answer; this one says why. */
|
|
19
|
+
function callsFrom(parsed) {
|
|
20
|
+
const calls = [];
|
|
21
|
+
const broken = [];
|
|
22
|
+
for (const p of parsed) ("error" in p ? broken : calls).push(p);
|
|
23
|
+
return {
|
|
24
|
+
calls,
|
|
25
|
+
broken
|
|
26
|
+
};
|
|
27
|
+
}
|
|
28
|
+
/** Merge adjacent messages of one role: every provider accepts that, not every one accepts the split. */
|
|
29
|
+
function mergeAdjacent(messages, join) {
|
|
30
|
+
const out = [];
|
|
31
|
+
for (const m of messages) {
|
|
32
|
+
const last = out[out.length - 1];
|
|
33
|
+
if (last && last.role === m.role) out[out.length - 1] = join(last, m);
|
|
34
|
+
else out.push(m);
|
|
35
|
+
}
|
|
36
|
+
return out;
|
|
37
|
+
}
|
|
38
|
+
const b64 = (png) => png.toString("base64");
|
|
39
|
+
function openAiCompatibleDriver(options) {
|
|
40
|
+
const url = options.url ?? "https://openrouter.ai/api/v1/chat/completions";
|
|
41
|
+
const fetcher = options.fetch ?? fetch;
|
|
42
|
+
const headers = {
|
|
43
|
+
...options.apiKey ? { Authorization: `Bearer ${options.apiKey}` } : {},
|
|
44
|
+
...options.headers
|
|
45
|
+
};
|
|
46
|
+
const content = (parts) => parts.map((p) => p.type === "text" ? {
|
|
47
|
+
type: "text",
|
|
48
|
+
text: p.text
|
|
49
|
+
} : {
|
|
50
|
+
type: "image_url",
|
|
51
|
+
image_url: { url: `data:image/png;base64,${b64(p.png)}` }
|
|
52
|
+
});
|
|
53
|
+
const render = (transcript) => {
|
|
54
|
+
const out = [];
|
|
55
|
+
for (const t of transcript) if (t.role === "user") out.push({
|
|
56
|
+
role: "user",
|
|
57
|
+
content: content(t.parts)
|
|
58
|
+
});
|
|
59
|
+
else if (t.role === "assistant") out.push(t.raw !== void 0 ? t.raw : {
|
|
60
|
+
role: "assistant",
|
|
61
|
+
content: t.text
|
|
62
|
+
});
|
|
63
|
+
else if (t.native) {
|
|
64
|
+
const images = [];
|
|
65
|
+
for (const r of t.results) {
|
|
66
|
+
out.push({
|
|
67
|
+
role: "tool",
|
|
68
|
+
tool_call_id: r.callId,
|
|
69
|
+
content: textOf(r)
|
|
70
|
+
});
|
|
71
|
+
const img = r.parts.filter((p) => p.type === "image");
|
|
72
|
+
if (img.length > 0) images.push({
|
|
73
|
+
type: "text",
|
|
74
|
+
text: `Zoom result for call ${r.callId}:`
|
|
75
|
+
}, ...img);
|
|
76
|
+
}
|
|
77
|
+
if (images.length > 0) out.push({
|
|
78
|
+
role: "user",
|
|
79
|
+
content: content(images)
|
|
80
|
+
});
|
|
81
|
+
} else out.push({
|
|
82
|
+
role: "user",
|
|
83
|
+
content: content(t.results.flatMap((r) => r.parts))
|
|
84
|
+
});
|
|
85
|
+
return out;
|
|
86
|
+
};
|
|
87
|
+
return {
|
|
88
|
+
model: options.model,
|
|
89
|
+
nativeTools: options.nativeTools ?? true,
|
|
90
|
+
async turn(transcript, { tool, maxTokens }) {
|
|
91
|
+
const data = await postJson(fetcher, url, headers, {
|
|
92
|
+
model: options.model,
|
|
93
|
+
max_tokens: maxTokens,
|
|
94
|
+
messages: render(transcript),
|
|
95
|
+
...tool ? { tools: [{
|
|
96
|
+
type: "function",
|
|
97
|
+
function: {
|
|
98
|
+
name: tool.name,
|
|
99
|
+
description: tool.description,
|
|
100
|
+
parameters: tool.parameters
|
|
101
|
+
}
|
|
102
|
+
}] } : {}
|
|
103
|
+
}, "OpenAI-compatible");
|
|
104
|
+
const choice = data.choices?.[0];
|
|
105
|
+
const message = choice?.message ?? {};
|
|
106
|
+
const toolCalls = message.tool_calls ?? [];
|
|
107
|
+
const { calls, broken } = callsFrom(toolCalls.filter((c) => c.function?.name === "zoom").map((c) => zoomCallFromArgs(c.id, c.function?.arguments)));
|
|
108
|
+
return withBroken({
|
|
109
|
+
text: typeof message.content === "string" ? message.content : "",
|
|
110
|
+
calls,
|
|
111
|
+
raw: {
|
|
112
|
+
role: "assistant",
|
|
113
|
+
content: message.content ?? null,
|
|
114
|
+
...toolCalls.length > 0 ? { tool_calls: toolCalls } : {}
|
|
115
|
+
},
|
|
116
|
+
usage: {
|
|
117
|
+
promptTokens: data.usage?.prompt_tokens ?? 0,
|
|
118
|
+
completionTokens: data.usage?.completion_tokens ?? 0
|
|
119
|
+
},
|
|
120
|
+
...choice?.finish_reason && !["stop", "tool_calls"].includes(choice.finish_reason) ? { stop: choice.finish_reason } : {}
|
|
121
|
+
}, broken);
|
|
122
|
+
}
|
|
123
|
+
};
|
|
124
|
+
}
|
|
125
|
+
function anthropicDriver(options) {
|
|
126
|
+
const url = `${(options.baseUrl ?? "https://api.anthropic.com").replace(/\/$/, "")}/v1/messages`;
|
|
127
|
+
const fetcher = options.fetch ?? fetch;
|
|
128
|
+
const blocks = (parts) => parts.map((p) => p.type === "text" ? {
|
|
129
|
+
type: "text",
|
|
130
|
+
text: p.text
|
|
131
|
+
} : {
|
|
132
|
+
type: "image",
|
|
133
|
+
source: {
|
|
134
|
+
type: "base64",
|
|
135
|
+
media_type: "image/png",
|
|
136
|
+
data: b64(p.png)
|
|
137
|
+
}
|
|
138
|
+
});
|
|
139
|
+
const render = (transcript) => {
|
|
140
|
+
const out = [];
|
|
141
|
+
for (const t of transcript) if (t.role === "user") out.push({
|
|
142
|
+
role: "user",
|
|
143
|
+
content: blocks(t.parts)
|
|
144
|
+
});
|
|
145
|
+
else if (t.role === "assistant") out.push({
|
|
146
|
+
role: "assistant",
|
|
147
|
+
content: t.raw !== void 0 ? t.raw : [...t.text ? [{
|
|
148
|
+
type: "text",
|
|
149
|
+
text: t.text
|
|
150
|
+
}] : [], ...t.calls.filter((c) => !c.id.startsWith("text-")).map((c) => ({
|
|
151
|
+
type: "tool_use",
|
|
152
|
+
id: c.id,
|
|
153
|
+
name: "zoom",
|
|
154
|
+
input: {
|
|
155
|
+
image_index: c.imageIndex,
|
|
156
|
+
...c.box
|
|
157
|
+
}
|
|
158
|
+
}))]
|
|
159
|
+
});
|
|
160
|
+
else if (t.native) out.push({
|
|
161
|
+
role: "user",
|
|
162
|
+
content: t.results.map((r) => ({
|
|
163
|
+
type: "tool_result",
|
|
164
|
+
tool_use_id: r.callId,
|
|
165
|
+
content: blocks(r.parts),
|
|
166
|
+
...r.isError ? { is_error: true } : {}
|
|
167
|
+
}))
|
|
168
|
+
});
|
|
169
|
+
else out.push({
|
|
170
|
+
role: "user",
|
|
171
|
+
content: blocks(t.results.flatMap((r) => r.parts))
|
|
172
|
+
});
|
|
173
|
+
return mergeAdjacent(out, (a, b) => ({
|
|
174
|
+
role: a.role,
|
|
175
|
+
content: [...a.content, ...b.content]
|
|
176
|
+
}));
|
|
177
|
+
};
|
|
178
|
+
return {
|
|
179
|
+
model: options.model,
|
|
180
|
+
nativeTools: true,
|
|
181
|
+
async turn(transcript, { tool, maxTokens }) {
|
|
182
|
+
const data = await postJson(fetcher, url, {
|
|
183
|
+
"x-api-key": options.apiKey,
|
|
184
|
+
"anthropic-version": "2023-06-01"
|
|
185
|
+
}, {
|
|
186
|
+
model: options.model,
|
|
187
|
+
max_tokens: maxTokens,
|
|
188
|
+
messages: render(transcript),
|
|
189
|
+
...tool ? { tools: [{
|
|
190
|
+
name: tool.name,
|
|
191
|
+
description: tool.description,
|
|
192
|
+
input_schema: tool.parameters
|
|
193
|
+
}] } : {}
|
|
194
|
+
}, "Anthropic");
|
|
195
|
+
const content = data.content ?? [];
|
|
196
|
+
const { calls, broken } = callsFrom(content.filter((b) => b.type === "tool_use" && b.name === "zoom").map((b) => zoomCallFromArgs(b.id, b.input)));
|
|
197
|
+
return withBroken({
|
|
198
|
+
text: content.filter((b) => b.type === "text").map((b) => b.text ?? "").join(""),
|
|
199
|
+
calls,
|
|
200
|
+
raw: content,
|
|
201
|
+
usage: {
|
|
202
|
+
promptTokens: data.usage?.input_tokens ?? 0,
|
|
203
|
+
completionTokens: data.usage?.output_tokens ?? 0
|
|
204
|
+
},
|
|
205
|
+
...data.stop_reason && ![
|
|
206
|
+
"end_turn",
|
|
207
|
+
"tool_use",
|
|
208
|
+
"stop_sequence"
|
|
209
|
+
].includes(data.stop_reason) ? { stop: data.stop_reason } : {}
|
|
210
|
+
}, broken);
|
|
211
|
+
}
|
|
212
|
+
};
|
|
213
|
+
}
|
|
214
|
+
/** Gemini's function schemas are an OpenAPI subset without `additionalProperties`. */
|
|
215
|
+
function geminiSchema(schema) {
|
|
216
|
+
const { additionalProperties: _drop, ...rest } = schema;
|
|
217
|
+
return rest;
|
|
218
|
+
}
|
|
219
|
+
function geminiDriver(options) {
|
|
220
|
+
const url = `${(options.baseUrl ?? "https://generativelanguage.googleapis.com/v1beta").replace(/\/$/, "")}/models/${encodeURIComponent(options.model)}:generateContent`;
|
|
221
|
+
const fetcher = options.fetch ?? fetch;
|
|
222
|
+
const parts = (ps) => ps.map((p) => p.type === "text" ? { text: p.text } : { inlineData: {
|
|
223
|
+
mimeType: "image/png",
|
|
224
|
+
data: b64(p.png)
|
|
225
|
+
} });
|
|
226
|
+
const render = (transcript) => {
|
|
227
|
+
const out = [];
|
|
228
|
+
for (const t of transcript) if (t.role === "user") out.push({
|
|
229
|
+
role: "user",
|
|
230
|
+
parts: parts(t.parts)
|
|
231
|
+
});
|
|
232
|
+
else if (t.role === "assistant") out.push({
|
|
233
|
+
role: "model",
|
|
234
|
+
parts: t.raw !== void 0 ? t.raw : [...t.text ? [{ text: t.text }] : [], ...t.calls.filter((c) => !c.id.startsWith("text-")).map((c) => ({ functionCall: {
|
|
235
|
+
name: "zoom",
|
|
236
|
+
args: {
|
|
237
|
+
image_index: c.imageIndex,
|
|
238
|
+
...c.box
|
|
239
|
+
}
|
|
240
|
+
} }))]
|
|
241
|
+
});
|
|
242
|
+
else if (t.native) out.push({
|
|
243
|
+
role: "user",
|
|
244
|
+
parts: t.results.flatMap((r) => [{ functionResponse: {
|
|
245
|
+
name: "zoom",
|
|
246
|
+
response: {
|
|
247
|
+
result: textOf(r),
|
|
248
|
+
...r.isError ? { error: true } : {}
|
|
249
|
+
}
|
|
250
|
+
} }, ...parts(r.parts.filter((p) => p.type === "image"))])
|
|
251
|
+
});
|
|
252
|
+
else out.push({
|
|
253
|
+
role: "user",
|
|
254
|
+
parts: parts(t.results.flatMap((r) => r.parts))
|
|
255
|
+
});
|
|
256
|
+
return mergeAdjacent(out, (a, b) => ({
|
|
257
|
+
role: a.role,
|
|
258
|
+
parts: [...a.parts, ...b.parts]
|
|
259
|
+
}));
|
|
260
|
+
};
|
|
261
|
+
return {
|
|
262
|
+
model: options.model,
|
|
263
|
+
nativeTools: true,
|
|
264
|
+
async turn(transcript, { tool, maxTokens }) {
|
|
265
|
+
const data = await postJson(fetcher, url, { "x-goog-api-key": options.apiKey }, {
|
|
266
|
+
contents: render(transcript),
|
|
267
|
+
generationConfig: { maxOutputTokens: maxTokens },
|
|
268
|
+
...tool ? { tools: [{ functionDeclarations: [{
|
|
269
|
+
name: tool.name,
|
|
270
|
+
description: tool.description,
|
|
271
|
+
parameters: geminiSchema(tool.parameters)
|
|
272
|
+
}] }] } : {}
|
|
273
|
+
}, "Gemini");
|
|
274
|
+
const candidate = data.candidates?.[0];
|
|
275
|
+
const ps = candidate?.content?.parts ?? [];
|
|
276
|
+
const { calls, broken } = callsFrom(ps.filter((p) => p.functionCall?.name === "zoom").map((p, i) => zoomCallFromArgs(`gemini-${i}`, p.functionCall.args)));
|
|
277
|
+
return withBroken({
|
|
278
|
+
text: ps.map((p) => p.text ?? "").join(""),
|
|
279
|
+
calls,
|
|
280
|
+
raw: ps,
|
|
281
|
+
usage: {
|
|
282
|
+
promptTokens: data.usageMetadata?.promptTokenCount ?? 0,
|
|
283
|
+
completionTokens: data.usageMetadata?.candidatesTokenCount ?? 0
|
|
284
|
+
},
|
|
285
|
+
...candidate?.finishReason && candidate.finishReason !== "STOP" ? { stop: candidate.finishReason } : {}
|
|
286
|
+
}, broken);
|
|
287
|
+
}
|
|
288
|
+
};
|
|
289
|
+
}
|
|
290
|
+
function textOf(r) {
|
|
291
|
+
return r.parts.filter((p) => p.type === "text").map((p) => p.text).join("\n");
|
|
292
|
+
}
|
|
293
|
+
/**
|
|
294
|
+
* A native call whose arguments did not parse still travels as a call, carrying its error, so
|
|
295
|
+
* the loop answers it with a message the model can act on instead of dropping it — an
|
|
296
|
+
* unanswered tool call is a 400 on the next request with every provider.
|
|
297
|
+
*/
|
|
298
|
+
function withBroken(turn, broken) {
|
|
299
|
+
if (broken.length === 0) return turn;
|
|
300
|
+
return {
|
|
301
|
+
...turn,
|
|
302
|
+
calls: [...turn.calls, ...broken.map((b) => ({
|
|
303
|
+
id: b.id,
|
|
304
|
+
imageIndex: 0,
|
|
305
|
+
box: {
|
|
306
|
+
x1: 0,
|
|
307
|
+
y1: 0,
|
|
308
|
+
x2: 0,
|
|
309
|
+
y2: 0
|
|
310
|
+
},
|
|
311
|
+
error: b.error
|
|
312
|
+
}))]
|
|
313
|
+
};
|
|
314
|
+
}
|
|
315
|
+
//#endregion
|
|
316
|
+
export { anthropicDriver, geminiDriver, openAiCompatibleDriver };
|