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

byteplus-pricing.ts

1,161 lines39.5 KB

1/**
2 * BytePlus chat prices from the ModelArk pricing page (issue #73). The page
3 * is a Lark document: `window._ROUTER_DATA` embeds `curDoc.Content`, and
4 * each table is an `aceTable` of a row zone plus a column zone. Cell text
5 * lives in a zone id `x{rowId}x{colId}`.
6 *
7 * Only the standard online-inference table is read (the one that quotes
8 * cache storage per hour). Flex and batch tables further down are half of
9 * standard and are not levers. Cache storage itself is per token-hour, not
10 * per request, so that column is ignored. A peak/off-peak row has no lever
11 * for time of day, so that model gets no card. A dated catalog id uses an
12 * undated page row only when exactly one page id is its prefix
13 * (`dola-seed-2-1-turbo` → `dola-seed-2-1-turbo-260628`).
14 *
15 * Video (Seedance) and image (Seedream) tables are read too (issue #99):
16 * see `parseByteplusVideo` and `parseByteplusImages`. A page missing chat,
17 * video, or image rows throws. The model list's "also supports" note copies
18 * a published image, video, or pixel-tier price onto that alias when the
19 * pair is unambiguous (issue #117). This page has no speech table, so Seed
20 * Speech stays unpriced. Seedance estimates also read frame rate and
21 * output sizes from the video generation tutorial; if that page fails, the
22 * cards publish without an estimate rather than failing the lookup.
23 */
24import { compileTokenCard, compileUnitCard } from '@modelschemas/rate-card'
25import type {
26 Expr,
27 RateCard,
28 RateCardEstimate,
29 TokenRateTier,
30} from '@modelschemas/rate-card'
31​
32import { errorMessage } from '#/server/errors.ts'
33​
34import { tagDocsFacts } from './fact-sources.ts'
35import { parseByteplusServerTools } from './server-tools.ts'
36import { assertParsed, cachedDocs } from './model-facts.ts'
37import { fetchText, sha256Text } from './types.ts'
38import type { ModelInfo } from './types.ts'
39​
40export const BYTEPLUS_PRICING_URL =
41 'https://docs.byteplus.com/en/docs/ModelArk/1544106'
42​
43/** Seedance output sizes and frame rates (the token formula's inputs). */
44export const BYTEPLUS_VIDEO_GUIDE_URL =
45 'https://docs.byteplus.com/en/docs/modelark/video-generation-tutorial'
46​
47/** "also supports" aliases. Not a price source. */
48export const BYTEPLUS_MODEL_LIST_URL =
49 'https://docs.byteplus.com/en/docs/ModelArk/1330310'
50​
51/** Header (unit stripped) → request lever. Cache storage is not one. */
52const LEVERS: Record<string, string> = {
53 'input (non-audio)': 'input_tokens',
54 'input (audio)': 'audio_tokens',
55 'cache-hit input (non-audio)': 'cache_read_tokens',
56 'cache-hit input (audio)': 'audio_cache_tokens',
57 output: 'output_tokens',
59​
60interface DocOp {
61 insert: string | { id?: string }
62 attributes?: { aceTable?: string; [key: string]: unknown }
64​
65interface DocZone {
66 ops?: Array<DocOp>
67 zoneType?: string
68 zoneId?: string
70​
71export interface ByteplusDoc {
72 data: Record<string, DocZone>
74​
75export interface ByteplusChatRates {
76 base: Record<string, number>
77 tiers: Array<TokenRateTier>
79​
80function zoneText(zone: DocZone | undefined): string {
81 return (zone?.ops ?? [])
82 .map((op) => (typeof op.insert === 'string' ? op.insert : ''))
83 .join('')
84 .split('\n')
85 .map((line) => line.replace(/^\*\s?/, '').trim())
86 .filter((line) => line !== '')
87 .join(' ')
88 .replace(/\s+/g, ' ')
89 .trim()
91​
92function headerKey(cell: string): string {
93 return (
94 cell
95 .toLowerCase()
96 // Drop the trailing unit ("(USD/M tokens)"), keep "(non-audio)".
97 .replace(/\s*\([^)]*\)\s*$/, '')
98 .replace(/\s+/g, ' ')
99 .trim()
100 )
102​
103/**
104 * `Prompt length [0, 128]` is the base. `(128, 256]` starts above 128K
105 * tokens. `-` is an untiered base row. Anything else (peak hours) refuses.
106 */
107function promptFloorK(label: string): number | null {
108 if (label === '-' || label === '') return 0
109 if (/^prompt length \[0,\s*[\d.]+\]$/i.test(label)) return 0
110 const next = label.match(/^prompt length \(([\d.]+),\s*[\d.]+\]$/i)
111 if (next?.[1]) return Number(next[1])
112 return null
114​
115/** USD per million tokens. `undefined` is a lever the cell does not price. */
116function usdPerMillion(cell: string): number | null | undefined {
117 if (cell === '-' || cell === '') return undefined
118 if (!/^[\d]+(?:\.[\d]+)?$/.test(cell)) return null
119 return Number(cell) / 1e6
121​
122function tableRows(
123 doc: ByteplusDoc,
124 spec: string,
125): Array<Array<string>> | null {
126 const [rowId, colId] = spec.split(' ')
127 const row = rowId ? doc.data[rowId] : undefined
128 const col = colId ? doc.data[colId] : undefined
129 if (!row || !col) return null
130 const cols = (col.ops ?? []).flatMap((op) =>
131 typeof op.insert === 'object' && op.insert.id ? [op.insert.id] : [],
132 )
133 return (row.ops ?? []).flatMap((op) => {
134 const rowCell = op.insert
135 if (typeof rowCell !== 'object' || !rowCell.id) return []
136 const cellId = rowCell.id
137 return [cols.map((column) => zoneText(doc.data[`x${cellId}x${column}`]))]
138 })
140​
141function ratesFromGroup(
142 rows: Array<Array<string>>,
143 columns: { tier: number; levers: Record<string, number> },
144): ByteplusChatRates | null {
145 const base: Record<string, number> = {}
146 const tiers: Array<TokenRateTier> = []
147 for (const [index, row] of rows.entries()) {
148 const floor = promptFloorK(row[columns.tier] ?? '')
149 if (floor === null) return null
150 const rates: Record<string, number> = {}
151 for (const [key, lever] of Object.entries(LEVERS)) {
152 const at = columns.levers[key]
153 if (at === undefined) continue
154 const value = usdPerMillion(row[at] ?? '')
155 if (value === null) return null
156 if (value !== undefined) rates[lever] = value
157 }
158 if (rates.input_tokens === undefined || rates.output_tokens === undefined) {
159 return null
160 }
161 if (index === 0) {
162 if (floor !== 0) return null
163 Object.assign(base, rates)
164 continue
165 }
166 if (floor <= 0) return null
167 // Prompt length is the request's input. Audio columns are re-quoted in
168 // the same bracket, so they count toward it when the card is compiled.
169 tiers.push({ minPromptTokens: floor * 1000, rates })
170 }
171 return Object.keys(base).length > 0 ? { base, tiers } : null
173​
174/** Every table whose header (units stripped) names all of `required`. */
175function tablesWith(
176 doc: ByteplusDoc,
177 required: Array<string>,
178): Array<{ keys: Array<string>; rows: Array<Array<string>> }> {
179 return (doc.data['0']?.ops ?? []).flatMap((op) => {
180 const spec = op.attributes?.aceTable
181 const rows = spec ? tableRows(doc, spec) : null
182 const keys = rows?.[0]?.map(headerKey)
183 if (!rows || !keys || !required.every((key) => keys.includes(key))) {
184 return []
185 }
186 return [{ keys, rows: rows.slice(1) }]
187 })
189​
190/** Page model id → standard online-inference rates. */
191export function parseByteplusPricing(
192 doc: ByteplusDoc,
193): Map<string, ByteplusChatRates> {
194 const out = new Map<string, ByteplusChatRates>()
195 const tables = tablesWith(doc, [
196 'model id',
197 'cache-storage',
198 'input (non-audio)',
199 'output',
200 ])
201 for (const { keys, rows } of tables) {
202 if (out.size > 0) break
203 const tier = keys.indexOf('pricing tiers')
204 const levers: Record<string, number> = {}
205 for (const key of Object.keys(LEVERS)) {
206 const at = keys.indexOf(key)
207 if (at >= 0) levers[key] = at
208 }
209 if (tier < 0 || levers['input (non-audio)'] === undefined) continue
210 let current: { id: string; rows: Array<Array<string>> } | null = null
211 const groups: Array<{ id: string; rows: Array<Array<string>> }> = []
212 for (const row of rows) {
213 const id = row[keys.indexOf('model id')] ?? ''
214 if (id !== '') {
215 if (current) groups.push(current)
216 current = { id, rows: [row] }
217 } else if (current) {
218 current.rows.push(row)
219 }
220 }
221 if (current) groups.push(current)
222 for (const group of groups) {
223 if (out.has(group.id) || /\s/.test(group.id)) continue
224 const rates = ratesFromGroup(group.rows, { tier, levers })
225 if (rates) out.set(group.id, rates)
226 }
227 }
228 return out
230​
231/**
232 * Catalog id → page row. Exact id wins. Otherwise the undated page id the
233 * catalog id extends with a `-YYMMDD` date — never another suffix, so
234 * `seedance-1-0-pro-fast-…` cannot take an undated `seedance-1-0-pro` row.
235 */
236export function byteplusRatesFor<T>(
237 rawId: string,
238 rates: Map<string, T>,
239): T | undefined {
240 const exact = rates.get(rawId)
241 if (exact) return exact
242 const dated = rawId.match(/^(.+)-\d{6}$/)?.[1]
243 return dated === undefined ? undefined : rates.get(dated)
245​
246const ALSO_SUPPORTS =
247 /\b([a-z0-9]+(?:-[a-z0-9]+)+)\s*\(also supports:\s*([a-z0-9]+(?:-[a-z0-9]+)+)\s*\)/g
248​
249/**
250 * Model-list "also supports" pairs. One id named with two different
251 * partners is dropped; the other pairs stay. Not a price.
252 */
253export function parseByteplusAliases(doc: ByteplusDoc): Map<string, string> {
254 const pairs = new Map<string, string>()
255 const dropped = new Set<string>()
256 const text = Object.values(doc.data).map(zoneText).join('\n')
257 for (const match of text.matchAll(ALSO_SUPPORTS)) {
258 const primary = match[1] ?? ''
259 const alias = match[2] ?? ''
260 if (primary === '' || primary === alias) continue
261 const previous = pairs.get(primary)
262 if (previous !== undefined && previous !== alias) {
263 dropped.add(primary)
264 continue
265 }
266 const claimed = [...pairs.entries()].some(
267 ([other, taken]) => other !== primary && taken === alias,
268 )
269 if (claimed) {
270 dropped.add(primary)
271 continue
272 }
273 pairs.set(primary, alias)
274 }
275 for (const id of dropped) pairs.delete(id)
276 return pairs
278​
279/**
280 * Copy a price onto the unpriced side of an alias pair. Both sides priced,
281 * or neither, stays as parsed. Chat rates are not passed here.
282 */
283export function sharePublishedAliases<T>(
284 rates: Map<string, T>,
285 aliases: Map<string, string>,
286): void {
287 for (const [primary, alias] of aliases) {
288 const left = rates.get(primary)
289 const right = rates.get(alias)
290 if (left !== undefined && right === undefined) rates.set(alias, left)
291 else if (right !== undefined && left === undefined)
292 rates.set(primary, right)
293 }
295​
296/**
297 * Seedance rates, USD per million tokens: service tier (`default` online,
298 * `flex` offline) → resolution (`*` when the row names none) → variant. A
299 * variant is `no_video`/`video` (does the input carry a video),
300 * `silent`/`audio` (`generate_audio`), or `all` when the model has one
301 * rate.
302 */
303export type ByteplusVideoRates = Record<
304 string,
305 Record<string, Record<string, number>>
307​
308const VIDEO_VARIANTS: Array<[RegExp, string]> = [
309 [/Input without video: (\d+(?:\.\d+)?)/i, 'no_video'],
310 [/Input with video: (\d+(?:\.\d+)?)/i, 'video'],
311 [/Video with audio: (\d+(?:\.\d+)?)/i, 'audio'],
312 [/Video without audio: (\d+(?:\.\d+)?)/i, 'silent'],
314​
315/** A plain positive decimal, or `null`. */
316function decimal(text: string): number | null {
317 const value = /^\d+(?:\.\d+)?$/.test(text) ? Number(text) : NaN
318 return Number.isFinite(value) && value > 0 ? value : null
320​
321/** Both halves of a split, or one flat rate — anything else refuses. */
322function variantRates(body: string): Record<string, number> | null {
323 const text = body.trim()
324 const flat = decimal(text)
325 if (flat !== null) return { all: flat }
326 if (/^[\d.]+$/.test(text)) return null
327 const rates: Record<string, number> = {}
328 let rest = text
329 for (const [pattern, variant] of VIDEO_VARIANTS) {
330 rest = rest.replace(pattern, (_, n: string) => {
331 rates[variant] = Number(n)
332 return ''
333 })
334 }
335 const pairs = [
336 ['no_video', 'video'],
337 ['silent', 'audio'],
338 ]
339 const paired = pairs.some(([a = '', b = '']) => {
340 const keys = Object.keys(rates).sort()
341 return keys.join() === [a, b].sort().join()
342 })
343 const usable = Object.values(rates).every((n) => Number.isFinite(n) && n > 0)
344 return rest.trim() === '' && paired && usable ? rates : null
346​
347/**
348 * One rate cell → resolution → variant. `undefined` is "Not supported yet";
349 * `null` is a cell this parser cannot read. Promo cells quote the list
350 * price as "(Original) 5.6 Time limited 25% off"; the list price is kept
351 * (the discount is enterprise-only and time-boxed). Promo text with no
352 * "(Original)" price beside it may be quoting the discounted rate, so it
353 * refuses.
354 */
355function videoCell(
356 cell: string,
357): Record<string, Record<string, number>> | null | undefined {
358 const promos = cell.match(/Time limited \d+% off/gi)?.length ?? 0
359 const originals = cell.match(/\(Original\)/gi)?.length ?? 0
360 if (promos !== originals) return null
361 const text = cell
362 .replace(/\(Original\)/gi, '')
363 .replace(/Time limited \d+% off/gi, '')
364 .replace(/\s+/g, ' ')
365 .trim()
366 if (/^not supported/i.test(text)) return undefined
367 // [lead, "480p and 720p", body, "1080p", body, …]
368 const parts = text.split(/For ([^:]+?) outputs?:/i)
369 const lead = parts[0]?.trim() ?? ''
370 // A rate with no "For … outputs" applies whatever the resolution.
371 if (lead && parts.length > 1) return null
372 const segments: Array<[Array<string>, string]> = lead ? [[['*'], lead]] : []
373 for (let at = 1; at < parts.length; at += 2) {
374 const named = parts[at]?.toLowerCase().match(/\d+p|4k/g) ?? []
375 segments.push([named, parts[at + 1] ?? ''])
376 }
377 if (segments.length === 0) return null
378 const out: Record<string, Record<string, number>> = {}
379 for (const [resolutions, body] of segments) {
380 const rates = variantRates(body)
381 if (!rates || resolutions.length === 0) return null
382 for (const resolution of resolutions) out[resolution] = rates
383 }
384 return out
386​
387/**
388 * Video table: `Model ID ‖ Online inference ‖ Offline inference`. The id
389 * cell trails a description ("… Pricing varies based on …"); its first word
390 * is the id. A model with any unreadable cell gets no rates (and a warning).
391 * Only the first matching table is read.
392 */
393export function parseByteplusVideo(
394 doc: ByteplusDoc,
395): Map<string, ByteplusVideoRates> {
396 const out = new Map<string, ByteplusVideoRates>()
397 const tables = tablesWith(doc, [
398 'model id',
399 'online inference',
400 'offline inference',
401 ])
402 const [table] = tables
403 if (!table) return out
404 const at = (key: string) => table.keys.indexOf(key)
405 for (const row of table.rows) {
406 const id = (row[at('model id')] ?? '').split(' ')[0] ?? ''
407 if (!/^[a-z0-9-]+$/.test(id)) continue
408 const online = videoCell(row[at('online inference')] ?? '')
409 const offline = videoCell(row[at('offline inference')] ?? '')
410 if (!online || offline === null) {
411 warnUnread('video', id, row)
412 continue
413 }
414 out.set(id, { default: online, ...(offline && { flex: offline }) })
415 }
416 return out
418​
419/**
420 * Image table: `Model ID ‖ Input image price ‖ Output image price`, USD per
421 * image. Only flat rows with free input images are read here; Seedream 5.0
422 * pro's pixel-tiered row is `parseByteplusPixelTiers`. Only the first
423 * matching table is read.
424 */
425export function parseByteplusImages(doc: ByteplusDoc): Map<string, number> {
426 const out = new Map<string, number>()
427 const tables = tablesWith(doc, [
428 'model id',
429 'input image price',
430 'output image price',
431 ])
432 const [table] = tables
433 if (!table) return out
434 const at = (key: string) => table.keys.indexOf(key)
435 for (const row of table.rows) {
436 const id = (row[at('model id')] ?? '').split(' ')[0] ?? ''
437 if (!/^[a-z0-9-]+$/.test(id)) continue
438 const input = (row[at('input image price')] ?? '').trim()
439 const output = decimal((row[at('output image price')] ?? '').trim())
440 if (!/^free$/i.test(input) || output === null) {
441 // Pixel-tiered rows belong to `parseByteplusPixelTiers`.
442 const tiered = pixelTierRates(input, row[at('output image price')] ?? '')
443 if (!tiered) warnUnread('image', id, row)
444 continue
445 }
446 out.set(id, output)
447 }
448 return out
450​
451/** A priced row this parser could not read: logged so drift is visible. */
452function warnUnread(table: string, id: string, row: Array<string>): void {
453 console.warn(
454 JSON.stringify({
455 job: 'byteplus-pricing',
456 skipped: id,
457 table,
458 cells: row,
459 }),
460 )
462​
463/**
464 * Output frame rate and pixel size per Seedance model, from the video
465 * generation tutorial. The page's token formula is
466 * `(input s + output s) × width × height × fps / 1024`; cards apply it to
467 * output seconds only, since a request with input video refuses the
468 * estimate (see `compileSeedanceCard`).
469 */
470export interface SeedanceGeometry {
471 fps: number
472 /** resolution → ratio → output pixels */
473 dims: Record<string, Record<string, { w: number; h: number }>>
475​
476/**
477 * A resolution cell's note, for one display name: `true` serves it,
478 * `false` does not, `null` is a note this parser cannot read. Known
479 * shapes: "X and Y do not support 1080p", "Only X supports 4K".
480 */
481function noteServes(note: string, name: string): boolean | null {
482 if (note === '') return true
483 const names = (list: string) =>
484 list.split(/,\s*|\s+and\s+/i).map((part) => part.trim().toLowerCase())
485 const excluded = note.match(/^(.+?) (?:do|does) not support\b/i)?.[1]
486 if (excluded) return !names(excluded).includes(name)
487 const only = note.match(/^Only (.+?) supports?\b/i)?.[1]
488 if (only) return names(only).includes(name)
489 return null
491​
492/**
493 * Two tables on the tutorial: the model table (`Model name` header row of
494 * display names, a `Model ID` row, a `Frame rate` row) and the pixel table
495 * (`Resolution ‖ Aspect ratio ‖ <model or "… series">…`). A pixel column
496 * names one display name, or a series every display name it prefixes; a
497 * model's own column beats its series. A resolution note ("… do not support
498 * 1080p") limits who gets that row, and a note it cannot read drops the row.
499 * Two columns of the same rank disagreeing on a size drops the model, as
500 * does a repeated display name. Models missing a fact get no geometry.
501 */
502export function parseSeedanceGeometry(
503 doc: ByteplusDoc,
504): Map<string, SeedanceGeometry> {
505 const out = new Map<string, SeedanceGeometry>()
506 const [models] = tablesWith(doc, ['model name'])
507 const [pixels] = tablesWith(doc, ['resolution', 'aspect ratio'])
508 if (!models || !pixels) return out
509 const row = (label: string) =>
510 models.rows.find((r) => r.some((c) => c.toLowerCase() === label))
511 const ids = row('model id')
512 const fpsRow = row('frame rate')
513 if (!ids || !fpsRow) return out
514​
515 // Display name (lowercase) → model id and fps.
516 const byName = new Map<string, { id: string; fps: number }>()
517 const repeated = new Set<string>()
518 models.keys.forEach((name, column) => {
519 const id = ids[column] ?? ''
520 const fps = fpsRow[column]?.match(/^(\d+) fps$/i)?.[1]
521 if (!/^[a-z0-9-]+$/.test(id) || !fps) return
522 if (byName.has(name)) repeated.add(name)
523 byName.set(name, { id, fps: Number(fps) })
524 })
525 for (const name of repeated) byName.delete(name)
526​
527 const at = (key: string) => pixels.keys.indexOf(key)
528 // id|resolution|ratio → rank of the column that set it (2 own, 1 series).
529 const rank = new Map<string, number>()
530 const conflicted = new Set<string>()
531 let resolution = ''
532 let note = ''
533 for (const cells of pixels.rows) {
534 const label = (cells[at('resolution')] ?? '').trim()
535 if (label) {
536 const [first = '', ...rest] = label.split(' ')
537 resolution = first.toLowerCase()
538 note = rest.join(' ')
539 }
540 const ratio = cells[at('aspect ratio')] ?? ''
541 if (!/^(\d+p|4k)$/.test(resolution) || !/^\d+:\d+$/.test(ratio)) continue
542 pixels.keys.forEach((column, index) => {
543 const size = cells[index]?.match(/^(\d+)×(\d+)$/)
544 if (!size) return
545 const series = column.replace(/ series$/, '')
546 for (const [name, model] of byName) {
547 const own = name === column
548 const inSeries =
549 series !== column &&
550 (name === series || name.startsWith(`${series} `))
551 if (!own && !inSeries) continue
552 if (noteServes(note, name) !== true) continue
553 const key = `${model.id}|${resolution}|${ratio}`
554 const level = own ? 2 : 1
555 const geometry = out.get(model.id) ?? { fps: model.fps, dims: {} }
556 const byRatio = (geometry.dims[resolution] ??= {})
557 const size2 = { w: Number(size[1]), h: Number(size[2]) }
558 const prior = rank.get(key) ?? 0
559 if (prior > level) continue
560 const held = byRatio[ratio]
561 if (
562 prior === level &&
563 held &&
564 (held.w !== size2.w || held.h !== size2.h)
565 ) {
566 conflicted.add(model.id)
567 }
568 byRatio[ratio] = size2
569 rank.set(key, level)
570 out.set(model.id, geometry)
571 }
572 })
573 }
574 for (const id of conflicted) out.delete(id)
575 return out
577​
578/** Seedream 5.0 pro: per-image output rates split at a pixel count. */
579export interface ByteplusPixelTiers {
580 /** USD per input image after the first (the first is free). */
581 extraInput: number
582 /** Tier boundary in pixels; at or below it is `low`. */
583 maxLowPixels: number
584 /** The largest `size` level the page puts in the low tier (`1.5K`). */
585 lowLevel: string
586 low: number
587 high: number
589​
590const PIXEL_TIER_INPUT = /^First image: Free From the 2nd image: ([\d.]+)$/i
591// Layer decomposition is not read: the page says one request's layers can
592// land in different tiers, so the card refuses that mode.
593const PIXEL_TIER_OUTPUT =
594 /^Single image generation: ≤ ([\d.]+) million pixels \(([\d.]+)K or lower\): ([\d.]+) > \1 million pixels \(higher than \2K\): ([\d.]+) Layer decomposition: /i
595​
596/** One image-table row as pixel tiers, or null for any other wording. */
597function pixelTierRates(
598 input: string,
599 output: string,
600): ByteplusPixelTiers | null {
601 const inMatch = PIXEL_TIER_INPUT.exec(input)
602 const outMatch = PIXEL_TIER_OUTPUT.exec(output)
603 if (!inMatch || !outMatch) return null
604 const extraInput = decimal(inMatch[1] ?? '')
605 const millions = decimal(outMatch[1] ?? '')
606 const low = decimal(outMatch[3] ?? '')
607 const high = decimal(outMatch[4] ?? '')
608 if (extraInput === null || millions === null || low === null) return null
609 if (high === null) return null
610 const lowLevel = `${outMatch[2]}K`
611 return { extraInput, maxLowPixels: millions * 1e6, lowLevel, low, high }
613​
614/** The image table's pixel-tiered rows; only the first table is read. */
615export function parseByteplusPixelTiers(
616 doc: ByteplusDoc,
617): Map<string, ByteplusPixelTiers> {
618 const out = new Map<string, ByteplusPixelTiers>()
619 const [table] = tablesWith(doc, [
620 'model id',
621 'input image price',
622 'output image price',
623 ])
624 if (!table) return out
625 const at = (key: string) => table.keys.indexOf(key)
626 for (const row of table.rows) {
627 const id = (row[at('model id')] ?? '').split(' ')[0] ?? ''
628 const rates = pixelTierRates(
629 row[at('input image price')] ?? '',
630 row[at('output image price')] ?? '',
631 )
632 if (/^[a-z0-9-]+$/.test(id) && rates) out.set(id, rates)
633 }
634 return out
636​
637/**
638 * Ark's `size` levels for Seedream 5.0 pro image generation (Image
639 * generation API, docs.byteplus.com/en/docs/ModelArk/1541523; default
640 * `2K`). The model picks the pixels, but every size that API doc lists for
641 * a level sits on one side of 2.61 MP, as the pricing page's "(1.5K or
642 * lower)" says. `4K` and `auto` are not image-generation sizes.
643 */
644const SEEDREAM_PRO_LEVELS = ['1K', '1.5K', '2K']
645​
646/**
647 * `usage.generated_images × tier rate + max(0, usage.input_images − 1) ×
648 * input fee`.
649 * `size` is a level (tier from the page's "(1.5K or lower)") or `WxH`
650 * (tier from its pixel count). `layer_decomposition: true` refuses: its
651 * layers are billed per layer at each one's own tier, which no request
652 * field fixes.
653 */
654export function compileSeedreamProCard(
655 rates: ByteplusPixelTiers,
656 source: RateCard['source'],
657): RateCard | null {
658 const levelNumber = (level: string) => Number(level.replace(/K$/, ''))
659 const boundary = levelNumber(rates.lowLevel)
660 if (!SEEDREAM_PRO_LEVELS.includes(rates.lowLevel)) return null
661 const levelTier: Array<Expr> = SEEDREAM_PRO_LEVELS.flatMap((level) => [
662 { '==': [{ var: 'size.level' }, level] },
663 levelNumber(level) <= boundary ? 'low' : 'high',
664 ])
665 const pixels = { '*': [{ var: 'size.width' }, { var: 'size.height' }] }
666 const tier: Expr = {
667 if: [
668 { missing: 'size.level' },
669 { if: [{ '<=': [pixels, rates.maxLowPixels] }, 'low', 'high'] },
670 { if: levelTier },
671 ],
672 }
673 const mode: Expr = {
674 if: [{ var: 'layer_decomposition' }, 'layer_decomposition', 'generation'],
675 }
676 return {
677 inputs: {
678 size: {
679 param: 'size',
680 kind: 'dimensions',
681 levels: SEEDREAM_PRO_LEVELS,
682 default: '2K',
683 },
684 layer_decomposition: {
685 param: 'layer_decomposition',
686 kind: 'boolean',
687 default: false,
688 },
689 // Ark's own count of the request's images: `image` is a string or a
690 // list, and the bill counts what Ark received. Live 2026-10-02: no
691 // image → 0, a string → 1, a list of 3 → 3.
692 input_images: { param: 'input_images', bound: 'usage', kind: 'number' },
693 generated_images: {
694 param: 'generated_images',
695 bound: 'usage',
696 kind: 'number',
697 },
698 },
699 tables: { output: { generation: { low: rates.low, high: rates.high } } },
700 price: {
701 '+': [
702 {
703 '*': [
704 { var: 'generated_images' },
705 { lookup: { table: 'output', keys: [mode, tier] } },
706 ],
707 },
708 {
709 '*': [
710 { max: [0, { '-': [{ var: 'input_images' }, 1] }] },
711 rates.extraInput,
712 ],
713 },
714 ],
715 },
716 examples: [],
717 source,
718 }
720​
721/**
722 * `rate × usage.completion_tokens / 1e6`. The page bills "Token unit price ×
723 * Token consumption" and says consumption is what `usage.completion_tokens`
724 * returns, so that is the price as billed.
725 *
726 * With `geometry`, an omitted `completion_tokens` is estimated by the
727 * page's own formula over the tutorial's published sizes, and the estimate
728 * endpoint labels it as such. The estimate refuses where the published
729 * method does not hold: draft renders, `ratio: adaptive`, and any
730 * resolution × ratio the tutorial does not list.
731 *
732 * When `videoMinimums` is set, an input video uses
733 * `max(input seconds, minimum input for that output length) + output`.
734 * The minimum input seconds are the Lark table's (output 4–15 for 2.0,
735 * 4–30 for 2.5): `output - floor((output - 3) / 3) - 1`. Every pasted
736 * minimum-token cell equals that length times the row's width, height,
737 * and 24 fps, divided by 1024 and rounded. The cron still cannot read
738 * the Lark base, so a duration the table does not list refuses.
739 *
740 * Draft refuses outright on resolution-priced models: the page bills a draft
741 * at a different resolution than the request names. Video input is not a
742 * request field Ark exposes as one value (it rides in `content`), so the
743 * caller states it as `usage.input_video`. Only models whose rates split on
744 * video input take it.
745 */
746/**
747 * Minimum input seconds for one output duration, from the Seedance 2.0 and
748 * 2.5 Lark tables. Same series on both: 3s in for 4s out, 4s in for 5s out,
749 * 20s in for 30s out.
750 */
751export function seedanceMinInputSeconds(output: number): number {
752 return output - Math.floor((output - 3) / 3) - 1
754​
755export function compileSeedanceCard(
756 rates: ByteplusVideoRates,
757 source: RateCard['source'],
758 geometry?: {
759 model: SeedanceGeometry
760 url: string
761 hash: string
762 /** Last output duration the Lark minimum-token table publishes. */
763 videoMinimumsThrough?: number
764 },
765): RateCard | null {
766 const online = rates.default
767 if (!online) return null
768 const resolutions = Object.keys(online)
769 const variants = Object.keys(online[resolutions[0] ?? ''] ?? {})
770 // Every tier prices the same resolutions, each with the same variants.
771 const shape = (tier: Record<string, Record<string, number>>) =>
772 Object.keys(tier).sort().join() === [...resolutions].sort().join() &&
773 Object.values(tier).every(
774 (v) => Object.keys(v).sort().join() === [...variants].sort().join(),
775 )
776 if (!Object.values(rates).every(shape)) return null
777​
778 const inputs: RateCard['inputs'] = {
779 // Ark's own defaults: omitted means online inference, not a draft.
780 service_tier: {
781 param: 'service_tier',
782 kind: 'enum',
783 values: Object.keys(rates),
784 default: 'default',
785 },
786 draft: { param: 'draft', kind: 'boolean', default: false },
787 completion_tokens: {
788 param: 'completion_tokens',
789 bound: 'usage',
790 kind: 'number',
791 },
792 }
793 let resolution: Expr = '*'
794 if (!resolutions.includes('*')) {
795 inputs.resolution = {
796 param: 'resolution',
797 kind: 'enum',
798 values: resolutions,
799 }
800 resolution = { if: [{ var: 'draft' }, 'draft', { var: 'resolution' }] }
801 }
802 let variant: Expr = 'all'
803 let inputVideo: Expr = 'no_input_video'
804 if (variants.includes('video')) {
805 inputs.input_video = {
806 param: 'input_video',
807 bound: 'usage',
808 kind: 'boolean',
809 }
810 variant = { if: [{ var: 'input_video' }, 'video', 'no_video'] }
811 inputVideo = {
812 if: [{ var: 'input_video' }, 'input_video', 'no_input_video'],
813 }
814 } else if (variants.includes('audio')) {
815 inputs.generate_audio = { param: 'generate_audio', kind: 'boolean' }
816 variant = { if: [{ var: 'generate_audio' }, 'audio', 'silent'] }
817 }
818​
819 const tables: RateCard['tables'] = { rate: rates }
820 if (geometry && inputs.completion_tokens?.kind === 'number') {
821 // A series column also lists resolutions a member does not serve
822 // ("2.0 Fast and Mini do not support 1080p"); the rate table is the
823 // model's own list.
824 const dims = inputs.resolution
825 ? Object.fromEntries(
826 Object.entries(geometry.model.dims).filter(([r]) =>
827 resolutions.includes(r),
828 ),
829 )
830 : geometry.model.dims
831 const ratios = [...new Set(Object.values(dims).flatMap(Object.keys))]
832 const through = geometry.videoMinimumsThrough
833 const minInput =
834 through === undefined || !variants.includes('video')
835 ? undefined
836 : Object.fromEntries(
837 Array.from({ length: through - 3 }, (_, i) => {
838 const output = i + 4
839 return [String(output), seedanceMinInputSeconds(output)]
840 }),
841 )
842 const estimateInputs: RateCardEstimate['inputs'] = {
843 ratio: { param: 'ratio', kind: 'enum', values: ratios },
844 duration: { param: 'duration', kind: 'number' },
845 }
846 if (minInput) {
847 estimateInputs.input_video_duration = {
848 param: 'input_video_duration',
849 kind: 'number',
850 default: 0,
851 }
852 }
853 if (!inputs.resolution) {
854 estimateInputs.resolution = {
855 param: 'resolution',
856 kind: 'enum',
857 values: Object.keys(dims),
858 }
859 }
860 const side = (key: 'w' | 'h'): Expr => ({
861 lookup: {
862 table: 'pixels',
863 keys: [{ var: 'resolution' }, { var: 'ratio' }, key],
864 },
865 })
866 tables.pixels = dims
867 if (minInput) tables.min_input_seconds = minInput
868 // Shapes the published method covers; any other key refuses.
869 tables.estimate_supported = minInput
870 ? { no_input_video: { not_draft: 1 }, input_video: { not_draft: 1 } }
871 : { no_input_video: { not_draft: 1 } }
872 const seconds: Expr = minInput
873 ? {
874 if: [
875 { var: 'input_video' },
876 {
877 '+': [
878 {
879 max: [
880 { var: 'input_video_duration' },
881 {
882 lookup: {
883 table: 'min_input_seconds',
884 keys: [{ var: 'duration' }],
885 },
886 },
887 ],
888 },
889 { var: 'duration' },
890 ],
891 },
892 { var: 'duration' },
893 ],
894 }
895 : { var: 'duration' }
896 inputs.completion_tokens.estimate = {
897 inputs: estimateInputs,
898 value: {
899 '*': [
900 {
901 lookup: {
902 table: 'estimate_supported',
903 keys: [
904 inputVideo,
905 { if: [{ var: 'draft' }, 'draft', 'not_draft'] },
906 ],
907 },
908 },
909 {
910 '/': [
911 {
912 '*': [seconds, side('w'), side('h'), geometry.model.fps],
913 },
914 1024,
915 ],
916 },
917 ],
918 },
919 source: { url: geometry.url, hash: geometry.hash },
920 }
921 }
922 return {
923 inputs,
924 tables,
925 price: {
926 '/': [
927 {
928 '*': [
929 {
930 lookup: {
931 table: 'rate',
932 keys: [{ var: 'service_tier' }, resolution, variant],
933 },
934 },
935 { var: 'completion_tokens' },
936 ],
937 },
938 1_000_000,
939 ],
940 },
941 examples: [],
942 source,
943 }
945​
946/** Standard-table rates from the pricing page HTML. */
947export function parseByteplusPricingPage(
948 html: string,
949): Map<string, ByteplusChatRates> {
950 return parseByteplusPricing(JSON.parse(pricingContent(html)) as ByteplusDoc)
952​
953/**
954 * `curDoc.Content` only. The page shell around it reshuffles between
955 * fetches, so hashing the HTML would mark unchanged prices as new.
956 */
957export function pricingContent(
958 html: string,
959 label = 'byteplus pricing page',
960): string {
961 const at = html.indexOf('window._ROUTER_DATA')
962 const start = html.indexOf('{', at)
963 const end = html.indexOf('</script>', start)
964 if (at < 0 || start < 0 || end < 0) {
965 throw new Error(`${label}: no _ROUTER_DATA`)
966 }
967 const router = JSON.parse(html.slice(start, end)) as {
968 loaderData?: Record<string, { curDoc?: { Content?: string } } | null>
969 }
970 const content = Object.values(router.loaderData ?? {}).find(
971 (entry) => typeof entry?.curDoc?.Content === 'string',
972 )?.curDoc?.Content
973 if (!content) throw new Error(`${label}: no curDoc.Content`)
974 return content
976​
977type PricedFacts = Pick<ModelInfo, 'pricing' | 'factSources' | 'serverTools'>
978​
979interface CachedPricing {
980 rates: Record<string, ByteplusChatRates>
981 video: Record<string, ByteplusVideoRates>
982 images: Record<string, number>
983 // Absent on entries cached before #102.
984 pixelTiers?: Record<string, ByteplusPixelTiers>
985 serverTools?: Record<string, Array<string>>
986 hash: string
987 extractedAt: string
989​
990interface CachedGuide {
991 geometry: Record<string, SeedanceGeometry>
992 hash: string
994​
995/**
996 * Tutorial geometry, or none: it only feeds the labelled estimate, so a
997 * failed fetch or parse publishes billed-only cards rather than failing
998 * every BytePlus price with it.
999 */
1000async function seedanceGuide(kv?: KVNamespace): Promise<CachedGuide | null> {
1001 const label = 'byteplus video generation tutorial'
1002 try {
1003 return await cachedDocs<CachedGuide>(
1004 kv,
1005 BYTEPLUS_VIDEO_GUIDE_URL,
1006 async () => {
1007 const content = pricingContent(
1008 await fetchText(BYTEPLUS_VIDEO_GUIDE_URL),
1009 label,
1011 const parsed = parseSeedanceGeometry(JSON.parse(content) as ByteplusDoc)
1012 assertParsed(parsed, label)
1013 return {
1014 geometry: Object.fromEntries(parsed),
1015 hash: await sha256Text(content),
1017 },
1019 } catch (error) {
1020 console.warn(
1021 JSON.stringify({
1022 job: 'byteplus-pricing',
1023 skipped: 'seedance estimates',
1024 error: errorMessage(error),
1025 }),
1027 return null
1030​
1031/**
1032 * Model-list document, or none. It only names aliases for prices the
1033 * pricing page already published, so a failed fetch still prices those rows.
1034 */
1035async function modelListContent(): Promise<string | null> {
1036 const label = 'byteplus model list'
1037 try {
1038 return pricingContent(await fetchText(BYTEPLUS_MODEL_LIST_URL), label)
1039 } catch (error) {
1040 console.warn(
1041 JSON.stringify({
1042 job: 'byteplus-pricing',
1043 skipped: 'model list aliases',
1044 error: errorMessage(error),
1045 }),
1047 return null
1050​
1051/** Card lookup by catalog id. Ids no table prices get nothing. */
1052export async function byteplusModelPricing(
1053 kv?: KVNamespace,
1054): Promise<(rawId: string) => PricedFacts> {
1055 const doc = await cachedDocs<CachedPricing>(
1056 kv,
1057 BYTEPLUS_PRICING_URL,
1058 async () => {
1059 const html = await fetchText(BYTEPLUS_PRICING_URL)
1060 const content = pricingContent(html)
1061 const page = JSON.parse(content) as ByteplusDoc
1062 const parsed = parseByteplusPricing(page)
1063 const video = parseByteplusVideo(page)
1064 const images = parseByteplusImages(page)
1065 const pixelTiers = parseByteplusPixelTiers(page)
1066 assertParsed(parsed, 'byteplus pricing page')
1067 assertParsed(video, 'byteplus pricing page (video)')
1068 assertParsed(images, 'byteplus pricing page (images)')
1069 const listContent = await modelListContent()
1070 const aliases = listContent
1071 ? parseByteplusAliases(JSON.parse(listContent) as ByteplusDoc)
1072 : new Map<string, string>()
1073 // Alias notes are not chat prices. A dated snapshot with no row stays
1074 // unpriced; only the published "also supports" pair is copied.
1075 sharePublishedAliases(video, aliases)
1076 sharePublishedAliases(images, aliases)
1077 sharePublishedAliases(pixelTiers, aliases)
1078 return {
1079 rates: Object.fromEntries(parsed),
1080 video: Object.fromEntries(video),
1081 images: Object.fromEntries(images),
1082 pixelTiers: Object.fromEntries(pixelTiers),
1083 serverTools: Object.fromEntries(parseByteplusServerTools(html)),
1084 hash: await sha256Text(listContent ? content + listContent : content),
1085 extractedAt: new Date().toISOString(),
1087 },
1089 const guide = await seedanceGuide(kv)
1090 const geometry = new Map(Object.entries(guide?.geometry ?? {}))
1091 const rates = new Map(Object.entries(doc.rates))
1092 const video = new Map(Object.entries(doc.video))
1093 const images = new Map(Object.entries(doc.images))
1094 const pixelTiers = new Map(Object.entries(doc.pixelTiers ?? {}))
1095 const source = {
1096 url: BYTEPLUS_PRICING_URL,
1097 hash: doc.hash,
1098 extractedAt: doc.extractedAt,
1100 const card = (rawId: string): RateCard | null => {
1101 const chat = byteplusRatesFor(rawId, rates)
1102 if (chat) {
1103 return compileTokenCard(chat.base, chat.tiers, source, {
1104 extraPromptLevers: ['audio_tokens', 'audio_cache_tokens'],
1105 })
1107 const seedance = byteplusRatesFor(rawId, video)
1108 if (seedance) {
1109 const model = byteplusRatesFor(rawId, geometry)
1110 return compileSeedanceCard(
1111 seedance,
1112 source,
1113 model && guide
1114 ? {
1115 model,
1116 url: BYTEPLUS_VIDEO_GUIDE_URL,
1117 hash: guide.hash,
1118 // Lark minimum-token table: 2.5 publishes outputs 4–30,
1119 // 2.0 publishes 4–15. Other video models have no table.
1120 videoMinimumsThrough: rawId.includes('seedance-2-5')
1121 ? 30
1122 : rawId.includes('seedance-2-0')
1123 ? 15
1124 : undefined,
1126 : undefined,
1129 const tiered = byteplusRatesFor(rawId, pixelTiers)
1130 if (tiered) return compileSeedreamProCard(tiered, source)
1131 const perImage = byteplusRatesFor(rawId, images)
1132 if (perImage === undefined) return null
1133 // Billed per image returned (usage.generated_images); group-image mode
1134 // returns a variable count, so the caller supplies it.
1135 return compileUnitCard(
1137 quantity: { param: 'generated_images', bound: 'usage' },
1138 rates: perImage,
1139 },
1140 source,
1143 return (rawId) => {
1144 const pricing = card(rawId)
1145 const tools = doc.serverTools?.[rawId]
1146 const pricingFacts = pricing
1147 ? tagDocsFacts({ pricing }, BYTEPLUS_PRICING_URL, doc.hash)
1148 : {}
1149 const toolFacts =
1150 tools && tools.length > 0
1151 ? tagDocsFacts({ serverTools: tools }, BYTEPLUS_PRICING_URL, doc.hash)
1152 : {}
1153 const factSources = { ...pricingFacts, ...toolFacts }
1154 if (!pricing && !tools) return {}
1155 return {
1156 ...(pricing ? { pricing } : {}),
1157 ...(tools && tools.length > 0 ? { serverTools: tools } : {}),
1158 ...(Object.keys(factSources).length > 0 ? { factSources } : {}),