| 1 | import { |
| 2 | calculateRequestCost, |
| 3 | CostBreakdown, |
| 4 | } from "core/llm/utils/calculateRequestCost"; |
| 5 | import { useMemo } from "react"; |
| 6 | import { LLMInteraction } from "./useLLMLog"; |
| 7 | |
| 8 | /** |
| 9 | * Hook returning memoized information about single logged prompt/response |
| 10 | * query to the LLM. |
| 11 | */ |
| 12 | export default function useLLMSummary(interaction: LLMInteraction) { |
| 13 | return useMemo(() => { |
| 14 | if (interaction.start == undefined) { |
| 15 | return { |
| 16 | result: "", |
| 17 | type: "", |
| 18 | }; |
| 19 | } |
| 20 | |
| 21 | const type = interaction.start.kind.slice(5); |
| 22 | |
| 23 | let result; |
| 24 | switch (interaction.end?.kind) { |
| 25 | case "cancel": |
| 26 | result = "Cancelled"; |
| 27 | break; |
| 28 | case "error": |
| 29 | result = "Error"; |
| 30 | break; |
| 31 | case "success": |
| 32 | result = "Success"; |
| 33 | break; |
| 34 | case undefined: |
| 35 | result = ""; |
| 36 | } |
| 37 | |
| 38 | let totalTime, |
| 39 | toFirstToken, |
| 40 | tokensPerSecond, |
| 41 | promptTokens, |
| 42 | generatedTokens, |
| 43 | thinkingTokens; |
| 44 | if (interaction.start != undefined && interaction.results.length > 0) { |
| 45 | const firstGroup = interaction.results[0]; |
| 46 | const firstItem = firstGroup ? firstGroup[0] : undefined; |
| 47 | toFirstToken = firstItem |
| 48 | ? firstItem.timestamp - interaction.start.timestamp |
| 49 | : undefined; |
| 50 | } |
| 51 | if (interaction.end != undefined) { |
| 52 | totalTime = interaction.end.timestamp - interaction.start.timestamp; |
| 53 | promptTokens = interaction.end.promptTokens; |
| 54 | generatedTokens = interaction.end.generatedTokens; |
| 55 | thinkingTokens = interaction.end.thinkingTokens; |
| 56 | if (toFirstToken != undefined) { |
| 57 | tokensPerSecond = |
| 58 | (generatedTokens + thinkingTokens) / |
| 59 | ((totalTime - toFirstToken) / 1000); |
| 60 | } |
| 61 | } else { |
| 62 | const lastGroup = interaction.results[interaction.results.length - 1]; |
| 63 | const lastItem = lastGroup ? lastGroup[lastGroup.length - 1] : undefined; |
| 64 | totalTime = lastItem |
| 65 | ? lastItem.timestamp - interaction.start.timestamp |
| 66 | : undefined; |
| 67 | } |
| 68 | |
| 69 | let costBreakdown: CostBreakdown | null = null; |
| 70 | if ( |
| 71 | interaction.end?.usage && |
| 72 | interaction.start?.provider && |
| 73 | interaction.start?.options?.model |
| 74 | ) { |
| 75 | costBreakdown = calculateRequestCost( |
| 76 | interaction.start.provider, |
| 77 | interaction.start.options.model, |
| 78 | interaction.end.usage, |
| 79 | ); |
| 80 | } |
| 81 | |
| 82 | return { |
| 83 | result, |
| 84 | type, |
| 85 | totalTime, |
| 86 | toFirstToken, |
| 87 | tokensPerSecond, |
| 88 | promptTokens, |
| 89 | generatedTokens, |
| 90 | thinkingTokens, |
| 91 | costBreakdown, |
| 92 | }; |
| 93 | }, [interaction]); |
| 94 | } |