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

cohere-pricing.ts

166 lines5.9 KB

1/**
2 * Cohere token prices from cohere.com/pricing (issue #111). The legacy FAQ
3 * prices dated Command R rows (`Command R+ 08-2024 pricing is $2.50/1M …`).
4 * Undated "Command" and "Command-light" do not name an API id, so they get
5 * no card. Aya Expanse states one rate for 8B and 32B; only backtick ids on
6 * the Aya model page receive it.
7 *
8 * The generative tab is not in the rendered HTML, only in the page's data
9 * payload, as cards named by product ("Command R7B", per "1M tokens"). A
10 * card prices the one `Live` id the models overview dates under that name
11 * (`command-r7b-12-2024`); none or several means no card. The "Free" cards
12 * (Command A+, North Mini Code) state no token price.
13 */
14import { compileTokenCard } from '@modelschemas/rate-card'
15​
16import {
17 COHERE_MODELS_DOC_URL,
18 parseCohereModelTable,
19} from './cohere-model-docs.ts'
20import { tagDocsFacts } from './fact-sources.ts'
21import { assertParsed, cachedDocs } from './model-facts.ts'
22import { fetchText, sha256Text } from './types.ts'
23import type { ModelInfo } from './types.ts'
24​
25export const COHERE_PRICING_URL = 'https://cohere.com/pricing'
26export const COHERE_AYA_URL = 'https://docs.cohere.com/docs/aya-expanse.md'
27​
28const DATED_COMMAND =
29 /Command R(\+)? (\d{2}-\d{4}) pricing is \$([\d.]+)\/1M tokens for input and \$([\d.]+)\/1M tokens for output/g
30​
31const AYA_RATE =
32 /Aya Expanse models \(8B and 32B\) on the API are charged at \$([\d.]+)\/1M tokens for input and \$([\d.]+)\/1M tokens for output/
33​
34const CARD = /"modelName":"([A-Za-z0-9 ]+)","per":"1M tokens"/g
35​
36const CARD_PRICE =
37 /"pricings":\[\{"_key":"[^"]*","_type":"pricing","inputLabel":"Input","inputPrice":(\d+(?:\.\d+)?),"outputLabel":"Output","outputPrice":(\d+(?:\.\d+)?)\}\]/
38​
39function perMillion(amount: string): number {
40 return Number((Number(amount) / 1e6).toPrecision(12))
42​
43/** Product name, input and output dollars per 1M, from the data payload. */
44function pricingCards(pricingHtml: string): Array<[string, string, string]> {
45 const payload = pricingHtml.replace(/\\"/g, '"')
46 const cards: Array<[string, string, string]> = []
47 for (const match of payload.matchAll(CARD)) {
48 const start = match.index + match[0].length
49 const next = payload.indexOf('"modelName":"', start)
50 const price = CARD_PRICE.exec(
51 payload.slice(start, next < 0 ? undefined : next),
52 )
53 if (match[1] && price?.[1] && price[2]) {
54 cards.push([match[1], price[1], price[2]])
55 }
56 }
57 return cards
59​
60/**
61 * API id → per-token rates. `ayaMarkdown` is the Aya Expanse model page,
62 * `liveIds` the ids the models overview marks `Live`.
63 */
64export function parseCoherePricing(
65 pricingHtml: string,
66 ayaMarkdown: string,
67 liveIds: Array<string> = [],
68): Map<string, Record<string, number>> {
69 const text = pricingHtml
70 .replace(/<script[\s\S]*?<\/script>/gi, ' ')
71 .replace(/<[^>]+>/g, ' ')
72 .replace(/&amp;/g, '&')
73 .replace(/\s+/g, ' ')
74 const out = new Map<string, Record<string, number>>()
75 for (const match of text.matchAll(DATED_COMMAND)) {
76 const plus = match[1] === '+'
77 const date = match[2]
78 const input = match[3]
79 const output = match[4]
80 if (!date || !input || !output) continue
81 const id = plus ? `command-r-plus-${date}` : `command-r-${date}`
82 if (out.has(id)) continue
83 out.set(id, {
84 input_tokens: perMillion(input),
85 output_tokens: perMillion(output),
86 })
87 }
88 const aya = text.match(AYA_RATE)
89 if (aya?.[1] && aya[2]) {
90 const rates = {
91 input_tokens: perMillion(aya[1]),
92 output_tokens: perMillion(aya[2]),
93 }
94 const ids = [
95 ...ayaMarkdown.matchAll(/`(c4ai-aya-expanse-(?:8|32)b)`/g),
96 ].map((match) => match[1] ?? '')
97 for (const id of ids) {
98 if (id && !out.has(id)) out.set(id, rates)
99 }
100 }
101 for (const [name, input, output] of pricingCards(pricingHtml)) {
102 const dated = new RegExp(
103 `^${name.toLowerCase().replace(/ /g, '-')}-\\d{2}-\\d{4}$`,
104 )
105 const ids = liveIds.filter((id) => dated.test(id))
106 const id = ids.length === 1 ? ids[0] : undefined
107 if (!id || out.has(id) || Number(input) <= 0 || Number(output) <= 0) {
108 continue
109 }
110 out.set(id, {
111 input_tokens: perMillion(input),
112 output_tokens: perMillion(output),
113 })
114 }
115 return out
117​
118type PricedFacts = Pick<ModelInfo, 'pricing' | 'factSources'>
119​
120/** Card lookup by listed model id. Ids the pages do not price get nothing. */
121export async function cohereModelPricing(
122 kv?: KVNamespace,
123): Promise<(rawId: string) => PricedFacts> {
124 const doc = await cachedDocs(kv, COHERE_PRICING_URL, async () => {
125 const page = (url: string) =>
126 fetchText(url, { signal: AbortSignal.timeout(30_000) })
127 const [pricingHtml, ayaMarkdown, modelsMarkdown] = await Promise.all([
128 page(COHERE_PRICING_URL),
129 page(COHERE_AYA_URL),
130 page(COHERE_MODELS_DOC_URL),
131 ])
132 const liveIds = [...parseCohereModelTable(modelsMarkdown)]
133 .filter(([, row]) => row.live)
134 .map(([id]) => id)
135 const parsed = parseCoherePricing(pricingHtml, ayaMarkdown, liveIds)
136 assertParsed(parsed, 'cohere pricing page')
137 const ayaNamed = /Aya Expanse models \(8B and 32B\)/.test(
138 pricingHtml.replace(/<[^>]+>/g, ' '),
139 )
140 const ayaIds = [...parsed.keys()].filter((id) => id.startsWith('c4ai-aya-'))
141 if (ayaNamed && ayaIds.length === 0) {
142 throw new Error('cohere pricing page: Aya Expanse rate matched no API id')
143 }
144 return {
145 rates: Object.fromEntries(parsed),
146 hash: await sha256Text(
147 `${pricingHtml}\n${ayaMarkdown}\n${modelsMarkdown}`,
148 ),
149 extractedAt: new Date().toISOString(),
150 }
151 })
152 return (rawId) => {
153 const rates = doc.rates[rawId]
154 if (!rates) return {}
155 const pricing = compileTokenCard(rates, [], {
156 url: COHERE_PRICING_URL,
157 hash: doc.hash,
158 extractedAt: doc.extractedAt,
159 })
160 if (!pricing) return {}
161 return {
162 pricing,
163 factSources: tagDocsFacts({ pricing }, COHERE_PRICING_URL, doc.hash),
164 }
165 }