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

bedrock-cards.ts

688 lines24.2 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(
329 Object.entries(a.rates).sort(([aKey], [bKey]) =>
330 aKey < bKey ? -1 : aKey > bKey ? 1 : 0,
331 ),
332 ) ===
333 JSON.stringify(
334 Object.entries(b.rates).sort(([aKey], [bKey]) =>
335 aKey < bKey ? -1 : aKey > bKey ? 1 : 0,
336 ),
337 )
338​
339export interface BedrockCardPrice {
340 base: Record<string, number>
341 tiers: Array<TokenRateTier>
342 /** Every published inference option bills the in-Region rate. */
343 uniform: boolean
345​
346/**
347 * Standard-tier commercial price of the base model id: the in-Region row.
348 * Null when the card names no dollar amount, quotes a unit other than one
349 * million tokens, or prices only cross-Region profiles — those bill a
350 * different rate than the id this row is keyed on.
351 */
352export function bedrockCardPrice(
353 markdown: string,
354 scope: 'regional' | 'global' = 'regional',
355): BedrockCardPrice | null {
356 const full = markdownSection(markdown, 'Pricing')
357 if (!/per 1 million tokens/.test(full)) return null
358 // GovCloud (US) republishes the same table at a different rate. The
359 // commercial block is the standard price; a GovCloud-only card stays.
360 const beforeGov = full.split('**AWS GovCloud')[0] ?? full
361 const section = quotes(beforeGov, markdown).length > 0 ? beforeGov : full
362 const blocks = section.split(/\n### /)
363 let baseBlock: string | undefined
364 for (const [index, block] of blocks.entries()) {
365 if (quotes(block, markdown).length === 0) continue
366 const heading = block.split('\n')[0] ?? ''
367 if (skippedPriceHeading(heading)) continue
368 // A headingless table (Grok) is already the commercial rate. A ###
369 // block has to be the standard short-context rate; Ultrafast uses
370 // the same "Commercial Regions, short context" words.
371 if (index > 0 && !standardShort(heading)) return null
372 baseBlock = block
373 break
374 }
375 if (baseBlock === undefined) return null
376 const baseQuotes = quotes(baseBlock, markdown)
377 const pick = (items: Array<Quote>) =>
378 scope === 'global'
379 ? items.find((quote) => /global/i.test(quote.label))
380 : inRegion(items)
381 const base = pick(baseQuotes)
382 if (!base) return null
383 let uniform = baseQuotes.every((quote) => sameRates(quote, base))
384 const tiers: Array<TokenRateTier> = []
385 for (const block of blocks) {
386 const heading = block.split('\n')[0] ?? ''
387 // GovCloud's long-context table is a #### inside the ### GovCloud
388 // block. Match the ### line only, or that table becomes the tier.
389 if (skippedPriceHeading(heading)) continue
390 const over = heading.match(
391 /long context \(more than ([\d.,]+\s*[KM]?) input tokens\)/i,
392 )
393 if (!over?.[1]) continue
394 const longQuotes = quotes(block, markdown)
395 const long = pick(longQuotes)
396 const minPromptTokens = tokenCount(over[1])
397 // A long-context table we cannot read would underprice long prompts.
398 if (!long || minPromptTokens === null) {
399 throw new Error(
400 'amazon-bedrock model card pricing: unreadable long-context tier',
401 )
402 }
403 uniform &&= longQuotes.every((quote) => sameRates(quote, long))
404 tiers.push({ minPromptTokens, rates: long.rates })
405 }
406 return { base: base.rates, tiers, uniform }
408​
409/** Profiles explicitly named by the provider's own programmatic-access table. */
410export function parseBedrockProfileRows(
411 markdown: string,
412 source: { url: string; hash: string; extractedAt: string },
413): Array<ModelInfo> {
414 const base = parseBedrockCard(markdown, source)
415 if (!base) return []
416 const runtimeIds = new Set(bedrockCardRuntimeIds(markdown))
417 const supportsConverse =
418 base.activity === 'chat' && cardTables(tableRows(markdown)).converse
419 const ids = new Set(
420 tableRows(markdown)
421 .filter(
422 (row) =>
423 row.length === 5 && /^bedrock-(runtime|mantle)$/.test(row[0] ?? ''),
424 )
425 .flatMap((row) => [
426 ...(row[3]?.match(MODEL_ID) ?? []),
427 ...(row[4]?.match(MODEL_ID) ?? []),
428 ]),
429 )
430 return [...ids]
431 .filter((id) => id !== base.rawId)
432 .map((rawId) => {
433 const quote = rawId.startsWith('global.')
434 ? bedrockCardPrice(markdown, 'global')
435 : null
436 const pricing = quote
437 ? compileTokenCard(quote.base, quote.tiers, source)
438 : null
439 // Geo ids do not identify the billed AWS region. A US-region quote
440 // cannot be assigned to an EU profile. Preserve other explicitly sourced
441 // model facts, but never inherit the base model's price or aliases.
442 const sources = { ...base.factSources }
443 const converse = supportsConverse && runtimeIds.has(rawId)
444 delete sources.pricing
445 // A mantle-only base does not own the runtime route. Its explicitly
446 // declared runtime profiles still do; derive each row independently.
447 delete sources.schemaEndpointId
448 delete sources.requestMap
449 delete sources.requestMapFields
450 return {
451 ...base,
452 rawId,
453 requestMap: null,
454 schemaEndpointId: converse
455 ? endpointIdFromPath(BEDROCK_CONVERSE_PATH)
456 : null,
457 aliases: [],
458 pricing,
459 absent: pricing ? {} : { pricing: 'cleared' },
460 factSources: {
461 ...sources,
462 ...(converse
463 ? {
464 schemaEndpointId: {
465 derivation: 'docs-derived' as const,
466 sourceUrl: source.url,
467 sourceHash: source.hash,
468 path: 'Programmatic Access: bedrock-runtime profile ID; APIs supported: Converse',
469 },
470 }
471 : {}),
472 ...(pricing
473 ? tagDocsFacts({ pricing }, source.url, source.hash)
474 : {}),
475 },
476 }
477 })
479​
480/** One card → a catalog row, or null when it states no model id. */
481export function parseBedrockCard(
482 markdown: string,
483 source: { url: string; hash: string; extractedAt: string },
484): ModelInfo | null {
485 const rows = tableRows(markdown)
486 const access = rows.filter(
487 (row) =>
488 row.length === 5 && /^bedrock-(runtime|mantle)$/.test(row[0] ?? ''),
489 )
490 const baseIds = access.flatMap((row) => row[1]?.match(MODEL_ID) ?? [])
491 const rawId = baseIds[0]
492 if (!rawId) return null
493 const price = bedrockCardPrice(markdown)
494 // Profile ids are distinct rows, even when today's rates happen to agree.
495 const aliases = [...new Set(baseIds)].filter((id) => id !== rawId)
496​
497 const tables = cardTables(rows)
498 const activity = activityOf(tables.output)
499 const reasoningText = field(markdown, 'Reasoning')
500 const reasoning =
501 bedrockReasoning(reasoningText) ?? reasoningEffortProse(markdown)
502 const converse =
503 activity === 'chat' &&
504 tables.converse &&
505 bedrockCardRuntimeIds(markdown).includes(rawId)
506 const info: ModelInfo = {
507 rawId,
508 displayName: markdown.match(/^# (.+)$/m)?.[1]?.trim() ?? null,
509 activity,
510 contextWindow: tokenCount(field(markdown, 'Context window')),
511 maxOutput: tokenCount(field(markdown, 'Max output tokens')),
512 modalities:
513 tables.input.length > 0 || tables.output.length > 0
514 ? { input: tables.input, output: tables.output }
515 : null,
516 pricing: price ? compileTokenCard(price.base, price.tiers, source) : null,
517 capabilities: cardFlags(
518 markdown,
519 reasoningText?.startsWith('Supported') === true || reasoning != null,
520 ),
521 reasoning,
522 requestMap: null,
523 schemaEndpointId: converse
524 ? endpointIdFromPath(BEDROCK_CONVERSE_PATH)
525 : null,
526 aliases,
527 deprecated: field(markdown, 'Model lifecycle') === 'Legacy',
528 releasedAt: launchDay(field(markdown, 'Model launch date')),
529 }
530 info.factSources = {
531 ...tagDocsFacts(info, source.url, source.hash),
532 ...(converse
533 ? {
534 schemaEndpointId: {
535 derivation: 'docs-derived' as const,
536 sourceUrl: source.url,
537 sourceHash: source.hash,
538 path: 'Programmatic Access: bedrock-runtime model ID; APIs supported: Converse',
539 },
540 }
541 : {}),
542 }
543 return info
545​
546/** Exact IDs from the card's own runtime access row, not prefix aliases. */
547export function bedrockCardRuntimeIds(markdown: string): Array<string> {
548 const rows = tableRows(
549 markdownSection(
550 markdown.replace(/```[\s\S]*?```/g, ''),
551 'Programmatic Access',
552 ),
553 )
554 const runtime = rows.filter((row) => row[0] === 'bedrock-runtime')
555 if (!runtime.length) return []
556 const header = rows[0]?.map((cell) => cell.replace(/\*/g, '')) ?? []
557 const columns = header.flatMap((cell, index) =>
558 /\b(?:model|inference) id\b/i.test(cell) ? [index] : [],
559 )
560 if (!columns.length || runtime.some((row) => row.length !== header.length))
561 throw new Error('amazon-bedrock card: unreadable runtime access table')
562 return [
563 ...new Set(
564 runtime.flatMap((row) =>
565 columns.flatMap((index) => row[index]?.match(MODEL_ID) ?? []),
566 ),
567 ),
568 ]
570​
571export async function bedrockCardListing(
572 kv?: KVNamespace,
573): Promise<{ models: Array<ModelInfo>; groups: Array<BedrockCardOwnedGroup> }> {
574 // The previous catalog cache did not store source-owned profile bindings.
575 return cachedDocs(
576 kv,
577 `${BEDROCK_CARDS_URL}#card-owned-thinking-v2`,
578 async () => {
579 const slugs = bedrockCardSlugs(
580 await fetchText(BEDROCK_CARDS_URL, DOCS_INIT),
581 )
582 // ponytail: one fetch per card (~135) on a six-hourly cache miss, out of
583 // the poll invocation's shared 1,000 subrequests. Move Bedrock to its own
584 // cron if the poll starts exhausting the budget.
585 const parsed = await mapConcurrent(slugs, 6, async (slug) => {
586 const url = `${DOCS}${slug}.md`
587 const markdown = await fetchText(url, DOCS_INIT)
588 const source = {
589 url,
590 hash: await sha256Text(markdown),
591 extractedAt: new Date().toISOString(),
592 }
593 return {
594 model: parseBedrockCard(markdown, source),
595 profiles: parseBedrockProfileRows(markdown, source),
596 runtimeRowIds: bedrockCardRuntimeIds(markdown),
597 }
598 })
599 const groups: Array<BedrockCardOwnedGroup> = parsed.flatMap(
600 ({ model, profiles, runtimeRowIds }) =>
601 model
602 ? [
603 {
604 modelName: model.displayName ?? null,
605 runtimeRowIds,
606 baseIds: [model.rawId, ...(model.aliases ?? [])],
607 rowIds: [
608 model.rawId,
609 ...profiles.map((profile) => profile.rawId),
610 ],
611 },
612 ]
613 : [],
614 )
615 const byId = new Map<string, ModelInfo>()
616 const profileById = new Map<string, ModelInfo>()
617 for (const { model, profiles } of parsed) {
618 for (const profile of profiles) {
619 if (!profileById.has(profile.rawId))
620 profileById.set(profile.rawId, profile)
621 }
622 if (model && !byId.has(model.rawId)) byId.set(model.rawId, model)
623 }
624 assertParsed(byId, 'amazon-bedrock model cards')
625 // The poll marks unlisted rows removed. A card layout change that drops
626 // most ids must fail the poll, not shrink the catalog.
627 if (byId.size < slugs.length * 0.8) {
628 throw new Error(
629 `amazon-bedrock model cards: ${String(byId.size)} of ${String(slugs.length)} cards state a model id`,
630 )
631 }
632 const models: Array<ModelInfo> = [...byId.values()].map((model) => ({
633 ...model,
634 aliases: (model.aliases ?? []).filter((id) => !byId.has(id)),
635 }))
636 const book = await fetchBedrockPriceBook()
637 for (const model of models) {
638 if (model.pricing != null) continue
639 const hit = lookupBedrockPrice(
640 book,
641 model.rawId,
642 model.displayName ?? null,
643 )
644 if (!hit) continue
645 const pricing = compileTokenCard(hit.rates, [], {
646 url: hit.url,
647 hash: hit.hash,
648 extractedAt: new Date().toISOString(),
649 })
650 if (!pricing) continue
651 model.pricing = pricing
652 model.factSources = {
653 ...model.factSources,
654 ...tagDocsFacts({ pricing }, hit.url, hit.hash),
655 }
656 }
657 for (const profile of profileById.values()) {
658 if (byId.has(profile.rawId)) continue
659 if (profile.pricing == null && profile.rawId.startsWith('global.')) {
660 const rates = book.globalPageByName?.get(
661 bedrockNameKey(profile.displayName ?? ''),
662 )
663 if (rates) {
664 const pricing = compileTokenCard(rates, [], {
665 url: BEDROCK_PRICING_PAGE_URL,
666 hash: book.pageHash,
667 extractedAt: new Date().toISOString(),
668 })
669 if (pricing) {
670 profile.pricing = pricing
671 profile.absent = {}
672 profile.factSources = {
673 ...profile.factSources,
674 ...tagDocsFacts(
675 { pricing },
676 BEDROCK_PRICING_PAGE_URL,
677 book.pageHash,
678 ),
679 }
680 }
681 }
682 }
683 models.push(profile)
684 }
685 return { models, groups }
686 },
687 )