Elffuss BraidHub

kikocis/continue public

main · 3.0 KiBRawPermalink
1import {
2 calculateRequestCost,
3 CostBreakdown,
4} from "core/llm/utils/calculateRequestCost";
5import { useMemo } from "react";
6import { LLMLog } from "./useLLMLog";
7
8export interface TotalUsage {
9 totalPromptTokens: number;
10 totalGeneratedTokens: number;
11 totalThinkingTokens: number;
12 totalCachedTokens: number;
13 totalCacheWriteTokens: number;
14 totalInteractions: number;
15 totalSuccessfulInteractions: number;
16 totalErrorInteractions: number;
17 totalCancelledInteractions: number;
18 totalCost: number;
19 costBreakdowns: CostBreakdown[];
20}
21
22/**
23 * Hook to calculate total usage across all interactions in the LLM log
24 */
25export default function useTotalUsage(llmLog: LLMLog): TotalUsage {
26 return useMemo(() => {
27 let totalPromptTokens = 0;
28 let totalGeneratedTokens = 0;
29 let totalThinkingTokens = 0;
30 let totalCachedTokens = 0;
31 let totalCacheWriteTokens = 0;
32 let totalInteractions = 0;
33 let totalSuccessfulInteractions = 0;
34 let totalErrorInteractions = 0;
35 let totalCancelledInteractions = 0;
36 let totalCost = 0;
37 const costBreakdowns: CostBreakdown[] = [];
38
39 // Iterate through all interactions
40 for (const interaction of llmLog.interactions.values()) {
41 if (interaction.end) {
42 totalInteractions++;
43
44 // Add basic token counts
45 totalPromptTokens += interaction.end.promptTokens || 0;
46 totalGeneratedTokens += interaction.end.generatedTokens || 0;
47 totalThinkingTokens += interaction.end.thinkingTokens || 0;
48
49 // Add cache-related tokens from usage if available
50 if (interaction.end.usage) {
51 const usage = interaction.end.usage;
52 totalCachedTokens += usage.promptTokensDetails?.cachedTokens || 0;
53 totalCacheWriteTokens +=
54 usage.promptTokensDetails?.cacheWriteTokens || 0;
55
56 // Calculate cost if we have the necessary information
57 if (
58 interaction.start?.provider &&
59 interaction.start?.options?.model
60 ) {
61 const costBreakdown = calculateRequestCost(
62 interaction.start.provider,
63 interaction.start.options.model,
64 usage,
65 );
66 if (costBreakdown) {
67 totalCost += costBreakdown.cost;
68 costBreakdowns.push(costBreakdown);
69 }
70 }
71 }
72
73 // Count interaction outcomes
74 switch (interaction.end.kind) {
75 case "success":
76 totalSuccessfulInteractions++;
77 break;
78 case "error":
79 totalErrorInteractions++;
80 break;
81 case "cancel":
82 totalCancelledInteractions++;
83 break;
84 }
85 }
86 }
87
88 return {
89 totalPromptTokens,
90 totalGeneratedTokens,
91 totalThinkingTokens,
92 totalCachedTokens,
93 totalCacheWriteTokens,
94 totalInteractions,
95 totalSuccessfulInteractions,
96 totalErrorInteractions,
97 totalCancelledInteractions,
98 totalCost,
99 costBreakdowns,
100 };
101 }, [llmLog]);
102}