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

anthropic-pricing.ts

117 lines4.0 KB

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'],
35​
36function lever(heading: string): string | null {
37 const normalized = heading.trim().toLowerCase()
38 return COLUMN_LEVERS.find(([match]) => match.test(normalized))?.[1] ?? null
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
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
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 cached: typeof cachedDocs = cachedDocs,
91): Promise<(displayName: string | null | undefined) => PricedFacts> {
92 const doc = await cached(kv, ANTHROPIC_PRICING_URL, async () => {
93 const markdown = await fetchText(ANTHROPIC_PRICING_URL)
94 const parsed = parseAnthropicPricing(markdown)
95 assertParsed(parsed, 'anthropic pricing page')
96 return {
97 rates: Object.fromEntries(parsed),
98 hash: await sha256Text(markdown),
99 extractedAt: new Date().toISOString(),
100 }
101 })
102 return (displayName) => {
103 const rates = doc.rates[(displayName ?? '').trim().toLowerCase()]
104 const pricing = rates
105 ? compileTokenCard(rates, [], {
106 url: ANTHROPIC_PRICING_URL,
107 hash: doc.hash,
108 extractedAt: doc.extractedAt,
109 })
110 : null
111 if (!pricing) return {}
112 return {
113 pricing,
114 factSources: tagDocsFacts({ pricing }, ANTHROPIC_PRICING_URL, doc.hash),
115 }
116 }