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