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
This commit is contained in:
hannesrudolph 2025-06-18 20:43:05 -06:00
parent 8482c58509
commit 4dd1ae6ca4

View file

@ -10,6 +10,7 @@ import { ApiStreamUsageChunk, type ApiStream } from "../transform/stream"
import { runClaudeCode } from "../../integrations/claude-code/run"
import { ClaudeCodeMessage } from "../../integrations/claude-code/types"
import { BaseProvider } from "./base-provider"
import { calculateApiCostAnthropic } from "../../shared/cost"
export class ClaudeCodeHandler extends BaseProvider implements ApiHandler {
private options: ApiHandlerOptions
@ -132,7 +133,20 @@ export class ClaudeCodeHandler extends BaseProvider implements ApiHandler {
}
if (chunk.type === "result" && "result" in chunk) {
usage.totalCost = chunk.cost_usd || 0
// Use the cost from the CLI if available, otherwise calculate it
if (chunk.cost_usd !== undefined && chunk.cost_usd !== null) {
usage.totalCost = chunk.cost_usd
} else {
// Calculate cost based on token usage and model pricing
const modelInfo = this.getModel().info
usage.totalCost = calculateApiCostAnthropic(
modelInfo,
usage.inputTokens,
usage.outputTokens,
usage.cacheWriteTokens,
usage.cacheReadTokens,
)
}
yield usage
}