Open History to see the last commit
1import { beforeAll, describe, expect, it, vi } from 'vitest'
2import { env } from 'cloudflare:test'
3
4import { compileTokenCard } from '@modelschemas/rate-card'
5
6import { GPT_4O } from '../../packages/rate-card/src/fixtures/gpt-4o.ts'
7import { getDb } from '../db/index.ts'
8import type { Db } from '../db/index.ts'
9import { models, providers } from '../db/schema.ts'
10import { estimateCost, parseEstimateBody } from './estimate.ts'
11import { anthropicModelPricing } from './providers/anthropic-pricing.ts'
12import { compileSeedanceCard } from './providers/byteplus-pricing.ts'
13import { ANTHROPIC_PRICING_PAGE } from './providers/fixtures/anthropic-pricing.ts'
14import { parseStoredRateCard } from './rate-card.ts'
15
16const NOW = 1_781_150_000
17let db: Db
18
19beforeAll(async () => {
20 db = getDb(env)
21 await db.insert(providers).values({
22 id: 'est-openai',
23 displayName: 'Estimate OpenAI',
24 specSourceUrl: 'https://example.com/o.json',
25 })
26 await db.insert(models).values([
27 {
28 id: 'est-openai-gpt-4o',
29 providerId: 'est-openai',
30 rawId: 'gpt-4o',
31 activity: 'chat',
32 displayName: 'GPT-4o',
33 pricing: GPT_4O,
34 firstSeenAt: NOW,
35 lastSeenAt: NOW,
36 },
37 {
38 id: 'est-openai-kimi-k3',
39 providerId: 'est-openai',
40 rawId: 'kimi-k3',
41 activity: 'chat',
42 pricing: compileTokenCard(
43 { input_tokens: 20 / 1e6, output_tokens: 100 / 1e6 },
44 [],
45 GPT_4O.source,
46 { currency: 'CNY' },
47 ),
48 firstSeenAt: NOW,
49 lastSeenAt: NOW,
50 },
51 {
52 id: 'est-openai-free',
53 providerId: 'est-openai',
54 rawId: 'free',
55 activity: 'chat',
56 firstSeenAt: NOW,
57 lastSeenAt: NOW,
58 },
59 ])
60 await db.insert(providers).values({
61 id: 'est-byteplus',
62 displayName: 'Estimate BytePlus',
63 specSourceUrl: 'https://example.com/b.json',
64 })
65 await db.insert(models).values({
66 id: 'est-byteplus-seedance',
67 providerId: 'est-byteplus',
68 rawId: 'seedance-1-0-pro-250528',
69 activity: 'video',
70 pricing: compileSeedanceCard(
71 { default: { '*': { all: 2.5 } } },
72 GPT_4O.source,
73 {
74 model: { fps: 24, dims: { '1080p': { '16:9': { w: 1920, h: 1088 } } } },
75 url: 'https://example.com/guide',
76 hash: 'b'.repeat(64),
77 },
78 ),
79 firstSeenAt: NOW,
80 lastSeenAt: NOW,
81 })
82 await db.insert(providers).values({
83 id: 'est-anthropic',
84 displayName: 'Estimate Anthropic',
85 specSourceUrl: 'https://example.com/anthropic.json',
86 })
87 vi.stubGlobal(
88 'fetch',
89 vi.fn().mockResolvedValue(new Response(ANTHROPIC_PRICING_PAGE)),
90 )
91 try {
92 const pricingFor = await anthropicModelPricing()
93 for (const [rawId, displayName] of [
94 ['claude-opus-5-5', 'Claude Opus 5.5'],
95 ['claude-fable-5-1', 'Claude Fable 5.1'],
96 ] as const) {
97 const pricing = parseStoredRateCard(pricingFor(displayName).pricing)
98 expect(pricing?.inputs.cache_read_tokens).toBeDefined()
99 await db.insert(models).values({
100 id: `est-anthropic-${rawId}`,
101 providerId: 'est-anthropic',
102 rawId,
103 displayName,
104 activity: 'chat',
105 pricing,
106 firstSeenAt: NOW,
107 lastSeenAt: NOW,
108 })
109 }
110 } finally {
111 vi.unstubAllGlobals()
112 }
113})
114
115describe('parseEstimateBody', () => {
116 it('requires provider and model, and objects for request/usage', () => {
117 expect(parseEstimateBody(null)).toBeNull()
118 expect(parseEstimateBody({ provider: 'openai' })).toBeNull()
119 expect(
120 parseEstimateBody({ provider: 'openai', model: 'gpt-4o', request: [] }),
121 ).toBeNull()
122 expect(
123 parseEstimateBody({
124 provider: 'openai',
125 model: 'gpt-4o',
126 usage: { input_tokens: 1 },
127 }),
128 ).toEqual({
129 provider: 'openai',
130 model: 'gpt-4o',
131 usage: { input_tokens: 1 },
132 })
133 })
134})
135
136describe('estimateCost', () => {
137 it.each([
138 ['claude-opus-5-5', 0.2],
139 ['claude-fable-5-1', 0.25],
140 ])(
141 'prices cache reads for %s from docs-derived cards',
142 async (model, usd) => {
143 const outcome = await estimateCost(db, {
144 provider: 'est-anthropic',
145 model,
146 usage: {
147 input_tokens: 0,
148 output_tokens: 0,
149 cache_read_tokens: 1_000_000,
150 },
151 })
152 expect(outcome).toMatchObject({ ok: true, result: { usd } })
153 },
154 )
155
156 it('prices a stored token card', async () => {
157 const outcome = await estimateCost(db, {
158 provider: 'est-openai',
159 model: 'gpt-4o',
160 usage: { input_tokens: 1200, output_tokens: 400 },
161 })
162 expect(outcome).toEqual({
163 ok: true,
164 result: {
165 amount: 0.007,
166 currency: 'USD',
167 usd: 0.007,
168 cardSource: GPT_4O.source,
169 estimated: [],
170 },
171 })
172 })
173
174 it('prices a yuan card in CNY, with no usd', async () => {
175 const outcome = await estimateCost(db, {
176 provider: 'est-openai',
177 model: 'kimi-k3',
178 usage: { input_tokens: 1_000_000, output_tokens: 500_000 },
179 })
180 // ¥20 in + ¥100 out per 1M: 20 + 50. Not converted.
181 expect(outcome).toEqual({
182 ok: true,
183 result: {
184 amount: 70,
185 currency: 'CNY',
186 cardSource: GPT_4O.source,
187 estimated: [],
188 },
189 })
190 })
191
192 it('returns 404 unknown_model when the model is missing', async () => {
193 const outcome = await estimateCost(db, {
194 provider: 'est-openai',
195 model: 'nope',
196 })
197 expect(outcome.ok).toBe(false)
198 if (!outcome.ok) {
199 expect(outcome.status).toBe(404)
200 expect(outcome.code).toBe('unknown_model')
201 }
202 })
203
204 it('returns 404 unknown_pricing when the model has no card', async () => {
205 const outcome = await estimateCost(db, {
206 provider: 'est-openai',
207 model: 'free',
208 })
209 expect(outcome.ok).toBe(false)
210 if (!outcome.ok) {
211 expect(outcome.status).toBe(404)
212 expect(outcome.code).toBe('unknown_pricing')
213 expect(outcome.message).toContain('GET /v1/models/est-openai/free')
214 }
215 })
216
217 it('returns 422 unbound_input naming the missing lever', async () => {
218 const outcome = await estimateCost(db, {
219 provider: 'est-openai',
220 model: 'gpt-4o',
221 })
222 expect(outcome.ok).toBe(false)
223 if (!outcome.ok) {
224 expect(outcome.status).toBe(422)
225 expect(outcome.code).toBe('unbound_input')
226 expect(outcome.message).toContain('usage.input_tokens')
227 }
228 })
229
230 it('labels an estimated price and names both ways to supply it', async () => {
231 const body = { provider: 'est-byteplus', model: 'seedance-1-0-pro-250528' }
232 // Seedance 1.0 Pro usage table: 1080p 16:9 10 s = 489600 tokens.
233 const estimated = await estimateCost(db, {
234 ...body,
235 request: { resolution: '1080p', ratio: '16:9', duration: 10 },
236 })
237 expect(estimated).toMatchObject({
238 ok: true,
239 result: { usd: 1.224, estimated: ['completion_tokens'] },
240 })
241 const billed = await estimateCost(db, {
242 ...body,
243 usage: { completion_tokens: 489_600 },
244 })
245 expect(billed).toMatchObject({
246 ok: true,
247 result: { usd: 1.224, estimated: [] },
248 })
249 const neither = await estimateCost(db, {
250 ...body,
251 request: { resolution: '1080p', duration: 10 },
252 })
253 expect(neither).toMatchObject({ ok: false, code: 'unbound_input' })
254 if (!neither.ok) {
255 expect(neither.message).toContain('requires usage.completion_tokens')
256 expect(neither.message).toContain('ratio (ratio): required')
257 }
258 // A draft's tokens are not what the formula gives: no estimate.
259 const draft = await estimateCost(db, {
260 ...body,
261 request: {
262 resolution: '1080p',
263 ratio: '16:9',
264 duration: 10,
265 draft: true,
266 },
267 })
268 expect(draft).toMatchObject({ ok: false, code: 'unbound_input' })
269 })
270})