Skip to content
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
67 changes: 66 additions & 1 deletion console/scripts/update-openrouter-price-rules.mjs
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,28 @@ const consoleDir = path.resolve(path.dirname(scriptPath), "..");
const outputPath = path.join(consoleDir, "src", "data", "openrouter-price-rules.json");
const DECIMAL = /^(-?)(\d+)(?:\.(\d+))?$/;
const SUPPORTED_OUTPUT_MODALITIES = new Set(["text", "image", "embeddings", "rerank"]);
const OFFICIAL_RULE_OVERRIDES = new Map([
["deepseek-v4-flash", { cache_read_price: "0.0028" }],
]);
const OFFICIAL_EXTRA_RULES = [{
provider_id: null,
match_type: "contains",
model_match: "grok-4.6",
input_price: "2",
output_price: "6",
cache_read_price: "0.5",
cache_creation_5m_price: "0",
cache_creation_30m_price: "0",
cache_creation_1h_price: "0",
image_output_price: "0",
pricing_tiers_json: [{
min_prompt_tokens: 200000,
input_price: "4",
output_price: "12",
cache_read_price: "1",
}],
enabled: true,
}];

/** Convert an OpenRouter USD/token decimal into GPROXY's USD/1M-token form. */
export function perMillion(value) {
Expand Down Expand Up @@ -84,6 +106,25 @@ export function buildPriceBundle(payload) {
const author = model.id.slice(0, model.id.indexOf("/")).replace(/^~/, "");
const modelMatch = model.id.slice(model.id.lastIndexOf("/") + 1);
const cacheWrite = perMillion(pricing.input_cache_write);
const pricingTiers = Array.isArray(pricing.overrides)
? pricing.overrides.map((override) => {
if (!Number.isInteger(override.min_prompt_tokens) || override.min_prompt_tokens <= 0) {
throw new Error(`model ${model.id} has an invalid pricing override threshold`);
}
const tier = { min_prompt_tokens: override.min_prompt_tokens };
const assign = (field, value) => {
if (value != null) tier[field] = perMillion(value);
};
assign("input_price", override.prompt);
assign("output_price", override.completion);
assign("cache_read_price", override.input_cache_read);
const tierCacheWrite = override.input_cache_write;
assign(author === "openai" ? "cache_creation_30m_price" : "cache_creation_5m_price", tierCacheWrite);
assign("cache_creation_1h_price", override.input_cache_write_1h);
assign("image_output_price", override.image_output);
return tier;
})
: null;
rules.push({
provider_id: null,
match_type: "contains",
Expand All @@ -99,6 +140,7 @@ export function buildPriceBundle(payload) {
// `image_output` is an output-token rate. Do not use `image`, which is an
// input-image or flat-image rate depending on the upstream model.
image_output_price: perMillion(pricing.image_output),
pricing_tiers_json: pricingTiers?.length ? pricingTiers : null,
enabled: true,
});
}
Expand Down Expand Up @@ -128,6 +170,29 @@ export function buildPriceBundle(payload) {
};
}

/** Apply pricing published directly by providers after the OpenRouter snapshot. */
export function applyOfficialPriceOverrides(bundle) {
const rules = bundle.price_rules.map((rule) => ({
...rule,
...(OFFICIAL_RULE_OVERRIDES.get(rule.model_match) ?? {}),
}));
for (const rule of OFFICIAL_EXTRA_RULES) {
if (!rules.some((candidate) => candidate.model_match === rule.model_match)) rules.push(rule);
}
rules.sort((left, right) => (
left.model_match < right.model_match ? -1 : left.model_match > right.model_match ? 1 : 0
));
return {
...bundle,
source: {
...bundle.source,
catalog: "openrouter+official-overrides",
included_models: rules.length,
},
price_rules: rules,
};
}

async function loadPayload(inputPath) {
if (inputPath) {
return JSON.parse(await readFile(path.resolve(process.cwd(), inputPath), "utf8"));
Expand All @@ -152,7 +217,7 @@ async function main() {
}

const payload = await loadPayload(args[1]);
const bundle = buildPriceBundle(payload);
const bundle = applyOfficialPriceOverrides(buildPriceBundle(payload));
await writeFile(outputPath, `${JSON.stringify(bundle, null, 2)}\n`, "utf8");

const variants = bundle.price_rules.filter((rule) => rule.model_match.includes(":")).length;
Expand Down
63 changes: 51 additions & 12 deletions console/scripts/update-openrouter-price-rules.test.mjs
Original file line number Diff line number Diff line change
@@ -1,6 +1,10 @@
import { readFile } from "node:fs/promises";
import { describe, expect, it } from "vitest";
import { buildPriceBundle, perMillion } from "./update-openrouter-price-rules.mjs";
import {
applyOfficialPriceOverrides,
buildPriceBundle,
perMillion,
} from "./update-openrouter-price-rules.mjs";

const bundledRulesUrl = new URL("../src/data/openrouter-price-rules.json", import.meta.url);

Expand Down Expand Up @@ -144,37 +148,72 @@ describe("OpenRouter price-rule generator", () => {
.toThrow("duplicate OpenRouter model basename");
});

it("applies current provider-published overrides", () => {
const bundle = applyOfficialPriceOverrides(buildPriceBundle({
data: [{
id: "deepseek/deepseek-v4-flash",
architecture: { output_modalities: ["text"] },
pricing: { prompt: "0.00000014", completion: "0.00000028", input_cache_read: "0.000000028" },
}],
}));
expect(bundle.source.catalog).toBe("openrouter+official-overrides");
expect(bundle.price_rules.find((rule) => rule.model_match === "deepseek-v4-flash")?.cache_read_price).toBe("0.0028");
expect(bundle.price_rules.find((rule) => rule.model_match === "grok-4.6")).toMatchObject({
input_price: "2",
output_price: "6",
cache_read_price: "0.5",
pricing_tiers_json: [{
min_prompt_tokens: 200000,
input_price: "4",
output_price: "12",
cache_read_price: "1",
}],
});
});

it("keeps the checked-in full catalog complete, sorted, and aligned with the generator", async () => {
const bundle = JSON.parse(await readFile(bundledRulesUrl, "utf8"));
const generatedShape = buildPriceBundle({
const generatedShape = applyOfficialPriceOverrides(buildPriceBundle({
data: [{
id: "test/shape",
architecture: { output_modalities: ["text"] },
pricing: { prompt: "0", completion: "0" },
}],
});
const expectedFields = Object.keys(generatedShape.price_rules[0]);
}));
const baseShape = buildPriceBundle({
data: [{
id: "test/shape",
architecture: { output_modalities: ["text"] },
pricing: { prompt: "0", completion: "0" },
}],
}).price_rules[0];
const expectedFields = Object.keys(baseShape);
const priceFields = expectedFields.filter((field) => field.endsWith("_price"));
const names = bundle.price_rules.map((rule) => rule.model_match);

expect(bundle.schema_version).toBe(generatedShape.schema_version);
expect(bundle.source).toEqual({
catalog: "openrouter",
total_models: 525,
supported_output_models: 470,
catalog: "openrouter+official-overrides",
total_models: 533,
supported_output_models: 480,
dynamic_price_models: 5,
included_models: 465,
included_models: 475,
embedding_models: 33,
rerank_models: 6,
image_output_priced_models: 40,
image_output_priced_models: 41,
});
expect(bundle.price_rules).toHaveLength(465);
expect(bundle.price_rules).toHaveLength(475);
expect(new Set(names).size).toBe(names.length);
expect(names).toEqual([...names].sort());
expect(bundle.price_rules.filter((rule) => rule.image_output_price !== "0")).toHaveLength(40);
expect(bundle.price_rules.filter((rule) => rule.image_output_price !== "0")).toHaveLength(41);
expect(bundle.price_rules.filter((rule) => rule.pricing_tiers_json != null)).toHaveLength(59);
expect(bundle.price_rules.filter((rule) => rule.model_match.includes("rerank"))).toHaveLength(6);
expect(bundle.price_rules.every((rule) => (
JSON.stringify(Object.keys(rule)) === JSON.stringify(expectedFields)
expectedFields.every((field) => field in rule)
&& Object.keys(rule).every((field) => (
expectedFields.includes(field)
|| field === "pricing_tiers_json"
))
))).toBe(true);
expect(bundle.price_rules.every((rule) => (
rule.provider_id === null
Expand Down
13 changes: 13 additions & 0 deletions console/src/api/price-rules.ts
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,7 @@ export interface PriceRule {
cache_creation_30m_price: string;
cache_creation_1h_price: string;
image_output_price: string;
pricing_tiers_json?: PricingTier[] | null;
enabled: boolean;
created_at: number;
updated_at: number;
Expand All @@ -30,9 +31,21 @@ export interface PriceRuleInput {
cache_creation_30m_price: string;
cache_creation_1h_price: string;
image_output_price: string;
pricing_tiers_json?: PricingTier[] | null;
enabled: boolean;
}

export interface PricingTier {
min_prompt_tokens: number;
input_price?: string;
output_price?: string;
cache_read_price?: string;
cache_creation_5m_price?: string;
cache_creation_30m_price?: string;
cache_creation_1h_price?: string;
image_output_price?: string;
}

export const priceRulesQuery = queryOptions({
queryKey: ["price-rules"],
queryFn: () => api<PriceRule[]>("/admin/price-rules"),
Expand Down
15 changes: 15 additions & 0 deletions console/src/components/pricing/price-rule-form.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -63,6 +63,9 @@ export function PriceRuleForm({
const [cacheCreation30mPrice, setCacheCreation30mPrice] = useState(() => decimalField(rule?.cache_creation_30m_price));
const [cacheCreation1hPrice, setCacheCreation1hPrice] = useState(() => decimalField(rule?.cache_creation_1h_price));
const [imageOutputPrice, setImageOutputPrice] = useState(() => decimalField(rule?.image_output_price));
const [pricingTiers, setPricingTiers] = useState(() =>
rule?.pricing_tiers_json == null ? "" : JSON.stringify(rule.pricing_tiers_json, null, 2),
);
const [formError, setFormError] = useState<string | null>(null);
const matchOptions = [...new Set(modelMatchOptions.map((v) => v.trim()).filter((v) => v !== ""))];
const defaultPriceRule = findDefaultPriceRule(modelMatch);
Expand All @@ -76,6 +79,7 @@ export function PriceRuleForm({
setCacheCreation30mPrice(defaultPriceRule.cache_creation_30m_price);
setCacheCreation1hPrice(defaultPriceRule.cache_creation_1h_price);
setImageOutputPrice(defaultPriceRule.image_output_price);
setPricingTiers(defaultPriceRule.pricing_tiers_json == null ? "" : JSON.stringify(defaultPriceRule.pricing_tiers_json, null, 2));
};

const mutation = useMutation({
Expand All @@ -93,6 +97,7 @@ export function PriceRuleForm({
cache_creation_30m_price: normalizeDecimal(cacheCreation30mPrice),
cache_creation_1h_price: normalizeDecimal(cacheCreation1hPrice),
image_output_price: normalizeDecimal(imageOutputPrice),
pricing_tiers_json: pricingTiers.trim() === "" ? null : JSON.parse(pricingTiers),
enabled,
});
},
Expand Down Expand Up @@ -198,6 +203,16 @@ export function PriceRuleForm({
onChange={(e) => setImageOutputPrice(e.target.value)}
/>
</div>
<div className="grid gap-2 md:col-span-2">
<Label htmlFor="price-pricing-tiers">{t("form.pricingTiers")}</Label>
<textarea
id="price-pricing-tiers"
className="min-h-32 rounded-md border bg-transparent px-3 py-2 font-mono text-sm"
value={pricingTiers}
onChange={(e) => setPricingTiers(e.target.value)}
placeholder={t("form.pricingTiersPlaceholder")}
/>
</div>
</div>
<p className="text-xs text-muted-foreground">{t("form.pricesHint")}</p>
</div>
Expand Down
Loading