Skip to content

Commit 0e2306b

Browse files
hannesrudolphdaniel-lxs
authored andcommitted
fix: calculate cost for Claude Code provider when CLI doesn't provide it
- Use cost_usd from CLI response when available - Fall back to calculating cost based on token usage and model pricing - Ensures consistent cost reporting across all providers
1 parent ff85ebc commit 0e2306b

File tree

1 file changed

+15
-1
lines changed

1 file changed

+15
-1
lines changed

src/api/providers/claude-code.ts

Lines changed: 15 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -10,6 +10,7 @@ import { ApiStreamUsageChunk, type ApiStream } from "../transform/stream"
1010
import { runClaudeCode } from "../../integrations/claude-code/run"
1111
import { ClaudeCodeMessage } from "../../integrations/claude-code/types"
1212
import { BaseProvider } from "./base-provider"
13+
import { calculateApiCostAnthropic } from "../../shared/cost"
1314

1415
export class ClaudeCodeHandler extends BaseProvider implements ApiHandler {
1516
private options: ApiHandlerOptions
@@ -132,7 +133,20 @@ export class ClaudeCodeHandler extends BaseProvider implements ApiHandler {
132133
}
133134

134135
if (chunk.type === "result" && "result" in chunk) {
135-
usage.totalCost = chunk.cost_usd || 0
136+
// Use the cost from the CLI if available, otherwise calculate it
137+
if (chunk.cost_usd !== undefined && chunk.cost_usd !== null) {
138+
usage.totalCost = chunk.cost_usd
139+
} else {
140+
// Calculate cost based on token usage and model pricing
141+
const modelInfo = this.getModel().info
142+
usage.totalCost = calculateApiCostAnthropic(
143+
modelInfo,
144+
usage.inputTokens,
145+
usage.outputTokens,
146+
usage.cacheWriteTokens,
147+
usage.cacheReadTokens,
148+
)
149+
}
136150

137151
yield usage
138152
}

0 commit comments

Comments
 (0)