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

baseten.ts

268 lines8.3 KB

1/**
2 * Baseten Model APIs. The catalog is `GET /v1/models` on the inference host.
3 * That list publishes id, context, modalities, and per-token prices. It
4 * requires `BASETEN_API_KEY`; a missing key skips so stored rows stay.
5 * Effort values come from the public reasoning page, joined by display name.
6 * A zero price string is not a rate. Schemas are the published OpenAPI files.
7 */
8import { compileTokenCard } from '@modelschemas/rate-card'
9import type { RateCard } from '@modelschemas/rate-card'
10​
11import type { Activity } from '#/db/schema.ts'
12​
13import { fetchOpenApi, fetchText, sha256Text, skippedResult } from '../types.ts'
14import type {
15 FactSource,
16 ListModelsResult,
17 ModelInfo,
18 ModelReasoning,
19 ProviderConfig,
20 ProviderSecrets,
21 SpecFetchResult,
22} from '../types.ts'
23​
24export const BASETEN_MODELS_URL = 'https://inference.baseten.co/v1/models'
25export const BASETEN_REASONING_URL =
26 'https://docs.baseten.co/inference/model-apis/reasoning.md'
27export const BASETEN_CHAT_OPENAPI_URL =
28 'https://docs.baseten.co/reference/inference-api/llm-openapi-spec.json'
29export const BASETEN_MESSAGES_OPENAPI_URL =
30 'https://docs.baseten.co/reference/inference-api/messages-openapi-spec.json'
31​
32const CHAT_ENDPOINT = 'v1/chat/completions'
33​
34interface TokenQuote {
35 input: number
36 output: number
37 cache: number | null
39​
40function isRecord(value: unknown): value is Record<string, unknown> {
41 return typeof value === 'object' && value !== null && !Array.isArray(value)
43​
44function cells(line: string): Array<string> | null {
45 if (!line.startsWith('|')) return null
46 const row = line
47 .split('|')
48 .slice(1, -1)
49 .map((cell) => cell.trim())
50 if (row.length === 0 || row.every((cell) => /^:?-+:?$/.test(cell)))
51 return null
52 return row
54​
55function positiveRate(value: unknown): number | null {
56 if (typeof value !== 'string' && typeof value !== 'number') return null
57 const parsed = typeof value === 'number' ? value : Number(value)
58 return Number.isFinite(parsed) && parsed > 0 ? parsed : null
60​
61function stringList(value: unknown): Array<string> | null {
62 if (!Array.isArray(value) || value.length === 0) return null
63 const out: Array<string> = []
64 for (const item of value) {
65 if (typeof item !== 'string' || item.length === 0) return null
66 out.push(item)
67 }
68 return out
70​
71function positiveInt(value: unknown): number | null {
72 return typeof value === 'number' && Number.isInteger(value) && value > 0
73 ? value
74 : null
76​
77function parseEfforts(markdown: string): Map<string, Array<string>> {
78 const start = markdown.search(/^## Control reasoning depth/m)
79 if (start < 0) {
80 throw new Error('baseten: reasoning page has no effort table')
81 }
82 const rest = markdown.slice(start)
83 const next = rest.slice(1).search(/^## /m)
84 const section = next < 0 ? rest : rest.slice(0, next + 1)
85 const efforts = new Map<string, Array<string>>()
86 for (const line of section.split('\n')) {
87 const row = cells(line)
88 if (!row || row.length < 2 || row[0] === 'Model') continue
89 const values = (row[1] ?? '')
90 .replace(/\(default\)/gi, '')
91 .split(',')
92 .map((value) => value.replace(/`/g, '').trim())
93 .filter((value) => value.length > 0)
94 if (values.length === 0) continue
95 efforts.set(row[0] ?? '', values)
96 }
97 if (efforts.size === 0) {
98 throw new Error('baseten: reasoning page listed no efforts')
99 }
100 return efforts
102​
103function alwaysOnPrefixes(markdown: string): Array<string> {
104 const match = /Thinking is always on for the ([^,\n]+?) family/i.exec(
105 markdown,
106 )
107 const prefix = match?.[1]?.trim()
108 return prefix ? [prefix] : []
110​
111function reasoningFor(
112 name: string,
113 efforts: Map<string, Array<string>>,
114 families: Array<string>,
115): ModelReasoning | null {
116 const values = efforts.get(name)
117 if (!values) return null
118 const alwaysOn = families.some(
119 (family) => name === family || name.startsWith(`${family} `),
120 )
121 return {
122 mode: 'effort',
123 mandatory: alwaysOn || !values.includes('none'),
124 efforts: values,
125 }
127​
128function quoteFor(pricing: unknown): TokenQuote | null {
129 if (!isRecord(pricing)) return null
130 const input = positiveRate(pricing.prompt)
131 const output = positiveRate(pricing.completion)
132 if (input === null || output === null) return null
133 return { input, output, cache: positiveRate(pricing.input_cache_read) }
135​
136function activityFor(output: Array<string> | null): Activity | null {
137 if (!output) return null
138 if (output.includes('text')) return 'chat'
139 if (output.includes('image')) return 'image'
140 if (output.includes('audio')) return 'audio'
141 return null
143​
144/** Rows from `GET /v1/models`. Efforts join by the row's display name. */
145export function parseBasetenModels(
146 payload: unknown,
147 reasoningMarkdown: string,
148 source: RateCard['source'],
149 reasoningHash: string,
150): Array<ModelInfo> {
151 if (!isRecord(payload) || !Array.isArray(payload.data)) {
152 throw new Error('baseten: models payload has no data array')
153 }
154 const efforts = parseEfforts(reasoningMarkdown)
155 const families = alwaysOnPrefixes(reasoningMarkdown)
156 const models: Array<ModelInfo> = []
157 for (const row of payload.data) {
158 if (!isRecord(row) || typeof row.id !== 'string' || row.id.length === 0) {
159 continue
160 }
161 const name = typeof row.name === 'string' ? row.name : null
162 const quote = quoteFor(row.pricing)
163 const pricing = quote
164 ? compileTokenCard(
165 {
166 input_tokens: quote.input,
167 output_tokens: quote.output,
168 ...(quote.cache !== null ? { cache_read_tokens: quote.cache } : {}),
169 },
170 [],
171 source,
172 )
173 : null
174 const reasoning = name ? reasoningFor(name, efforts, families) : null
175 const input = stringList(row.input_modalities)
176 const output = stringList(row.output_modalities)
177 const reasoningSource: FactSource | undefined = reasoning
178 ? {
179 derivation: 'docs-derived',
180 sourceUrl: BASETEN_REASONING_URL,
181 sourceHash: reasoningHash,
182 path: 'reasoning_effort',
183 }
184 : undefined
185 models.push({
186 rawId: row.id,
187 displayName: name,
188 activity: activityFor(output),
189 contextWindow: positiveInt(row.context_length),
190 maxOutput: positiveInt(row.max_completion_tokens),
191 modalities: input && output ? { input, output } : null,
192 pricing,
193 reasoning,
194 releasedAt: positiveInt(row.created),
195 ...(reasoningSource
196 ? { factSources: { reasoning: reasoningSource } }
197 : {}),
198 })
199 }
200 if (models.length === 0) {
201 throw new Error('baseten: models payload listed no ids')
202 }
203 return models
205​
206async function listModels(env: ProviderSecrets): Promise<ListModelsResult> {
207 const key = env.BASETEN_API_KEY
208 if (!key)
209 return { models: [], ...skippedResult('baseten', 'BASETEN_API_KEY') }
210 const [modelsText, reasoning] = await Promise.all([
211 fetchText(BASETEN_MODELS_URL, {
212 headers: { Authorization: `Bearer ${key}` },
213 }),
214 fetchText(BASETEN_REASONING_URL),
215 ])
216 const [modelsHash, reasoningHash] = await Promise.all([
217 sha256Text(modelsText),
218 sha256Text(reasoning),
219 ])
220 return {
221 models: parseBasetenModels(
222 JSON.parse(modelsText) as unknown,
223 reasoning,
224 {
225 url: BASETEN_MODELS_URL,
226 hash: modelsHash,
227 extractedAt: new Date().toISOString(),
228 },
229 reasoningHash,
230 ),
231 }
233​
234async function fetchSpec(_env: ProviderSecrets): Promise<SpecFetchResult> {
235 const [chat, messages] = await Promise.all([
236 fetchOpenApi(BASETEN_CHAT_OPENAPI_URL),
237 fetchOpenApi(BASETEN_MESSAGES_OPENAPI_URL),
238 ])
239 return {
240 specs: [chat.spec, messages.spec],
241 sources: [
242 { url: BASETEN_CHAT_OPENAPI_URL, hash: chat.hash },
243 { url: BASETEN_MESSAGES_OPENAPI_URL, hash: messages.hash },
244 ],
245 outputStrategy: 'post-200',
246 specRevision: chat.hash,
247 }
249​
250export function classifyBasetenPath(path: string): Activity | null {
251 const bare = path.replace(/^\//, '')
252 if (bare === CHAT_ENDPOINT || bare === 'v1/messages') return 'chat'
253 return null
255​
256export const provider: ProviderConfig = {
257 id: 'baseten',
258 displayName: 'Baseten',
259 authEnvVar: 'BASETEN_API_KEY',
260 specSourceUrl: BASETEN_CHAT_OPENAPI_URL,
261 modelsEndpoint: BASETEN_MODELS_URL,
262 defaultDerivation: 'upstream-spec',
263 fetchSpec,
264 listModels,
265 classify: (path) => classifyBasetenPath(path),
266 generationEndpointId: ({ activity }) =>
267 activity === 'chat' ? CHAT_ENDPOINT : null,