Open History to see the last commit
1/**
2 * Standard-tier Bedrock token prices from AWS's own price list and the
3 * public pricing page. The us-east-1 offer is the in-region / standard
4 * rate. The pricing page fills marketplace models the offer does not
5 * name (Anthropic, AI21, Cohere). Global quotes are parsed separately
6 * and never inherited from Geo or in-region rows. Batch, flex, and priority
7 * are excluded. A card that already states dollars
8 * wins. A page or offer that parses nothing throws.
9 */
10import { assertParsed } from './model-facts.ts'
11import { fetchText, sha256Text } from './types.ts'
12
13const AWS_INIT = {
14 headers: {
15 'User-Agent': 'modelschemas (+https://modelschemas.openstory.workers.dev)',
16 },
17}
18
19export const BEDROCK_PRICE_LIST_URL =
20 'https://pricing.us-east-1.amazonaws.com/offers/v1.0/aws/AmazonBedrock/current/us-east-1/index.json'
21export const BEDROCK_PRICING_PAGE_URL =
22 'https://aws.amazon.com/bedrock/pricing/'
23export const BEDROCK_METERED_URL =
24 'https://b0.p.awsstatic.com/pricing/2.0/meteredUnitMaps/bedrockfoundationmodels/USD/current/bedrockfoundationmodels.json'
25
26const USE1 = 'US East (N. Virginia)'
27const NONSTANDARD =
28 /batch|priority|flex|global|cross-region|latency|govcloud|provisioned|custom|training|reserved/i
29const SKIP_HEADING =
30 /priority|flex|\bbatch\b|reserved|latency|provisioned|custom|fine-tun|training|embedding|speech|creative|guardrail|evaluation|example/i
31
32const INPUT = 'input_tokens'
33const OUTPUT = 'output_tokens'
34
35interface OfferDimension {
36 unit?: string
37 beginRange?: string
38 endRange?: string
39 pricePerUnit?: { USD?: string }
40}
41
42interface OfferFile {
43 products?: Record<string, { attributes?: Record<string, string> }>
44 terms?: {
45 OnDemand?: Record<
46 string,
47 Record<string, { priceDimensions?: Record<string, OfferDimension> }>
48 >
49 }
50}
51
52interface MeterFile {
53 regions?: Record<string, Record<string, { price?: string }>>
54}
55
56export interface BedrockPriceBook {
57 offerById: Map<string, Record<string, number>>
58 offerByName: Map<string, Record<string, number>>
59 /** Offer display name, dotted decimals collapsed (`25.02` → `2502`). */
60 offerBySlug: Map<string, Record<string, number>>
61 pageByName: Map<string, Record<string, number>>
62 /** Only prices explicitly published for global cross-region inference. */
63 globalPageByName?: Map<string, Record<string, number>>
64 offerHash: string
65 pageHash: string
66}
67
68export interface BedrockPriceHit {
69 rates: Record<string, number>
70 url: string
71 hash: string
72}
73
74function close(a: number, b: number): boolean {
75 return Math.abs(a - b) <= 1e-12
76}
77
78function sameRates(
79 a: Record<string, number>,
80 b: Record<string, number>,
81): boolean {
82 const keys = new Set([...Object.keys(a), ...Object.keys(b)])
83 for (const key of keys) {
84 if (
85 a[key] === undefined ||
86 b[key] === undefined ||
87 !close(a[key], b[key])
88 ) {
89 return false
90 }
91 }
92 return true
93}
94
95/** Last write wins until two different rate maps share a key; then the key is dropped. */
96function assign(
97 map: Map<string, Record<string, number>>,
98 dropped: Set<string>,
99 key: string,
100 rates: Record<string, number>,
101): void {
102 if (dropped.has(key)) return
103 const prev = map.get(key)
104 if (!prev) {
105 map.set(key, rates)
106 return
107 }
108 if (sameRates(prev, rates)) return
109 map.delete(key)
110 dropped.add(key)
111}
112
113function complete(rates: Record<string, number>): boolean {
114 return (rates[INPUT] ?? 0) > 0 && (rates[OUTPUT] ?? 0) > 0
115}
116
117const CLAUDE_FAMILY = 'haiku|sonnet|opus|fable|mythos'
118
119/**
120 * `Nova 2.0 Lite` and `Llama 4 Maverick 17B Instruct` share one key.
121 * `+` stays so Command R and Command R+ stay apart. A markdown `\+`
122 * is the same plus. Claude puts the family on either side of the
123 * version (`Claude Haiku 4.5`, `Claude 4.5 Haiku`); other names keep
124 * their token order (`Ministral 3 8B` is not `Ministral 8B 3`).
125 */
126export function bedrockNameKey(name: string): string {
127 const key = name
128 .replace(/\\/g, '')
129 .toLowerCase()
130 .replace(/\b(\d+)\.0+\b/g, '$1')
131 .replace(/[^a-z0-9+]+/g, ' ')
132 .replace(/\s+instruct$/, '')
133 .replace(/\s+/g, ' ')
134 .trim()
135 const match = key.match(
136 new RegExp(
137 `^claude(?:\\s+(${CLAUDE_FAMILY}))?\\s+((?:\\d+\\s+)*\\d+)(?:\\s+(${CLAUDE_FAMILY}))?$`,
138 ),
139 )
140 const family = match?.[1] || match?.[3]
141 if (!match?.[2] || !family) return key
142 if (match[1] && match[3] && match[1] !== match[3]) return key
143 return `claude ${match[2]} ${family}`
144}
145
146function usageModelId(usagetype: string): string | null {
147 const dotted = usagetype
148 .replace(/^[A-Z0-9]+-/, '')
149 .match(/^([a-z][a-z0-9]*\.[a-z0-9][a-z0-9.:-]*)/)?.[1]
150 if (!dotted) return null
151 return dotted
152 .replace(/-mantle(?:-.*)?$/, '')
153 .replace(/-(?:input|output)-tokens(?:-.*)?$/, '')
154 .replace(/-cache-(?:read|write)(?:-.*)?$/, '')
155}
156
157/**
158 * 5-minute and unnamed writes use `cache_write_tokens`. A 1-hour write is
159 * its own lever. 30-minute and any other duration have no lever.
160 */
161const FIVE_MINUTES = /(?:^|[^a-z0-9])5(?:m|[\s-]*min(?:ute)?s?)(?:[^a-z0-9]|$)/
162const ONE_HOUR = /(?:^|[^a-z0-9])1(?:h|[\s-]*hours?)(?:[^a-z0-9]|$)/
163const OTHER_DURATION =
164 /(?:^|[^a-z0-9])\d+\s*(?:m|h)\b|\d+\s*-?\s*(?:min(?:ute)?s?|hours?)\b/
165
166export function cacheWriteLever(text: string): string | null {
167 const name = text.toLowerCase()
168 if (ONE_HOUR.test(name)) return 'cache_write_1h_tokens'
169 if (FIVE_MINUTES.test(name)) return 'cache_write_tokens'
170 if (OTHER_DURATION.test(name)) return null
171 return 'cache_write_tokens'
172}
173
174/** True when the header itself names a cache duration, including 30 minutes. */
175export function cacheWriteNamesDuration(text: string): boolean {
176 return OTHER_DURATION.test(text.toLowerCase())
177}
178
179/** `Pixtral Large 25.02` → `pixtral-large-2502`, the form inside the model id. */
180export function bedrockOfferSlug(model: string): string {
181 return model
182 .toLowerCase()
183 .replace(/(\d)\.(\d)/g, '$1$2')
184 .replace(/[^a-z0-9]+/g, '-')
185 .replace(/^-+|-+$/g, '')
186}
187
188function textLever(inferenceType: string, usagetype: string): string | null {
189 const text = `${inferenceType} ${usagetype}`.toLowerCase()
190 if (/video|image|audio|speech/.test(text)) return null
191 if (/cache[- ]read/.test(text)) return 'cache_read_tokens'
192 if (/cache[- ]write/.test(text)) return cacheWriteLever(text)
193 if (/output/.test(text)) return OUTPUT
194 if (/input/.test(text)) return INPUT
195 return null
196}
197
198function isMedia(inferenceType: string, usagetype: string): boolean {
199 return /video|image|audio|speech/i.test(`${inferenceType} ${usagetype}`)
200}
201
202function isStandard(attributes: Record<string, string>): boolean {
203 const tier = attributes.service_tier ?? ''
204 const feature = attributes.feature ?? ''
205 const inferenceType = attributes.inferenceType ?? ''
206 const usagetype = attributes.usagetype ?? ''
207 if (
208 NONSTANDARD.test(tier) ||
209 NONSTANDARD.test(feature) ||
210 NONSTANDARD.test(inferenceType) ||
211 NONSTANDARD.test(usagetype)
212 ) {
213 return false
214 }
215 if (tier === 'standard') return true
216 return tier === '' && feature === 'On-demand Inference'
217}
218
219function perToken(dimension: OfferDimension): number | null {
220 const unit = dimension.unit?.match(/^(\d+(?:\.\d+)?)([km]) tokens?$/i)
221 if (!unit || dimension.beginRange !== '0' || dimension.endRange !== 'Inf') {
222 return null
223 }
224 const tokens = Number(unit[1]) * (unit[2]?.toLowerCase() === 'm' ? 1e6 : 1e3)
225 const usd = Number(dimension.pricePerUnit?.USD)
226 if (!Number.isFinite(usd) || tokens <= 0) return null
227 return usd / tokens
228}
229
230interface Group {
231 rates: Record<string, number>
232 media: boolean
233 conflict: boolean
234 name: string
235 nameConflict: boolean
236 slug: string
237 slugConflict: boolean
238}
239
240/**
241 * Standard on-demand token rates. Speech and text prices for one model
242 * (Nova Sonic) are a conflict: the model is dropped, not averaged.
243 */
244export function parseBedrockOffer(offer: OfferFile): {
245 byId: Map<string, Record<string, number>>
246 byName: Map<string, Record<string, number>>
247 bySlug: Map<string, Record<string, number>>
248} {
249 const products = offer.products
250 const terms = offer.terms?.OnDemand
251 if (!products || !terms) {
252 throw new Error(
253 'amazon-bedrock price list: missing products or OnDemand terms',
254 )
255 }
256 const groups = new Map<string, Group>()
257 for (const [sku, product] of Object.entries(products)) {
258 const attributes = product.attributes ?? {}
259 if (!isStandard(attributes)) continue
260 const inferenceType = attributes.inferenceType ?? ''
261 const usagetype = attributes.usagetype ?? ''
262 const lever = textLever(inferenceType, usagetype)
263 const media = isMedia(inferenceType, usagetype)
264 if (!lever && !media) continue
265 const term = Object.values(terms[sku] ?? {})[0]
266 const dimensions = Object.values(term?.priceDimensions ?? {})
267 if (dimensions.length !== 1) continue
268 const rate = dimensions[0] ? perToken(dimensions[0]) : null
269 if (rate === null) continue
270 const id = usageModelId(usagetype)
271 const name = bedrockNameKey(attributes.model ?? '')
272 const slug = bedrockOfferSlug(attributes.model ?? '')
273 const key = id ?? (name ? `name:${name}` : '')
274 if (!key) continue
275 const group = groups.get(key) ?? {
276 rates: {},
277 media: false,
278 conflict: false,
279 name: '',
280 nameConflict: false,
281 slug: '',
282 slugConflict: false,
283 }
284 if (name && group.name && group.name !== name) group.nameConflict = true
285 if (name && !group.name) group.name = name
286 if (slug && group.slug && group.slug !== slug) group.slugConflict = true
287 if (slug && !group.slug) group.slug = slug
288 if (media) group.media = true
289 if (lever) {
290 const prev = group.rates[lever]
291 if (prev !== undefined && !close(prev, rate)) group.conflict = true
292 group.rates[lever] = rate
293 }
294 groups.set(key, group)
295 }
296
297 const byId = new Map<string, Record<string, number>>()
298 const byName = new Map<string, Record<string, number>>()
299 const bySlug = new Map<string, Record<string, number>>()
300 const dropped = new Set<string>()
301 for (const [key, group] of groups) {
302 if (group.media || group.conflict || !complete(group.rates)) continue
303 // The offer id can be longer (`-instruct`) or punctuated differently
304 // (`zai.glm5`, `deepseek.v3.1`) than the card id. The model attribute
305 // is the join for those. A longer offer id is never a prefix of the card.
306 if (!key.startsWith('name:')) assign(byId, dropped, key, group.rates)
307 if (!group.nameConflict && group.name) {
308 assign(byName, dropped, group.name, group.rates)
309 }
310 // `Pixtral Large 25.02` is `pixtral-large-2502` inside the card id.
311 // Short slugs (`r1`, `glm-5`) stay off this map so they cannot land
312 // on a longer id.
313 if (!group.slugConflict && group.slug.length >= 12) {
314 assign(bySlug, dropped, group.slug, group.rates)
315 }
316 }
317 const rows = new Map<string, Record<string, number>>([...byId, ...byName])
318 assertParsed(rows, 'amazon-bedrock price list')
319 return { byId, byName, bySlug }
320}
321
322function cellText(cell: string): string {
323 return cell
324 .replace(/<br\s*\/?>/gi, ' ')
325 .replace(/<[^>]+>/g, '')
326 .replace(/ /gi, ' ')
327 .replace(/&/gi, '&')
328 .replace(/'/g, "'")
329 .replace(/"/gi, '"')
330 .replace(/\s+/g, ' ')
331 .trim()
332}
333
334function columnLever(header: string, perMillionNote: boolean): string | null {
335 const name = header.toLowerCase().replace(/\*/g, '').trim()
336 if (/cache/.test(name) && /read/.test(name)) return 'cache_read_tokens'
337 if (/cache/.test(name) && /write/.test(name)) return cacheWriteLever(name)
338 const priced =
339 /price per 1m/.test(name) ||
340 (perMillionNote && /^(input|output)$/.test(name))
341 if (!priced) return null
342 if (/batch|image|video|audio|speech|\(text\)/.test(name)) return null
343 if (/output/.test(name)) return OUTPUT
344 if (/input/.test(name)) return INPUT
345 return null
346}
347
348function perMillion(
349 cell: string,
350 region: Record<string, { price?: string }>,
351): number | null {
352 const literal = cellText(cell).match(/\$\s*(\d+(?:,\d{3})*(?:\.\d+)?)/)
353 if (literal?.[1]) return Number(literal[1].replace(/,/g, ''))
354 const code = cell
355 .replace(/\s+/g, '')
356 .match(/\{priceOf!bedrockfoundationmodels\/[^!]+!([A-Za-z0-9_-]+)/)?.[1]
357 const price = code ? region[code]?.price : undefined
358 if (price === undefined) return null
359 const amount = Number(price)
360 return Number.isFinite(amount) ? amount : null
361}
362
363/**
364 * Standard on-demand tables selected by inference scope. Priority, flex,
365 * batch and long-context rows are ignored. Rate codes resolve against
366 * US East (N. Virginia). A published Global quote with unresolved meters
367 * throws; it must not be replaced with a regional quote.
368 */
369export function parseBedrockPricingPage(
370 html: string,
371 meter: MeterFile,
372 scope: 'regional' | 'global' = 'regional',
373): Map<string, Record<string, number>> {
374 const region = meter.regions?.[USE1]
375 if (!region) {
376 throw new Error(
377 'amazon-bedrock pricing page: no US East (N. Virginia) meter',
378 )
379 }
380 const flat = html.replace(/\{priceOf![\s\S]*?\}/g, (token) =>
381 token.replace(/\s+/g, ''),
382 )
383 const out = new Map<string, Record<string, number>>()
384 const dropped = new Set<string>()
385 const stack: Array<{ level: number; text: string }> = []
386 let pendingLabel = ''
387 const token =
388 /<h([1-4])[^>]*>([\s\S]*?)<\/h\1>|<div class="lb-txt-none lb-txt">\s*([^<]+?)\s*<\/div>|<table[\s\S]*?<\/table>/gi
389 for (const match of flat.matchAll(token)) {
390 const level = match[1]
391 if (level) {
392 const heading = cellText(match[2] ?? '')
393 const depth = Number(level)
394 while (stack.length > 0 && (stack.at(-1)?.level ?? 0) >= depth)
395 stack.pop()
396 stack.push({ level: depth, text: heading })
397 continue
398 }
399 const label = match[3]
400 if (label) {
401 const text = cellText(label)
402 if (text && !/pricing|on-demand|^regions/i.test(text)) pendingLabel = text
403 continue
404 }
405 const headings = stack.map((item) => item.text).join(' ')
406 if (SKIP_HEADING.test(headings)) continue
407 const globalHeading = /global/i.test(headings)
408 if (scope === 'regional' && globalHeading) continue
409 const table = match[0]
410 const after = flat.slice(
411 match.index + table.length,
412 match.index + table.length + 800,
413 )
414 const perMillionNote = /per 1 million tokens/i.test(`${table}\n${after}`)
415 const rows = [...table.matchAll(/<tr[\s\S]*?<\/tr>/gi)].map((row) =>
416 [...row[0].matchAll(/<t[dh][^>]*>([\s\S]*?)<\/t[dh]>/gi)].map((cell) =>
417 cellText(cell[1] ?? ''),
418 ),
419 )
420 const head = rows[0]
421 if (!head) continue
422 const levers = head.map((cell) => columnLever(cell, perMillionNote))
423 if (!levers.includes(INPUT) || !levers.includes(OUTPUT)) continue
424 const ratesOf = (row: Array<string>): Record<string, number> => {
425 const rates: Record<string, number> = {}
426 row.forEach((cell, index) => {
427 const lever = levers[index]
428 const amount = perMillion(cell, region)
429 if (
430 scope === 'global' &&
431 lever &&
432 /\$|\{priceOf!/.test(cell) &&
433 amount === null
434 ) {
435 throw new Error('amazon-bedrock global pricing: unreadable quote')
436 }
437 if (lever && amount !== null && amount >= 0) rates[lever] = amount / 1e6
438 })
439 return rates
440 }
441 // A tab names the model. Rows are tiers. US CRIS is the standard rate.
442 if (head.some((cell) => /inference option/i.test(cell))) {
443 const chosen = rows.slice(1).find((row) => {
444 const tier = row[0] ?? ''
445 return scope === 'global'
446 ? /global/i.test(tier)
447 : /us cris|in-region|regional/i.test(tier) && !/global/i.test(tier)
448 })
449 const rates = chosen ? ratesOf(chosen) : null
450 const key = bedrockNameKey(pendingLabel)
451 if (scope === 'global' && chosen && (!rates || !complete(rates))) {
452 throw new Error(
453 `amazon-bedrock global pricing: unreadable quote ${key}`,
454 )
455 }
456 if (!rates || !key || !complete(rates)) continue
457 assign(out, dropped, key, rates)
458 continue
459 }
460 if (scope === 'global' && !globalHeading) continue
461 const nameCol = head.findIndex((cell) => /model/i.test(cell))
462 const modelCol = nameCol >= 0 ? nameCol : 0
463 for (const row of rows.slice(1)) {
464 const name = (row[modelCol] ?? '').replace(/\*+/g, '').trim()
465 if (!name || /long context/i.test(name)) continue
466 const rates = ratesOf(row)
467 const key = bedrockNameKey(name)
468 if (scope === 'global' && !complete(rates)) {
469 throw new Error(
470 `amazon-bedrock global pricing: unreadable quote ${key}`,
471 )
472 }
473 if (!key || !complete(rates)) continue
474 assign(out, dropped, key, rates)
475 }
476 }
477 if (scope === 'regional') assertParsed(out, 'amazon-bedrock pricing page')
478 return out
479}
480
481/** Longest offer id that is `rawId` or a `-` / `:` boundary prefix of it. */
482export function matchBedrockModelId(
483 ids: Iterable<string>,
484 rawId: string,
485): string | null {
486 let best: string | null = null
487 for (const id of ids) {
488 const boundary = rawId.charAt(id.length)
489 const hit =
490 id === rawId ||
491 (rawId.startsWith(id) && (boundary === '-' || boundary === ':'))
492 if (hit && (best === null || id.length > best.length)) best = id
493 }
494 return best
495}
496
497/**
498 * Longest offer slug inside `rawId`. A following digit continues the
499 * version (`250` is not `2502`, `glm-5` is not `glm-5.3`). `-v1` stays.
500 */
501export function matchBedrockOfferSlug(
502 slugs: Iterable<string>,
503 rawId: string,
504): string | null {
505 const id = rawId.toLowerCase()
506 let best: string | null = null
507 for (const slug of slugs) {
508 if (slug.length < 12) continue
509 let from = 0
510 while (from < id.length) {
511 const at = id.indexOf(slug, from)
512 if (at < 0) break
513 const before = at === 0 ? '' : id.charAt(at - 1)
514 const after = id.slice(at + slug.length)
515 const boundaryBefore = before === '' || /[^a-z0-9]/.test(before)
516 // `250` inside `2502`, or `glm-5` inside `glm-5.3`. `-v1` stays.
517 const longerVersion = /^(?:[.-])?\d/.test(after)
518 if (
519 boundaryBefore &&
520 !longerVersion &&
521 (best === null || slug.length > best.length)
522 ) {
523 best = slug
524 }
525 from = at + 1
526 }
527 }
528 return best
529}
530
531export function lookupBedrockPrice(
532 book: BedrockPriceBook,
533 rawId: string,
534 displayName: string | null,
535): BedrockPriceHit | null {
536 const id = matchBedrockModelId(book.offerById.keys(), rawId)
537 if (id) {
538 const rates = book.offerById.get(id)
539 if (rates)
540 return { rates, url: BEDROCK_PRICE_LIST_URL, hash: book.offerHash }
541 }
542 const name = bedrockNameKey(displayName ?? '')
543 if (!name) return null
544 const offered = book.offerByName.get(name)
545 if (offered) {
546 return {
547 rates: offered,
548 url: BEDROCK_PRICE_LIST_URL,
549 hash: book.offerHash,
550 }
551 }
552 const slug = matchBedrockOfferSlug(book.offerBySlug.keys(), rawId)
553 if (slug) {
554 const rates = book.offerBySlug.get(slug)
555 if (rates)
556 return { rates, url: BEDROCK_PRICE_LIST_URL, hash: book.offerHash }
557 }
558 const page = book.pageByName.get(name)
559 if (!page) return null
560 return { rates: page, url: BEDROCK_PRICING_PAGE_URL, hash: book.pageHash }
561}
562
563export async function fetchBedrockPriceBook(): Promise<BedrockPriceBook> {
564 const [offerText, html, meterText] = await Promise.all([
565 fetchText(BEDROCK_PRICE_LIST_URL, AWS_INIT),
566 fetchText(BEDROCK_PRICING_PAGE_URL, AWS_INIT),
567 fetchText(BEDROCK_METERED_URL, AWS_INIT),
568 ])
569 const offer = parseBedrockOffer(JSON.parse(offerText) as OfferFile)
570 const meter = JSON.parse(meterText) as MeterFile
571 const page = parseBedrockPricingPage(html, meter)
572 const globalPage = parseBedrockPricingPage(html, meter, 'global')
573 return {
574 offerById: offer.byId,
575 offerByName: offer.byName,
576 offerBySlug: offer.bySlug,
577 pageByName: page,
578 globalPageByName: globalPage,
579 offerHash: await sha256Text(offerText),
580 pageHash: await sha256Text(`${html}\n${meterText}`),
581 }
582}