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

stability-pricing.ts

91 lines3.5 KB

1/**
2 * Stability prices from the pricing docs (issues #122, #362). The page
3 * moved to Mintlify at docs.stability.ai, which serves it as markdown:
4 * `1 credit = \$0.01` (the dollar sign escaped), then
5 * `| Service | Description | Price (credits) |` tables. A service whose
6 * price is a single credit count becomes that many cents per request. "From 0.9" is not a single amount, so that
7 * service stays unpriced. A page that prices nothing throws.
8 */
9import { compileUnitCard } from '@modelschemas/rate-card'
10import type { RateCard } from '@modelschemas/rate-card'
11​
12import { tagDocsFacts } from './fact-sources.ts'
13import { assertParsed, markdownTableRows } from './model-facts.ts'
14import type { cachedDocs } from './model-facts.ts'
15import { fetchText, sha256Text } from './types.ts'
16import type { ModelInfo } from './types.ts'
17​
18export const STABILITY_PRICING_URL = 'https://docs.stability.ai/pricing.md'
19​
20const CREDIT_USD = /1 credit = \\?\$(\d+(?:\.\d+)?)/
21const EXACT_CREDITS = /^\d+(?:\.\d+)?$/
22/** `[Stable Image Ultra](/api-reference/...)` → `Stable Image Ultra`. */
23const LINKED_NAME = /^\[([^\]]+)\]\([^)]*\)$/
24​
25/** Service name → USD per request. Inexact prices are absent. */
26export function parseStabilityPricing(source: string): Map<string, number> {
27 const credit = source.match(CREDIT_USD)?.[1]
28 if (credit === undefined) return new Map()
29 const usd = Number(credit)
30 const out = new Map<string, number>()
31 // Only tables headed `| Service | … | Price (credits) |` are credits
32 // per request; any other table on the page is not read.
33 for (const block of source.split(/\n\s*\n/)) {
34 const [header, ...rows] = markdownTableRows(block)
35 if (header?.[0] !== 'Service' || header[2] !== 'Price (credits)') continue
36 for (const [service, , price] of rows) {
37 if (service === undefined || price === undefined) continue
38 if (!EXACT_CREDITS.test(price)) continue
39 const name = service.match(LINKED_NAME)?.[1] ?? service
40 const rate = Number(price) * usd
41 const prior = out.get(name)
42 if (prior !== undefined && prior !== rate) {
43 throw new Error(`stability pricing: ${name} has two prices`)
44 }
45 out.set(name, rate)
46 }
47 }
48 return out
50​
51type PricedFacts = Pick<ModelInfo, 'pricing' | 'factSources'>
52​
53/**
54 * Card lookup by catalog id against the page's service names. The page
55 * names services, not `/v1/engines/list` ids, so an engine id matches only
56 * where the page states that same string; today none does, and no card is
57 * attached. Load it through `tryDocs`; this throws when the page prices
58 * nothing.
59 */
60export async function stabilityModelPricing(
61 kv: KVNamespace | undefined,
62 cached: typeof cachedDocs,
63): Promise<(rawId: string) => PricedFacts> {
64 const doc = await cached(kv, STABILITY_PRICING_URL, async () => {
65 const source = await fetchText(STABILITY_PRICING_URL)
66 const parsed = parseStabilityPricing(source)
67 assertParsed(parsed, 'stability pricing page')
68 return {
69 rates: Object.fromEntries(parsed),
70 hash: await sha256Text(source),
71 extractedAt: new Date().toISOString(),
72 }
73 })
74 return (rawId) => {
75 const usd = doc.rates[rawId]
76 if (usd === undefined) return {}
77 const pricing: RateCard | null = compileUnitCard(
78 { rates: usd },
79 {
80 url: STABILITY_PRICING_URL,
81 hash: doc.hash,
82 extractedAt: doc.extractedAt,
83 },
84 )
85 if (!pricing) return {}
86 return {
87 pricing,
88 factSources: tagDocsFacts({ pricing }, STABILITY_PRICING_URL, doc.hash),
89 }
90 }