Open History to see the last commit
1/**
2 * Context window and output cap from a Replicate model's own README
3 * (`GET /v1/models/{owner}/{name}/readme`, markdown) and its listing
4 * description. Only a spec line is read: a two-column table, a
5 * `Context length:` label, or the phrase "N token context window".
6 * A line that names two windows, or an approximate count, is not a count.
7 * Several counts are kept only when they are the same number (a `262k`
8 * beside `262,144` keeps the exact one).
9 */
10import { markdownTableRows } from './model-facts.ts'
11
12const APPROX = /~|≈|\bapprox|\babout\b|\baround\b/i
13const CONTEXT_LABEL = /^(context window|context length|context)$/i
14const MAX_LABEL = /^max(?:imum)? output(?: tokens)?$/i
15const LABELED =
16 /^\s*[-*+]?\s*\**\s*(context window|context length)\s*\**\s*:\s*(.+)$/i
17const TOKEN_WINDOW =
18 /\b(\d{1,3}(?:,\d{3})+|\d+(?:\.\d+)?\s+million|one million)\s+token context window\b/gi
19/**
20 * Abbreviation only (`262k context window`). A README aside uses the same
21 * shape for a different model ("128K context window" in an eval note), so
22 * this is read from the one-line listing description and not the README.
23 */
24const ABBREV_WINDOW = /\b(\d+(?:\.\d+)?)([kKmM])\s+context window\b/gi
25const UP_TO_OUTPUT = /\bup to\s+([\d,]{4,})\s+output tokens\b/gi
26const MAX_TOKENS_BULLET =
27 /^\s*[-*]\s*`?max_tokens`?\b[^\n]*\boutput tokens?\b[^\n]*\bup to\s+([\d,]{4,})/i
28
29export interface ReplicateReadmeFacts {
30 contextWindow: number | null
31 maxOutput: number | null
32 context: { from: 'readme' | 'description'; path: string } | null
33 max: { path: string } | null
34}
35
36interface Stated {
37 value: number
38 exact: boolean
39 from: 'readme' | 'description'
40 path: string
41}
42
43function normalizeLabel(cell: string): string {
44 return cell.replace(/[*_`]/g, '').trim().toLowerCase().replace(/\s+/g, ' ')
45}
46
47function digits(text: string): number | null {
48 const n = Number(text.replace(/,/g, ''))
49 return Number.isInteger(n) && n > 0 ? n : null
50}
51
52/** One token count in a spec cell. Null when the cell is mixed or approximate. */
53export function replicateTokenCount(text: string): number | null {
54 const raw = text.replace(/[*_`]/g, ' ').replace(/\s+/g, ' ').trim()
55 if (raw === '' || APPROX.test(raw)) return null
56 const native = raw.match(
57 /^([\d,]{4,})\s+(?:tokens?\s+)?natively(?:[,.]?\s+extensible up to\s+[\d,]+\s+tokens?)?\.?$/i,
58 )
59 const nativeCount = native?.[1] ? digits(native[1]) : null
60 if (nativeCount) return nativeCount
61 // "128K (extension to 512K)" is two windows, not one.
62 if (/\bextension\b/i.test(raw)) return null
63
64 const amounts: Array<number> = []
65 for (const match of raw.matchAll(
66 /(\d{1,3}(?:,\d{3})+|\d+(?:\.\d+)?)(?:\s+(million)|\s*([kKmM])\b)?/g,
67 )) {
68 const base = Number((match[1] ?? '').replace(/,/g, ''))
69 if (!Number.isFinite(base)) continue
70 const suffix = match[3]?.toLowerCase()
71 if (match[2] || suffix === 'm') amounts.push(Math.round(base * 1_000_000))
72 else if (suffix === 'k') amounts.push(Math.round(base * 1_000))
73 else if ((match[1] ?? '').includes(',') || base >= 1000) {
74 if (!Number.isInteger(base)) return null
75 amounts.push(base)
76 }
77 }
78 const [only] = [...new Set(amounts)]
79 return amounts.length > 0 && new Set(amounts).size === 1
80 ? (only ?? null)
81 : null
82}
83
84function statedFrom(
85 text: string,
86 from: Stated['from'],
87 path: string,
88): Stated | null {
89 const value = /^one million\b/i.test(text.trim())
90 ? 1_000_000
91 : replicateTokenCount(text)
92 if (value === null) return null
93 const exact = /\d{1,3}(?:,\d{3})+/.test(text) || /\b\d{5,}\b/.test(text)
94 return { value, from, path, exact: exact && !/[kKmM]\s*$/.test(text.trim()) }
95}
96
97/** A `~` / "about" just before the phrase is an estimate, not a count. */
98function phraseCount(
99 line: string,
100 match: RegExpMatchArray,
101 from: Stated['from'],
102): Stated | null {
103 const index = match.index ?? 0
104 if (
105 APPROX.test(line.slice(Math.max(0, index - 8), index + match[0].length))
106 ) {
107 return null
108 }
109 const path = from === 'description' ? 'description' : 'token context window'
110 return statedFrom(match[1] ?? '', from, path)
111}
112
113function withoutCode(markdown: string): string {
114 return markdown.replace(/```[\s\S]*?```/g, '')
115}
116
117/**
118 * A spec cell with digits that is not one count blocks the fact. A header
119 * cell ("Input") is skipped.
120 */
121function takeCell(
122 text: string,
123 from: Stated['from'],
124 path: string,
125 into: Array<Stated>,
126): boolean {
127 if (!/\d/.test(text)) return false
128 const stated = statedFrom(text, from, path)
129 if (!stated) return true
130 into.push(stated)
131 return false
132}
133
134function pick(values: Array<Stated>): Stated | null {
135 const [anchor] = values
136 if (!anchor) return null
137 const close = values.every(
138 (row) =>
139 Math.abs(row.value - anchor.value) / Math.max(row.value, anchor.value) <=
140 0.01,
141 )
142 if (!close) return null
143 return values.find((row) => row.exact) ?? anchor
144}
145
146export function replicateReadmeFacts(
147 markdown: string,
148 description = '',
149): ReplicateReadmeFacts {
150 // The README endpoint sends CRLF. A trailing CR keeps a table row from
151 // ending on `|` and a labeled line from matching `$`.
152 const readme = withoutCode(markdown.replace(/\r\n?/g, '\n'))
153 const context: Array<Stated> = []
154 const max: Array<Stated> = []
155 let blockedContext = false
156 let blockedMax = false
157
158 for (const row of markdownTableRows(readme)) {
159 const label = normalizeLabel(row[0] ?? '')
160 const value = row.slice(1).join(' ')
161 if (CONTEXT_LABEL.test(label)) {
162 blockedContext =
163 takeCell(value, 'readme', normalizeLabel(row[0] ?? ''), context) ||
164 blockedContext
165 } else if (MAX_LABEL.test(label)) {
166 blockedMax =
167 takeCell(value, 'readme', normalizeLabel(row[0] ?? ''), max) ||
168 blockedMax
169 }
170 }
171
172 for (const line of readme.split('\n')) {
173 const labeled = line.match(LABELED)
174 if (labeled?.[2]) {
175 blockedContext =
176 takeCell(
177 labeled[2],
178 'readme',
179 normalizeLabel(labeled[1] ?? ''),
180 context,
181 ) || blockedContext
182 }
183 const bullet = line.match(MAX_TOKENS_BULLET)
184 if (bullet?.[1]) {
185 blockedMax =
186 takeCell(bullet[1], 'readme', 'max_tokens', max) || blockedMax
187 }
188 for (const match of line.matchAll(UP_TO_OUTPUT)) {
189 if (match[1]) {
190 blockedMax =
191 takeCell(match[1], 'readme', 'output tokens', max) || blockedMax
192 }
193 }
194 for (const match of line.matchAll(TOKEN_WINDOW)) {
195 const stated = phraseCount(line, match, 'readme')
196 if (stated) context.push(stated)
197 }
198 }
199
200 const blurb = description.replace(/\s+/g, ' ')
201 for (const match of blurb.matchAll(TOKEN_WINDOW)) {
202 const stated = phraseCount(blurb, match, 'description')
203 if (stated) context.push(stated)
204 }
205 for (const match of blurb.matchAll(ABBREV_WINDOW)) {
206 const index = match.index
207 if (APPROX.test(blurb.slice(Math.max(0, index - 8), index))) continue
208 const stated = statedFrom(
209 `${match[1] ?? ''}${match[2] ?? ''}`,
210 'description',
211 'description',
212 )
213 if (stated) context.push({ ...stated, exact: false })
214 }
215
216 const contextWinner = blockedContext ? null : pick(context)
217 const maxWinner = blockedMax ? null : pick(max)
218 return {
219 contextWindow: contextWinner?.value ?? null,
220 maxOutput: maxWinner?.value ?? null,
221 context: contextWinner
222 ? { from: contextWinner.from, path: contextWinner.path }
223 : null,
224 max: maxWinner ? { path: maxWinner.path } : null,
225 }
226}