Skip to content

:hedgehog: PostHog is the leading platform for building self-driving products. Our developer tools – AI observability, analytics, session replay, flags, experiments, error tracking, logs, and more – capture all the context agents need to diagnose problems, uncover opportunities, and ship fixes. Steer it all from Slack, web, desktop, or the MCP.

fix(llma): preserve default modality rates during cost updates (#86882)

posthog[bot]1bdc0ce73b3e
diff --git a/nodejs/src/ingestion/pipelines/ai/costs/output-costs.test.ts b/nodejs/src/ingestion/pipelines/ai/costs/output-costs.test.ts
index 6cbe8d63649a..6c58b2907fec 100644
--- a/nodejs/src/ingestion/pipelines/ai/costs/output-costs.test.ts
+++ b/nodejs/src/ingestion/pipelines/ai/costs/output-costs.test.ts
@@ -1,4 +1,6 @@
import { calculateOutputCost } from './output-costs'
+import { resolveModelCostForProvider } from './provider-matching'
+import { openRouterCostsByModel } from './providers'
import { ResolvedModelCost } from './providers/types'
import { createAIEvent } from './test-helpers'
@@ -451,6 +453,26 @@ describe('calculateOutputCost()', () => {
})
})
+ describe('committed cost data - image output regression', () => {
+ it('bills gemini-3-pro-image-preview image output on the default variant at the image rate, not the completion fallback', () => {
+ const row = openRouterCostsByModel['google/gemini-3-pro-image-preview']
+
+ const event = createAIEvent({
+ $ai_provider: 'unmatched-provider',
+ $ai_model: 'gemini-3-pro-image-preview',
+ $ai_output_tokens: 1000,
+ $ai_image_output_tokens: 1000,
+ })
+ const resolved = resolveModelCostForProvider(row.cost, event.properties.$ai_provider, row.model)!
+
+ const result = calculateOutputCost(event, resolved)
+ const imageOutputRate = row.cost.default.image_output
+
+ expect(imageOutputRate).toBeDefined()
+ expectCost(result, imageOutputRate! * 1000)
+ })
+ })
+
describe('edge cases', () => {
const testModel = createModel('test-model')
diff --git a/nodejs/src/ingestion/pipelines/ai/costs/scripts/update-ai-costs.test.ts b/nodejs/src/ingestion/pipelines/ai/costs/scripts/update-ai-costs.test.ts
index 876f0c097461..9803eb00f3a9 100644
--- a/nodejs/src/ingestion/pipelines/ai/costs/scripts/update-ai-costs.test.ts
+++ b/nodejs/src/ingestion/pipelines/ai/costs/scripts/update-ai-costs.test.ts
@@ -3,6 +3,7 @@ import path from 'path'
import { parseJSON } from '~/common/utils/json-parse'
import { normalizeProviderKey } from '~/ingestion/pipelines/ai/costs/provider-matching'
+import { openRouterCostsByModel } from '~/ingestion/pipelines/ai/costs/providers'
import type { ModelCost } from '~/ingestion/pipelines/ai/costs/providers/types'
import {
@@ -49,6 +50,7 @@ const cost = (promptPrice: string, discount = 0, completion = promptPrice): Retu
const candidate = (key: string, promptPrice: string, discount: number, vendorPromotion = false): EndpointCandidate => ({
key,
cost: cost(promptPrice, discount)!,
+ servedCost: cost(promptPrice, 0)!,
discount,
vendorPromotion,
unrefutable: false,
@@ -619,6 +621,124 @@ describe('buildModelRow()', () => {
expect(built!.cost.openai.prompt_token).toBe(0.000001)
})
+ it.each([
+ { field: 'image_output' as const, rate: 0.00012 },
+ { field: 'audio_output' as const, rate: 0.00006 },
+ ])('backfills $field onto `default` from a provider variant', ({ field, rate }) => {
+ const built = buildModelRow('google/gemini-3-pro-image-preview', listPricing, [
+ {
+ tag: 'google-vertex',
+ provider_name: 'google-vertex',
+ pricing: { prompt: '0.0000005', completion: '0.0000005', [field]: String(rate) },
+ },
+ ])
+ expect(built!.cost.default[field]).toBe(rate)
+ })
+
+ it('leaves an existing `default` modality rate untouched', () => {
+ const built = buildModelRow('x/y', { ...listPricing, image_output: '0.00012' }, [
+ {
+ tag: 'openai',
+ provider_name: 'openai',
+ pricing: { prompt: '0.0000005', completion: '0.0000005', image_output: '0.00009' },
+ },
+ ])
+ expect(built!.cost.default.image_output).toBe(0.00012)
+ })
+
+ it('prefers an undiscounted variant when backfilling a modality rate', () => {
+ const built = buildModelRow('x/y', listPricing, [
+ {
+ tag: 'discounted',
+ provider_name: 'discounted',
+ pricing: { prompt: '0.0000005', completion: '0.0000005', image_output: '0.00005', discount: 0.5 },
+ },
+ {
+ tag: 'listed',
+ provider_name: 'listed',
+ pricing: { prompt: '0.0000005', completion: '0.0000005', image_output: '0.00012' },
+ },
+ ])
+ expect(built!.cost.default.image_output).toBe(0.00012)
+ })
+
+ it('prefers the endpoint tier that matches the default prompt rate regardless of response order', () => {
+ const standard = {
+ tag: 'google-standard',
+ provider_name: 'google-standard',
+ pricing: { prompt: '0.0000005', completion: '0.0000005', image_output: '0.00012' },
+ }
+ const flex = {
+ tag: 'google-flex',
+ provider_name: 'google-flex',
+ pricing: { prompt: '0.00000025', completion: '0.00000025', image_output: '0.00006' },
+ }
+
+ const rates = [
+ buildModelRow('x/y', listPricing, [flex, standard])!.cost.default.image_output,
+ buildModelRow('x/y', listPricing, [standard, flex])!.cost.default.image_output,
+ ]
+
+ expect(rates).toEqual([0.00012, 0.00012])
+ })
+
+ it('uses the provider key as a deterministic fallback when no endpoint matches the default prompt rate', () => {
+ const firstByKey = {
+ tag: 'a-provider',
+ provider_name: 'a-provider',
+ pricing: { prompt: '0.00000025', completion: '0.00000025', image_output: '0.00006', discount: 0.5 },
+ }
+ const lastByKey = {
+ tag: 'z-provider',
+ provider_name: 'z-provider',
+ pricing: { prompt: '0.00000075', completion: '0.00000075', image_output: '0.00009', discount: 0.5 },
+ }
+
+ const rates = [
+ buildModelRow('x/y', listPricing, [lastByKey, firstByKey])!.cost.default.image_output,
+ buildModelRow('x/y', listPricing, [firstByKey, lastByKey])!.cost.default.image_output,
+ ]
+
+ expect(rates).toEqual([0.00006, 0.00006])
+ })
+
+ it('prefers an undiscounted variant when no endpoint matches the default prompt rate', () => {
+ const discounted = {
+ tag: 'a-discounted',
+ provider_name: 'a-discounted',
+ pricing: { prompt: '0.00000025', completion: '0.00000025', image_output: '0.00006', discount: 0.5 },
+ }
+ const undiscounted = {
+ tag: 'z-undiscounted',
+ provider_name: 'z-undiscounted',
+ pricing: { prompt: '0.00000075', completion: '0.00000075', image_output: '0.00009' },
+ }
+
+ const rates = [
+ buildModelRow('x/y', listPricing, [discounted, undiscounted])!.cost.default.image_output,
+ buildModelRow('x/y', listPricing, [undiscounted, discounted])!.cost.default.image_output,
+ ]
+
+ expect(rates).toEqual([0.00009, 0.00009])
+ })
+
+ it('prefers a matching discounted variant over a nonmatching undiscounted variant', () => {
+ const built = buildModelRow('x/y', listPricing, [
+ {
+ tag: 'a-nonmatching',
+ provider_name: 'a-nonmatching',
+ pricing: { prompt: '0.00000025', completion: '0.00000025', image_output: '0.00006' },
+ },
+ {
+ tag: 'z-matching',
+ provider_name: 'z-matching',
+ pricing: { prompt: '0.0000005', completion: '0.0000005', image_output: '0.00005', discount: 0.5 },
+ },
+ ])
+ expect(built!.cost.default.image_output).toBe(0.00005)
+ expect(built!.cost['z-matching'].image_output).toBe(0.0001)
+ })
+
it('confines a hostile provider name to a safe key', () => {
// Interpolated into generated TypeScript, so an apostrophe must not reach it.
const built = buildModelRow('evil/model', listPricing, [
@@ -674,6 +794,7 @@ describe('confirmDiscountAgainstSiblings()', () => {
const discounted: EndpointCandidate = {
key: 'openai',
cost: buildModelCost({ prompt: '0.0000005', completion: '0.000009', discount: 0.5 })!,
+ servedCost: buildModelCost({ prompt: '0.0000005', completion: '0.000009' })!,
discount: 0.5,
vendorPromotion: false,
unrefutable: false,
@@ -683,6 +804,7 @@ describe('confirmDiscountAgainstSiblings()', () => {
const sibling: EndpointCandidate = {
key: 'azure',
cost: buildModelCost({ prompt: '0.000001', completion: '0.000002' })!,
+ servedCost: buildModelCost({ prompt: '0.000001', completion: '0.000002' })!,
discount: 0,
vendorPromotion: false,
unrefutable: false,
@@ -1236,6 +1358,56 @@ describe('collectModelRows()', () => {
})
expect(seen).toStrictEqual(['a/a', 'b/b'])
})
+
+ it.each([
+ { field: 'image_output' as const, rate: 0.00012 },
+ { field: 'audio_output' as const, rate: 0.00006 },
+ ])('preserves the previous default $field rate when endpoint fetching fails', async ({ field, rate }) => {
+ jest.spyOn(console, 'warn').mockImplementation(() => {})
+ const previousDefaults = new Map<string, ModelCost>([
+ ['a/a', { prompt_token: 0.0000005, completion_token: 0.0000005, [field]: rate }],
+ ])
+
+ const totals = await collectModelRows(
+ [priced('a/a')],
+ () => Promise.reject(new Error('socket hang up')),
+ previousDefaults
+ )
+
+ expect(totals.models[0].cost.default[field]).toBe(rate)
+ })
+
+ it('keeps collecting other models after an endpoint fetch fails', async () => {
+ jest.spyOn(console, 'warn').mockImplementation(() => {})
+ const totals = await collectModelRows([priced('a/a'), priced('b/b')], (id) =>
+ id === 'a/a' ? Promise.reject(new Error('socket hang up')) : Promise.resolve([])
+ )
+
+ expect(totals.models.map((model) => model.model)).toStrictEqual(['a/a', 'b/b'])
+ })
+
+ it('keeps a current model-level modality rate when endpoint fetching fails', async () => {
+ jest.spyOn(console, 'warn').mockImplementation(() => {})
+ const previousDefaults = new Map<string, ModelCost>([
+ ['a/a', { prompt_token: 0.0000005, completion_token: 0.0000005, image_output: 0.00012 }],
+ ])
+ const totals = await collectModelRows(
+ [{ ...priced('a/a'), pricing: { ...priced('a/a').pricing, image_output: '0.00009' } }],
+ () => Promise.reject(new Error('socket hang up')),
+ previousDefaults
+ )
+
+ expect(totals.models[0].cost.default.image_output).toBe(0.00009)
+ })
+
+ it('does not preserve a previous modality rate after a successful empty response', async () => {
+ const previousDefaults = new Map<string, ModelCost>([
+ ['a/a', { prompt_token: 0.0000005, completion_token: 0.0000005, image_output: 0.00012 }],
+ ])
+ const totals = await collectModelRows([priced('a/a')], noEndpoints, previousDefaults)
+
+ expect(totals.models[0].cost.default.image_output).toBeUndefined()
+ })
})
describe('readEndpointsFromOpenRouter()', () => {
@@ -1247,20 +1419,26 @@ describe('readEndpointsFromOpenRouter()', () => {
await expect(readEndpointsFromOpenRouter('a/b')).resolves.toStrictEqual([1, 2])
})
- it('degrades to no endpoints on a non-ok response, and says so', async () => {
+ it('rejects a non-ok response so the caller can preserve prior data', async () => {
const warn = jest.spyOn(console, 'warn').mockImplementation(() => {})
mockFetch(() => Promise.resolve({ ok: false, status: 429, statusText: 'Too Many Requests' }))
- await expect(readEndpointsFromOpenRouter('a/b')).resolves.toStrictEqual([])
+ await expect(readEndpointsFromOpenRouter('a/b')).rejects.toThrow('429 Too Many Requests')
expect(warn).toHaveBeenCalledWith(expect.stringContaining('a/b'))
})
- it('degrades to no endpoints when the request throws, and says so', async () => {
+ it('rejects when the request throws so the caller can preserve prior data', async () => {
const warn = jest.spyOn(console, 'warn').mockImplementation(() => {})
mockFetch(() => Promise.reject(new Error('socket hang up')))
- await expect(readEndpointsFromOpenRouter('a/b')).resolves.toStrictEqual([])
+ await expect(readEndpointsFromOpenRouter('a/b')).rejects.toThrow('socket hang up')
expect(warn).toHaveBeenCalledWith(expect.stringContaining('Error fetching'), 'a/b', expect.anything())
})
+ it('rejects malformed JSON so the caller can preserve prior data', async () => {
+ jest.spyOn(console, 'warn').mockImplementation(() => {})
+ mockFetch(() => Promise.resolve({ ok: true, json: () => Promise.reject(new Error('bad JSON')) }))
+ await expect(readEndpointsFromOpenRouter('a/b')).rejects.toThrow('bad JSON')
+ })
+
it('degrades to no endpoints when the payload has no endpoints key', async () => {
mockFetch(() => Promise.resolve({ ok: true, json: () => Promise.resolve({}) }))
await expect(readEndpointsFromOpenRouter('a/b')).resolves.toStrictEqual([])
@@ -1306,6 +1484,35 @@ describe('fetchOpenRouterCosts()', () => {
expect(totals.models.map((m) => m.model)).toStrictEqual(['a/b'])
})
+ it('uses committed default modality rates when an endpoint request fails', async () => {
+ jest.spyOn(console, 'log').mockImplementation(() => {})
+ jest.spyOn(console, 'warn').mockImplementation(() => {})
+ jest.spyOn(global, 'fetch' as never).mockImplementation(((url: string) => {
+ if (url.includes('/endpoints')) {
+ return Promise.reject(new Error('socket hang up'))
+ }
+ return Promise.resolve({
+ ok: true,
+ json: () =>
+ Promise.resolve({
+ data: [
+ {
+ id: 'google/gemini-3-pro-image-preview',
+ pricing: { prompt: '0.000002', completion: '0.000012' },
+ },
+ ],
+ }),
+ })
+ }) as never)
+
+ const totals = await fetchOpenRouterCosts()
+ const committedImageOutputRate =
+ openRouterCostsByModel['google/gemini-3-pro-image-preview'].cost.default.image_output
+
+ expect(committedImageOutputRate).toBeDefined()
+ expect(totals.models[0].cost.default.image_output).toBe(committedImageOutputRate)
+ })
+
it('throws when the models list cannot be fetched', async () => {
jest.spyOn(global, 'fetch' as never).mockImplementation((() =>
Promise.resolve({ ok: false, status: 503, statusText: 'Service Unavailable' })) as never)
diff --git a/nodejs/src/ingestion/pipelines/ai/costs/scripts/update-ai-costs.ts b/nodejs/src/ingestion/pipelines/ai/costs/scripts/update-ai-costs.ts
index ec06c779864a..5eacab7b5975 100644
--- a/nodejs/src/ingestion/pipelines/ai/costs/scripts/update-ai-costs.ts
+++ b/nodejs/src/ingestion/pipelines/ai/costs/scripts/update-ai-costs.ts
@@ -3,7 +3,8 @@ import bigDecimal from 'js-big-decimal'
import path from 'path'
import { normalizeProviderKey } from '~/ingestion/pipelines/ai/costs/provider-matching'
-import type { ModelCost } from '~/ingestion/pipelines/ai/costs/providers/types'
+import committedOpenRouterCostsRaw from '~/ingestion/pipelines/ai/costs/providers/llm-costs.json'
+import type { ModelCost, ModelCostRow } from '~/ingestion/pipelines/ai/costs/providers/types'
interface ModelRow {
model: string
@@ -12,6 +13,10 @@ interface ModelRow {
const PATH_TO_PROVIDERS = path.join(__dirname, '../providers')
const OPENROUTER_COSTS_FILENAME = 'llm-costs.json'
+const ENDPOINT_REQUEST_TIMEOUT_MS = 10_000
+const COMMITTED_DEFAULT_COSTS = new Map<string, ModelCost>(
+ (committedOpenRouterCostsRaw as ModelCostRow[]).map((row) => [row.model.toLowerCase(), row.cost.default])
+)
const parsePricingNumber = (value: unknown): number | undefined => {
if (value === null || value === undefined) {
@@ -202,7 +207,10 @@ export const buildModelCost = (pricing: Record<string, unknown> | undefined, con
export interface EndpointCandidate {
key: string
+ /** De-discounted list price, stored under the provider key a direct caller resolves to. */
cost: ModelCost
+ /** Price as OpenRouter serves it, used to backfill `default`, which keeps the promotion. */
+ servedCost: ModelCost
discount: number
vendorPromotion: boolean
/** True when nothing in the model could have refuted `vendorPromotion`. */
@@ -213,6 +221,31 @@ export interface EndpointCandidate {
listPrompt: number | undefined
}
+export const MODALITY_OUTPUT_FIELDS: ReadonlyArray<keyof ModelCost> = ['image_output', 'audio_output']
+
+export const backfillDefaultModalityRates = (defaultCost: ModelCost, candidates: EndpointCandidate[]): void => {
+ for (const field of MODALITY_OUTPUT_FIELDS) {
+ if (defaultCost[field] !== undefined) {
+ continue
+ }
+
+ const sources = candidates
+ .filter((candidate) => candidate.servedCost[field] !== undefined)
+ .sort((left, right) => left.key.localeCompare(right.key))
+ const matchesDefaultPromptRate = (candidate: EndpointCandidate): boolean =>
+ candidate.servedCost.prompt_token === defaultCost.prompt_token
+ const source =
+ sources.find((candidate) => matchesDefaultPromptRate(candidate) && candidate.discount === 0) ??
+ sources.find(matchesDefaultPromptRate) ??
+ sources.find((candidate) => candidate.discount === 0) ??
+ sources[0]
+ const rate = source?.servedCost[field]
+ if (rate !== undefined) {
+ defaultCost[field] = rate
+ }
+ }
+}
+
/*
* `default` keeps the promotion. `PROVIDER_ALIASES` maps `$ai_provider:
* 'openrouter'` onto it, and for those callers the promo price is what they were
@@ -422,9 +455,11 @@ export const buildModelRow = (
for (const route of routes) {
const vendorPromotion = isVendorPromotion(route, routes)
- const endpointCost = vendorPromotion
- ? buildServedCost(route.endpoint.pricing, route.context)
- : buildModelCost(route.endpoint.pricing, route.context)
+ const servedCost = buildServedCost(route.endpoint.pricing, route.context)
+ if (!servedCost) {
+ continue
+ }
+ const endpointCost = vendorPromotion ? servedCost : buildModelCost(route.endpoint.pricing, route.context)
if (!endpointCost) {
continue
}
@@ -433,6 +468,7 @@ export const buildModelRow = (
candidates.push({
key: route.key,
cost: endpointCost,
+ servedCost,
discount: route.discount,
vendorPromotion,
unrefutable,
@@ -441,6 +477,8 @@ export const buildModelRow = (
})
}
+ backfillDefaultModalityRates(defaultCost, candidates)
+
// Keyed on parsed candidates rather than the raw endpoint count: a payload
// whose entries all fail to parse yielded nothing to check either.
if (candidates.length === 0) {
@@ -536,9 +574,31 @@ interface ListedModel {
pricing?: Record<string, unknown>
}
+const preservePreviousDefaultModalityRates = (
+ pricing: Record<string, unknown> | undefined,
+ previousDefault: ModelCost | undefined
+): Record<string, unknown> | undefined => {
+ if (!previousDefault) {
+ return pricing
+ }
+
+ const preserved = { ...pricing }
+ for (const field of MODALITY_OUTPUT_FIELDS) {
+ const currentRate = parsePricingNumber(pricing?.[field])
+ if ((currentRate === undefined || currentRate === 0) && previousDefault[field] !== undefined) {
+ preserved[field] = previousDefault[field]
+ }
+ }
+ return preserved
+}
+
/** Takes the endpoint reader as an argument so this loop is reachable without a
* network. */
-export const collectModelRows = async (models: ListedModel[], readEndpoints: EndpointFetcher): Promise<RunTotals> => {
+export const collectModelRows = async (
+ models: ListedModel[],
+ readEndpoints: EndpointFetcher,
+ previousDefaults: ReadonlyMap<string, ModelCost> = new Map()
+): Promise<RunTotals> => {
let totals: RunTotals = { models: [], discounts: [], uncheckedModels: 0 }
for (const [modelIndex, model] of models.entries()) {
@@ -548,7 +608,15 @@ export const collectModelRows = async (models: ListedModel[], readEndpoints: End
}
console.log(`Fetching endpoint pricing for ${modelIndex + 1}/${models.length} ${model.id}...`)
- totals = foldModelIntoTotals(model.id, model.pricing, await readEndpoints(model.id), totals)
+ let endpoints: unknown[]
+ let pricing = model.pricing
+ try {
+ endpoints = await readEndpoints(model.id)
+ } catch {
+ endpoints = []
+ pricing = preservePreviousDefaultModalityRates(pricing, previousDefaults.get(model.id.toLowerCase()))
+ }
+ totals = foldModelIntoTotals(model.id, pricing, endpoints, totals)
}
if (totals.uncheckedModels > 0) {
@@ -565,25 +633,35 @@ export const collectModelRows = async (models: ListedModel[], readEndpoints: End
return finalizeTotals(totals)
}
-/** Endpoint reader against the live API. Every failure degrades to no endpoints. */
+/** Endpoint reader against the live API. */
export const readEndpointsFromOpenRouter: EndpointFetcher = async (modelId) => {
const encoded = modelId
.split('/')
.map((segment: string) => encodeURIComponent(segment))
.join('/')
+ let res: Response
try {
// eslint-disable-next-line no-restricted-globals
- const res = await fetch(`https://openrouter.ai/api/v1/models/${encoded}/endpoints`, {})
- if (!res.ok) {
- console.warn(`Failed to fetch endpoint pricing for ${modelId}: ${res.status} ${res.statusText}`)
- return []
- }
+ res = await fetch(`https://openrouter.ai/api/v1/models/${encoded}/endpoints`, {
+ signal: AbortSignal.timeout(ENDPOINT_REQUEST_TIMEOUT_MS),
+ })
+ } catch (error) {
+ console.warn('Error fetching endpoint pricing for model:', modelId, error)
+ throw error
+ }
+
+ if (!res.ok) {
+ console.warn(`Failed to fetch endpoint pricing for ${modelId}: ${res.status} ${res.statusText}`)
+ throw new Error(`Failed to fetch endpoint pricing for ${modelId}: ${res.status} ${res.statusText}`)
+ }
+
+ try {
const payload = await res.json()
return payload?.data?.endpoints ?? []
} catch (error) {
- console.warn('Error fetching endpoint pricing for model:', modelId, error)
- return []
+ console.warn('Error parsing endpoint pricing for model:', modelId, error)
+ throw error
}
}
@@ -602,7 +680,7 @@ export const fetchOpenRouterCosts = async (): Promise<RunTotals> => {
}
console.log('OpenRouter models:', data.data.length)
- return collectModelRows(data.data, readEndpointsFromOpenRouter)
+ return collectModelRows(data.data, readEndpointsFromOpenRouter, COMMITTED_DEFAULT_COSTS)
}
const sortProviderCosts = (models: ModelRow[]): ModelRow[] => {