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

moonshot-pricing.ts

112 lines3.8 KB

1/**
2 * Kimi prices from the international pricing page (issue #109). Amounts
3 * are USD per 1M tokens (`$0.16 / MTok`; the page states 1 MTok =
4 * 1,000,000 tokens). Columns are read by title (issue #484). A row is
5 * priced only when every price cell is a bare `$0.16 / MTok`, every title
6 * is one this knows, and the row has input, output and cache-hit prices,
7 * so a struck or footnoted price leaves its row unpriced, and a table
8 * whose first title is not `Model` or that has a title this does not know
9 * (a batch column) prices no row. `moonshotModelPricing` throws on a
10 * zero-row parse. The tables are read from the HTML page: its `.md`
11 * export renders them empty.
12 */
13import { compileTokenCard } from '@modelschemas/rate-card'
14​
15import { parseKimiDocTables } from './kimi-doc-tables.ts'
16import type { KimiDocTable } from './kimi-doc-tables.ts'
17import { assertParsed, cachedDocs } from './model-facts.ts'
18import { fetchText, sha256Text } from './types.ts'
19import type { ModelInfo } from './types.ts'
20​
21export const MOONSHOT_PRICING_URL = 'https://platform.kimi.ai/docs/pricing/chat'
22​
23export interface MoonshotRates {
24 input: number
25 output: number
26 cacheRead: number
27 cacheWrite?: number
28 cacheWrite1h?: number
30​
31/** Price column title → the rate it states. */
32const PRICE_COLUMNS: Record<string, keyof MoonshotRates> = {
33 Input: 'input',
34 Output: 'output',
35 'Cached Input': 'cacheRead',
36 '5m writes': 'cacheWrite',
37 '1h writes': 'cacheWrite1h',
39const ID_COLUMN = 'Model'
40​
41/** Model id → USD per million tokens. */
42export function parseMoonshotPricing(
43 tables: Array<KimiDocTable>,
44): Map<string, MoonshotRates> {
45 const out = new Map<string, MoonshotRates>()
46 for (const { titles, rows } of tables) {
47 if (
48 titles[0] !== ID_COLUMN ||
49 !titles
50 .slice(1)
51 .every((title) => title !== null && title in PRICE_COLUMNS)
52 ) {
53 continue
54 }
55 for (const [id, ...cells] of rows) {
56 if (!id?.startsWith('kimi-') || out.has(id)) continue
57 const rates: Partial<MoonshotRates> = {}
58 cells.forEach((cell, index) => {
59 const lever = PRICE_COLUMNS[titles[index + 1] ?? '']
60 const amount = cell?.match(/^\$(\d+(?:\.\d+)?) \/ MTok$/)?.[1]
61 if (lever && amount !== undefined) rates[lever] = Number(amount)
62 })
63 const { input, output, cacheRead } = rates
64 if (
65 cells.length !== titles.length - 1 ||
66 Object.keys(rates).length !== cells.length ||
67 input === undefined ||
68 output === undefined ||
69 cacheRead === undefined
70 ) {
71 continue
72 }
73 out.set(id, { ...rates, input, output, cacheRead })
74 }
75 }
76 return out
78​
79type PricedFacts = Pick<ModelInfo, 'pricing'>
80​
81export async function moonshotModelPricing(
82 kv?: KVNamespace,
83): Promise<(rawId: string) => PricedFacts> {
84 const doc = await cachedDocs(kv, MOONSHOT_PRICING_URL, async () => {
85 const tables = parseKimiDocTables(await fetchText(MOONSHOT_PRICING_URL))
86 const parsed = parseMoonshotPricing(tables)
87 assertParsed(parsed, 'moonshot pricing page')
88 return {
89 rates: Object.fromEntries(parsed),
90 // The tables, not the page: its HTML changes with every docs deploy.
91 hash: await sha256Text(JSON.stringify(tables)),
92 extractedAt: new Date().toISOString(),
93 }
94 })
95 return (rawId) => {
96 const row = doc.rates[rawId]
97 if (!row) return {}
98 const rates: Record<string, number> = {
99 input_tokens: row.input / 1e6,
100 output_tokens: row.output / 1e6,
101 cache_read_tokens: row.cacheRead / 1e6,
102 }
103 if (row.cacheWrite) rates.cache_write_tokens = row.cacheWrite / 1e6
104 if (row.cacheWrite1h) rates.cache_write_1h_tokens = row.cacheWrite1h / 1e6
105 const pricing = compileTokenCard(rates, [], {
106 url: MOONSHOT_PRICING_URL,
107 hash: doc.hash,
108 extractedAt: doc.extractedAt,
109 })
110 return pricing ? { pricing } : {}
111 }