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 { fetchText, fetchWithRetry, 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
115interface RetailPage {
116 Items?: Array<RetailItem>
117 NextPageLink?: string | null
118}
119
120const UNIT_TOKENS: Record<string, number> = { '1K': 1e3, '1M': 1e6 }
121
122export function parseAzureMeters(items: Array<RetailItem>): Array<AzureMeter> {
123 const out: Array<AzureMeter> = []
124 for (const item of items) {
125 const tokens = UNIT_TOKENS[item.unitOfMeasure ?? '']
126 const sku = parseAzureSku(item.skuName ?? '')
127 if (!tokens || !sku || typeof item.retailPrice !== 'number') continue
128 // Stored as a per-million figure over 1e6, like every other provider,
129 // so the served per-million price is the meter's. The product itself
130 // carries float noise (0.00003 * 1000), hence the rounding.
131 const perMillion = Number(
132 (item.retailPrice * (1e6 / tokens)).toPrecision(12),
133 )
134 out.push({ ...sku, rate: perMillion / 1e6 })
135 }
136 return out
137}
138
139function ratesOf(meters: Array<AzureMeter>): Record<string, number> | null {
140 const rates: Record<string, number> = {}
141 for (const meter of meters) {
142 const known = rates[meter.lever]
143 if (known !== undefined && known !== meter.rate) return null
144 rates[meter.lever] = meter.rate
145 }
146 return rates.input_tokens !== undefined && rates.output_tokens !== undefined
147 ? rates
148 : null
149}
150
151function names(meter: AzureMeter, rawId: string): boolean {
152 const id = rawId.toLowerCase().replace(/[^a-z0-9]/g, '')
153 // `computer-use-inpt-glbl` is the meter for `computer-use-preview`.
154 // The suffix is only appended, so a meter that already names the full id
155 // still matches that id and not a shorter one.
156 return (
157 meter.name === id ||
158 `gpt${meter.name}` === id ||
159 `${meter.name}preview` === id
160 )
161}
162
163/**
164 * Whether a Global Standard token meter names this id and none of `taken`.
165 * `chat-latest` is OpenAI's name for `gpt-chat-latest`; its meter belongs to
166 * the tabulated model, so the bare name is not a second one.
167 */
168export function azureMetered(
169 meters: Array<AzureMeter>,
170 rawId: string,
171 taken: Array<string> = [],
172): boolean {
173 return meters.some(
174 (meter) =>
175 names(meter, rawId) && !taken.some((other) => names(meter, other)),
176 )
177}
178
179export interface AzureRates {
180 base: Record<string, number>
181 /** The long-context band, when the model's meters price one. */
182 long: Record<string, number> | null
183}
184
185/**
186 * Rates for one model version. `null` when no meter names the model, when
187 * its meters are for other versions, when two meters disagree, or when a
188 * band lacks input or output.
189 */
190/** `2024-11-20` → `1120`, the version word a SKU carries. */
191function meterVersion(version: string | null): string | null {
192 return version ? version.slice(5).replace('-', '') : null
193}
194
195export function azureModelRates(
196 meters: Array<AzureMeter>,
197 rawId: string,
198 version: string | null,
199): AzureRates | null {
200 const mine = meters.filter((meter) => names(meter, rawId))
201 const dated = meterVersion(version)
202 const exact = mine.filter((m) => m.version !== null && m.version === dated)
203 const picked = exact.length > 0 ? exact : mine.filter((m) => !m.version)
204
205 const base = ratesOf(picked.filter((m) => !m.long))
206 const longMeters = picked.filter((m) => m.long)
207 const long = longMeters.length > 0 ? ratesOf(longMeters) : null
208 if (!base || (longMeters.length > 0 && !long)) return null
209 return { base, long }
210}
211
212/**
213 * Where the long-context band starts, from the pricing page's row labels:
214 * `GPT-5.4 Pro (<272k context length)` and its `>272k` twin give
215 * `gpt-5.4-pro` → 272000. A model with one label, or with labels that
216 * disagree, is left out. Rows labelled only "short context" state nothing.
217 */
218export function parseAzureContextThresholds(html: string): Map<string, number> {
219 const seen = new Map<string, { lt: Set<number>; gt: Set<number> }>()
220 for (const match of html.matchAll(
221 /GPT-(\d[\d.]*(?: [A-Za-z]+)*) \((?:&(lt|gt);|([<>]))(\d+)k context length\)/g,
222 )) {
223 const id = `gpt-${(match[1] ?? '').toLowerCase().replace(/ /g, '-')}`
224 const entry = seen.get(id) ?? { lt: new Set(), gt: new Set() }
225 const below = match[2] === 'lt' || match[3] === '<'
226 entry[below ? 'lt' : 'gt'].add(Number(match[4]) * 1000)
227 seen.set(id, entry)
228 }
229 const out = new Map<string, number>()
230 for (const [id, { lt, gt }] of seen) {
231 const [tokens] = lt
232 if (
233 tokens !== undefined &&
234 lt.size === 1 &&
235 gt.size === 1 &&
236 gt.has(tokens)
237 ) {
238 out.set(id, tokens)
239 }
240 }
241 return out
242}
243
244export interface AzurePriceDoc {
245 meters: Array<AzureMeter>
246 /** Model id → prompt tokens above which the long band applies. */
247 thresholds: Record<string, number>
248 hash: string
249 extractedAt: string
250}
251
252async function fetchMeters(): Promise<Array<AzureMeter>> {
253 const items: Array<RetailItem> = []
254 let url: string | null = AZURE_PRICES_URL
255 for (let page = 0; url; page++) {
256 if (page === MAX_PAGES) {
257 throw new Error(`azure: price list runs past ${String(MAX_PAGES)} pages`)
258 }
259 // A 429 on any page used to fail the whole price load (#691). Retry
260 // that page; the last failure still throws with its URL.
261 const body: RetailPage = await fetchWithRetry(
262 url,
263 () => ({}),
264 async (response) => (await response.json()) as RetailPage,
265 )
266 items.push(...(body.Items ?? []))
267 url = body.NextPageLink ?? null
268 }
269 const meters = parseAzureMeters(items)
270 if (meters.length === 0) {
271 throw new Error('azure: price list held no Global Standard token meters')
272 }
273 return meters
274}
275
276/**
277 * Every page of the price list plus the pricing page's thresholds. Throws
278 * when either parses nothing.
279 */
280export async function fetchAzurePrices(): Promise<AzurePriceDoc> {
281 const [meters, html] = await Promise.all([
282 fetchMeters(),
283 fetchText(AZURE_PRICING_PAGE_URL),
284 ])
285 const thresholds = parseAzureContextThresholds(html)
286 if (thresholds.size === 0) {
287 throw new Error('azure: pricing page labels no context-length threshold')
288 }
289 // Page order is not stable; hash the meters, sorted.
290 const lines = meters.map((m) => JSON.stringify(m)).sort()
291 lines.push(
292 JSON.stringify(
293 [...thresholds].sort(([a], [b]) => (a < b ? -1 : a > b ? 1 : 0)),
294 ),
295 )
296 return {
297 meters,
298 thresholds: Object.fromEntries(thresholds),
299 hash: await sha256Text(lines.join('\n')),
300 extractedAt: new Date().toISOString(),
301 }
302}
303
304/**
305 * Every meter that names the model is for another dated version: a new
306 * `gpt-chat-latest` version before Azure publishes its meters. A model with
307 * no meter at all, or with an undated one, is not this.
308 */
309function azureVersionUnmetered(
310 meters: Array<AzureMeter>,
311 rawId: string,
312 version: string | null,
313): boolean {
314 const dated = meterVersion(version)
315 const mine = meters.filter((meter) => names(meter, rawId))
316 return (
317 dated !== null &&
318 mine.length > 0 &&
319 mine.every((meter) => meter.version !== null && meter.version !== dated)
320 )
321}
322
323export function azureModelPricing(
324 doc: AzurePriceDoc,
325 rawId: string,
326 version: string | null,
327): Pick<ModelInfo, 'pricing' | 'factSources' | 'absent'> {
328 const rates = azureModelRates(doc.meters, rawId, version)
329 if (!rates) {
330 return azureVersionUnmetered(doc.meters, rawId, version)
331 ? { absent: { pricing: 'cleared' } }
332 : {}
333 }
334 const threshold = doc.thresholds[rawId]
335 // Never the short band alone for a model that also has a long one.
336 if (rates.long && threshold === undefined) return {}
337 const pricing = compileTokenCard(
338 rates.base,
339 rates.long && threshold !== undefined
340 ? [{ minPromptTokens: threshold, rates: rates.long }]
341 : [],
342 { url: AZURE_PRICES_URL, hash: doc.hash, extractedAt: doc.extractedAt },
343 )
344 if (!pricing) return {}
345 return {
346 pricing,
347 factSources: {
348 pricing: {
349 derivation: 'docs-derived',
350 sourceUrl: AZURE_PRICES_URL,
351 sourceHash: doc.hash,
352 path: rates.long
353 ? `Pricing; long-context threshold: ${AZURE_PRICING_PAGE_URL}`
354 : 'Pricing',
355 },
356 },
357 }
358}