Open History to see the last commit
1import { beforeAll, describe, expect, it, vi } from 'vitest'
2import { env } from 'cloudflare:test'
3
4import { compileTokenCard, evaluateCard } from '@modelschemas/rate-card'
5
6import { ESTIMATE_CASES } from '../../packages/rate-card/src/fixtures/estimate-cases.ts'
7import { GPT_4O } from '../../packages/rate-card/src/fixtures/gpt-4o.ts'
8import { getDb } from '../db/index.ts'
9import type { Db } from '../db/index.ts'
10import { models, providers } from '../db/schema.ts'
11import { estimateCost, parseEstimateBody } from './estimate.ts'
12import { anthropicModelPricing } from './providers/anthropic-pricing.ts'
13import { compileSeedanceCard } from './providers/byteplus-pricing.ts'
14import { ANTHROPIC_PRICING_PAGE } from './providers/fixtures/anthropic-pricing.ts'
15import { parseStoredRateCard } from './rate-card.ts'
16
17const NOW = 1_781_150_000
18let db: Db
19
20beforeAll(async () => {
21 db = getDb(env)
22 await db.insert(providers).values({
23 id: 'est-openai',
24 displayName: 'Estimate OpenAI',
25 specSourceUrl: 'https://example.com/o.json',
26 })
27 await db.insert(models).values([
28 {
29 id: 'est-openai-gpt-4o',
30 providerId: 'est-openai',
31 rawId: 'gpt-4o',
32 activity: 'chat',
33 displayName: 'GPT-4o',
34 pricing: GPT_4O,
35 firstSeenAt: NOW,
36 lastSeenAt: NOW,
37 },
38 {
39 id: 'est-openai-kimi-k3',
40 providerId: 'est-openai',
41 rawId: 'kimi-k3',
42 activity: 'chat',
43 pricing: compileTokenCard(
44 { input_tokens: 20 / 1e6, output_tokens: 100 / 1e6 },
45 [],
46 GPT_4O.source,
47 { currency: 'CNY' },
48 ),
49 firstSeenAt: NOW,
50 lastSeenAt: NOW,
51 },
52 {
53 id: 'est-openai-gpt-5',
54 providerId: 'est-openai',
55 rawId: 'gpt-5',
56 activity: 'chat',
57 pricing: compileTokenCard(
58 {
59 input_tokens: 1.25 / 1e6,
60 cache_read_tokens: 0.125 / 1e6,
61 output_tokens: 10 / 1e6,
62 },
63 [],
64 GPT_4O.source,
65 ),
66 firstSeenAt: NOW,
67 lastSeenAt: NOW,
68 },
69 {
70 id: 'est-openai-free',
71 providerId: 'est-openai',
72 rawId: 'free',
73 activity: 'chat',
74 firstSeenAt: NOW,
75 lastSeenAt: NOW,
76 },
77 ])
78 await db.insert(providers).values({
79 id: 'est-byteplus',
80 displayName: 'Estimate BytePlus',
81 specSourceUrl: 'https://example.com/b.json',
82 })
83 await db.insert(models).values({
84 id: 'est-byteplus-seedance',
85 providerId: 'est-byteplus',
86 rawId: 'seedance-1-0-pro-250528',
87 activity: 'video',
88 pricing: compileSeedanceCard(
89 { default: { '*': { all: 2.5 } } },
90 GPT_4O.source,
91 {
92 model: { fps: 24, dims: { '1080p': { '16:9': { w: 1920, h: 1088 } } } },
93 url: 'https://example.com/guide',
94 hash: 'b'.repeat(64),
95 },
96 ),
97 firstSeenAt: NOW,
98 lastSeenAt: NOW,
99 })
100 await db.insert(providers).values({
101 id: 'est-anthropic',
102 displayName: 'Estimate Anthropic',
103 specSourceUrl: 'https://example.com/anthropic.json',
104 })
105 vi.stubGlobal(
106 'fetch',
107 vi.fn().mockResolvedValue(new Response(ANTHROPIC_PRICING_PAGE)),
108 )
109 try {
110 const pricingFor = await anthropicModelPricing()
111 for (const [rawId, displayName] of [
112 ['claude-opus-5-5', 'Claude Opus 5.5'],
113 ['claude-fable-5-1', 'Claude Fable 5.1'],
114 ] as const) {
115 const pricing = parseStoredRateCard(pricingFor(displayName).pricing)
116 expect(pricing?.inputs.cache_read_tokens).toBeDefined()
117 await db.insert(models).values({
118 id: `est-anthropic-${rawId}`,
119 providerId: 'est-anthropic',
120 rawId,
121 displayName,
122 activity: 'chat',
123 pricing,
124 firstSeenAt: NOW,
125 lastSeenAt: NOW,
126 })
127 }
128 } finally {
129 vi.unstubAllGlobals()
130 }
131})
132
133describe('parseEstimateBody', () => {
134 it('requires provider and model, and objects for request/usage', () => {
135 expect(parseEstimateBody(null)).toBeNull()
136 expect(parseEstimateBody({ provider: 'openai' })).toBeNull()
137 expect(
138 parseEstimateBody({ provider: 'openai', model: 'gpt-4o', request: [] }),
139 ).toBeNull()
140 expect(
141 parseEstimateBody({
142 provider: 'openai',
143 model: 'gpt-4o',
144 usage: { input_tokens: 1 },
145 }),
146 ).toEqual({
147 provider: 'openai',
148 model: 'gpt-4o',
149 usage: { input_tokens: 1 },
150 })
151 })
152})
153
154describe('estimateCost', () => {
155 it.each([
156 ['claude-opus-5-5', 0.2],
157 ['claude-fable-5-1', 0.25],
158 ])(
159 'prices cache reads for %s from docs-derived cards',
160 async (model, usd) => {
161 const outcome = await estimateCost(db, {
162 provider: 'est-anthropic',
163 model,
164 usage: {
165 input_tokens: 0,
166 output_tokens: 0,
167 cache_read_tokens: 1_000_000,
168 },
169 })
170 expect(outcome).toMatchObject({ ok: true, result: { usd } })
171 },
172 )
173
174 it.each([
175 [
176 'Responses',
177 {
178 input_tokens: 12_000,
179 input_tokens_details: { cached_tokens: 4000 },
180 output_tokens: 800,
181 output_tokens_details: { reasoning_tokens: 0 },
182 total_tokens: 12_800,
183 },
184 ],
185 [
186 'Chat',
187 {
188 prompt_tokens: 12_000,
189 prompt_tokens_details: { cached_tokens: 4000, audio_tokens: 0 },
190 completion_tokens: 800,
191 total_tokens: 12_800,
192 },
193 ],
194 ])(
195 'prices native OpenAI %s usage with cached tokens counted once',
196 async (_, usage) => {
197 const outcome = await estimateCost(db, {
198 provider: 'est-openai',
199 model: 'gpt-5',
200 usage,
201 })
202 // 8000 × 1.25/M + 4000 × 0.125/M + 800 × 10/M, not 0.0235.
203 expect(outcome).toMatchObject({ ok: true, result: { defaulted: [] } })
204 if (outcome.ok) expect(outcome.result.amount).toBeCloseTo(0.0185, 10)
205 },
206 )
207
208 it.each([
209 ['claude-opus-5-5', 0.2],
210 ['claude-fable-5-1', 0.25],
211 ])('prices native Anthropic cache reads for %s', async (model, usd) => {
212 const outcome = await estimateCost(db, {
213 provider: 'est-anthropic',
214 model,
215 usage: {
216 input_tokens: 0,
217 cache_creation_input_tokens: 0,
218 cache_read_input_tokens: 1_000_000,
219 output_tokens: 0,
220 service_tier: 'standard',
221 },
222 })
223 expect(outcome).toMatchObject({ ok: true, result: { usd } })
224 })
225
226 it('returns 422 mixed_usage for native fields beside card levers', async () => {
227 const outcome = await estimateCost(db, {
228 provider: 'est-openai',
229 model: 'gpt-5',
230 usage: {
231 input_tokens: 12_000,
232 input_tokens_details: { cached_tokens: 4000 },
233 output_tokens: 800,
234 cache_read_tokens: 4000,
235 },
236 })
237 expect(outcome).toMatchObject({
238 ok: false,
239 status: 422,
240 code: 'mixed_usage',
241 })
242 })
243
244 it('prices a stored token card', async () => {
245 const outcome = await estimateCost(db, {
246 provider: 'est-openai',
247 model: 'gpt-4o',
248 request: { model: 'gpt-4o', messages: [], max_tokens: 400 },
249 usage: { input_tokens: 1200, output_tokens: 400 },
250 })
251 expect(outcome).toEqual({
252 ok: true,
253 result: {
254 amount: 0.007,
255 currency: 'USD',
256 usd: 0.007,
257 cardSource: GPT_4O.source,
258 estimated: [],
259 defaulted: ['cache_read_tokens'],
260 ignored: ['model', 'messages', 'max_tokens'],
261 },
262 })
263 })
264
265 it('prices a yuan card in CNY, with no usd', async () => {
266 const outcome = await estimateCost(db, {
267 provider: 'est-openai',
268 model: 'kimi-k3',
269 usage: { input_tokens: 1_000_000, output_tokens: 500_000 },
270 })
271 // ¥20 in + ¥100 out per 1M: 20 + 50. Not converted.
272 expect(outcome).toEqual({
273 ok: true,
274 result: {
275 amount: 70,
276 currency: 'CNY',
277 cardSource: GPT_4O.source,
278 estimated: [],
279 defaulted: [],
280 ignored: [],
281 },
282 })
283 })
284
285 it('returns 422 unknown_usage_key for a usage key the card does not read', async () => {
286 const outcome = await estimateCost(db, {
287 provider: 'est-anthropic',
288 model: 'claude-opus-5-5',
289 usage: {
290 input_tokens: 12_000,
291 output_tokens: 800,
292 cache_hits: 4000,
293 },
294 })
295 expect(outcome).toMatchObject({
296 ok: false,
297 status: 422,
298 code: 'unknown_usage_key',
299 })
300 if (!outcome.ok) {
301 expect(outcome.message).toContain(
302 'usage.cache_hits: not read by this card; it reads',
303 )
304 expect(outcome.message).toContain('usage.cache_read_tokens')
305 expect(outcome.message).toContain('usage.input_tokens')
306 }
307 })
308
309 it('returns 404 unknown_model when the model is missing', async () => {
310 const outcome = await estimateCost(db, {
311 provider: 'est-openai',
312 model: 'nope',
313 })
314 expect(outcome.ok).toBe(false)
315 if (!outcome.ok) {
316 expect(outcome.status).toBe(404)
317 expect(outcome.code).toBe('unknown_model')
318 }
319 })
320
321 it('returns 404 unknown_pricing when the model has no card', async () => {
322 const outcome = await estimateCost(db, {
323 provider: 'est-openai',
324 model: 'free',
325 })
326 expect(outcome.ok).toBe(false)
327 if (!outcome.ok) {
328 expect(outcome.status).toBe(404)
329 expect(outcome.code).toBe('unknown_pricing')
330 expect(outcome.message).toContain('GET /v1/models/est-openai/free')
331 }
332 })
333
334 it('returns 422 unbound_input naming the missing lever', async () => {
335 const outcome = await estimateCost(db, {
336 provider: 'est-openai',
337 model: 'gpt-4o',
338 })
339 expect(outcome.ok).toBe(false)
340 if (!outcome.ok) {
341 expect(outcome.status).toBe(422)
342 expect(outcome.code).toBe('unbound_input')
343 expect(outcome.message).toContain('usage.input_tokens')
344 }
345 })
346
347 it('labels an estimated price and names both ways to supply it', async () => {
348 const body = { provider: 'est-byteplus', model: 'seedance-1-0-pro-250528' }
349 // Seedance 1.0 Pro usage table: 1080p 16:9 10 s = 489600 tokens.
350 const estimated = await estimateCost(db, {
351 ...body,
352 request: { resolution: '1080p', ratio: '16:9', duration: 10 },
353 })
354 expect(estimated).toMatchObject({
355 ok: true,
356 result: { usd: 1.224, estimated: ['completion_tokens'] },
357 })
358 const billed = await estimateCost(db, {
359 ...body,
360 usage: { completion_tokens: 489_600 },
361 })
362 expect(billed).toMatchObject({
363 ok: true,
364 result: { usd: 1.224, estimated: [] },
365 })
366 const neither = await estimateCost(db, {
367 ...body,
368 request: { resolution: '1080p', duration: 10 },
369 })
370 expect(neither).toMatchObject({ ok: false, code: 'unbound_input' })
371 if (!neither.ok) {
372 expect(neither.message).toContain('requires usage.completion_tokens')
373 expect(neither.message).toContain('ratio (ratio): required')
374 }
375 // A draft's tokens are not what the formula gives: no estimate.
376 const draft = await estimateCost(db, {
377 ...body,
378 request: {
379 resolution: '1080p',
380 ratio: '16:9',
381 duration: 10,
382 draft: true,
383 },
384 })
385 expect(draft).toMatchObject({ ok: false, code: 'unbound_input' })
386 })
387})
388
389// The shared cases (packages/rate-card/src/fixtures/estimate-cases.ts) run
390// the route's path: JSON body → parseEstimateBody → estimateCost → JSON.
391// Each must match evaluateCard on amount, currency, and estimated.
392describe('POST /v1/estimate conformance with evaluateCard', () => {
393 beforeAll(async () => {
394 await db.insert(providers).values({
395 id: 'conformance',
396 displayName: 'Conformance',
397 specSourceUrl: 'https://example.com/c.json',
398 })
399 await db.insert(models).values(
400 ESTIMATE_CASES.map((c, i) => ({
401 id: `conformance-case-${i}`,
402 providerId: 'conformance',
403 rawId: `case-${i}`,
404 activity: 'chat' as const,
405 pricing: c.card,
406 firstSeenAt: NOW,
407 lastSeenAt: NOW,
408 })),
409 )
410 })
411
412 it.each(ESTIMATE_CASES.map((c, i) => [c.name, c, i] as const))(
413 '%s',
414 async (_, c, i) => {
415 const body = parseEstimateBody(
416 JSON.parse(
417 JSON.stringify({
418 provider: 'conformance',
419 model: `case-${i}`,
420 request: c.request,
421 usage: c.usage,
422 }),
423 ),
424 )
425 if (!body) throw new Error('body did not parse')
426 const outcome = await estimateCost(db, body)
427 if ('error' in c.expected) {
428 expect(outcome).toMatchObject({
429 ok: false,
430 status: 422,
431 code: c.expected.apiError,
432 })
433 return
434 }
435 if (!outcome.ok) throw new Error(`${outcome.code}: ${outcome.message}`)
436 const { amount, currency, estimated } = JSON.parse(
437 JSON.stringify(outcome.result),
438 ) as typeof outcome.result
439 expect({ amount, currency, estimated }).toEqual(
440 evaluateCard(c.card, { request: c.request, usage: c.usage }),
441 )
442 },
443 )
444})