Open History to see the last commit
1/**
2 * Claude prices from Anthropic's own pricing page (issue #61). The "Model
3 * pricing" section is one markdown table keyed by display name — the same
4 * string the Models API returns as `display_name` — with a `$x / MTok`
5 * column per lever. A parse of zero rows throws rather than nulling stored
6 * cards; a model the table does not name simply gets none.
7 *
8 * Batch, tool-use (search, code execution) and long-context premiums are
9 * priced elsewhere on the page and are not levers here: a card quotes the
10 * standard per-token rates.
11 */
12import { compileTokenCard } from '@modelschemas/rate-card'
13
14import { tagDocsFacts } from './fact-sources.ts'
15import {
16 assertParsed,
17 cachedDocs,
18 markdownSection,
19 markdownTableRows,
20} from './model-facts.ts'
21import { fetchText, sha256Text } from './types.ts'
22import type { ModelInfo } from './types.ts'
23
24export const ANTHROPIC_PRICING_URL =
25 'https://platform.claude.com/docs/en/about-claude/pricing.md'
26
27/** Column heading → the lever it prices. Unlisted columns are ignored. */
28const COLUMN_LEVERS: Array<[RegExp, string]> = [
29 [/^base input/, 'input_tokens'],
30 [/^5m cache writes/, 'cache_write_tokens'],
31 [/^1h cache writes/, 'cache_write_1h_tokens'],
32 [/^cache hits/, 'cache_read_tokens'],
33 [/^output/, 'output_tokens'],
34]
35
36function lever(heading: string): string | null {
37 const normalized = heading.trim().toLowerCase()
38 return COLUMN_LEVERS.find(([match]) => match.test(normalized))?.[1] ?? null
39}
40
41/** `$12.50 / MTok` (footnote markers allowed) → USD per token. */
42function perToken(cell: string | undefined): number | null {
43 // The source markdown retains HTML superscripts on footnoted prices.
44 const value = cell?.replace(/<sup>\d+<\/sup>\s*$/, '').trim()
45 const amount = value?.match(/^\$([\d,]+(?:\.\d+)?)\s*\/\s*MTok\d*$/)?.[1]
46 return amount === undefined ? null : Number(amount.replace(/,/g, '')) / 1e6
47}
48
49/**
50 * Display name (lowercased) → per-token rates. The name cell carries
51 * markdown links for retired/limited models (`Claude Opus 4 ([retired…])`);
52 * only the plain name before them keys the row.
53 */
54export function parseAnthropicPricing(
55 markdown: string,
56): Map<string, Record<string, number>> {
57 const out = new Map<string, Record<string, number>>()
58 let levers: Array<string | null> = []
59 for (const cells of markdownTableRows(
60 markdownSection(markdown, 'Model pricing'),
61 )) {
62 const [name = '', ...values] = cells
63 if (/^model$/i.test(name)) {
64 levers = values.map(lever)
65 continue
66 }
67 if (levers.length === 0) continue
68 const key = name
69 .replace(/\s*[([].*$/, '')
70 .trim()
71 .toLowerCase()
72 const rates: Record<string, number> = {}
73 values.forEach((cell, index) => {
74 const target = levers[index]
75 const rate = perToken(cell)
76 if (target && rate !== null) rates[target] = rate
77 })
78 if (key && Object.keys(rates).length > 0 && !out.has(key)) {
79 out.set(key, rates)
80 }
81 }
82 return out
83}
84
85type PricedFacts = Pick<ModelInfo, 'pricing' | 'factSources'>
86
87/** Card lookup by `display_name`; models off the table get nothing. */
88export async function anthropicModelPricing(
89 kv?: KVNamespace,
90): Promise<(displayName: string | null | undefined) => PricedFacts> {
91 const doc = await cachedDocs(kv, ANTHROPIC_PRICING_URL, async () => {
92 const markdown = await fetchText(ANTHROPIC_PRICING_URL)
93 const parsed = parseAnthropicPricing(markdown)
94 assertParsed(parsed, 'anthropic pricing page')
95 return {
96 rates: Object.fromEntries(parsed),
97 hash: await sha256Text(markdown),
98 extractedAt: new Date().toISOString(),
99 }
100 })
101 return (displayName) => {
102 const rates = doc.rates[(displayName ?? '').trim().toLowerCase()]
103 const pricing = rates
104 ? compileTokenCard(rates, [], {
105 url: ANTHROPIC_PRICING_URL,
106 hash: doc.hash,
107 extractedAt: doc.extractedAt,
108 })
109 : null
110 if (!pricing) return {}
111 return {
112 pricing,
113 factSources: tagDocsFacts({ pricing }, ANTHROPIC_PRICING_URL, doc.hash),
114 }
115 }
116}