(
model: string,
inputText: string,
outputText: string,
systemPrompt?: string,
context?: string,
messages?: Array<{ role: string; content: string }>
)
| 29 | * Calculates cost estimate for streaming execution using token estimation |
| 30 | */ |
| 31 | export function calculateStreamingCost( |
| 32 | model: string, |
| 33 | inputText: string, |
| 34 | outputText: string, |
| 35 | systemPrompt?: string, |
| 36 | context?: string, |
| 37 | messages?: Array<{ role: string; content: string }> |
| 38 | ): StreamingCostResult { |
| 39 | try { |
| 40 | // Validate inputs |
| 41 | validateTokenizationInput(model, inputText, outputText) |
| 42 | |
| 43 | const providerId = getProviderForTokenization(model) |
| 44 | |
| 45 | // Estimate input tokens (combine all input sources) |
| 46 | const inputEstimate = estimateInputTokens(systemPrompt, context, messages, providerId) |
| 47 | |
| 48 | // Add the main input text to the estimation |
| 49 | const mainInputEstimate = estimateTokenCount(inputText, providerId) |
| 50 | const totalPromptTokens = inputEstimate.count + mainInputEstimate.count |
| 51 | |
| 52 | // Estimate output tokens |
| 53 | const outputEstimate = estimateOutputTokens(outputText, providerId) |
| 54 | const completionTokens = outputEstimate.count |
| 55 | |
| 56 | // Calculate total tokens |
| 57 | const totalTokens = totalPromptTokens + completionTokens |
| 58 | |
| 59 | // Create token usage object |
| 60 | const tokens: TokenUsage = { |
| 61 | input: totalPromptTokens, |
| 62 | output: completionTokens, |
| 63 | total: totalTokens, |
| 64 | } |
| 65 | |
| 66 | // Calculate cost using provider pricing |
| 67 | const costResult = calculateCost(model, totalPromptTokens, completionTokens, false) |
| 68 | |
| 69 | const cost: CostBreakdown = { |
| 70 | input: costResult.input, |
| 71 | output: costResult.output, |
| 72 | total: costResult.total, |
| 73 | } |
| 74 | |
| 75 | const result: StreamingCostResult = { |
| 76 | tokens, |
| 77 | cost, |
| 78 | model, |
| 79 | provider: providerId, |
| 80 | method: 'tokenization', |
| 81 | } |
| 82 | |
| 83 | logTokenizationDetails('Streaming cost calculation completed', { |
| 84 | model, |
| 85 | provider: providerId, |
| 86 | inputLength: inputText.length, |
| 87 | outputLength: outputText.length, |
| 88 | tokens, |
no test coverage detected