Open History to see the last commit
1/** Google-hosted Claude catalog; every id and fact is read from Google's cards. */
2import { compileTokenCard } from '@modelschemas/rate-card'
3import type { RateCard } from '@modelschemas/rate-card'
4import { tagDocsFacts } from './fact-sources.ts'
5import {
6 cachedDocs,
7 mapConcurrent,
8 parseDay,
9 tokenCount,
10} from './model-facts.ts'
11import { fetchText, sha256Text } from './types.ts'
12import type { ModelInfo } from './types.ts'
13import { VERTEX_PRICING_URL } from './vertex-pricing.ts'
14import { htmlText, normModelName } from './vertex-text.ts'
15
16const HOST = 'https://docs.cloud.google.com'
17const ROOT = '/gemini-enterprise-agent-platform/models/partner-models/claude'
18export const VERTEX_CLAUDE_URL = `${HOST}${ROOT}`
19export const VERTEX_CLAUDE_REQUEST_URL = `${VERTEX_CLAUDE_URL}/use-claude`
20
21export function claudeCardPaths(html: string): string[] {
22 const article = html.match(/<article\b[\s\S]*?<\/article>/i)?.[0]
23 if (!article) throw new Error('vertex claude: missing catalog article')
24 const paths = [...article.matchAll(/href="([^"]+)"/g)].flatMap((match) => {
25 const path = match[1] ?? ''
26 return path.startsWith(`${ROOT}/`) &&
27 /\/(?:opus|sonnet|haiku|fable)-[\d-]+$/.test(path)
28 ? [path]
29 : []
30 })
31 if (!paths.length) throw new Error('vertex claude: no linked model cards')
32 return [...new Set(paths)]
33}
34
35function lines(html: string): string[] {
36 return html
37 .replace(/<style\b[\s\S]*?<\/style>|<script\b[\s\S]*?<\/script>/gi, '')
38 .split(/<[^>]+>/)
39 .map(htmlText)
40 .filter(Boolean)
41}
42
43export function claudeCardModels(
44 html: string,
45 url: string,
46 hash: string,
47): ModelInfo[] {
48 const article = html.match(/<article\b[\s\S]*?<\/article>/i)?.[0]
49 if (!article) throw new Error('vertex claude: missing model article')
50 const text = lines(article)
51 const idAt = text.indexOf('Model ID')
52 const rawId = text[idAt + 1]
53 if (idAt < 0 || !rawId || !/^claude-[a-z0-9.@-]+$/.test(rawId)) {
54 throw new Error(`vertex claude: unreadable model id ${url}`)
55 }
56 const limit = (label: string): number | null => {
57 const entry = text.find((line) => line.startsWith(`${label}:`))
58 if (!entry) return null
59 const value = tokenCount(entry.slice(label.length + 1).trim())
60 if (value === null) throw new Error(`vertex claude: unreadable ${label}`)
61 return value
62 }
63 const inputAt = text.indexOf('Inputs:')
64 const outputAt = text.indexOf('Outputs:')
65 const tokenAt = text.indexOf('Token limits')
66 const modalities = {
67 Text: 'text',
68 Code: 'text',
69 Images: 'image',
70 Image: 'image',
71 Documents: 'pdf',
72 Document: 'pdf',
73 PDF: 'pdf',
74 }
75 const kinds = (items: string[]): string[] => [
76 ...new Set(
77 items.flatMap((item) => {
78 if (item === ',') return []
79 const kind = modalities[item as keyof typeof modalities]
80 if (!kind) throw new Error(`vertex claude: unknown modality ${item}`)
81 return [kind]
82 }),
83 ),
84 ]
85 const caps = text.slice(
86 text.indexOf('Capabilities') + 1,
87 text.indexOf('Usage types'),
88 )
89 const supportedAt = caps.indexOf('Supported')
90 const unsupportedAt = caps.indexOf('Not supported')
91 const supported =
92 supportedAt >= 0 && unsupportedAt > supportedAt
93 ? caps.slice(supportedAt + 1, unsupportedAt)
94 : []
95 const capabilities = [
96 ...(supported.includes('Function calling') ? ['tools'] : []),
97 ...(supported.includes('Extended thinking') ? ['reasoning'] : []),
98 ...(supported.includes('Structured outputs') ? ['structured_outputs'] : []),
99 ]
100 const facts = {
101 contextWindow: limit('Maximum input tokens'),
102 maxOutput: limit('Maximum output tokens'),
103 modalities:
104 inputAt >= 0 && outputAt > inputAt && tokenAt > outputAt
105 ? {
106 input: kinds(text.slice(inputAt + 1, outputAt)),
107 output: kinds(text.slice(outputAt + 1, tokenAt)),
108 }
109 : null,
110 capabilities: capabilities.length ? capabilities : null,
111 // Capability labels do not publish the accepted tools[].type wire ids.
112 serverTools: null,
113 }
114 const title = htmlText(
115 article.match(
116 /<h1\b[^>]*>([\s\S]*?)<devsite-|<h1\b[^>]*>([\s\S]*?)<\/h1>/i,
117 )?.[1] ?? '',
118 )
119 .replace(/^Anthropic['’]s /, '')
120 .replace(/ on Google Cloud$/, '')
121 const versionsAt = text.indexOf('Versions')
122 const versions =
123 versionsAt < 0
124 ? []
125 : text.slice(versionsAt + 1, text.indexOf('Supported regions'))
126 const ids = [
127 ...new Set([
128 rawId,
129 ...versions.filter((line) => /^claude-[a-z0-9.@-]+$/.test(line)),
130 ]),
131 ]
132 return ids.map((id) => {
133 const at = versions.indexOf(id)
134 const next = versions.findIndex(
135 (line, index) => index > at && /^claude-/.test(line),
136 )
137 const block =
138 at < 0 ? [] : versions.slice(at + 1, next < 0 ? undefined : next)
139 const releaseAt = block.indexOf('Release date:')
140 const release = releaseAt < 0 ? null : parseDay(block[releaseAt + 1] ?? '')
141 return {
142 rawId: id,
143 displayName: title || null,
144 activity: 'chat',
145 ...facts,
146 reasoning: null,
147 requestMap: null,
148 schemaEndpointId: null,
149 releasedAt: release === null ? null : release / 1000,
150 deprecated: block.some((line) => /^(Deprecated|Retired)$/i.test(line)),
151 factSources: tagDocsFacts(facts, url, hash),
152 }
153 })
154}
155
156/** Only the explicitly Global Google price panel; no regional substitution. */
157export function claudeGlobalPrices(
158 html: string,
159 source: RateCard['source'],
160): Map<string, RateCard> {
161 const globalTabs = [
162 ...html.matchAll(/<button\b[^>]*role="tab"[^>]*>[\s\S]*?<\/button>/gi),
163 ]
164 .filter((match) => /^Global(?: endpoint)?$/i.test(htmlText(match[0])))
165 .flatMap((match) => match[0].match(/\bid="([^"]+)"/)?.[1] ?? [])
166 const out = new Map<string, RateCard>()
167 for (const tab of globalTabs) {
168 const panelAt = html.indexOf(`aria-labelledby="${tab}"`)
169 if (panelAt < 0)
170 throw new Error('vertex claude: missing Global price panel')
171 const panelStart = html.lastIndexOf('<div', panelAt)
172 let depth = 0
173 let panelEnd = -1
174 for (const tag of html.slice(panelStart).matchAll(/<\/?div\b[^>]*>/gi)) {
175 depth += tag[0].startsWith('</') ? -1 : 1
176 if (depth === 0) {
177 panelEnd = panelStart + tag.index + tag[0].length
178 break
179 }
180 }
181 if (panelStart < 0 || panelEnd < 0)
182 throw new Error('vertex claude: unreadable Global panel')
183 const table = html
184 .slice(panelStart, panelEnd)
185 .match(/<table\b[\s\S]*?<\/table>/i)?.[0]
186 if (!table || !/Claude/.test(table)) continue
187 const rows = [...table.matchAll(/<tr\b[\s\S]*?<\/tr>/gi)].map((row) =>
188 [...row[0].matchAll(/<t[dh]\b[^>]*>([\s\S]*?)<\/t[dh]>/gi)].map((cell) =>
189 htmlText(cell[1] ?? ''),
190 ),
191 )
192 const head = rows.shift() ?? []
193 if (head[0] !== 'Model' || head[1] !== 'Type')
194 throw new Error('vertex claude: unknown price columns')
195 const groups = new Map<
196 string,
197 {
198 base: Record<string, number>
199 long: Record<string, number>
200 threshold: number | null
201 }
202 >()
203 let name = ''
204 for (const row of rows) {
205 if (row[0]) name = normModelName(row[0].replace(/^Claude\s+/i, ''))
206 const type = row[1] ?? ''
207 if (/batch/i.test(type)) continue
208 const lever =
209 type === 'Input'
210 ? 'input_tokens'
211 : type === 'Output'
212 ? 'output_tokens'
213 : type === 'Cache Hit'
214 ? 'cache_read_tokens'
215 : type === '5m Cache Write'
216 ? 'cache_write_tokens'
217 : /^1h(?:r)? Cache Write$/.test(type)
218 ? 'cache_write_1h_tokens'
219 : null
220 if (!lever)
221 throw new Error(`vertex claude: unknown Global price meter ${type}`)
222 const group = groups.get(name) ?? { base: {}, long: {}, threshold: null }
223 let found = false
224 for (let index = 2; index < row.length; index++) {
225 const cell = row[index] ?? ''
226 if (!cell) continue
227 if (!/^\$\d+(?:\.\d+)?$/.test(cell))
228 throw new Error('vertex claude: unreadable price')
229 const column = head[index] ?? ''
230 const threshold = /([\d,]+)K input tokens/.exec(column)?.[1]
231 if (!threshold) throw new Error('vertex claude: unreadable price tier')
232 const bound = Number(threshold.replace(/,/g, '')) * 1000
233 if (group.threshold !== null && group.threshold !== bound)
234 throw new Error('vertex claude: conflicting price tiers')
235 group.threshold = bound
236 const target = / > /.test(` ${column} `) ? group.long : group.base
237 const amount = Number(cell.slice(1)) / 1e6
238 if (target[lever] !== undefined && target[lever] !== amount)
239 throw new Error('vertex claude: conflicting price')
240 target[lever] = amount
241 found = true
242 }
243 if (!found) throw new Error('vertex claude: missing published price')
244 groups.set(name, group)
245 }
246 for (const [key, group] of groups) {
247 if (
248 group.base.input_tokens === undefined ||
249 group.base.output_tokens === undefined
250 )
251 throw new Error('vertex claude: incomplete rate card')
252 const long = Object.keys(group.long).length ? group.long : null
253 // A blank published tier cell does not authorize borrowing the short
254 // price. Omit this model's card so its unsourced quote becomes null.
255 if (
256 long &&
257 Object.keys(group.base).some((lever) => long[lever] === undefined)
258 )
259 continue
260 const card = compileTokenCard(
261 group.base,
262 long && group.threshold !== null
263 ? [{ minPromptTokens: group.threshold, rates: long }]
264 : [],
265 source,
266 )
267 if (!card) throw new Error('vertex claude: unrepresentable rate card')
268 out.set(key, card)
269 }
270 }
271 if (!out.size) throw new Error('vertex claude: no Global Claude price rows')
272 return out
273}
274
275export async function vertexClaudeModels(
276 kv?: KVNamespace,
277): Promise<ModelInfo[]> {
278 return cachedDocs(kv, VERTEX_CLAUDE_URL, async () => {
279 const paths = claudeCardPaths(await fetchText(VERTEX_CLAUDE_URL))
280 const rows = (
281 await mapConcurrent(paths, 6, async (path) => {
282 const url = `${HOST}${path}`
283 const html = await fetchText(url)
284 return claudeCardModels(html, url, await sha256Text(html))
285 })
286 ).flat()
287 const pricesText = await fetchText(VERTEX_PRICING_URL)
288 const hash = await sha256Text(pricesText)
289 const prices = claudeGlobalPrices(pricesText, {
290 url: VERTEX_PRICING_URL,
291 hash,
292 extractedAt: new Date().toISOString(),
293 })
294 const byId = new Map<string, ModelInfo>()
295 for (const row of rows) {
296 const pricing =
297 prices.get(
298 normModelName((row.displayName ?? '').replace(/^Claude\s+/i, '')),
299 ) ?? null
300 byId.set(row.rawId, {
301 ...row,
302 pricing,
303 absent: { pricing: pricing ? undefined : 'cleared' },
304 factSources: {
305 ...row.factSources,
306 ...tagDocsFacts({ pricing }, VERTEX_PRICING_URL, hash),
307 },
308 })
309 }
310 if (!byId.size) throw new Error('vertex claude: empty catalog')
311 return [...byId.values()]
312 })
313}