: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.
Python ab-testingai-analyticsanalyticscdpdata-warehouseexperimentsfeature-flagsjavascriptproduct-analyticspythonreactsession-replaysurveystypescriptweb-analytics
fix(llma): keep per-call fees at the served price (#84587)
Brandon4b048409196b
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.tsindex 9741bebd4053..8f027530b5d7 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@@ -2,6 +2,7 @@ import fs from 'fs'import path from 'path'import { parseJSON } from '~/common/utils/json-parse'+import type { ModelCost } from '~/ingestion/pipelines/ai/costs/providers/types'import {type BuiltModelRow,@@ -9,6 +10,8 @@ import {DISCOUNT_SUMMARY_ENV,type DiscountReportEntry,type EndpointCandidate,+ FLAT_FEE_FIELDS,+ OPTIONAL_PRICING_FIELDS,type RunTotals,UNCHECKED_WARN_FRACTION,accumulateModelRow,@@ -176,14 +179,15 @@ describe('buildModelCost() discount handling', () => {})})- it('applies the rate uniformly to every field, flat fees included', () => {- // web_search is a per-call fee and is discounted at the same ratio.+ it('de-discounts the per-token rates but carries flat fees across untouched', () => {+ // A promotional route serves web_search at the same price as its undiscounted sibling.expect(buildModelCost({prompt: '0.0000005',completion: '0.000003',input_cache_read: '0.00000005',- web_search: '0.005',+ web_search: '0.01',+ request: '0.004',discount: 0.5,})).toEqual({@@ -191,9 +195,16 @@ describe('buildModelCost() discount handling', () => {completion_token: 0.000006,cache_read_token: 0.0000001,web_search: 0.01,+ request: 0.004,})})+ it.each([-0.25, 0, 0.1, 0.41, 0.5, 0.9])('leaves a flat fee alone at a rate of %d', (discount) => {+ expect(buildModelCost({ prompt: '0.000001', completion: '0.000006', web_search: '0.01', discount })).toEqual(+ expect.objectContaining({ web_search: 0.01 })+ )+ })+it('does not adjust prices when the rate is out of range', () => {jest.spyOn(console, 'warn').mockImplementation(() => {})expect(buildModelCost({ prompt: '0.000001', completion: '0.000006', discount: 1 })).toEqual({@@ -210,6 +221,69 @@ describe('buildModelCost() discount handling', () => {})})+describe('FLAT_FEE_FIELDS is bound to the field list it filters', () => {+ // Neither direction is a type error: a member outside the loop is dead, and a+ // loop field outside the set is silently de-discounted.+ const targetFields = OPTIONAL_PRICING_FIELDS.map(([targetField]) => targetField)++ it.each([...FLAT_FEE_FIELDS])('%s is a field the loop actually reads', (field) => {+ expect(targetFields).toContain(field)+ })++ it('reads the OpenRouter field names this list claims to read', () => {+ // Spelled out rather than derived: every other assertion feeds the source name+ // back into its own fixture, so only a literal catches a typo or a dropped pair.+ expect(OPTIONAL_PRICING_FIELDS).toEqual([+ ['cache_read_token', 'input_cache_read'],+ ['cache_write_token', 'input_cache_write'],+ ['request', 'request'],+ ['web_search', 'web_search'],+ ['image', 'image'],+ ['image_output', 'image_output'],+ ['audio', 'audio'],+ ['audio_output', 'audio_output'],+ ['input_audio_cache', 'input_audio_cache'],+ ['internal_reasoning', 'internal_reasoning'],+ ])+ })++ // Partial, so the absent-policy guard below is type-honest. A stray key+ // outside `keyof ModelCost` fails to compile; one inside it but outside the+ // loop fails the keys-equality test.+ const policy: Partial<Record<keyof ModelCost, 'flat' | 'de-discounted'>> = {+ cache_read_token: 'de-discounted',+ cache_write_token: 'de-discounted',+ request: 'flat',+ web_search: 'flat',+ image: 'de-discounted',+ image_output: 'de-discounted',+ audio: 'de-discounted',+ audio_output: 'de-discounted',+ input_audio_cache: 'de-discounted',+ internal_reasoning: 'de-discounted',+ }++ it('declares a policy for every field the loop reads, and no others', () => {+ expect(Object.keys(policy).sort()).toEqual([...targetFields].sort())+ })++ it.each(OPTIONAL_PRICING_FIELDS)('%s is priced as its declared policy says', (targetField, sourceField) => {+ const expected = policy[targetField]+ // A loop field with no policy here fails rather than silently inheriting the de-discount.+ expect(expected).toBeTruthy()++ const built = buildModelCost({+ prompt: '0.000001',+ completion: '0.000001',+ [sourceField]: '0.01',+ discount: 0.5,+ })++ expect(built?.[targetField]).toBe(expected === 'flat' ? 0.01 : 0.02)+ expect(FLAT_FEE_FIELDS.has(targetField)).toBe(expected === 'flat')+ })+})+describe('buildModelCost() recovers prices the cost book previously recorded', () => {// Expectations are the list prices the cost book itself held before each// promotion began, so a wrong divisor fails on values this suite did not pick.@@ -420,6 +494,25 @@ describe('renderDiscountReport()', () => {expect(renderDiscountReport([])).toContain('No discounted endpoints found')})+ it('says that per-call fees are not de-discounted', () => {+ const report = renderDiscountReport([entry()])+ expect(report).toContain(+ 'Per-call fees (`request`, `web_search`) carry across untouched: promotional routes in\n' ++ 'the feed serve `web_search` at the same fee as their undiscounted siblings,\n' ++ 'and every other per-call fee follows the same policy.'+ )+ })++ it('derives the flat-fee list from FLAT_FEE_FIELDS', () => {+ // The literal pin above catches a retyped sentence; this binds it to the set.+ expect(renderDiscountReport([entry()])).toContain(+ `Per-call fees (${[...FLAT_FEE_FIELDS]+ .sort()+ .map((field) => `\`${field}\``)+ .join(', ')}) carry across untouched`+ )+ })+it('names each discounted model, endpoint and rate', () => {const report = renderDiscountReport([entry()])expect(report).toContain('openai/gpt-5.6-luna')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.tsindex 34470565ba5b..bf96bcf947ba 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,21 +3,7 @@ import bigDecimal from 'js-big-decimal'import path from 'path'import { normalizeProviderKey } from '~/ingestion/pipelines/ai/costs/provider-matching'--interface ModelCost {- prompt_token: number- completion_token: number- cache_read_token?: number- cache_write_token?: number- request?: number- web_search?: number- image?: number- image_output?: number- audio?: number- audio_output?: number- input_audio_cache?: number- internal_reasoning?: number-}+import type { ModelCost } from '~/ingestion/pipelines/ai/costs/providers/types'interface ModelRow {model: string@@ -57,6 +43,29 @@ const parsePricingNumber = (value: unknown): number | undefined => {}}+/** Carried at the served price: the live feed corroborates this for `web_search`,+ * where promotional routes serve the same fee as their undiscounted siblings. It+ * corroborates neither `request` (no model in the feed carries a non-zero fee)+ * nor a markup route (a negative rate has no sibling); both stay flat by policy. */+export const FLAT_FEE_FIELDS: ReadonlySet<keyof ModelCost> = new Set(['request', 'web_search'])++/** A field added here and not to `FLAT_FEE_FIELDS` is de-discounted by default.+ * `cache_write_1h_token` has no pair on purpose: OpenRouter serves no 1h write+ * rate. Book-priced events fall back to 2x `prompt_token` (input-costs.ts); only+ * the custom-pricing path reads it from event properties. */+export const OPTIONAL_PRICING_FIELDS: ReadonlyArray<[keyof ModelCost, string]> = [+ ['cache_read_token', 'input_cache_read'],+ ['cache_write_token', 'input_cache_write'],+ ['request', 'request'],+ ['web_search', 'web_search'],+ ['image', 'image'],+ ['image_output', 'image_output'],+ ['audio', 'audio'],+ ['audio_output', 'audio_output'],+ ['input_audio_cache', 'input_audio_cache'],+ ['internal_reasoning', 'internal_reasoning'],+]+/** A provider key means what that provider charges a direct caller, so whatever* OpenRouter applied is divided back out. A negative `discount_to_user` is a* markup and the same division recovers list; only a rate at or above 1 is@@ -109,8 +118,6 @@ export const buildModelCost = (pricing: Record<string, unknown> | undefined, conreturn null}- // The rate applies to every field, flat fees included: a 50%-off route serves- // web_search at 0.005 against 0.01 on its undiscounted sibling.const discount = parseDiscountRate(pricing, context)const toListPrice = (value: number): number =>discount === 0 ? value : parseFloat((value / (1 - discount)).toPrecision(10))@@ -120,23 +127,10 @@ export const buildModelCost = (pricing: Record<string, unknown> | undefined, concompletion_token: toListPrice(completionToken),}- const optionalPricingFields: Array<[keyof ModelCost, string]> = [- ['cache_read_token', 'input_cache_read'],- ['cache_write_token', 'input_cache_write'],- ['request', 'request'],- ['web_search', 'web_search'],- ['image', 'image'],- ['image_output', 'image_output'],- ['audio', 'audio'],- ['audio_output', 'audio_output'],- ['input_audio_cache', 'input_audio_cache'],- ['internal_reasoning', 'internal_reasoning'],- ]-- for (const [targetField, sourceField] of optionalPricingFields) {+ for (const [targetField, sourceField] of OPTIONAL_PRICING_FIELDS) {const parsedValue = parsePricingNumber(pricing[sourceField])if (parsedValue !== undefined && parsedValue !== 0) {- cost[targetField] = toListPrice(parsedValue)+ cost[targetField] = FLAT_FEE_FIELDS.has(targetField) ? parsedValue : toListPrice(parsedValue)}}@@ -215,12 +209,20 @@ export const renderDiscountReport = (entries: DiscountReportEntry[], uncheckedMoconst checkable = verdicts.filter((v) => v.some((c) => c !== 'not-checkable')).lengthconst endpointCount = rows.reduce((total, row) => total + row.endpoints.length, 0)+ const flatFeeList = [...FLAT_FEE_FIELDS]+ .sort()+ .map((field) => `\`${field}\``)+ .join(', ')+const lines = ['## Discounts','',`OpenRouter is running a promotion on **${endpointCount} endpoint(s)** across **${rows.length} model(s)**.`,'Per-provider keys below are stored at list rate, with the promotion divided back','out, so a provider key keeps meaning what that provider charges a direct caller.',+ `Per-call fees (${flatFeeList}) carry across untouched: promotional routes in`,+ 'the feed serve `web_search` at the same fee as their undiscounted siblings,',+ 'and every other per-call fee follows the same policy.','The `default` key is left as OpenRouter serves it.','',`Independently confirmed against an undiscounted sibling route: ${confirmed}/${checkable} checkable model(s).`,