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