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