mirror of
https://github.com/pacnpal/Roo-Code.git
synced 2025-12-20 04:11:10 -05:00
56 lines
1.7 KiB
TypeScript
56 lines
1.7 KiB
TypeScript
import { ClaudeMessage } from "../../../src/shared/ExtensionMessage"
|
|
|
|
interface ApiMetrics {
|
|
totalTokensIn: number
|
|
totalTokensOut: number
|
|
totalCost: number
|
|
}
|
|
|
|
/**
|
|
* Calculates API metrics from an array of ClaudeMessages.
|
|
*
|
|
* This function processes 'api_req_started' messages that have been combined with their
|
|
* corresponding 'api_req_finished' messages by the combineApiRequests function.
|
|
* It extracts and sums up the tokensIn, tokensOut, and cost from these messages.
|
|
*
|
|
* @param messages - An array of ClaudeMessage objects to process.
|
|
* @returns An ApiMetrics object containing totalTokensIn, totalTokensOut, and totalCost.
|
|
*
|
|
* @example
|
|
* const messages = [
|
|
* { type: "say", say: "api_req_started", text: '{"request":"GET /api/data","tokensIn":10,"tokensOut":20,"cost":0.005}', ts: 1000 }
|
|
* ];
|
|
* const { totalTokensIn, totalTokensOut, totalCost } = getApiMetrics(messages);
|
|
* // Result: { totalTokensIn: 10, totalTokensOut: 20, totalCost: 0.005 }
|
|
*/
|
|
export function getApiMetrics(messages: ClaudeMessage[]): ApiMetrics {
|
|
const result: ApiMetrics = {
|
|
totalTokensIn: 0,
|
|
totalTokensOut: 0,
|
|
totalCost: 0,
|
|
}
|
|
|
|
messages.forEach((message) => {
|
|
if (message.type === "say" && message.say === "api_req_started" && message.text) {
|
|
try {
|
|
const parsedData = JSON.parse(message.text)
|
|
const { tokensIn, tokensOut, cost } = parsedData
|
|
|
|
if (typeof tokensIn === "number") {
|
|
result.totalTokensIn += tokensIn
|
|
}
|
|
if (typeof tokensOut === "number") {
|
|
result.totalTokensOut += tokensOut
|
|
}
|
|
if (typeof cost === "number") {
|
|
result.totalCost += cost
|
|
}
|
|
} catch (error) {
|
|
console.error("Error parsing JSON:", error)
|
|
}
|
|
}
|
|
})
|
|
|
|
return result
|
|
}
|