Open History to see the last commit
1/**
2 * Azure OpenAI token prices from the public Azure Retail Prices API. It is
3 * the only place Azure publishes these numbers as data: the pricing page
4 * renders `$-` and fills the figures in the browser.
5 *
6 * A meter names its model only in the SKU name, an abbreviation such as
7 * `5.4 mini cd Inp Gl` or `gpt-4o-0806-Outp-glbl`. `parseAzureSku` reads the
8 * words it knows (direction, cache, deployment, version) and leaves the rest
9 * as the model name. A SKU for another tier (batch, flex, priority,
10 * fine-tuning, audio) keeps that word in its name and so matches no model.
11 * Only Global Standard meters are read.
12 *
13 * The API prices a short and a long context band for some models and does
14 * not say where the long band starts. The pricing page's row labels do for
15 * a few (`GPT-5.4 (<272k context length)`); those get a tiered card. A model
16 * with long-context meters and no published threshold gets no card.
17 *
18 * A model version the price list does not meter yet, while it meters other
19 * versions of that model, is `cleared`: the list visibly has no price for it.
20 */
21import { compileTokenCard } from '@modelschemas/rate-card'
22
23import { fetchJson, fetchText, sha256Text } from './types.ts'
24import type { ModelInfo } from './types.ts'
25
26/**
27 * Global Standard meters are listed in every region at one price, so one
28 * region bounds the response without choosing a regional price.
29 */
30const FILTER =
31 "serviceName eq 'Foundry Models' and armRegionName eq 'eastus2' and priceType eq 'Consumption' and startswith(productName,'Azure OpenAI')"
32export const AZURE_PRICES_URL = `https://prices.azure.com/api/retail/prices?$filter=${encodeURIComponent(FILTER)}`
33
34/** Read only for the context-length labels on its rows. */
35export const AZURE_PRICING_PAGE_URL =
36 'https://azure.microsoft.com/en-us/pricing/details/azure-openai/'
37
38const MAX_PAGES = 10
39
40const GLOBAL = new Set(['gl', 'glb', 'glbl', 'global'])
41const INPUT = new Set(['in', 'inp', 'inpt', 'input'])
42const OUTPUT = new Set(['opt', 'out', 'outp', 'outpt', 'output'])
43const CACHED = new Set(['cd', 'cached', 'cchd', 'cched', 'ccchd'])
44const LONG = new Set(['longco', 'loco'])
45/** Words that say "standard, short context": the tier being read. */
46const STANDARD = new Set(['std', 'shortco', 'shco'])
47
48export type AzureLever =
49 | 'input_tokens'
50 | 'output_tokens'
51 | 'cache_read_tokens'
52 | 'cache_write_tokens'
53
54export interface AzureSku {
55 /** Model words with punctuation dropped: `54mini`, `gpt4o`, `o3`. */
56 name: string
57 /** `MMDD` of the model version, when the SKU carries one. */
58 version: string | null
59 lever: AzureLever
60 long: boolean
61}
62
63export interface AzureMeter extends AzureSku {
64 /** USD per token. */
65 rate: number
66}
67
68/** `null` for a SKU that is not a Global Standard token meter. */
69export function parseAzureSku(skuName: string): AzureSku | null {
70 const words = skuName
71 .toLowerCase()
72 .split(/[\s-]+/)
73 .filter(Boolean)
74 if (!words.some((word) => GLOBAL.has(word))) return null
75
76 let input = false
77 let output = false
78 let cached = false
79 let write = false
80 let long = false
81 let version: string | null = null
82 const name: Array<string> = []
83 for (const word of words) {
84 if (GLOBAL.has(word) || STANDARD.has(word)) continue
85 // `gpt-4-turbo128K` is the Global Standard meter for the `gpt-4` row.
86 // `gpt-4-Turbo-Batch-128K` stays a different name: its words are split.
87 if (word === 'turbo128k') continue
88 if (INPUT.has(word)) input = true
89 else if (OUTPUT.has(word)) output = true
90 else if (CACHED.has(word)) cached = true
91 else if (word === 'wr') write = true
92 else if (LONG.has(word)) long = true
93 // `0806`, or `08062026` on the dated chat-latest meters.
94 else if (/^\d{4}(?:\d{4})?$/.test(word)) version = word.slice(0, 4)
95 else name.push(word)
96 }
97
98 let lever: AzureLever
99 if (cached && write && !input && !output) lever = 'cache_write_tokens'
100 else if (write || input === output) return null
101 else if (input) lever = cached ? 'cache_read_tokens' : 'input_tokens'
102 else if (cached) return null
103 else lever = 'output_tokens'
104
105 const joined = name.join('').replace(/[^a-z0-9]/g, '')
106 return joined === '' ? null : { name: joined, version, lever, long }
107}
108
109interface RetailItem {
110 skuName?: string
111 unitOfMeasure?: string
112 retailPrice?: number
113}
114
115const UNIT_TOKENS: Record<string, number> = { '1K': 1e3, '1M': 1e6 }
116
117export function parseAzureMeters(items: Array<RetailItem>): Array<AzureMeter> {
118 const out: Array<AzureMeter> = []
119 for (const item of items) {
120 const tokens = UNIT_TOKENS[item.unitOfMeasure ?? '']
121 const sku = parseAzureSku(item.skuName ?? '')
122 if (!tokens || !sku || typeof item.retailPrice !== 'number') continue
123 // Stored as a per-million figure over 1e6, like every other provider,
124 // so the served per-million price is the meter's. The product itself
125 // carries float noise (0.00003 * 1000), hence the rounding.
126 const perMillion = Number(
127 (item.retailPrice * (1e6 / tokens)).toPrecision(12),
128 )
129 out.push({ ...sku, rate: perMillion / 1e6 })
130 }
131 return out
132}
133
134function ratesOf(meters: Array<AzureMeter>): Record<string, number> | null {
135 const rates: Record<string, number> = {}
136 for (const meter of meters) {
137 const known = rates[meter.lever]
138 if (known !== undefined && known !== meter.rate) return null
139 rates[meter.lever] = meter.rate
140 }
141 return rates.input_tokens !== undefined && rates.output_tokens !== undefined
142 ? rates
143 : null
144}
145
146function names(meter: AzureMeter, rawId: string): boolean {
147 const id = rawId.toLowerCase().replace(/[^a-z0-9]/g, '')
148 // `computer-use-inpt-glbl` is the meter for `computer-use-preview`.
149 // The suffix is only appended, so a meter that already names the full id
150 // still matches that id and not a shorter one.
151 return (
152 meter.name === id ||
153 `gpt${meter.name}` === id ||
154 `${meter.name}preview` === id
155 )
156}
157
158/**
159 * Whether a Global Standard token meter names this id and none of `taken`.
160 * `chat-latest` is OpenAI's name for `gpt-chat-latest`; its meter belongs to
161 * the tabulated model, so the bare name is not a second one.
162 */
163export function azureMetered(
164 meters: Array<AzureMeter>,
165 rawId: string,
166 taken: Array<string> = [],
167): boolean {
168 return meters.some(
169 (meter) =>
170 names(meter, rawId) && !taken.some((other) => names(meter, other)),
171 )
172}
173
174export interface AzureRates {
175 base: Record<string, number>
176 /** The long-context band, when the model's meters price one. */
177 long: Record<string, number> | null
178}
179
180/**
181 * Rates for one model version. `null` when no meter names the model, when
182 * its meters are for other versions, when two meters disagree, or when a
183 * band lacks input or output.
184 */
185/** `2024-11-20` → `1120`, the version word a SKU carries. */
186function meterVersion(version: string | null): string | null {
187 return version ? version.slice(5).replace('-', '') : null
188}
189
190export function azureModelRates(
191 meters: Array<AzureMeter>,
192 rawId: string,
193 version: string | null,
194): AzureRates | null {
195 const mine = meters.filter((meter) => names(meter, rawId))
196 const dated = meterVersion(version)
197 const exact = mine.filter((m) => m.version !== null && m.version === dated)
198 const picked = exact.length > 0 ? exact : mine.filter((m) => !m.version)
199
200 const base = ratesOf(picked.filter((m) => !m.long))
201 const longMeters = picked.filter((m) => m.long)
202 const long = longMeters.length > 0 ? ratesOf(longMeters) : null
203 if (!base || (longMeters.length > 0 && !long)) return null
204 return { base, long }
205}
206
207/**
208 * Where the long-context band starts, from the pricing page's row labels:
209 * `GPT-5.4 Pro (<272k context length)` and its `>272k` twin give
210 * `gpt-5.4-pro` → 272000. A model with one label, or with labels that
211 * disagree, is left out. Rows labelled only "short context" state nothing.
212 */
213export function parseAzureContextThresholds(html: string): Map<string, number> {
214 const seen = new Map<string, { lt: Set<number>; gt: Set<number> }>()
215 for (const match of html.matchAll(
216 /GPT-(\d[\d.]*(?: [A-Za-z]+)*) \((?:&(lt|gt);|([<>]))(\d+)k context length\)/g,
217 )) {
218 const id = `gpt-${(match[1] ?? '').toLowerCase().replace(/ /g, '-')}`
219 const entry = seen.get(id) ?? { lt: new Set(), gt: new Set() }
220 const below = match[2] === 'lt' || match[3] === '<'
221 entry[below ? 'lt' : 'gt'].add(Number(match[4]) * 1000)
222 seen.set(id, entry)
223 }
224 const out = new Map<string, number>()
225 for (const [id, { lt, gt }] of seen) {
226 const [tokens] = lt
227 if (
228 tokens !== undefined &&
229 lt.size === 1 &&
230 gt.size === 1 &&
231 gt.has(tokens)
232 ) {
233 out.set(id, tokens)
234 }
235 }
236 return out
237}
238
239export interface AzurePriceDoc {
240 meters: Array<AzureMeter>
241 /** Model id → prompt tokens above which the long band applies. */
242 thresholds: Record<string, number>
243 hash: string
244 extractedAt: string
245}
246
247async function fetchMeters(): Promise<Array<AzureMeter>> {
248 const items: Array<RetailItem> = []
249 let url: string | null = AZURE_PRICES_URL
250 for (let page = 0; url; page++) {
251 if (page === MAX_PAGES) {
252 throw new Error(`azure: price list runs past ${String(MAX_PAGES)} pages`)
253 }
254 const body = (await fetchJson(url)) as {
255 Items?: Array<RetailItem>
256 NextPageLink?: string | null
257 }
258 items.push(...(body.Items ?? []))
259 url = body.NextPageLink ?? null
260 }
261 const meters = parseAzureMeters(items)
262 if (meters.length === 0) {
263 throw new Error('azure: price list held no Global Standard token meters')
264 }
265 return meters
266}
267
268/**
269 * Every page of the price list plus the pricing page's thresholds. Throws
270 * when either parses nothing.
271 */
272export async function fetchAzurePrices(): Promise<AzurePriceDoc> {
273 const [meters, html] = await Promise.all([
274 fetchMeters(),
275 fetchText(AZURE_PRICING_PAGE_URL),
276 ])
277 const thresholds = parseAzureContextThresholds(html)
278 if (thresholds.size === 0) {
279 throw new Error('azure: pricing page labels no context-length threshold')
280 }
281 // Page order is not stable; hash the meters, sorted.
282 const lines = meters.map((m) => JSON.stringify(m)).sort()
283 lines.push(JSON.stringify([...thresholds].sort()))
284 return {
285 meters,
286 thresholds: Object.fromEntries(thresholds),
287 hash: await sha256Text(lines.join('\n')),
288 extractedAt: new Date().toISOString(),
289 }
290}
291
292/**
293 * Every meter that names the model is for another dated version: a new
294 * `gpt-chat-latest` version before Azure publishes its meters. A model with
295 * no meter at all, or with an undated one, is not this.
296 */
297function azureVersionUnmetered(
298 meters: Array<AzureMeter>,
299 rawId: string,
300 version: string | null,
301): boolean {
302 const dated = meterVersion(version)
303 const mine = meters.filter((meter) => names(meter, rawId))
304 return (
305 dated !== null &&
306 mine.length > 0 &&
307 mine.every((meter) => meter.version !== null && meter.version !== dated)
308 )
309}
310
311export function azureModelPricing(
312 doc: AzurePriceDoc,
313 rawId: string,
314 version: string | null,
315): Pick<ModelInfo, 'pricing' | 'factSources' | 'absent'> {
316 const rates = azureModelRates(doc.meters, rawId, version)
317 if (!rates) {
318 return azureVersionUnmetered(doc.meters, rawId, version)
319 ? { absent: { pricing: 'cleared' } }
320 : {}
321 }
322 const threshold = doc.thresholds[rawId]
323 // Never the short band alone for a model that also has a long one.
324 if (rates.long && threshold === undefined) return {}
325 const pricing = compileTokenCard(
326 rates.base,
327 rates.long && threshold !== undefined
328 ? [{ minPromptTokens: threshold, rates: rates.long }]
329 : [],
330 { url: AZURE_PRICES_URL, hash: doc.hash, extractedAt: doc.extractedAt },
331 )
332 if (!pricing) return {}
333 return {
334 pricing,
335 factSources: {
336 pricing: {
337 derivation: 'docs-derived',
338 sourceUrl: AZURE_PRICES_URL,
339 sourceHash: doc.hash,
340 path: rates.long
341 ? `Pricing; long-context threshold: ${AZURE_PRICING_PAGE_URL}`
342 : 'Pricing',
343 },
344 },
345 }
346}