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