Files

400 lines
16 KiB
TypeScript

import { expect, test } from "bun:test";
import { mkdir, mkdtemp, readFile, rm, writeFile } from "node:fs/promises";
import { tmpdir } from "node:os";
import path from "node:path";
import { formatModelV2 } from "../src/model-file-v2.js";
import { AuthoredModelV2 } from "../src/schema-v2.js";
import { batchFactor } from "../src/sync/batch.js";
import { syncProvider, type SyncedModel, type SyncProvider } from "../src/sync/index.js";
import { openrouter, type OpenRouterModel } from "../src/sync/providers/openrouter.js";
import { vercel, type VercelModel } from "../src/sync/providers/vercel.js";
import { modelV2ToV1 } from "../src/translate.js";
type Translated = {
model: SyncedModel;
v2Set: Record<string, unknown>;
unsupported?: string[];
notices?: string[];
};
type Update = (current: unknown) => unknown;
const context = { existing: () => undefined, authored: () => undefined };
const CLAUDE_CACHE = { capabilities: { cache: { explicit: { ttl: ["5m", "1h"] } } } };
const batchRule = (factor: unknown) => ({ when: { batch: { equals: true } }, factor });
const flex = { when: { service_tier: { equals: "flex" } }, factor: { text: 0.5 } };
// Shaped like https://openrouter.ai/api/v1/models (2026-12-01).
function openRouterModel(overrides: Partial<OpenRouterModel> = {}): OpenRouterModel {
return {
id: "anthropic/claude-sonnet-5",
name: "Anthropic: Claude Sonnet 5",
created: 1_782_777_600,
hugging_face_id: null,
knowledge_cutoff: "2026-01-31",
context_length: 1_000_000,
architecture: { input_modalities: ["text", "image", "file"], output_modalities: ["text"] },
pricing: {
prompt: "0.000002",
completion: "0.00001",
web_search: "0.01",
input_cache_read: "0.0000002",
input_cache_write: "0.0000025",
input_cache_write_1h: "0.000004",
overrides: [{ min_prompt_tokens: 200_000, prompt: "0.000004", completion: "0.000015", input_cache_read: "0.0000004" }],
},
top_provider: { context_length: 1_000_000, max_completion_tokens: 128_000 },
supported_parameters: ["include_reasoning", "reasoning", "structured_outputs", "tools"],
...overrides,
};
}
// Half of every token price, as the catalog lists `anthropic/claude-sonnet-5:batch`; web search isn't discounted.
function openRouterBatch(model: OpenRouterModel, pricing: Partial<OpenRouterModel["pricing"]> = {}): OpenRouterModel {
return {
...model,
id: `${model.id}:batch`,
pricing: {
prompt: "0.000001",
completion: "0.000005",
web_search: "0.01",
input_cache_read: "0.0000001",
input_cache_write: "0.00000125",
input_cache_write_1h: "0.000002",
overrides: [{ min_prompt_tokens: 200_000, prompt: "0.000002", completion: "0.0000075", input_cache_read: "0.0000002" }],
...pricing,
},
};
}
// google/gemini-4-neon and its :batch variant: Gemini's cache write (storage) price isn't discounted.
function openRouterGemini() {
const base = openRouterModel({
id: "google/gemini-4-neon",
name: "Google: Gemini 4 Neon",
pricing: {
prompt: "0.000003",
completion: "0.000015",
image: "0.000003",
audio: "0.000003",
input_audio_cache: "0.00000015",
web_search: "0.014",
internal_reasoning: "0.000015",
input_cache_read: "0.00000015",
input_cache_write: "0.0000000833333333333333",
},
});
const batch = {
...base,
id: "google/gemini-4-neon:batch",
pricing: {
prompt: "0.0000015",
completion: "0.0000075",
image: "0.0000015",
audio: "0.0000015",
input_audio_cache: "0.000000075",
web_search: "0.014",
internal_reasoning: "0.0000075",
input_cache_read: "0.000000075",
input_cache_write: "0.0000000833333333333333",
},
};
return [base, batch];
}
function vercelModel(overrides: Record<string, unknown> = {}) {
return {
id: "google/gemini-3-flash",
name: "Gemini 3 Flash",
created: 1_765_929_600,
context_window: 1_000_000,
max_tokens: 65_000,
type: "language",
tags: ["reasoning", "tool-use", "implicit-caching"],
pricing: { input: "0.0000005", output: "0.000003", input_cache_read: "0.00000005", web_search: "14" },
...overrides,
};
}
function translateOpenRouter(models: OpenRouterModel[], v2?: Record<string, unknown>) {
const [model] = openrouter.parseModels({ data: models });
return openrouter.translateModel(model!, { ...context, v2: () => v2 }) as unknown as Translated;
}
function translateVercel(models: Record<string, unknown>[]) {
const [model] = vercel.parseModels({ data: models });
return vercel.translateModel(model!, context) as unknown as Translated;
}
const multipliers = (translated: Translated, current?: unknown) => (translated.v2Set["cost.multipliers"] as Update)(current);
test("a batch variant at half of every token price is a flat text factor, tiers and 1h cache writes included", () => {
const base = openRouterModel();
const translated = translateOpenRouter([base, openRouterBatch(base)], CLAUDE_CACHE);
expect(translated.v2Set["capabilities.batch"]).toBe(true);
expect(multipliers(translated, [flex])).toEqual([flex, batchRule({ text: 0.5 })]);
expect(translated.unsupported).toBeUndefined();
expect(translated.notices).toEqual([]);
});
test("prices the batch API discounts differently get their own ratio, down to the price", () => {
const gemini = translateOpenRouter(openRouterGemini());
expect(multipliers(gemini)).toEqual([batchRule({
text: { input: { price: 0.5, cache: { read: 0.5, write: 1 } }, output: 0.5 },
image: 0.5,
audio: 0.5,
})]);
// Vercel's Gemini 3 Flash batch variant keeps the cache read price.
const vercelGemini = translateVercel([
vercelModel(),
vercelModel({ id: "google/gemini-3-flash-batch", pricing: { input: "0.00000025", output: "0.0000015", input_cache_read: "0.00000005" } }),
]);
expect(vercelGemini.v2Set["capabilities.batch"]).toBe(true);
expect(multipliers(vercelGemini)).toEqual([batchRule({ text: { input: { price: 0.5, cache: { read: 1 } }, output: 0.5 } })]);
});
test("one ratio reproduces every price of a model discounted by an uneven fraction", () => {
// gemini-3.8-flash:batch is 1/2.2 of its base price: 0.4545 or 0.454545 alone misses some of its prices.
const result = batchFactor([
{ path: ["text", "input", "price"], when: "", base: 0.55, batch: 0.25 },
{ path: ["text", "input", "cache", "read"], when: "", base: 0.055, batch: 0.025 },
{ path: ["text", "output", "price"], when: "", base: 2.75, batch: 1.25 },
]);
expect(result).toEqual({ factor: { text: 0.4545455 } });
});
test("a batch variant whose base model isn't in the catalog is reported and gets no file", () => {
const orphan = openRouterBatch(openRouterModel({ id: "openai/o4-mini" }));
const models = openrouter.parseModels({ data: [openRouterModel(), orphan] });
expect(models.map((model) => model.id)).toEqual(["anthropic/claude-sonnet-5", "openai/o4-mini:batch"]);
expect(openrouter.translateModel(models[1]!, context)).toBeUndefined();
expect(openrouter.sourceNotices!(models)).toContain(
"openai/o4-mini:batch: batch variant without its base model in the catalog, so no batch price",
);
const vercelModels = vercel.parseModels({ data: [vercelModel({ id: "openai/o3-batch" })] });
expect(vercel.translateModel(vercelModels[0]!, context)).toBeUndefined();
expect(vercel.sourceNotices!(vercelModels)).toEqual([
"openai/o3-batch: batch variant without its base model in the catalog, so no batch price",
]);
});
test("a batch price above the base price is skipped and reported, keeping the file's batch data", () => {
const base = openRouterModel({ id: "moonshotai/kimi-k3" });
const translated = translateOpenRouter([base, openRouterBatch(base, { prompt: "0.000003" })], CLAUDE_CACHE);
expect(translated.v2Set).not.toHaveProperty("capabilities.batch");
expect(translated.v2Set).not.toHaveProperty("cost.multipliers");
expect(translated.unsupported).toEqual(["capabilities.batch"]);
expect(translated.notices).toEqual([
"moonshotai/kimi-k3:batch: batch price not synced: text.input.price costs more in batch (3 vs 2)",
]);
});
test("a context tier with another batch ratio than the base price is skipped, as one multiplier can't express it", () => {
const base = openRouterModel();
const tiered = translateOpenRouter([
base,
openRouterBatch(base, { overrides: [{ min_prompt_tokens: 200_000, prompt: "0.000003", completion: "0.0000075", input_cache_read: "0.0000002" }] }),
], CLAUDE_CACHE);
expect(tiered.v2Set).not.toHaveProperty("capabilities.batch");
expect(tiered.notices).toEqual([
"anthropic/claude-sonnet-5:batch: batch price not synced: text.input.price has a different batch ratio in its tiers",
]);
// A tier only the base model has.
const untiered = translateOpenRouter([base, openRouterBatch(base, { overrides: [] })], CLAUDE_CACHE);
expect(untiered.notices).toEqual([
'anthropic/claude-sonnet-5:batch: batch price not synced: only the base model prices text.input.price when {"context":{"gt":200000}}',
]);
const vercelTiers = translateVercel([
vercelModel({ pricing: { input: "0.000001", output: "0.000006", input_tiers: [{ cost: "0.000001", max: 272_000 }, { cost: "0.000002", min: 272_000 }] } }),
vercelModel({
id: "google/gemini-3-flash-batch",
pricing: { input: "0.0000005", output: "0.000003", input_tiers: [{ cost: "0.0000005", max: 272_000 }, { cost: "0.0000015", min: 272_000 }] },
}),
]);
expect(vercelTiers.v2Set).not.toHaveProperty("capabilities.batch");
expect(vercelTiers.notices).toEqual([
"google/gemini-3-flash-batch: batch price not synced: text.input.price has a different batch ratio in its tiers",
]);
});
test("a model whose batch variant disappears loses its batch support and multiplier, keeping the others", async () => {
const root = await mkdtemp(path.join(tmpdir(), "models-dev-batch-sync-"));
const modelsDir = path.join(root, "providers", "example", "models");
await mkdir(path.join(root, "models", "lab"), { recursive: true });
await mkdir(path.join(modelsDir, "lab"), { recursive: true });
await writeFile(path.join(root, "models", "lab", "chat.toml"), [
"schema = 2",
'name = "Chat"',
'description = "Example chat model"',
"open_weights = false",
'release_date = "2026-01-01"',
"",
"[modalities]",
'input = ["text"]',
'output = ["text"]',
"",
"[capabilities]",
"tools = { supported = true }",
"reasoning = { supported = false }",
"temperature = true",
"top_p = true",
"top_k = false",
"",
"[limit]",
"context = 100_000",
"output = 10_000",
"",
].join("\n"));
const file = path.join(modelsDir, "lab", "chat.toml");
await writeFile(file, [
"schema = 2",
'base_model = "lab/chat"',
"",
"[capabilities]",
'service_tier = ["flex"]',
"",
"[cost.text.input]",
"price = 0.5",
"cache = { read = 0.05 }",
"",
"[cost.text.output]",
"price = 3",
"",
"[[cost.multipliers]]",
'when = { service_tier = { equals = "flex" } }',
"factor = { text = 0.5 }",
"",
].join("\n"));
const base = vercelModel({ pricing: { input: "0.0000005", output: "0.000003", input_cache_read: "0.00000005" } });
const batch = vercelModel({ id: "google/gemini-3-flash-batch", pricing: { input: "0.00000025", output: "0.0000015", input_cache_read: "0.00000005" } });
let source = [base, batch];
const provider: SyncProvider<string> = {
id: "vercel-batch-test",
name: "Vercel batch test",
modelsDir,
async fetchModels() {
return ["lab/chat"];
},
parseModels(raw) {
return raw as string[];
},
translateModel(id) {
const translated = translateVercel(source);
const v2Set = { "capabilities.batch": translated.v2Set["capabilities.batch"], "cost.multipliers": translated.v2Set["cost.multipliers"] };
return { id, model: { base_model: "lab/chat", cost: translated.model.cost }, v2Set, unsupported: translated.unsupported };
},
};
const read = async () => {
const doc = Bun.TOML.parse(await readFile(file, "utf8")) as Record<string, any>;
const { schema: _schema, ...authored } = doc;
// bun validate's rule: a batch multiplier needs capabilities.batch.
expect(AuthoredModelV2.safeParse({ ...authored, id: "lab/chat" }).error?.issues).toBeUndefined();
return { doc, v1: modelV2ToV1({ ...doc, id: "lab/chat" }, { modelPath: file }) };
};
try {
const before = (await read()).v1;
expect(await syncProvider(provider)).toMatchObject({ updated: 1 });
let { doc, v1 } = await read();
expect(doc.capabilities).toEqual({ service_tier: ["flex"], batch: true });
expect(doc.cost.multipliers).toEqual([flex, batchRule({ text: { input: { price: 0.5, cache: { read: 1 } }, output: 0.5 } })]);
expect(v1).toEqual(before);
expect(await syncProvider(provider)).toMatchObject({ updated: 0, unchanged: 1 });
source = [base];
expect(await syncProvider(provider)).toMatchObject({ updated: 1 });
({ doc, v1 } = await read());
expect(doc.capabilities).toEqual({ service_tier: ["flex"] });
expect(doc.cost.multipliers).toEqual([flex]);
expect(v1).toEqual(before);
expect(await syncProvider(provider)).toMatchObject({ updated: 0, unchanged: 1 });
} finally {
await rm(root, { recursive: true, force: true });
}
});
test("a new v2-only file the catalog prices no batch for doesn't inherit its predecessor's batch price", async () => {
const root = await mkdtemp(path.join(tmpdir(), "models-dev-batch-v2-"));
const modelsDir = path.join(root, "providers", "example", "models");
await mkdir(path.join(root, "models", "lab"), { recursive: true });
await mkdir(path.join(modelsDir, "lab"), { recursive: true });
const lab = (name: string, date: string) => [
"schema = 2",
'type = "embedding"',
`name = "${name}"`,
'description = "Example embedding model"',
'family = "text-embedding"',
"open_weights = false",
`release_date = "${date}"`,
"",
"[modalities]",
'input = ["text"]',
'output = ["embedding"]',
"",
"[capabilities]",
"tools = { supported = false }",
"reasoning = { supported = false }",
"temperature = false",
"top_p = false",
"top_k = false",
"",
"[limit]",
"context = 8_192",
"output = 0",
"",
].join("\n");
await writeFile(path.join(root, "models", "lab", "embed-1.toml"), lab("Embed 1", "2026-01-01"));
await writeFile(path.join(root, "models", "lab", "embed-2.toml"), lab("Embed 2", "2026-06-01"));
const doc = (id: string, batched: boolean) => ({
base_model: `lab/${id}`,
...(batched ? { capabilities: { batch: true } } : {}),
api: { embeddings: {} },
cost: {
text: { input: { price: 0.1 } },
...(batched ? { multipliers: [batchRule({ text: 0.5 })] } : {}),
},
});
await writeFile(path.join(modelsDir, "lab", "embed-1.toml"), "schema = 2\n" + formatModelV2(doc("embed-1", true)));
const provider = (unsupported?: string[]): SyncProvider<string> => ({
id: "embedding-batch-test",
name: "Embedding batch test",
modelsDir,
async fetchModels() {
return ["lab/embed-1", "lab/embed-2"];
},
parseModels(raw) {
return raw as string[];
},
translateModel(id) {
return id === "lab/embed-1"
? { id, v2: { schema: 2, ...doc("embed-1", true) } }
: { id, v2: { schema: 2, ...doc("embed-2", false) }, unsupported };
},
});
const created = path.join(modelsDir, "lab", "embed-2.toml");
try {
expect(await syncProvider(provider(["capabilities.batch"]))).toMatchObject({ created: 1 });
const next = Bun.TOML.parse(await readFile(created, "utf8")) as Record<string, any>;
expect(next.capabilities?.batch).toBeUndefined();
expect(next.cost.multipliers).toBeUndefined();
// Without the marker, the predecessor copy would publish a batch price the catalog never stated.
await rm(created);
await syncProvider(provider());
expect((Bun.TOML.parse(await readFile(created, "utf8")) as Record<string, any>).capabilities?.batch).toBe(true);
} finally {
await rm(root, { recursive: true, force: true });
}
});
test("an OpenRouter embedding without a batch variant is marked so a new file doesn't inherit batch", () => {
const embedding = openRouterModel({ id: "lab/embed-2", architecture: { ...openRouterModel().architecture, output_modalities: ["embeddings"] } });
const translated = translateOpenRouter([embedding]);
expect(translated).toMatchObject({ unsupported: ["capabilities.batch"] });
});