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 and tool-use (search, code execution) prices live in other sections
9 * and are not levers here. A model the table splits into "up to N tokens"
10 * and "over N tokens" rows (Claude Haiku 5.5, issue #481) is one card: the
11 * short row is the base, and the long row is a prompt-length tier at N.
12 * The tier fires when input plus cache reads and cache writes are over N,
13 * which is the prompt total `compileTokenCard` already sums, and it
14 * re-quotes the whole request. A split the table does not pair throws, so
15 * a short row is never stored on its own.
16 */
17import { compileTokenCard } from '@modelschemas/rate-card'
18import type { TokenRateTier } from '@modelschemas/rate-card'
19
20import { tagDocsFacts } from './fact-sources.ts'
21import {
22 assertParsed,
23 cachedDocs,
24 markdownSection,
25 markdownTableRows,
26} from './model-facts.ts'
27import { fetchText, sha256Text } from './types.ts'
28import type { ModelInfo } from './types.ts'
29import type { Fetcher } from './us-egress.ts'
30
31export const ANTHROPIC_PRICING_URL =
32 'https://platform.claude.com/docs/en/about-claude/pricing.md'
33
34/** Column heading → the lever it prices. Unlisted columns are ignored. */
35const COLUMN_LEVERS: Array<[RegExp, string]> = [
36 [/^base input/, 'input_tokens'],
37 [/^5m cache writes/, 'cache_write_tokens'],
38 [/^1h cache writes/, 'cache_write_1h_tokens'],
39 [/^cache hits/, 'cache_read_tokens'],
40 [/^output/, 'output_tokens'],
41]
42
43function lever(heading: string): string | null {
44 const normalized = heading.trim().toLowerCase()
45 return COLUMN_LEVERS.find(([match]) => match.test(normalized))?.[1] ?? null
46}
47
48/** `$12.50 / MTok` (footnote markers allowed) → USD per token. */
49function perToken(cell: string | undefined): number | null {
50 // The source markdown retains HTML superscripts on footnoted prices.
51 const value = cell?.replace(/<sup>\d+<\/sup>\s*$/, '').trim()
52 const amount = value?.match(/^\$([\d,]+(?:\.\d+)?)\s*\/\s*MTok\d*$/)?.[1]
53 return amount === undefined ? null : Number(amount.replace(/,/g, '')) / 1e6
54}
55
56/** One display name's base rates and any prompt-length re-quote. */
57export interface AnthropicModelRates {
58 rates: Record<string, number>
59 tiers: Array<TokenRateTier>
60}
61
62interface PendingRates {
63 base: Record<string, number> | null
64 long: Record<string, number> | null
65 /** Token count on an "up to" row, when that row was read. */
66 upTo: number | null
67 /** Token count on an "over" row, when that row was read. */
68 over: number | null
69}
70
71/**
72 * `(for prompts up to 100,000 tokens)` / `(for prompts over 100,000 tokens)`.
73 * Retirement links stay on the display name and are not a prompt band.
74 */
75function promptBand(name: string): {
76 key: string
77 upTo: number | null
78 over: number | null
79} {
80 const labeled =
81 /^(.*?)\s+\(for prompts (up to|over) ([\d,]+) tokens\)$/i.exec(name)
82 if (labeled?.[1] && labeled[2] && labeled[3]) {
83 const count = Number(labeled[3].replace(/,/g, ''))
84 if (!Number.isInteger(count) || count <= 0) {
85 throw new Error(
86 `anthropic pricing page: unreadable prompt-length row "${name}"`,
87 )
88 }
89 const over = labeled[2].toLowerCase() === 'over'
90 return {
91 key: labeled[1].trim().toLowerCase(),
92 upTo: over ? null : count,
93 over: over ? count : null,
94 }
95 }
96 if (/for prompts/i.test(name)) {
97 throw new Error(
98 `anthropic pricing page: unreadable prompt-length row "${name}"`,
99 )
100 }
101 return {
102 key: name
103 .replace(/\s*[([].*$/, '')
104 .trim()
105 .toLowerCase(),
106 upTo: null,
107 over: null,
108 }
109}
110
111function sameLevers(
112 left: Record<string, number>,
113 right: Record<string, number>,
114): boolean {
115 const leftKeys = Object.keys(left)
116 return (
117 leftKeys.length === Object.keys(right).length &&
118 leftKeys.every((key) => right[key] !== undefined)
119 )
120}
121
122/**
123 * Display name (lowercased) → per-token rates. The name cell carries
124 * markdown links for retired/limited models (`Claude Opus 4 ([retired…])`);
125 * only the plain name before them keys the row. Two rows that name the
126 * same model on either side of one prompt length collapse into one entry.
127 */
128export function parseAnthropicPricing(
129 markdown: string,
130): Map<string, AnthropicModelRates> {
131 const pending = new Map<string, PendingRates>()
132 let levers: Array<string | null> = []
133 for (const cells of markdownTableRows(
134 markdownSection(markdown, 'Model pricing'),
135 )) {
136 const [name = '', ...values] = cells
137 if (/^model$/i.test(name)) {
138 levers = values.map(lever)
139 continue
140 }
141 if (levers.length === 0) continue
142 const band = promptBand(name)
143 const rates: Record<string, number> = {}
144 values.forEach((cell, index) => {
145 const target = levers[index]
146 const rate = perToken(cell)
147 if (target && rate !== null) rates[target] = rate
148 })
149 if (!band.key || Object.keys(rates).length === 0) continue
150 const entry = pending.get(band.key) ?? {
151 base: null,
152 long: null,
153 upTo: null,
154 over: null,
155 }
156 const labeled = band.upTo !== null || band.over !== null
157 const stored = entry.base !== null || entry.long !== null
158 if (labeled !== (entry.upTo !== null || entry.over !== null) && stored) {
159 throw new Error(
160 `anthropic pricing page: ${band.key} prompt-length rows do not pair`,
161 )
162 }
163 if (band.upTo !== null) {
164 if (entry.upTo !== null) {
165 throw new Error(
166 `anthropic pricing page: ${band.key} prompt-length rows do not pair`,
167 )
168 }
169 entry.base = rates
170 entry.upTo = band.upTo
171 } else if (band.over !== null) {
172 if (entry.over !== null) {
173 throw new Error(
174 `anthropic pricing page: ${band.key} prompt-length rows do not pair`,
175 )
176 }
177 entry.long = rates
178 entry.over = band.over
179 } else if (entry.base === null) {
180 entry.base = rates
181 }
182 pending.set(band.key, entry)
183 }
184
185 const out = new Map<string, AnthropicModelRates>()
186 for (const [key, entry] of pending) {
187 const banded = entry.upTo !== null || entry.over !== null
188 if (!banded) {
189 if (entry.base) out.set(key, { rates: entry.base, tiers: [] })
190 continue
191 }
192 if (
193 !entry.base ||
194 !entry.long ||
195 entry.upTo === null ||
196 entry.over === null ||
197 entry.upTo !== entry.over ||
198 !sameLevers(entry.base, entry.long)
199 ) {
200 throw new Error(
201 `anthropic pricing page: ${key} prompt-length rows do not pair`,
202 )
203 }
204 out.set(key, {
205 rates: entry.base,
206 tiers: [{ minPromptTokens: entry.over, rates: entry.long }],
207 })
208 }
209 return out
210}
211
212type PricedFacts = Pick<ModelInfo, 'pricing' | 'factSources'>
213
214/** Card lookup by `display_name`; models off the table get nothing. */
215export async function anthropicModelPricing(
216 kv?: KVNamespace,
217 cached: typeof cachedDocs = cachedDocs,
218 fetcher: Fetcher = fetch,
219): Promise<(displayName: string | null | undefined) => PricedFacts> {
220 const doc = await cached(kv, ANTHROPIC_PRICING_URL, async () => {
221 const markdown = await fetchText(ANTHROPIC_PRICING_URL, undefined, fetcher)
222 const parsed = parseAnthropicPricing(markdown)
223 assertParsed(parsed, 'anthropic pricing page')
224 return {
225 rates: Object.fromEntries(parsed),
226 hash: await sha256Text(markdown),
227 extractedAt: new Date().toISOString(),
228 }
229 })
230 return (displayName) => {
231 const row = doc.rates[(displayName ?? '').trim().toLowerCase()]
232 const pricing = row
233 ? compileTokenCard(row.rates, row.tiers, {
234 url: ANTHROPIC_PRICING_URL,
235 hash: doc.hash,
236 extractedAt: doc.extractedAt,
237 })
238 : null
239 if (!pricing) return {}
240 return {
241 pricing,
242 factSources: tagDocsFacts({ pricing }, ANTHROPIC_PRICING_URL, doc.hash),
243 }
244 }
245}