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

vertex-pricing.ts

329 lines10.8 KB

1/**
2 * Standard pay-as-you-go token prices from the Agent Platform pricing
3 * page (issue #203). Priority, Flex, and Batch tables are other
4 * products. A dated introductory row applies only while it is in
5 * effect. Global wins when the same model lists both regions.
6 * A row this parser does not understand drops that model rather than
7 * quoting part of its bill. Per-count Veo and embedding tables do not
8 * match the token header, so those models stay null.
9 */
10import { compileTokenCard } from '@modelschemas/rate-card'
11import type { RateCard, TokenRateTier } from '@modelschemas/rate-card'
12​
13import { tagDocsFacts } from './fact-sources.ts'
14import { assertParsed, cachedDocs, parseDay } from './model-facts.ts'
15import { fetchText, sha256Text } from './types.ts'
16import type { ModelInfo } from './types.ts'
17import { htmlText, normModelName } from './vertex-text.ts'
18​
19export const VERTEX_PRICING_URL =
20 'https://cloud.google.com/gemini-enterprise-agent-platform/generative-ai/pricing'
21​
22const DAY_MS = 86_400_000
23const LONG_CONTEXT = 200_000
24​
25export interface VertexRates {
26 base: Record<string, number>
27 tiers: Array<TokenRateTier>
28 expiresAt?: string
30​
31interface Columns {
32 model: number
33 type: number
34 region: number
35 shortIn: number
36 longIn: number
37 shortCache: number
38 longCache: number
40​
41interface PriceRow {
42 type: string
43 region: string
44 prices: [number | null, number | null, number | null, number | null]
46​
47interface PriceGroup {
48 rows: Array<PriceRow>
49 expiresAt: string | null
51​
52function cells(row: string): Array<string> {
53 return [...row.matchAll(/<t[dh][^>]*>([\s\S]*?)<\/t[dh]>/gi)].map((match) =>
54 htmlText(match[1] ?? ''),
55 )
57​
58function columnsOf(header: Array<string>): Columns | null {
59 const joined = header.join(' ').toLowerCase()
60 if (/priority|flex|batch|codemender|alphaevolve/.test(joined)) return null
61 if (!/1m tokens|token price/.test(joined)) return null
62 // The image models moved to a table with one price per row and no 200K
63 // split (issue #258).
64 const tiered = /200k/.test(joined)
65 const model = header.findIndex((cell) => /^model$/i.test(cell))
66 const type = header.findIndex((cell) => /^type$/i.test(cell))
67 const region = header.findIndex((cell) => /^region$/i.test(cell))
68 let shortIn = -1
69 let longIn = -1
70 let shortCache = -1
71 let longCache = -1
72 header.forEach((cell, index) => {
73 const text = cell.toLowerCase()
74 if (!(tiered ? /200k/ : /1m tokens/).test(text)) return
75 const cached = /cach/.test(text)
76 const greater = />/.test(text)
77 if (cached && greater) longCache = index
78 else if (cached) shortCache = index
79 else if (greater) longIn = index
80 else shortIn = index
81 })
82 if (model < 0 || type < 0 || shortIn < 0) return null
83 // A flat table counts only with a cached-input column. That is what
84 // tells the standard table from the page's other single-price tables
85 // (open models, embeddings, an unlabelled discount tab).
86 if (tiered ? longIn < 0 : shortCache < 0) return null
87 return { model, type, region, shortIn, longIn, shortCache, longCache }
89​
90/** `null` is an unrecognised row. A priced unrecognised row refuses the model. */
91export function priceLevers(type: string): Array<string> | null {
92 const text = type.toLowerCase().replace(/\s+/g, ' ').trim()
93 // "per picture" / "per second" is a different unit than the token columns.
94 if (/\bper\b/.test(text) && !/\bper 1m\b/.test(text)) return null
95 if (/^input(?::| \()/.test(text) && /\btext\b/.test(text)) {
96 return ['input_tokens']
97 }
98 if (/^input: audio\b|^audio input\b|^input \(audio\)$/.test(text)) {
99 return ['audio_tokens']
100 }
101 if (/^input: video, image\b/.test(text))
102 return ['image_tokens', 'video_tokens']
103 if (/^input: image\b|^image input\b/.test(text)) return ['image_tokens']
104 if (/^input: video\b|^video input\b/.test(text)) return ['video_tokens']
105 if (/^text output\b|^output: text\b/.test(text)) return ['output_tokens']
106 if (/^image output\b|^output: image\b/.test(text)) {
107 return ['image_output_tokens']
108 }
109 if (/^audio output\b|^output: audio\b/.test(text)) {
110 return ['audio_output_tokens']
111 }
112 if (/^output: video\b|^video output\b/.test(text)) {
113 return ['video_output_tokens']
114 }
115 return null
117​
118const CACHE_LEVER: Record<string, string> = {
119 input_tokens: 'cache_read_tokens',
120 audio_tokens: 'audio_cache_tokens',
121 image_tokens: 'image_cache_tokens',
122 video_tokens: 'video_cache_tokens',
124​
125function money(cell: string | undefined): number | null | 'bad' {
126 const text = cell?.trim() ?? ''
127 if (text === '' || /^n\/a$/i.test(text)) return null
128 const match = /^\$([\d,]+(?:\.\d+)?)$/.exec(text)
129 if (!match?.[1]) return 'bad'
130 return Number(match[1].replace(/,/g, '')) / 1e6
132​
133function activeName(
134 name: string,
135 now: number,
136): { key: string; expiresAt: string | null } | null {
137 if (/\bcomputer use\b/i.test(name)) return null
138 const through = /through ([A-Za-z]+ \d{1,2}, \d{4})/i.exec(name)
139 const starting = /starting ([A-Za-z]+ \d{1,2}, \d{4})/i.exec(name)
140 let end: number | null = null
141 if (through?.[1]) {
142 const day = parseDay(through[1])
143 if (day === null) return null
144 end = day + DAY_MS
145 if (now >= end) return null
146 }
147 if (starting?.[1]) {
148 const day = parseDay(starting[1])
149 if (day === null) return null
150 if (now < day) return null
151 }
152 const key = normModelName(name)
153 if (!key) return null
154 return {
155 key,
156 expiresAt: end === null ? null : new Date(end).toISOString(),
157 }
159​
160function readPrice(row: Array<string>, index: number): number | null | 'bad' {
161 if (index < 0) return null
162 return money(row[index])
164​
165/** Normed display name → rates. A poisoned name is absent. */
166export function parseVertexPricing(
167 html: string,
168 now: number = Date.now(),
169): Map<string, VertexRates> {
170 const groups = new Map<string, PriceGroup>()
171 const poisoned = new Set<string>()
172 for (const match of html.matchAll(/<table[\s\S]*?<\/table>/gi)) {
173 const rows = [...match[0].matchAll(/<tr[\s\S]*?<\/tr>/gi)].map((row) =>
174 cells(row[0]),
175 )
176 const header = rows[0]
177 if (!header) continue
178 const columns = columnsOf(header)
179 if (!columns) continue
180 let modelName = ''
181 let region = ''
182 for (const row of rows.slice(1)) {
183 if (row[columns.model]) {
184 modelName = row[columns.model] ?? ''
185 region = columns.region >= 0 ? (row[columns.region] ?? '') : ''
186 } else if (columns.region >= 0 && row[columns.region]) {
187 region = row[columns.region] ?? ''
188 }
189 const named = activeName(modelName, now)
190 if (!named || poisoned.has(named.key)) continue
191 const type = row[columns.type] ?? ''
192 if (type === '' || /^type$/i.test(type)) continue
193 const prices = [
194 readPrice(row, columns.shortIn),
195 readPrice(row, columns.longIn),
196 readPrice(row, columns.shortCache),
197 readPrice(row, columns.longCache),
198 ] as const
199 if (prices.some((price) => price === 'bad')) {
200 poisoned.add(named.key)
201 groups.delete(named.key)
202 continue
203 }
204 const group = groups.get(named.key) ?? {
205 rows: [],
206 expiresAt: named.expiresAt,
207 }
208 if (named.expiresAt) group.expiresAt = named.expiresAt
209 group.rows.push({
210 type,
211 region,
212 prices: prices.map((price) =>
213 price === 'bad' ? null : price,
214 ) as PriceRow['prices'],
215 })
216 groups.set(named.key, group)
217 }
218 }
219​
220 const out = new Map<string, VertexRates>()
221 for (const [key, group] of groups) {
222 if (poisoned.has(key)) continue
223 const rates = ratesFor(group)
224 if (rates) out.set(key, rates)
225 }
226 return out
228​
229function ratesFor(group: PriceGroup): VertexRates | null {
230 const global = group.rows.some((row) => /^global$/i.test(row.region))
231 const rows = global
232 ? group.rows.filter(
233 (row) => row.region === '' || /^global$/i.test(row.region),
234 )
235 : group.rows
236 const base: Record<string, number> = {}
237 const tier: Record<string, number> = {}
238 let tiered = false
239 for (const row of rows) {
240 const levers = priceLevers(row.type)
241 const [shortIn, longIn, shortCache, longCache] = row.prices
242 if (!levers) {
243 if (row.prices.some((price) => price !== null)) return null
244 continue
245 }
246 if (shortIn === null) return null
247 for (const lever of levers) {
248 if (base[lever] !== undefined && base[lever] !== shortIn) return null
249 base[lever] = shortIn
250 if (longIn !== null && longIn !== shortIn) {
251 if (tier[lever] !== undefined && tier[lever] !== longIn) return null
252 tier[lever] = longIn
253 tiered = true
254 }
255 const cacheLever = CACHE_LEVER[lever]
256 if (!cacheLever || shortCache === null) continue
257 if (base[cacheLever] !== undefined && base[cacheLever] !== shortCache) {
258 return null
259 }
260 base[cacheLever] = shortCache
261 if (longCache !== null && longCache !== shortCache) {
262 if (tier[cacheLever] !== undefined && tier[cacheLever] !== longCache) {
263 return null
264 }
265 tier[cacheLever] = longCache
266 tiered = true
267 }
268 }
269 }
270 if (base.input_tokens === undefined || base.output_tokens === undefined) {
271 return null
272 }
273 const tiers: Array<TokenRateTier> = tiered
274 ? [{ minPromptTokens: LONG_CONTEXT, rates: tier }]
275 : []
276 return {
277 base,
278 tiers,
279 ...(group.expiresAt ? { expiresAt: group.expiresAt } : {}),
280 }
282​
283type PricedFacts = Pick<ModelInfo, 'pricing' | 'factSources'>
284​
285/** Card-title lookup. Names the page does not price get nothing. */
286export async function vertexModelPricing(
287 kv?: KVNamespace,
288): Promise<(title: string) => PricedFacts> {
289 const doc = await cachedDocs(kv, VERTEX_PRICING_URL, async () => {
290 const html = await fetchText(VERTEX_PRICING_URL)
291 const parsed = parseVertexPricing(html)
292 assertParsed(parsed, 'vertex pricing page')
293 return {
294 rates: Object.fromEntries(parsed),
295 hash: await sha256Text(html),
296 extractedAt: new Date().toISOString(),
297 }
298 })
299 return (title) => {
300 const rates = doc.rates[normModelName(title)]
301 if (!rates) return {}
302 const source = {
303 url: VERTEX_PRICING_URL,
304 hash: doc.hash,
305 extractedAt: doc.extractedAt,
306 ...(rates.expiresAt ? { expiresAt: rates.expiresAt } : {}),
307 }
308 const pricing = compileTokenCard(rates.base, rates.tiers, source, {
309 extraPromptLevers: ['audio_tokens', 'image_tokens', 'video_tokens'],
310 })
311 if (!pricing) return {}
312 return {
313 pricing,
314 factSources: tagDocsFacts({ pricing }, VERTEX_PRICING_URL, doc.hash),
315 }
316 }
318​
319/** The rate map compileTokenCard stored, for tests. */
320export function baseRates(card: RateCard): Record<string, number> {
321 const table = card.tables.rate
322 const base = table && typeof table === 'object' ? table.base : undefined
323 if (!base || typeof base !== 'object') return {}
324 return Object.fromEntries(
325 Object.entries(base).filter(
326 (entry): entry is [string, number] => typeof entry[1] === 'number',
327 ),
328 )