File size: 9,234 Bytes
eb1202c
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
import * as fs from "node:fs/promises"
import * as path from "node:path"

const RECORDINGS_DIR = path.resolve(import.meta.dir, "..", "test", "fixtures", "recordings")
const MODELS_DEV_URL = "https://models.opencode.ai/api.json"

type JsonRecord = Record<string, unknown>

type Pricing = {
  readonly input?: number
  readonly output?: number
  readonly cache_read?: number
  readonly cache_write?: number
  readonly reasoning?: number
}

type Usage = {
  readonly inputTokens: number
  readonly outputTokens: number
  readonly cacheReadTokens: number
  readonly cacheWriteTokens: number
  readonly reasoningTokens: number
  readonly reportedCost: number
}

type Row = Usage & {
  readonly cassette: string
  readonly provider: string
  readonly model: string
  readonly estimatedCost: number
  readonly pricingSource: string
}

const isRecord = (value: unknown): value is JsonRecord =>
  value !== null && typeof value === "object" && !Array.isArray(value)

const asNumber = (value: unknown) => (typeof value === "number" && Number.isFinite(value) ? value : 0)

const asString = (value: unknown) => (typeof value === "string" ? value : undefined)

const readJson = async (file: string) => JSON.parse(await Bun.file(file).text()) as unknown

const walk = async (dir: string): Promise<ReadonlyArray<string>> =>
  (await fs.readdir(dir, { withFileTypes: true }))
    .flatMap((entry) => {
      const file = path.join(dir, entry.name)
      return entry.isDirectory() ? [] : [file]
    })
    .concat(
      ...(await Promise.all(
        (await fs.readdir(dir, { withFileTypes: true }))
          .filter((entry) => entry.isDirectory())
          .map((entry) => walk(path.join(dir, entry.name))),
      )),
    )

const providerFromUrl = (url: string) => {
  if (url.includes("api.openai.com")) return "openai"
  if (url.includes("api.anthropic.com")) return "anthropic"
  if (url.includes("generativelanguage.googleapis.com")) return "google"
  if (url.includes("bedrock")) return "amazon-bedrock"
  if (url.includes("openrouter.ai")) return "openrouter"
  if (url.includes("api.x.ai")) return "xai"
  if (url.includes("api.groq.com")) return "groq"
  if (url.includes("api.deepseek.com")) return "deepseek"
  if (url.includes("api.together.xyz")) return "togetherai"
  return "unknown"
}

const providerAliases: Record<string, ReadonlyArray<string>> = {
  openai: ["openai"],
  anthropic: ["anthropic"],
  google: ["google"],
  "amazon-bedrock": ["amazon-bedrock"],
  openrouter: ["openrouter", "openai", "anthropic", "google"],
  xai: ["xai"],
  groq: ["groq"],
  deepseek: ["deepseek"],
  togetherai: ["togetherai"],
}

const modelAliases = (model: string) => [
  model,
  model.replace(/^models\//, ""),
  model.replace(/-\d{8}$/, ""),
  model.replace(/-\d{4}-\d{2}-\d{2}$/, ""),
  model.replace(/-\d{4}-\d{2}-\d{2}$/, "").replace(/-\d{8}$/, ""),
  model.replace(/^openai\//, ""),
  model.replace(/^anthropic\//, ""),
  model.replace(/^google\//, ""),
]

const pricingFor = (models: JsonRecord, provider: string, model: string) => {
  for (const providerID of providerAliases[provider] ?? [provider]) {
    const providerEntry = models[providerID]
    if (!isRecord(providerEntry) || !isRecord(providerEntry.models)) continue
    for (const modelID of modelAliases(model)) {
      const modelEntry = providerEntry.models[modelID]
      if (isRecord(modelEntry) && isRecord(modelEntry.cost))
        return { pricing: modelEntry.cost as Pricing, source: `${providerID}/${modelID}` }
    }
  }
  return { pricing: undefined, source: "missing" }
}

const estimateCost = (usage: Usage, pricing: Pricing | undefined) => {
  if (!pricing) return 0
  return (
    (usage.inputTokens * (pricing.input ?? 0) +
      usage.outputTokens * (pricing.output ?? 0) +
      usage.cacheReadTokens * (pricing.cache_read ?? 0) +
      usage.cacheWriteTokens * (pricing.cache_write ?? 0) +
      usage.reasoningTokens * (pricing.reasoning ?? 0)) /
    1_000_000
  )
}

const emptyUsage = (): Usage => ({
  inputTokens: 0,
  outputTokens: 0,
  cacheReadTokens: 0,
  cacheWriteTokens: 0,
  reasoningTokens: 0,
  reportedCost: 0,
})

const addUsage = (a: Usage, b: Usage): Usage => ({
  inputTokens: a.inputTokens + b.inputTokens,
  outputTokens: a.outputTokens + b.outputTokens,
  cacheReadTokens: a.cacheReadTokens + b.cacheReadTokens,
  cacheWriteTokens: a.cacheWriteTokens + b.cacheWriteTokens,
  reasoningTokens: a.reasoningTokens + b.reasoningTokens,
  reportedCost: a.reportedCost + b.reportedCost,
})

const usageFromObject = (usage: unknown): Usage => {
  if (!isRecord(usage)) return emptyUsage()
  const promptDetails = isRecord(usage.prompt_tokens_details) ? usage.prompt_tokens_details : {}
  const completionDetails = isRecord(usage.completion_tokens_details) ? usage.completion_tokens_details : {}
  const inputDetails = isRecord(usage.input_tokens_details) ? usage.input_tokens_details : {}
  const outputDetails = isRecord(usage.output_tokens_details) ? usage.output_tokens_details : {}
  const cacheWriteTokens = asNumber(promptDetails.cache_write_tokens) + asNumber(inputDetails.cache_write_tokens)
  return {
    inputTokens: asNumber(usage.prompt_tokens) + asNumber(usage.input_tokens),
    outputTokens: asNumber(usage.completion_tokens) + asNumber(usage.output_tokens),
    cacheReadTokens: asNumber(promptDetails.cached_tokens) + asNumber(inputDetails.cached_tokens),
    cacheWriteTokens,
    reasoningTokens: asNumber(completionDetails.reasoning_tokens) + asNumber(outputDetails.reasoning_tokens),
    reportedCost: asNumber(usage.cost),
  }
}

const jsonPayloads = (body: string) =>
  body
    .split("\n")
    .map((line) => line.trim())
    .filter((line) => line.startsWith("data:"))
    .map((line) => line.slice("data:".length).trim())
    .filter((line) => line !== "" && line !== "[DONE]")
    .flatMap((line) => {
      try {
        return [JSON.parse(line) as unknown]
      } catch {
        return []
      }
    })

const usageFromResponseBody = (body: string) =>
  jsonPayloads(body).reduce<Usage>((usage, payload) => {
    if (!isRecord(payload)) return usage
    return addUsage(
      usage,
      addUsage(
        usageFromObject(payload.usage),
        usageFromObject(isRecord(payload.response) ? payload.response.usage : undefined),
      ),
    )
  }, emptyUsage())

const modelFromRequest = (request: unknown) => {
  if (!isRecord(request)) return "unknown"
  const requestBody = asString(request.body)
  if (!requestBody) return "unknown"
  try {
    const body = JSON.parse(requestBody) as unknown
    if (!isRecord(body)) return "unknown"
    return asString(body.model) ?? "unknown"
  } catch {
    return "unknown"
  }
}

const rowFor = (models: JsonRecord, file: string, cassette: unknown): Row | undefined => {
  if (!isRecord(cassette) || !Array.isArray(cassette.interactions)) return undefined
  const first = cassette.interactions.find(isRecord)
  if (!first || !isRecord(first.request)) return undefined
  const provider = providerFromUrl(asString(first.request.url) ?? "")
  const model = modelFromRequest(first.request)
  const usage = cassette.interactions.filter(isRecord).reduce<Usage>((total, interaction) => {
    if (!isRecord(interaction.response)) return total
    const responseBody = asString(interaction.response.body)
    if (!responseBody) return total
    return addUsage(total, usageFromResponseBody(responseBody))
  }, emptyUsage())
  const priced = pricingFor(models, provider, model)
  return {
    cassette: path.relative(RECORDINGS_DIR, file),
    provider,
    model,
    ...usage,
    estimatedCost: estimateCost(usage, priced.pricing),
    pricingSource: priced.source,
  }
}

const money = (value: number) => (value === 0 ? "$0.000000" : `$${value.toFixed(6)}`)
const tokens = (value: number) => value.toLocaleString("en-US")

const models = (await (await fetch(MODELS_DEV_URL)).json()) as JsonRecord
const rows = (
  await Promise.all(
    (await walk(RECORDINGS_DIR))
      .filter((file) => file.endsWith(".json"))
      .map(async (file) => rowFor(models, file, await readJson(file))),
  )
).filter((row): row is Row => row !== undefined)

const totals = rows.reduce(
  (total, row) => ({
    ...addUsage(total, row),
    estimatedCost: total.estimatedCost + row.estimatedCost,
  }),
  { ...emptyUsage(), estimatedCost: 0 },
)

console.log("# Recording Cost Report")
console.log("")
console.log(`Pricing: ${MODELS_DEV_URL}`)
console.log(`Cassettes: ${rows.length}`)
console.log(`Reported cost: ${money(totals.reportedCost)}`)
console.log(`Estimated cost: ${money(totals.estimatedCost)}`)
console.log("")
console.log("| Provider | Model | Input | Output | Reasoning | Reported | Estimated | Pricing | Cassette |")
console.log("|---|---:|---:|---:|---:|---:|---:|---|---|")
for (const row of rows.toSorted((a, b) => b.reportedCost + b.estimatedCost - (a.reportedCost + a.estimatedCost))) {
  if (row.inputTokens + row.outputTokens + row.reasoningTokens + row.reportedCost + row.estimatedCost === 0) continue
  console.log(
    `| ${row.provider} | ${row.model} | ${tokens(row.inputTokens)} | ${tokens(row.outputTokens)} | ${tokens(row.reasoningTokens)} | ${money(row.reportedCost)} | ${money(row.estimatedCost)} | ${row.pricingSource} | ${row.cassette} |`,
  )
}