Open History to see the last commit
1/**
2 * Command model pages (issue #447). The models overview links each Command
3 * model to its own page. The showcase's token rates and knowledge cutoff
4 * are stored. "Free until rate limits are reached" is an evaluation quota
5 * (20 req/min, 1,000 calls/month; production is sales or Model Vault), so
6 * it writes no card. The context-window cell is not copied: `GET /v1/models`
7 * `context_length` and this cell disagree (Command A+ is 436000 on the
8 * listing and 128,000 on the page), and neither source says which wins.
9 *
10 * A page that does not fetch throws. A token-price sentence that no longer
11 * matches writes no card.
12 */
13import { compileTokenCard } from '@modelschemas/rate-card'
14import type { RateCard } from '@modelschemas/rate-card'
15
16import { COHERE_MODELS_DOC_URL } from './cohere-model-docs.ts'
17import { tagDocsFacts } from './fact-sources.ts'
18import { cachedDocs } from './model-facts.ts'
19import { fetchText, sha256Text } from './types.ts'
20import type { ModelInfo } from './types.ts'
21
22const FAMILY =
23 /The Command family of models includes((?:\s*(?:and\s+)?\[[^\]]+\]\([^)]+\),?)+)/
24
25const FREE =
26 /For both trial keys and production keys, .+ is free until rate limits are reached\./
27
28const TOKEN_PRICE =
29 /Input \$ (\d+(?:\.\d+)?) \/ 1M tokens Output \$ (\d+(?:\.\d+)?) \/ 1M tokens/
30
31const MONTHS: Record<string, string> = {
32 January: '01',
33 February: '02',
34 March: '03',
35 April: '04',
36 May: '05',
37 June: '06',
38 July: '07',
39 August: '08',
40 September: '09',
41 October: '10',
42 November: '11',
43 December: '12',
44}
45
46const CUTOFF = new RegExp(
47 `Knowledge Cutoff: (${Object.keys(MONTHS).join('|')}) (\\d{1,2}), (\\d{4})`,
48)
49
50export interface CoherePageFacts {
51 pricing?: RateCard
52 knowledgeCutoff?: string
53}
54
55/**
56 * Relative slugs in the overview's Command-family sentence, as page URLs.
57 * A page that no longer has that sentence throws: returning no URLs would
58 * clear stored cutoffs and the Command A card on the next poll.
59 */
60export function commandFamilyPageUrls(markdown: string): Array<string> {
61 const sentence = FAMILY.exec(markdown)?.[1]
62 if (!sentence) {
63 throw new Error('cohere models page: Command family links are missing')
64 }
65 const urls: Array<string> = []
66 for (const link of sentence.matchAll(/\[[^\]]+\]\(([^)]+)\)/g)) {
67 const href = link[1] ?? ''
68 if (!/^[a-z0-9-]+$/.test(href)) continue
69 const url = `https://docs.cohere.com/docs/${href}`
70 if (!urls.includes(url)) urls.push(url)
71 }
72 if (urls.length === 0) {
73 throw new Error('cohere models page: Command family links are unreadable')
74 }
75 return urls
76}
77
78function showcase(html: string): string | null {
79 const text = html
80 .replace(/<script[\s\S]*?<\/script>/gi, ' ')
81 .replace(/<style[\s\S]*?<\/style>/gi, ' ')
82 .replace(/<[^>]+>/g, ' ')
83 .replace(/'|'/g, "'")
84 .replace(/&/g, '&')
85 .replace(/\s+/g, ' ')
86 const start = text.indexOf(' Pricing ')
87 const end = text.indexOf(' Try in Playground ')
88 if (start < 0 || end < start) return null
89 return text.slice(start, end)
90}
91
92function perMillion(amount: string): number {
93 return Number((Number(amount) / 1e6).toPrecision(12))
94}
95
96/**
97 * Facts the showcase states for its Model ID. No showcase, no model id,
98 * or a price sentence that no longer matches: nothing, not a guess.
99 * The "free until rate limits" sentence is a quota, so it stores no card.
100 * That sentence beside a token price is a conflict, so neither is stored.
101 */
102export function parseCohereModelPage(
103 html: string,
104 source: RateCard['source'],
105): { id: string; facts: CoherePageFacts } | null {
106 const box = showcase(html)
107 if (!box) return null
108 const id = /Model ID ([a-z0-9][a-z0-9.-]*)/.exec(box)?.[1]
109 if (!id) return null
110 const facts: CoherePageFacts = {}
111 const free = FREE.test(box)
112 const token = TOKEN_PRICE.exec(box)
113 if (!free && token?.[1] && token[2]) {
114 const card = compileTokenCard(
115 {
116 input_tokens: perMillion(token[1]),
117 output_tokens: perMillion(token[2]),
118 },
119 [],
120 source,
121 )
122 if (card) facts.pricing = card
123 }
124 const cutoff = CUTOFF.exec(box)
125 const month = cutoff?.[1] ? MONTHS[cutoff[1]] : undefined
126 const day = cutoff?.[2] ? Number(cutoff[2]) : NaN
127 const year = cutoff?.[3]
128 if (month && year && day >= 1 && day <= 31) {
129 facts.knowledgeCutoff = `${year}-${month}-${String(day).padStart(2, '0')}`
130 }
131 return { id, facts }
132}
133
134type PagePatch = Pick<ModelInfo, 'pricing' | 'knowledgeCutoff' | 'factSources'>
135
136/** Lookup by the model id the page names. An id with no page gets nothing. */
137export async function cohereCommandPageFacts(
138 kv?: KVNamespace,
139): Promise<(rawId: string) => PagePatch> {
140 const index = await cachedDocs(
141 kv,
142 `${COHERE_MODELS_DOC_URL}#command-family-links`,
143 async () => {
144 const markdown = await fetchText(COHERE_MODELS_DOC_URL, {
145 signal: AbortSignal.timeout(30_000),
146 })
147 return { urls: commandFamilyPageUrls(markdown) }
148 },
149 )
150 const pages = await Promise.all(
151 index.urls.map((url) =>
152 cachedDocs(kv, url, async () => {
153 const html = await fetchText(url, {
154 signal: AbortSignal.timeout(30_000),
155 })
156 const hash = await sha256Text(html)
157 const parsed = parseCohereModelPage(html, {
158 url,
159 hash,
160 extractedAt: new Date().toISOString(),
161 })
162 return {
163 id: parsed?.id ?? null,
164 facts: parsed?.facts ?? {},
165 hash,
166 }
167 }),
168 ),
169 )
170 const byId = new Map<
171 string,
172 { facts: CoherePageFacts; url: string; hash: string }
173 >()
174 for (const [indexUrl, page] of index.urls.map(
175 (url, i) => [url, pages[i]] as const,
176 )) {
177 if (!page?.id) continue
178 // Two links that name one id (the undated Command slug redirects): keep
179 // the first. A later page does not overwrite a card already read.
180 if (byId.has(page.id)) continue
181 byId.set(page.id, { facts: page.facts, url: indexUrl, hash: page.hash })
182 }
183 return (rawId) => {
184 const page = byId.get(rawId)
185 if (!page) return {}
186 const facts = page.facts
187 if (!facts.pricing && !facts.knowledgeCutoff) return {}
188 return {
189 ...facts,
190 factSources: tagDocsFacts(facts, page.url, page.hash),
191 }
192 }
193}