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

estimate.ts

344 lines11.2 KB

1/**
2 * POST /v1/estimate — evaluate a stored rate card against a request/usage
3 * pair. Thin wrapper around `normalizeUsage` and `priceDetailed` from
4 * @modelschemas/rate-card, so `usage` is card levers or the provider's own
5 * usage object;
6 * `estimated` names any input filled by the card's published estimate,
7 * `defaulted` any input that took the card's default, and `ignored` any
8 * request key the card does not read. A routed id with a `pricingRange`
9 * and no card is priced on every route's card and returns `{ min, max }`.
10 * A card missing only one required choice input returns `{ byInput }`,
11 * one price per allowed value.
12 */
13import {
14 cardCurrency,
15 normalizeUsage,
16 priceDetailed,
17 RateCardError,
18} from '@modelschemas/rate-card'
19import type { RateCard, RateCardInput } from '@modelschemas/rate-card'
20​
21import { and, eq, inArray } from 'drizzle-orm'
22​
23import type { Db } from '#/db/index.ts'
24import { models } from '#/db/schema.ts'
25import { getModelDetail } from '#/server/catalog.ts'
26import { parseStoredRateCard } from '#/server/rate-card.ts'
27import type { PricingRange } from '#/server/rate-card.ts'
28​
29export interface EstimateRequestBody {
30 provider: string
31 model: string
32 request?: Record<string, unknown>
33 usage?: Record<string, unknown>
35​
36export interface EstimateResult {
37 /** The price, in `currency` (ISO 4217). Never converted. */
38 amount: number
39 currency: string
40 /** `amount` again for a USD card; absent for any other currency. */
41 usd?: number
42 cardSource: RateCard['source']
43 /** Omitted params the card estimated; empty means billed price. */
44 estimated: string[]
45 /** Omitted params that took the card's default value. */
46 defaulted: string[]
47 /** Request keys the card does not read. */
48 ignored: string[]
50​
51/**
52 * A routed id with no single billed price (issue #406): the call priced
53 * on every route's card. The bill is one route's amount, somewhere in
54 * [min, max]; neither end is the billed price.
55 */
56export interface EstimateRangeResult {
57 currency: string
58 min: EstimateResult & { model: string }
59 max: EstimateResult & { model: string }
60 /** Every route priced, as model ids under the same provider. */
61 routes: string[]
63​
64/**
65 * A card whose one required choice input (enum or boolean, no default)
66 * was not supplied (issue #450): the call priced once per allowed value.
67 * The bill is the amount for the value the call actually uses.
68 */
69export interface EstimateByInputResult {
70 currency: string
71 byInput: {
72 /** The param the call omitted. */
73 input: string
74 /** Each allowed value (booleans as "true"/"false") → its price. */
75 values: Record<string, EstimateResult>
76 }
78​
79type EstimateError = {
80 ok: false
81 status: number
82 code: string
83 message: string
85​
86export type EstimateOutcome =
87 | {
88 ok: true
89 result: EstimateResult | EstimateRangeResult | EstimateByInputResult
90 }
91 | EstimateError
92​
93const isRecord = (value: unknown): value is Record<string, unknown> =>
94 typeof value === 'object' && value !== null && !Array.isArray(value)
95​
96export function parseEstimateBody(raw: unknown): EstimateRequestBody | null {
97 if (!isRecord(raw)) return null
98 if (typeof raw.provider !== 'string' || typeof raw.model !== 'string') {
99 return null
100 }
101 if (raw.request !== undefined && !isRecord(raw.request)) return null
102 if (raw.usage !== undefined && !isRecord(raw.usage)) return null
103 return {
104 provider: raw.provider,
105 model: raw.model,
106 request: raw.request,
107 usage: raw.usage,
108 }
110​
111function mapRateCardError(
112 error: RateCardError,
113 card: RateCard,
114 body: EstimateRequestBody,
115): { code: string; message: string } {
116 const input = error.input === undefined ? undefined : card.inputs[error.input]
117 const slot = input ? slotOf(input) : undefined
118 if (error.code === 'bad-input' && slot) {
119 return {
120 code: 'unbound_input',
121 message:
122 `Rate card requires ${slot} which was not provided. ` +
123 `Pass it on the estimate body. See GET /v1/models/${body.provider}/${body.model}.`,
124 }
125 }
126 if (error.code === 'estimate-unavailable' && slot) {
127 return {
128 code: 'unbound_input',
129 message:
130 `Rate card requires ${slot}; it was not provided and could not be estimated (${error.message}). ` +
131 `Pass it on the estimate body. See GET /v1/models/${body.provider}/${body.model}.`,
132 }
133 }
134 return {
135 code: error.code.replaceAll('-', '_'),
136 message:
137 `${error.message}. Check request/usage against the model's rate card ` +
138 `at GET /v1/models/${body.provider}/${body.model}.`,
139 }
141​
142export async function estimateCost(
143 db: Db,
144 body: EstimateRequestBody,
145): Promise<EstimateOutcome> {
146 const model = await getModelDetail(db, body.provider, body.model)
147 if (!model) {
148 return {
149 ok: false,
150 status: 404,
151 code: 'unknown_model',
152 message: `Unknown model '${body.model}' for provider '${body.provider}'. Try GET /v1/providers/${body.provider}/models for valid ids.`,
153 }
154 }
155 const card = parseStoredRateCard(model.pricing)
156 if (card) return priceCard(card, body)
157 if (model.pricingRange) {
158 return priceRoutes(db, body, model.pricingRange.routes)
159 }
160 return noCard(body)
162​
163function noCard(body: EstimateRequestBody): EstimateError {
164 return {
165 ok: false,
166 status: 404,
167 code: 'unknown_pricing',
168 message: `No rate card for '${body.provider}/${body.model}'. See GET /v1/models/${body.provider}/${body.model}.`,
169 }
171​
172/** The values a required choice input (enum or boolean, no default) takes. */
173function choiceValues(
174 input: RateCardInput | undefined,
175): Array<string | boolean> | undefined {
176 if (input?.kind === 'enum' && input.default === undefined) return input.values
177 if (input?.kind === 'boolean' && input.default === undefined) {
178 return [true, false]
179 }
180 return undefined
182​
183const slotOf = (input: RateCardInput) =>
184 `${input.bound === 'usage' ? 'usage' : 'request'}.${input.param}`
185​
186/**
187 * Price the call. When exactly one required choice input is missing and
188 * nothing else is, price it once per allowed value (issue #450); two
189 * missing choices, or any missing quantity, refuse.
190 */
191function priceCard(
192 card: RateCard,
193 body: EstimateRequestBody,
194):
195 | { ok: true; result: EstimateResult | EstimateByInputResult }
196 | EstimateError {
197 const refuse = (error: unknown, prefix = ''): EstimateError => {
198 if (!(error instanceof RateCardError)) throw error
199 const mapped = mapRateCardError(error, card, body)
200 return {
201 ok: false,
202 status: 422,
203 ...mapped,
204 message: prefix + mapped.message,
205 }
206 }
207 let request = body.request ?? {}
208 let usage: Record<string, unknown>
209 try {
210 usage = normalizeUsage(card, body.usage ?? {})
211 } catch (error) {
212 return refuse(error)
213 }
214 const fill = (name: string, value: unknown) => {
215 const input = card.inputs[name]
216 if (input?.bound === 'usage') usage = { ...usage, [input.param]: value }
217 else if (input) request = { ...request, [input.param]: value }
218 }
219 const run = (): EstimateResult => ({
220 ...priceDetailed(card, request, usage),
221 cardSource: card.source,
222 })
223 // Fill each missing choice with its first value to find every missing
224 // input; any other refusal stands, unless it may hang on the value tried.
225 const missing: string[] = []
226 for (;;) {
227 try {
228 const result = run()
229 if (missing.length === 0) return { ok: true, result }
230 break
231 } catch (error) {
232 const name = error instanceof RateCardError ? error.input : undefined
233 const first =
234 name === undefined ? undefined : choiceValues(card.inputs[name])?.[0]
235 if (name === undefined || first === undefined) {
236 // A missing quantity, or nothing missing: refuse as before.
237 if (missing.length === 0 || name !== undefined) return refuse(error)
238 break // may hang on the value tried; the per-value pass names it
239 }
240 missing.push(name)
241 fill(name, first)
242 }
243 }
244 if (missing.length > 1) {
245 const named = missing.map((name) => {
246 const input = card.inputs[name] as RateCardInput
247 return `${slotOf(input)} (${choiceValues(input)?.join(' | ')})`
248 })
249 return {
250 ok: false,
251 status: 422,
252 code: 'unbound_input',
253 message:
254 `Rate card requires ${named.join(' and ')}, which were not provided. ` +
255 `Pass them on the estimate body. See GET /v1/models/${body.provider}/${body.model}.`,
256 }
257 }
258 const [name] = missing as [string]
259 const input = card.inputs[name] as RateCardInput
260 const values: EstimateByInputResult['byInput']['values'] = {}
261 for (const value of choiceValues(input) ?? []) {
262 fill(name, value)
263 try {
264 values[String(value)] = run()
265 } catch (error) {
266 return refuse(error, `With ${slotOf(input)} = ${JSON.stringify(value)}: `)
267 }
268 }
269 return {
270 ok: true,
271 result: {
272 currency: cardCurrency(card),
273 byInput: { input: input.param, values },
274 },
275 }
277​
278/**
279 * Price the call on each route's own stored card. Any route that cannot
280 * be priced refuses the whole estimate: without it the bounds are unknown.
281 */
282async function priceRoutes(
283 db: Db,
284 body: EstimateRequestBody,
285 routes: PricingRange['routes'],
286): Promise<EstimateOutcome> {
287 const lookups = routes
288 .filter((route) => !route.card)
289 .map((route) => route.model)
290 const rows =
291 lookups.length === 0
292 ? []
293 : await db
294 .select({ rawId: models.rawId, pricing: models.pricing })
295 .from(models)
296 .where(
297 and(
298 eq(models.providerId, body.provider),
299 inArray(models.rawId, lookups),
300 ),
301 )
302 const byRaw = new Map(rows.map((row) => [row.rawId, row.pricing]))
303 const priced: Array<EstimateResult & { model: string }> = []
304 const names: Array<string> = []
305 for (const route of routes) {
306 // An inline card is the route (Vercel provider_name). A catalog row
307 // is named by its rawId.
308 const name = route.provider ?? route.model
309 names.push(name)
310 const routeBody = { ...body, model: name }
311 const card = route.card
312 ? parseStoredRateCard(route.card)
313 : parseStoredRateCard(byRaw.get(route.model))
314 if (!card) return noCard(routeBody)
315 const outcome = priceCard(card, routeBody)
316 if (!outcome.ok) {
317 return { ...outcome, message: `Route ${name}: ${outcome.message}` }
318 }
319 if ('byInput' in outcome.result) {
320 // ponytail: no range-per-value shape yet; nest them if a caller needs it.
321 return {
322 ok: false,
323 status: 422,
324 code: 'unbound_input',
325 message: `Route ${name}: rate card requires ${outcome.result.byInput.input}, which was not provided. Pass it on the estimate body. See GET /v1/models/${body.provider}/${route.model}.`,
326 }
327 }
328 priced.push({ model: name, ...outcome.result })
329 }
330 const byAmount = [...priced].sort((a, b) => a.amount - b.amount)
331 const min = byAmount[0]
332 const max = byAmount.at(-1)
333 if (!min || !max) return noCard(body)
334 const currency = min.currency
335 if (priced.some((route) => route.currency !== currency)) {
336 return {
337 ok: false,
338 status: 422,
339 code: 'mixed_currency',
340 message: `The routes of '${body.provider}/${body.model}' price in different currencies; nothing is converted. Estimate one route: ${names.join(', ')}.`,
341 }
342 }
343 return { ok: true, result: { currency, min, max, routes: names } }