Skip to content
Source
Sign inSign up
TanStack/schemas
Open History to see the last commit

bedrock-cards.ts

680 lines24.0 KB

1/**
2 * Amazon Bedrock model cards (issue #153). The user guide's "Models at a
3 * glance" page links one card per model; each card states the API model id,
4 * inference-profile ids, limits, modalities, lifecycle, and reasoning. A few
5 * cards (OpenAI, xAI, Moonshot) also state token prices. A card with no
6 * dollars is filled from the AWS price list, then the pricing page
7 * (`bedrock-pricing.ts`). Every card is fetched as the `.md` twin AWS
8 * publishes next to the HTML.
9 */
10import { compileTokenCard } from '@modelschemas/rate-card'
11import type { TokenRateTier } from '@modelschemas/rate-card'
12​
13import type { Activity } from '#/db/schema.ts'
14​
15import { endpointIdFromPath } from '../ingest/bundle.ts'
16import {
17 cacheWriteLever,
18 cacheWriteNamesDuration,
19 bedrockNameKey,
20 BEDROCK_PRICING_PAGE_URL,
21 fetchBedrockPriceBook,
22 lookupBedrockPrice,
23} from './bedrock-pricing.ts'
24import { tagDocsFacts } from './fact-sources.ts'
25import type { BedrockCardOwnedGroup } from './bedrock-thinking-guides.ts'
26import {
27 assertParsed,
28 cachedDocs,
29 mapConcurrent,
30 markdownSection,
31 markdownTableRows,
32 tokenCount,
33} from './model-facts.ts'
34import { fetchText, sha256Text } from './types.ts'
35import type { ModelInfo, ModelReasoning } from './types.ts'
36​
37const DOCS = 'https://docs.aws.amazon.com/bedrock/latest/userguide/'
38/** docs.aws.amazon.com answers 403 without a User-Agent; workerd sends none. */
39const DOCS_INIT = {
40 headers: {
41 'User-Agent': 'modelschemas (+https://modelschemas.openstory.workers.dev)',
42 },
44export const BEDROCK_CARDS_URL = `${DOCS}model-cards.md`
45export const BEDROCK_CONVERSE_PATH = '/model/{modelId}/converse'
46​
47/** `anthropic.claude-sonnet-4-5-20250929-v1:0`, `us.openai.gpt-6-sol`. */
48const MODEL_ID = /[a-z][a-z0-9-]*\.[a-z0-9][a-z0-9.:-]*/g
49/** AWS ends table lines with `| `; the shared reader wants a closing `|`. */
50const tableRows = (text: string) =>
51 markdownTableRows(text.replace(/[ \t]+$/gm, ''))
52​
53const YES = 'icon-yes.png'
54const MONTHS = 'janfebmaraprmayjunjulaugsepoctnovdec'
55​
56/** Card slugs linked from the index, provider overview pages excluded. */
57export function bedrockCardSlugs(index: string): Array<string> {
58 const slugs = [...index.matchAll(/\]\((model-card-[a-z0-9.-]+)\.md\)/g)]
59 return [...new Set(slugs.map((match) => match[1] ?? ''))]
61​
62function field(markdown: string, name: string): string | undefined {
63 // GPT-6.1 Sol indents the bullet with two spaces; other cards use one.
64 return markdown
65 .match(new RegExp(`^\\+\\s+\\*\\*${name}:\\*\\*\\s+(.+)$`, 'm'))?.[1]
66 ?.trim()
68​
69/** `Sep 30, 2025` / `September 30, 2025` → epoch seconds. */
70function launchDay(text: string | undefined): number | null {
71 const match = text?.match(/^([A-Za-z]{3})[a-z]* (\d{1,2}), (\d{4})$/)
72 const month = match?.[1] ? MONTHS.indexOf(match[1].toLowerCase()) / 3 : -1
73 if (!match || !Number.isInteger(month) || month < 0) return null
74 return Date.UTC(Number(match[3]), month, Number(match[2])) / 1000
76​
77/**
78 * `Supported (…)` → the control the note names. A bare `Supported` states no
79 * control, so reasoning stays null and only the capability flag is set.
80 */
81export function bedrockReasoning(
82 text: string | undefined,
83): ModelReasoning | null {
84 const note = text?.match(/^Supported \((.+)\)$/)?.[1]
85 if (!note) return null
86 const efforts = note
87 .match(/configurable\s*[—:]\s*([a-z, ]+)/)?.[1]
88 ?.split(',')
89 .map((effort) => effort.trim())
90 .filter(Boolean)
91 const cannotDisable =
92 /cannot be disabled|cannot be turned off|thinking is always on/.test(note)
93 const canDisable = /\bcan be (?:disabled|turned off)\b/.test(note)
94 const mandatory = cannotDisable ? true : canDisable ? false : null
95 const named = efforts && efforts.length > 0 ? efforts : undefined
96 // Adaptive cards name the levels after "configurable —". Keep the mode
97 // and store those levels; a note with no list still has no efforts.
98 if (/adaptive/.test(note)) {
99 return {
100 mode: 'adaptive',
101 mandatory,
102 ...(named ? { efforts: named } : {}),
103 }
104 }
105 if (named) {
106 return {
107 mode: 'effort',
108 mandatory,
109 efforts: named,
110 }
111 }
112 return null
114​
115const EFFORT_LEVELS = [
116 'none',
117 'minimal',
118 'low',
119 'medium',
120 'high',
121 'xhigh',
122 'max',
124​
125/**
126 * A card whose Reasoning bullet is only `Supported` sometimes names the
127 * levels under `**Reasoning effort**`. Adaptive notes with no level list
128 * stay as the bullet parsed them.
129 */
130function reasoningEffortProse(markdown: string): ModelReasoning | null {
131 const prose = markdown.replace(/```[\s\S]*?```/g, '')
132 const honored: ModelReasoning | null =
133 /^\+\s+\*\*Reasoning mode\*\*\s+[—-]\s+Reasoning effort is honored on both the Chat Completions and Responses APIs\b/m.test(
134 prose,
135 )
136 ? { mode: 'effort', mandatory: null }
137 : null
138 const block = prose.match(
139 /\*\*Reasoning effort\*\*([\s\S]*?)(?:\n\*\*|\n## |\n### |$)/,
140 )?.[1]
141 if (!block) return honored
142 const declared = block.match(
143 /(?:Set reasoning effort to|(?:You can )?configure effort through[^:]*:)\s*([^\n]+)/i,
144 )?.[1]
145 if (!declared) return honored
146 const efforts: Array<string> = []
147 for (const match of declared.matchAll(
148 /`(?:\{[^`]*?"effort"\s*:\s*"([a-z]+)"[^`]*|"([a-z]+)"|([a-z]+))`/g,
149 )) {
150 const level = match[1] ?? match[2] ?? match[3]
151 if (level && EFFORT_LEVELS.includes(level) && !efforts.includes(level)) {
152 efforts.push(level)
153 }
154 }
155 if (efforts.length < 2) return honored
156 const cannot = /cannot be disabled|cannot be turned off/.test(block)
157 const can = /\bcan be (?:disabled|turned off)\b|\(disables reasoning\)/.test(
158 block,
159 )
160 return {
161 mode: 'effort',
162 mandatory: cannot ? true : can ? false : null,
163 efforts,
164 }
166​
167/** Ticked feature labels state capabilities; a reasoning tick names no control. */
168function cardFlags(
169 markdown: string,
170 reasoningOn: boolean,
171): Array<string> | null {
172 const flags: Array<string> = []
173 if (reasoningOn) flags.push('reasoning')
174 const seen = new Set<string>(flags)
175 const parts = markdown.split(/icon-(yes|no)\.png/i)
176 for (let index = 1; index < parts.length; index += 2) {
177 if (parts[index]?.toLowerCase() !== 'yes') continue
178 const label = (parts[index + 1] ?? '').split(/<br|\n|icon-/i)[0] ?? ''
179 if (/\[Reasoning\]/i.test(label) && !seen.has('reasoning')) {
180 seen.add('reasoning')
181 flags.push('reasoning')
182 }
183 if (/client-side tool calling/i.test(label) && !seen.has('tools')) {
184 seen.add('tools')
185 flags.push('tools')
186 }
187 if (/structured outputs?/i.test(label) && !seen.has('structured_outputs')) {
188 seen.add('structured_outputs')
189 flags.push('structured_outputs')
190 }
191 }
192 return flags.length > 0 ? flags : null
194​
195interface CardTables {
196 input: Array<string>
197 output: Array<string>
198 converse: boolean
200​
201/** Labels with a green tick in one table cell. */
202function ticked(cell: string | undefined): Array<string> {
203 if (!cell?.includes(YES)) return []
204 const label = cell.slice(cell.lastIndexOf(')') + 1).trim()
205 return label ? [label] : []
207​
208function modalityName(label: string): string {
209 const name = label.toLowerCase()
210 return name === 'speech' ? 'audio' : name
212​
213function cardTables(rows: Array<Array<string>>): CardTables {
214 const input = new Set<string>()
215 const output = new Set<string>()
216 let converse = false
217 const head = rows.findIndex((row) =>
218 /^\*\*input modalities\*\*$/i.test(row[0] ?? ''),
219 )
220 const width = rows[head]?.length
221 for (const row of rows.slice(head + 1)) {
222 if (head < 0 || row.length !== width || row[0]?.startsWith('**')) break
223 for (const label of ticked(row[0])) input.add(modalityName(label))
224 for (const label of ticked(row[1])) output.add(modalityName(label))
225 // Newer cards list APIs in the third column of the same table.
226 if (ticked(row[2]).includes('Converse')) converse = true
227 }
228 // Older cards: an API table per endpoint; the first is bedrock-runtime.
229 const apis = rows.findIndex((row) => row.includes('**Converse**'))
230 const column = rows[apis]?.indexOf('**Converse**') ?? -1
231 if (rows[apis + 1]?.[column]?.includes(YES)) converse = true
232 return { input: [...input], output: [...output], converse }
234​
235function activityOf(output: Array<string>): Activity | null {
236 if (output.includes('text')) return 'chat'
237 if (output.includes('embedding')) return 'embeddings'
238 for (const activity of ['image', 'video', 'audio'] as const) {
239 if (output.includes(activity)) return activity
240 }
241 return null
243​
244interface Quote {
245 label: string
246 rates: Record<string, number>
248​
249/**
250 * A bare "cache write" column takes the one TTL the card names. GPT-6
251 * headers omit the duration; the prompt-caching section says `ttl` `30m`
252 * is the only one. No TTL mentioned keeps the 5-minute lever. Two
253 * different TTLs have no single lever.
254 */
255function proseWriteLever(markdown: string): string | null {
256 const found = new Set<'5m' | '1h' | 'other'>()
257 const ttls = /ttl\b[^.\n]{0,80}?(\d+)\s*(m|h|min(?:ute)?s?|hours?)\b/gi
258 for (const match of markdown.matchAll(ttls)) {
259 const n = match[1]
260 const unit = match[2]?.toLowerCase()
261 if (!n || !unit) continue
262 if (n === '5' && unit.startsWith('m')) found.add('5m')
263 else if (n === '1' && unit.startsWith('h')) found.add('1h')
264 else found.add('other')
265 }
266 if (found.size === 0) return 'cache_write_tokens'
267 if (found.size > 1) return null
268 if (found.has('5m')) return 'cache_write_tokens'
269 if (found.has('1h')) return 'cache_write_1h_tokens'
270 return null
272​
273function lever(header: string, markdown: string): string | null {
274 const name = header.replace(/\*/g, '').toLowerCase()
275 if (name.includes('cache read')) return 'cache_read_tokens'
276 if (name.includes('cache write')) {
277 if (cacheWriteNamesDuration(name)) return cacheWriteLever(name)
278 return proseWriteLever(markdown)
279 }
280 if (name === 'input') return 'input_tokens'
281 if (name === 'output') return 'output_tokens'
282 return null
284​
285/** Rows of a `| **Inference option** | **Input** | … |` table. */
286function quotes(block: string, markdown: string): Array<Quote> {
287 const rows = tableRows(block)
288 const head = rows.find((row) => row[0] === '**Inference option**')
289 if (!head) return []
290 const out: Array<Quote> = []
291 for (const row of rows) {
292 if (row === head) continue
293 const rates: Record<string, number> = {}
294 row.forEach((cell, index) => {
295 const key = lever(head[index] ?? '', markdown)
296 const dollars = cell.match(/^\$(\d+(?:\.\d+)?)$/)?.[1]
297 if (key && cell.includes('$') && dollars === undefined) {
298 throw new Error('amazon-bedrock model card pricing: unreadable quote')
299 }
300 if (key && dollars) rates[key] = Number(dollars) / 1e6
301 })
302 if (
303 row.some((cell) => cell.includes('$')) &&
304 (!('input_tokens' in rates) || !('output_tokens' in rates))
305 ) {
306 throw new Error('amazon-bedrock model card pricing: unreadable quote')
307 }
308 if ('input_tokens' in rates && 'output_tokens' in rates) {
309 out.push({ label: row[0] ?? '', rates })
310 }
311 }
312 return out
314​
315/** Ultrafast, priority, flex, batch, and GovCloud are not the standard rate. */
316function skippedPriceHeading(heading: string): boolean {
317 return /ultrafast|priority|flex|batch|govcloud/i.test(heading)
319​
320function standardShort(heading: string): boolean {
321 return /commercial regions/i.test(heading) && /short context/i.test(heading)
323​
324const inRegion = (all: Array<Quote>) =>
325 all.find((quote) => /in-region|regional/i.test(quote.label))
326​
327const sameRates = (a: Quote, b: Quote) =>
328 JSON.stringify(Object.entries(a.rates).sort()) ===
329 JSON.stringify(Object.entries(b.rates).sort())
330​
331export interface BedrockCardPrice {
332 base: Record<string, number>
333 tiers: Array<TokenRateTier>
334 /** Every published inference option bills the in-Region rate. */
335 uniform: boolean
337​
338/**
339 * Standard-tier commercial price of the base model id: the in-Region row.
340 * Null when the card names no dollar amount, quotes a unit other than one
341 * million tokens, or prices only cross-Region profiles — those bill a
342 * different rate than the id this row is keyed on.
343 */
344export function bedrockCardPrice(
345 markdown: string,
346 scope: 'regional' | 'global' = 'regional',
347): BedrockCardPrice | null {
348 const full = markdownSection(markdown, 'Pricing')
349 if (!/per 1 million tokens/.test(full)) return null
350 // GovCloud (US) republishes the same table at a different rate. The
351 // commercial block is the standard price; a GovCloud-only card stays.
352 const beforeGov = full.split('**AWS GovCloud')[0] ?? full
353 const section = quotes(beforeGov, markdown).length > 0 ? beforeGov : full
354 const blocks = section.split(/\n### /)
355 let baseBlock: string | undefined
356 for (const [index, block] of blocks.entries()) {
357 if (quotes(block, markdown).length === 0) continue
358 const heading = block.split('\n')[0] ?? ''
359 if (skippedPriceHeading(heading)) continue
360 // A headingless table (Grok) is already the commercial rate. A ###
361 // block has to be the standard short-context rate; Ultrafast uses
362 // the same "Commercial Regions, short context" words.
363 if (index > 0 && !standardShort(heading)) return null
364 baseBlock = block
365 break
366 }
367 if (baseBlock === undefined) return null
368 const baseQuotes = quotes(baseBlock, markdown)
369 const pick = (items: Array<Quote>) =>
370 scope === 'global'
371 ? items.find((quote) => /global/i.test(quote.label))
372 : inRegion(items)
373 const base = pick(baseQuotes)
374 if (!base) return null
375 let uniform = baseQuotes.every((quote) => sameRates(quote, base))
376 const tiers: Array<TokenRateTier> = []
377 for (const block of blocks) {
378 const heading = block.split('\n')[0] ?? ''
379 // GovCloud's long-context table is a #### inside the ### GovCloud
380 // block. Match the ### line only, or that table becomes the tier.
381 if (skippedPriceHeading(heading)) continue
382 const over = heading.match(
383 /long context \(more than ([\d.,]+\s*[KM]?) input tokens\)/i,
384 )
385 if (!over?.[1]) continue
386 const longQuotes = quotes(block, markdown)
387 const long = pick(longQuotes)
388 const minPromptTokens = tokenCount(over[1])
389 // A long-context table we cannot read would underprice long prompts.
390 if (!long || minPromptTokens === null) {
391 throw new Error(
392 'amazon-bedrock model card pricing: unreadable long-context tier',
393 )
394 }
395 uniform &&= longQuotes.every((quote) => sameRates(quote, long))
396 tiers.push({ minPromptTokens, rates: long.rates })
397 }
398 return { base: base.rates, tiers, uniform }
400​
401/** Profiles explicitly named by the provider's own programmatic-access table. */
402export function parseBedrockProfileRows(
403 markdown: string,
404 source: { url: string; hash: string; extractedAt: string },
405): Array<ModelInfo> {
406 const base = parseBedrockCard(markdown, source)
407 if (!base) return []
408 const runtimeIds = new Set(bedrockCardRuntimeIds(markdown))
409 const supportsConverse =
410 base.activity === 'chat' && cardTables(tableRows(markdown)).converse
411 const ids = new Set(
412 tableRows(markdown)
413 .filter(
414 (row) =>
415 row.length === 5 && /^bedrock-(runtime|mantle)$/.test(row[0] ?? ''),
416 )
417 .flatMap((row) => [
418 ...(row[3]?.match(MODEL_ID) ?? []),
419 ...(row[4]?.match(MODEL_ID) ?? []),
420 ]),
421 )
422 return [...ids]
423 .filter((id) => id !== base.rawId)
424 .map((rawId) => {
425 const quote = rawId.startsWith('global.')
426 ? bedrockCardPrice(markdown, 'global')
427 : null
428 const pricing = quote
429 ? compileTokenCard(quote.base, quote.tiers, source)
430 : null
431 // Geo ids do not identify the billed AWS region. A US-region quote
432 // cannot be assigned to an EU profile. Preserve other explicitly sourced
433 // model facts, but never inherit the base model's price or aliases.
434 const sources = { ...base.factSources }
435 const converse = supportsConverse && runtimeIds.has(rawId)
436 delete sources.pricing
437 // A mantle-only base does not own the runtime route. Its explicitly
438 // declared runtime profiles still do; derive each row independently.
439 delete sources.schemaEndpointId
440 delete sources.requestMap
441 delete sources.requestMapFields
442 return {
443 ...base,
444 rawId,
445 requestMap: null,
446 schemaEndpointId: converse
447 ? endpointIdFromPath(BEDROCK_CONVERSE_PATH)
448 : null,
449 aliases: [],
450 pricing,
451 absent: pricing ? {} : { pricing: 'cleared' },
452 factSources: {
453 ...sources,
454 ...(converse
455 ? {
456 schemaEndpointId: {
457 derivation: 'docs-derived' as const,
458 sourceUrl: source.url,
459 sourceHash: source.hash,
460 path: 'Programmatic Access: bedrock-runtime profile ID; APIs supported: Converse',
461 },
462 }
463 : {}),
464 ...(pricing
465 ? tagDocsFacts({ pricing }, source.url, source.hash)
466 : {}),
467 },
468 }
469 })
471​
472/** One card → a catalog row, or null when it states no model id. */
473export function parseBedrockCard(
474 markdown: string,
475 source: { url: string; hash: string; extractedAt: string },
476): ModelInfo | null {
477 const rows = tableRows(markdown)
478 const access = rows.filter(
479 (row) =>
480 row.length === 5 && /^bedrock-(runtime|mantle)$/.test(row[0] ?? ''),
481 )
482 const baseIds = access.flatMap((row) => row[1]?.match(MODEL_ID) ?? [])
483 const rawId = baseIds[0]
484 if (!rawId) return null
485 const price = bedrockCardPrice(markdown)
486 // Profile ids are distinct rows, even when today's rates happen to agree.
487 const aliases = [...new Set(baseIds)].filter((id) => id !== rawId)
488​
489 const tables = cardTables(rows)
490 const activity = activityOf(tables.output)
491 const reasoningText = field(markdown, 'Reasoning')
492 const reasoning =
493 bedrockReasoning(reasoningText) ?? reasoningEffortProse(markdown)
494 const converse =
495 activity === 'chat' &&
496 tables.converse &&
497 bedrockCardRuntimeIds(markdown).includes(rawId)
498 const info: ModelInfo = {
499 rawId,
500 displayName: markdown.match(/^# (.+)$/m)?.[1]?.trim() ?? null,
501 activity,
502 contextWindow: tokenCount(field(markdown, 'Context window')),
503 maxOutput: tokenCount(field(markdown, 'Max output tokens')),
504 modalities:
505 tables.input.length > 0 || tables.output.length > 0
506 ? { input: tables.input, output: tables.output }
507 : null,
508 pricing: price ? compileTokenCard(price.base, price.tiers, source) : null,
509 capabilities: cardFlags(
510 markdown,
511 reasoningText?.startsWith('Supported') === true || reasoning != null,
512 ),
513 reasoning,
514 requestMap: null,
515 schemaEndpointId: converse
516 ? endpointIdFromPath(BEDROCK_CONVERSE_PATH)
517 : null,
518 aliases,
519 deprecated: field(markdown, 'Model lifecycle') === 'Legacy',
520 releasedAt: launchDay(field(markdown, 'Model launch date')),
521 }
522 info.factSources = {
523 ...tagDocsFacts(info, source.url, source.hash),
524 ...(converse
525 ? {
526 schemaEndpointId: {
527 derivation: 'docs-derived' as const,
528 sourceUrl: source.url,
529 sourceHash: source.hash,
530 path: 'Programmatic Access: bedrock-runtime model ID; APIs supported: Converse',
531 },
532 }
533 : {}),
534 }
535 return info
537​
538/** Exact IDs from the card's own runtime access row, not prefix aliases. */
539export function bedrockCardRuntimeIds(markdown: string): Array<string> {
540 const rows = tableRows(
541 markdownSection(
542 markdown.replace(/```[\s\S]*?```/g, ''),
543 'Programmatic Access',
544 ),
545 )
546 const runtime = rows.filter((row) => row[0] === 'bedrock-runtime')
547 if (!runtime.length) return []
548 const header = rows[0]?.map((cell) => cell.replace(/\*/g, '')) ?? []
549 const columns = header.flatMap((cell, index) =>
550 /\b(?:model|inference) id\b/i.test(cell) ? [index] : [],
551 )
552 if (!columns.length || runtime.some((row) => row.length !== header.length))
553 throw new Error('amazon-bedrock card: unreadable runtime access table')
554 return [
555 ...new Set(
556 runtime.flatMap((row) =>
557 columns.flatMap((index) => row[index]?.match(MODEL_ID) ?? []),
558 ),
559 ),
560 ]
562​
563export async function bedrockCardListing(
564 kv?: KVNamespace,
565): Promise<{ models: Array<ModelInfo>; groups: Array<BedrockCardOwnedGroup> }> {
566 // The previous catalog cache did not store source-owned profile bindings.
567 return cachedDocs(
568 kv,
569 `${BEDROCK_CARDS_URL}#card-owned-thinking-v2`,
570 async () => {
571 const slugs = bedrockCardSlugs(
572 await fetchText(BEDROCK_CARDS_URL, DOCS_INIT),
573 )
574 // ponytail: one fetch per card (~135) on a six-hourly cache miss, out of
575 // the poll invocation's shared 1,000 subrequests. Move Bedrock to its own
576 // cron if the poll starts exhausting the budget.
577 const parsed = await mapConcurrent(slugs, 6, async (slug) => {
578 const url = `${DOCS}${slug}.md`
579 const markdown = await fetchText(url, DOCS_INIT)
580 const source = {
581 url,
582 hash: await sha256Text(markdown),
583 extractedAt: new Date().toISOString(),
584 }
585 return {
586 model: parseBedrockCard(markdown, source),
587 profiles: parseBedrockProfileRows(markdown, source),
588 runtimeRowIds: bedrockCardRuntimeIds(markdown),
589 }
590 })
591 const groups: Array<BedrockCardOwnedGroup> = parsed.flatMap(
592 ({ model, profiles, runtimeRowIds }) =>
593 model
594 ? [
595 {
596 modelName: model.displayName ?? null,
597 runtimeRowIds,
598 baseIds: [model.rawId, ...(model.aliases ?? [])],
599 rowIds: [
600 model.rawId,
601 ...profiles.map((profile) => profile.rawId),
602 ],
603 },
604 ]
605 : [],
606 )
607 const byId = new Map<string, ModelInfo>()
608 const profileById = new Map<string, ModelInfo>()
609 for (const { model, profiles } of parsed) {
610 for (const profile of profiles) {
611 if (!profileById.has(profile.rawId))
612 profileById.set(profile.rawId, profile)
613 }
614 if (model && !byId.has(model.rawId)) byId.set(model.rawId, model)
615 }
616 assertParsed(byId, 'amazon-bedrock model cards')
617 // The poll marks unlisted rows removed. A card layout change that drops
618 // most ids must fail the poll, not shrink the catalog.
619 if (byId.size < slugs.length * 0.8) {
620 throw new Error(
621 `amazon-bedrock model cards: ${String(byId.size)} of ${String(slugs.length)} cards state a model id`,
622 )
623 }
624 const models: Array<ModelInfo> = [...byId.values()].map((model) => ({
625 ...model,
626 aliases: (model.aliases ?? []).filter((id) => !byId.has(id)),
627 }))
628 const book = await fetchBedrockPriceBook()
629 for (const model of models) {
630 if (model.pricing != null) continue
631 const hit = lookupBedrockPrice(
632 book,
633 model.rawId,
634 model.displayName ?? null,
635 )
636 if (!hit) continue
637 const pricing = compileTokenCard(hit.rates, [], {
638 url: hit.url,
639 hash: hit.hash,
640 extractedAt: new Date().toISOString(),
641 })
642 if (!pricing) continue
643 model.pricing = pricing
644 model.factSources = {
645 ...model.factSources,
646 ...tagDocsFacts({ pricing }, hit.url, hit.hash),
647 }
648 }
649 for (const profile of profileById.values()) {
650 if (byId.has(profile.rawId)) continue
651 if (profile.pricing == null && profile.rawId.startsWith('global.')) {
652 const rates = book.globalPageByName?.get(
653 bedrockNameKey(profile.displayName ?? ''),
654 )
655 if (rates) {
656 const pricing = compileTokenCard(rates, [], {
657 url: BEDROCK_PRICING_PAGE_URL,
658 hash: book.pageHash,
659 extractedAt: new Date().toISOString(),
660 })
661 if (pricing) {
662 profile.pricing = pricing
663 profile.absent = {}
664 profile.factSources = {
665 ...profile.factSources,
666 ...tagDocsFacts(
667 { pricing },
668 BEDROCK_PRICING_PAGE_URL,
669 book.pageHash,
670 ),
671 }
672 }
673 }
674 }
675 models.push(profile)
676 }
677 return { models, groups }
678 },
679 )