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

together-pricing.ts

171 lines5.2 KB

1/**
2 * Together image, video, and audio prices from the serverless catalog
3 * (issue #115). Chat token rates stay on the models listing. A per-image
4 * cell marked as varying is the provider’s pass-through estimate, not a
5 * rate, so it stays null. Video rows that name a clip length are per
6 * second (price ÷ seconds). A video price with no length is the catalog’s
7 * per-video figure. All-zero and unpublished rows stay null.
8 */
9import { compileUnitCard } from '@modelschemas/rate-card'
10import type { RateCard, UnitCardSpec } from '@modelschemas/rate-card'
11​
12import { tagDocsFacts } from './fact-sources.ts'
13import {
14 assertParsed,
15 cachedDocs,
16 markdownSection,
17 markdownTableRows,
18} from './model-facts.ts'
19import { fetchText, sha256Text } from './types.ts'
20import type { ModelInfo } from './types.ts'
21​
22export const TOGETHER_MODELS_DOCS_URL =
23 'https://docs.together.ai/docs/serverless/models.md'
24​
25const MEDIA_ACTIVITIES = new Set(['image', 'video', 'audio'])
26​
27function clean(cell: string): string {
28 return cell.replace(/\\/g, '').replace(/`/g, '').replace(/\s+/g, ' ').trim()
30​
31function modelId(cell: string): string | null {
32 const id = clean(cell)
33 return /^[A-Za-z0-9][\w.+-]*\/[\w.+-]+$/.test(id) ? id : null
35​
36/** Leading dollar amount. `null` when the cell is not a single rate. */
37function fixedDollars(cell: string): number | null {
38 const text = clean(cell)
39 if (text === '' || text === '-' || /varies|\+/i.test(text)) return null
40 const amounts = [...text.matchAll(/\$(\d+(?:\.\d+)?)/g)]
41 if (amounts.length !== 1 || !amounts[0]?.[1]) return null
42 const amount = Number(amounts[0][1])
43 return Number.isFinite(amount) && amount > 0 ? amount : null
45​
46function put(
47 out: Map<string, UnitCardSpec>,
48 id: string | null,
49 spec: UnitCardSpec | null,
50): void {
51 if (!id || !spec || out.has(id.toLowerCase())) return
52 out.set(id.toLowerCase(), spec)
54​
55function imageSpec(unitCell: string, priceCell: string): UnitCardSpec | null {
56 const amount = fixedDollars(priceCell)
57 if (amount === null) return null
58 const unit = clean(unitCell).toLowerCase()
59 if (unit === 'megapixel') {
60 return {
61 quantity: { param: 'megapixels', bound: 'usage' },
62 rates: amount,
63 }
64 }
65 if (unit === 'image') {
66 return {
67 quantity: { param: 'images', bound: 'usage' },
68 rates: amount,
69 }
70 }
71 return null
73​
74function videoSpec(
75 priceCell: string,
76 _detailCell: string,
77): UnitCardSpec | null {
78 // The catalog column is "Price per video". Dividing by the duration cell
79 // would invent a per-second rate the page does not print.
80 const amount = fixedDollars(priceCell)
81 if (amount === null) return null
82 return { rates: amount }
84​
85function audioSpec(priceCell: string): UnitCardSpec | null {
86 const text = clean(priceCell)
87 const amount = fixedDollars(priceCell)
88 if (amount === null) return null
89 if (/per 1M chars/i.test(text)) {
90 return {
91 quantity: { param: 'characters', bound: 'usage' },
92 rates: amount / 1e6,
93 }
94 }
95 if (/per audio min/i.test(text)) {
96 return {
97 quantity: { param: 'audio_seconds', bound: 'usage' },
98 rates: amount / 60,
99 }
100 }
101 return null
103​
104/** Model id (lowercase) → unit sheet. Ids the catalog does not rate are absent. */
105export function parseTogetherMediaPrices(
106 markdown: string,
107): Map<string, UnitCardSpec> {
108 const out = new Map<string, UnitCardSpec>()
109 for (const cells of markdownTableRows(
110 markdownSection(markdown, 'Image models'),
111 )) {
112 put(out, modelId(cells[2] ?? ''), imageSpec(cells[3] ?? '', cells[4] ?? ''))
113 }
114 for (const cells of markdownTableRows(
115 markdownSection(markdown, 'Video models'),
116 )) {
117 put(out, modelId(cells[2] ?? ''), videoSpec(cells[3] ?? '', cells[4] ?? ''))
118 }
119 for (const cells of markdownTableRows(
120 markdownSection(markdown, 'Audio models'),
121 )) {
122 put(out, modelId(cells[3] ?? ''), audioSpec(cells[4] ?? ''))
123 }
124 return out
126​
127/** The unit card `listModels` stores. `null` when the sheet is not a price. */
128export function togetherMediaCard(
129 spec: UnitCardSpec,
130 source: RateCard['source'],
131): RateCard | null {
132 return compileUnitCard(spec, source)
134​
135type PricedFacts = Pick<ModelInfo, 'pricing' | 'factSources'>
136​
137/** Card lookup for image, video, and audio ids. Chat ids are not in the map. */
138export async function togetherMediaPricing(
139 kv?: KVNamespace,
140): Promise<(rawId: string, activity: string | null) => PricedFacts> {
141 const doc = await cachedDocs(kv, TOGETHER_MODELS_DOCS_URL, async () => {
142 const markdown = await fetchText(TOGETHER_MODELS_DOCS_URL)
143 const parsed = parseTogetherMediaPrices(markdown)
144 assertParsed(parsed, 'together models catalog')
145 return {
146 rates: Object.fromEntries(parsed),
147 hash: await sha256Text(markdown),
148 extractedAt: new Date().toISOString(),
149 }
150 })
151 return (rawId, activity) => {
152 if (!activity || !MEDIA_ACTIVITIES.has(activity)) return {}
153 const spec = doc.rates[rawId.toLowerCase()]
154 if (!spec) return {}
155 const source = {
156 url: TOGETHER_MODELS_DOCS_URL,
157 hash: doc.hash,
158 extractedAt: doc.extractedAt,
159 }
160 const pricing = togetherMediaCard(spec, source)
161 if (!pricing) return {}
162 return {
163 pricing,
164 factSources: tagDocsFacts(
165 { pricing },
166 TOGETHER_MODELS_DOCS_URL,
167 doc.hash,
168 ),
169 }
170 }