improv: cost breakdown in continue console
This commit is contained in:
parent
09951e840c
commit
409935d998
7 changed files with 309 additions and 3 deletions
26
core/index.d.ts
vendored
26
core/index.d.ts
vendored
|
|
@ -362,10 +362,32 @@ export interface ThinkingChatMessage {
|
|||
toolCalls?: ToolCallDelta[];
|
||||
}
|
||||
|
||||
/**
|
||||
* This is meant to be equivalent to the OpenAI [usage object](https://platform.openai.com/docs/api-reference/chat/object#chat/object-usage)
|
||||
* but potentially with additional information that is needed for other providers.
|
||||
*/
|
||||
export interface Usage {
|
||||
completionTokens: number;
|
||||
promptTokens: number;
|
||||
promptTokensDetails?: {
|
||||
cachedTokens?: number;
|
||||
/** This an Anthropic-specific property */
|
||||
cacheWriteTokens?: number;
|
||||
audioTokens?: number;
|
||||
};
|
||||
completionTokensDetails?: {
|
||||
acceptedPredictionTokens?: number;
|
||||
reasoningTokens?: number;
|
||||
rejectedPredictionTokens?: number;
|
||||
audioTokens?: number;
|
||||
};
|
||||
}
|
||||
|
||||
export interface AssistantChatMessage {
|
||||
role: "assistant";
|
||||
content: MessageContent;
|
||||
toolCalls?: ToolCallDelta[];
|
||||
usage?: Usage;
|
||||
}
|
||||
|
||||
export interface SystemChatMessage {
|
||||
|
|
@ -483,12 +505,14 @@ export interface LLMInteractionStartChat extends LLMInteractionBase {
|
|||
kind: "startChat";
|
||||
messages: ChatMessage[];
|
||||
options: CompletionOptions;
|
||||
provider: string;
|
||||
}
|
||||
|
||||
export interface LLMInteractionStartComplete extends LLMInteractionBase {
|
||||
kind: "startComplete";
|
||||
prompt: string;
|
||||
options: CompletionOptions;
|
||||
provider: string;
|
||||
}
|
||||
|
||||
export interface LLMInteractionStartFim extends LLMInteractionBase {
|
||||
|
|
@ -496,6 +520,7 @@ export interface LLMInteractionStartFim extends LLMInteractionBase {
|
|||
prefix: string;
|
||||
suffix: string;
|
||||
options: CompletionOptions;
|
||||
provider: string;
|
||||
}
|
||||
|
||||
export interface LLMInteractionChunk extends LLMInteractionBase {
|
||||
|
|
@ -512,6 +537,7 @@ export interface LLMInteractionEnd extends LLMInteractionBase {
|
|||
promptTokens: number;
|
||||
generatedTokens: number;
|
||||
thinkingTokens: number;
|
||||
usage: Usage | undefined;
|
||||
}
|
||||
|
||||
export interface LLMInteractionSuccess extends LLMInteractionEnd {
|
||||
|
|
|
|||
|
|
@ -27,6 +27,7 @@ import {
|
|||
RequestOptions,
|
||||
TabAutocompleteOptions,
|
||||
TemplateType,
|
||||
Usage,
|
||||
} from "../index.js";
|
||||
import mergeJson from "../util/merge.js";
|
||||
import { renderChatMessage } from "../util/messageContent.js";
|
||||
|
|
@ -320,6 +321,7 @@ export abstract class BaseLLM implements ILLM {
|
|||
completion: string,
|
||||
thinking: string | undefined,
|
||||
interaction: ILLMInteractionLog | undefined,
|
||||
usage: Usage | undefined,
|
||||
error?: any,
|
||||
): InteractionStatus {
|
||||
let promptTokens = this.countTokens(prompt);
|
||||
|
|
@ -361,6 +363,7 @@ export abstract class BaseLLM implements ILLM {
|
|||
promptTokens,
|
||||
generatedTokens,
|
||||
thinkingTokens,
|
||||
usage,
|
||||
});
|
||||
return "cancelled";
|
||||
} else {
|
||||
|
|
@ -372,6 +375,7 @@ export abstract class BaseLLM implements ILLM {
|
|||
promptTokens,
|
||||
generatedTokens,
|
||||
thinkingTokens,
|
||||
usage,
|
||||
});
|
||||
return "error";
|
||||
}
|
||||
|
|
@ -381,6 +385,7 @@ export abstract class BaseLLM implements ILLM {
|
|||
promptTokens,
|
||||
generatedTokens,
|
||||
thinkingTokens,
|
||||
usage,
|
||||
});
|
||||
return "success";
|
||||
}
|
||||
|
|
@ -567,6 +572,7 @@ export abstract class BaseLLM implements ILLM {
|
|||
prefix,
|
||||
suffix,
|
||||
options: completionOptions,
|
||||
provider: this.providerName,
|
||||
});
|
||||
if (this.llmRequestHook) {
|
||||
this.llmRequestHook(completionOptions.model, fimLog);
|
||||
|
|
@ -615,6 +621,7 @@ export abstract class BaseLLM implements ILLM {
|
|||
completion,
|
||||
undefined,
|
||||
interaction,
|
||||
undefined,
|
||||
);
|
||||
} catch (e) {
|
||||
status = this._logEnd(
|
||||
|
|
@ -623,6 +630,7 @@ export abstract class BaseLLM implements ILLM {
|
|||
completion,
|
||||
undefined,
|
||||
interaction,
|
||||
undefined,
|
||||
e,
|
||||
);
|
||||
throw e;
|
||||
|
|
@ -634,6 +642,7 @@ export abstract class BaseLLM implements ILLM {
|
|||
completion,
|
||||
undefined,
|
||||
interaction,
|
||||
undefined,
|
||||
"cancel",
|
||||
);
|
||||
}
|
||||
|
|
@ -674,6 +683,7 @@ export abstract class BaseLLM implements ILLM {
|
|||
kind: "startComplete",
|
||||
prompt,
|
||||
options: completionOptions,
|
||||
provider: this.providerName,
|
||||
});
|
||||
if (this.llmRequestHook) {
|
||||
this.llmRequestHook(completionOptions.model, prompt);
|
||||
|
|
@ -729,6 +739,7 @@ export abstract class BaseLLM implements ILLM {
|
|||
completion,
|
||||
undefined,
|
||||
interaction,
|
||||
undefined,
|
||||
);
|
||||
} catch (e) {
|
||||
status = this._logEnd(
|
||||
|
|
@ -737,6 +748,7 @@ export abstract class BaseLLM implements ILLM {
|
|||
completion,
|
||||
undefined,
|
||||
interaction,
|
||||
undefined,
|
||||
e,
|
||||
);
|
||||
throw e;
|
||||
|
|
@ -748,6 +760,7 @@ export abstract class BaseLLM implements ILLM {
|
|||
completion,
|
||||
undefined,
|
||||
interaction,
|
||||
undefined,
|
||||
"cancel",
|
||||
);
|
||||
}
|
||||
|
|
@ -789,6 +802,7 @@ export abstract class BaseLLM implements ILLM {
|
|||
kind: "startComplete",
|
||||
prompt: prompt,
|
||||
options: completionOptions,
|
||||
provider: this.providerName,
|
||||
});
|
||||
if (this.llmRequestHook) {
|
||||
this.llmRequestHook(completionOptions.model, prompt);
|
||||
|
|
@ -822,6 +836,7 @@ export abstract class BaseLLM implements ILLM {
|
|||
completion,
|
||||
undefined,
|
||||
interaction,
|
||||
undefined,
|
||||
);
|
||||
} catch (e) {
|
||||
status = this._logEnd(
|
||||
|
|
@ -830,6 +845,7 @@ export abstract class BaseLLM implements ILLM {
|
|||
completion,
|
||||
undefined,
|
||||
interaction,
|
||||
undefined,
|
||||
e,
|
||||
);
|
||||
throw e;
|
||||
|
|
@ -841,6 +857,7 @@ export abstract class BaseLLM implements ILLM {
|
|||
completion,
|
||||
undefined,
|
||||
interaction,
|
||||
undefined,
|
||||
"cancel",
|
||||
);
|
||||
}
|
||||
|
|
@ -912,6 +929,7 @@ export abstract class BaseLLM implements ILLM {
|
|||
kind: "startChat",
|
||||
messages,
|
||||
options: completionOptions,
|
||||
provider: this.providerName,
|
||||
});
|
||||
if (this.llmRequestHook) {
|
||||
this.llmRequestHook(completionOptions.model, prompt);
|
||||
|
|
@ -920,6 +938,7 @@ export abstract class BaseLLM implements ILLM {
|
|||
|
||||
let thinking = "";
|
||||
let completion = "";
|
||||
let usage: Usage | undefined = undefined;
|
||||
|
||||
try {
|
||||
if (this.templateMessages) {
|
||||
|
|
@ -986,6 +1005,11 @@ export abstract class BaseLLM implements ILLM {
|
|||
kind: "message",
|
||||
message: chunk,
|
||||
});
|
||||
|
||||
if (chunk.role === "assistant" && chunk.usage) {
|
||||
usage = chunk.usage;
|
||||
}
|
||||
|
||||
yield chunk;
|
||||
}
|
||||
}
|
||||
|
|
@ -996,6 +1020,7 @@ export abstract class BaseLLM implements ILLM {
|
|||
completion,
|
||||
thinking,
|
||||
interaction,
|
||||
usage,
|
||||
);
|
||||
} catch (e) {
|
||||
status = this._logEnd(
|
||||
|
|
@ -1004,6 +1029,7 @@ export abstract class BaseLLM implements ILLM {
|
|||
completion,
|
||||
thinking,
|
||||
interaction,
|
||||
usage,
|
||||
e,
|
||||
);
|
||||
throw e;
|
||||
|
|
@ -1015,6 +1041,7 @@ export abstract class BaseLLM implements ILLM {
|
|||
completion,
|
||||
undefined,
|
||||
interaction,
|
||||
usage,
|
||||
"cancel",
|
||||
);
|
||||
}
|
||||
|
|
|
|||
|
|
@ -1,5 +1,10 @@
|
|||
import { streamSse } from "@continuedev/fetch";
|
||||
import { ChatMessage, CompletionOptions, LLMOptions } from "../../index.js";
|
||||
import {
|
||||
ChatMessage,
|
||||
CompletionOptions,
|
||||
LLMOptions,
|
||||
Usage,
|
||||
} from "../../index.js";
|
||||
import { safeParseToolCallArgs } from "../../tools/parseArgs.js";
|
||||
import { renderChatMessage, stripImages } from "../../util/messageContent.js";
|
||||
import { BaseLLM } from "../index.js";
|
||||
|
|
@ -234,15 +239,49 @@ class Anthropic extends BaseLLM {
|
|||
|
||||
if (options.stream === false) {
|
||||
const data = await response.json();
|
||||
yield { role: "assistant", content: data.content[0].text };
|
||||
const cost = data.usage
|
||||
? {
|
||||
inputTokens: data.usage.input_tokens,
|
||||
outputTokens: data.usage.output_tokens,
|
||||
totalTokens: data.usage.input_tokens + data.usage.output_tokens,
|
||||
}
|
||||
: {};
|
||||
yield {
|
||||
role: "assistant",
|
||||
content: data.content[0].text,
|
||||
...(Object.keys(cost).length > 0 ? { cost } : {}),
|
||||
};
|
||||
return;
|
||||
}
|
||||
|
||||
let lastToolUseId: string | undefined;
|
||||
let lastToolUseName: string | undefined;
|
||||
let usage: Usage = {
|
||||
promptTokens: 0,
|
||||
completionTokens: 0,
|
||||
promptTokensDetails: {
|
||||
cachedTokens: 0,
|
||||
cacheWriteTokens: 0,
|
||||
},
|
||||
};
|
||||
|
||||
for await (const value of streamSse(response)) {
|
||||
// https://docs.anthropic.com/en/api/messages-streaming#event-types
|
||||
switch (value.type) {
|
||||
case "message_start":
|
||||
// Capture initial usage information
|
||||
usage.promptTokens = value.message.usage.input_tokens;
|
||||
usage.promptTokensDetails!.cachedTokens =
|
||||
value.message.usage.cache_read_input_tokens;
|
||||
usage.promptTokensDetails!.cacheWriteTokens =
|
||||
value.message.usage.cache_creation_input_tokens;
|
||||
break;
|
||||
case "message_delta":
|
||||
// Update usage information during streaming
|
||||
if (value.usage) {
|
||||
usage.completionTokens = value.usage.output_tokens;
|
||||
}
|
||||
break;
|
||||
case "content_block_start":
|
||||
if (value.content_block.type === "tool_use") {
|
||||
lastToolUseId = value.content_block.id;
|
||||
|
|
@ -250,7 +289,6 @@ class Anthropic extends BaseLLM {
|
|||
}
|
||||
// handle redacted thinking
|
||||
if (value.content_block.type === "redacted_thinking") {
|
||||
console.log("redacted thinking", value.content_block.data);
|
||||
yield {
|
||||
role: "thinking",
|
||||
content: "",
|
||||
|
|
@ -303,6 +341,12 @@ class Anthropic extends BaseLLM {
|
|||
break;
|
||||
}
|
||||
}
|
||||
|
||||
yield {
|
||||
role: "assistant",
|
||||
content: "",
|
||||
usage,
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
|
|
|
|||
|
|
@ -44,6 +44,7 @@ describe("LLMLogFormatter", () => {
|
|||
content: "You are a helpful assistant",
|
||||
},
|
||||
],
|
||||
provider: "watsonx",
|
||||
});
|
||||
logger._logItem({
|
||||
interactionId: "1",
|
||||
|
|
@ -79,6 +80,7 @@ describe("LLMLogFormatter", () => {
|
|||
promptTokens: 10,
|
||||
generatedTokens: 20,
|
||||
thinkingTokens: 0,
|
||||
usage: undefined,
|
||||
});
|
||||
|
||||
expect(output.getText()).toBe(
|
||||
|
|
@ -113,6 +115,7 @@ describe("LLMLogFormatter", () => {
|
|||
model: "granite3.2-dense:8b",
|
||||
},
|
||||
prompt: "A horse is a horse",
|
||||
provider: "watsonx",
|
||||
});
|
||||
logger._logItem({
|
||||
interactionId: "1",
|
||||
|
|
@ -149,6 +152,7 @@ describe("LLMLogFormatter", () => {
|
|||
},
|
||||
prefix: "A\nB",
|
||||
suffix: "D\nE",
|
||||
provider: "watsonx",
|
||||
});
|
||||
logger._logItem({
|
||||
interactionId: "1",
|
||||
|
|
@ -225,6 +229,7 @@ describe("LLMLogFormatter", () => {
|
|||
promptTokens: 10,
|
||||
generatedTokens: 20,
|
||||
thinkingTokens: 0,
|
||||
usage: undefined,
|
||||
});
|
||||
logger._logItem({
|
||||
interactionId: "3",
|
||||
|
|
|
|||
181
core/llm/utils/calculateRequestCost.ts
Normal file
181
core/llm/utils/calculateRequestCost.ts
Normal file
|
|
@ -0,0 +1,181 @@
|
|||
import { Usage } from "../..";
|
||||
|
||||
export interface CostBreakdown {
|
||||
cost: number;
|
||||
breakdown: string;
|
||||
}
|
||||
|
||||
function calculateAnthropicCost(
|
||||
model: string,
|
||||
usage: Usage,
|
||||
): CostBreakdown | null {
|
||||
// Normalize model name to handle various formats
|
||||
const normalizedModel = model.toLowerCase();
|
||||
|
||||
// Define pricing per million tokens (MTok)
|
||||
const pricing: Record<
|
||||
string,
|
||||
{ input: number; output: number; cacheWrite: number; cacheRead: number }
|
||||
> = {
|
||||
// Claude Opus 4 (most intelligent model)
|
||||
"claude-3-opus": {
|
||||
input: 15,
|
||||
output: 75,
|
||||
cacheWrite: 18.75,
|
||||
cacheRead: 1.5,
|
||||
},
|
||||
"claude-3-opus-20240229": {
|
||||
input: 15,
|
||||
output: 75,
|
||||
cacheWrite: 18.75,
|
||||
cacheRead: 1.5,
|
||||
},
|
||||
|
||||
// Claude Sonnet 4 (optimal balance)
|
||||
"claude-3-5-sonnet": {
|
||||
input: 3,
|
||||
output: 15,
|
||||
cacheWrite: 3.75,
|
||||
cacheRead: 0.3,
|
||||
},
|
||||
"claude-3-5-sonnet-20241022": {
|
||||
input: 3,
|
||||
output: 15,
|
||||
cacheWrite: 3.75,
|
||||
cacheRead: 0.3,
|
||||
},
|
||||
"claude-3-5-sonnet-20240620": {
|
||||
input: 3,
|
||||
output: 15,
|
||||
cacheWrite: 3.75,
|
||||
cacheRead: 0.3,
|
||||
},
|
||||
|
||||
// Claude Haiku 3.5 (fastest, most cost-effective)
|
||||
"claude-3-5-haiku": {
|
||||
input: 0.8,
|
||||
output: 4,
|
||||
cacheWrite: 1,
|
||||
cacheRead: 0.08,
|
||||
},
|
||||
"claude-3-5-haiku-20241022": {
|
||||
input: 0.8,
|
||||
output: 4,
|
||||
cacheWrite: 1,
|
||||
cacheRead: 0.08,
|
||||
},
|
||||
|
||||
// Legacy Claude 3 Haiku
|
||||
"claude-3-haiku": {
|
||||
input: 0.25,
|
||||
output: 1.25,
|
||||
cacheWrite: 0.3,
|
||||
cacheRead: 0.03,
|
||||
},
|
||||
"claude-3-haiku-20240307": {
|
||||
input: 0.25,
|
||||
output: 1.25,
|
||||
cacheWrite: 0.3,
|
||||
cacheRead: 0.03,
|
||||
},
|
||||
};
|
||||
|
||||
// Find matching pricing model
|
||||
let modelPricing = pricing[normalizedModel];
|
||||
|
||||
// If exact match not found, try to find by partial match
|
||||
if (!modelPricing) {
|
||||
for (const [key, value] of Object.entries(pricing)) {
|
||||
if (normalizedModel.includes(key) || key.includes(normalizedModel)) {
|
||||
modelPricing = value;
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// If still no match, try common patterns
|
||||
if (!modelPricing) {
|
||||
if (normalizedModel.includes("opus")) {
|
||||
modelPricing = pricing["claude-3-opus"];
|
||||
} else if (normalizedModel.includes("sonnet")) {
|
||||
modelPricing = pricing["claude-3-5-sonnet"];
|
||||
} else if (normalizedModel.includes("haiku")) {
|
||||
modelPricing = pricing["claude-3-5-haiku"];
|
||||
}
|
||||
}
|
||||
|
||||
if (!modelPricing) {
|
||||
return null; // Unknown model
|
||||
}
|
||||
|
||||
// Calculate costs
|
||||
const inputCost = (usage.promptTokens / 1_000_000) * modelPricing.input;
|
||||
const outputCost = (usage.completionTokens / 1_000_000) * modelPricing.output;
|
||||
|
||||
// Build breakdown components
|
||||
const breakdownParts: string[] = [];
|
||||
|
||||
// Input tokens breakdown
|
||||
if (usage.promptTokens > 0) {
|
||||
breakdownParts.push(
|
||||
`Input: ${usage.promptTokens.toLocaleString()} tokens × $${modelPricing.input}/MTok = $${inputCost.toFixed(6)}`,
|
||||
);
|
||||
}
|
||||
|
||||
// Output tokens breakdown
|
||||
if (usage.completionTokens > 0) {
|
||||
breakdownParts.push(
|
||||
`Output: ${usage.completionTokens.toLocaleString()} tokens × $${modelPricing.output}/MTok = $${outputCost.toFixed(6)}`,
|
||||
);
|
||||
}
|
||||
|
||||
// Handle prompt caching costs if available
|
||||
let cacheCost = 0;
|
||||
if (usage.promptTokensDetails) {
|
||||
const { cachedTokens, cacheWriteTokens } = usage.promptTokensDetails;
|
||||
|
||||
if (cacheWriteTokens && cacheWriteTokens > 0) {
|
||||
const cacheWriteCost =
|
||||
(cacheWriteTokens / 1_000_000) * modelPricing.cacheWrite;
|
||||
cacheCost += cacheWriteCost;
|
||||
breakdownParts.push(
|
||||
`Cache Write: ${cacheWriteTokens.toLocaleString()} tokens × $${modelPricing.cacheWrite}/MTok = $${cacheWriteCost.toFixed(6)}`,
|
||||
);
|
||||
}
|
||||
|
||||
if (cachedTokens && cachedTokens > 0) {
|
||||
const cacheReadCost = (cachedTokens / 1_000_000) * modelPricing.cacheRead;
|
||||
cacheCost += cacheReadCost;
|
||||
breakdownParts.push(
|
||||
`Cache Read: ${cachedTokens.toLocaleString()} tokens × $${modelPricing.cacheRead}/MTok = $${cacheReadCost.toFixed(6)}`,
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
const totalCost = inputCost + outputCost + cacheCost;
|
||||
|
||||
// Build final breakdown string
|
||||
let breakdown = `Model: ${model}\n`;
|
||||
breakdown += breakdownParts.join("\n");
|
||||
if (breakdownParts.length > 1) {
|
||||
breakdown += `\nTotal: $${totalCost.toFixed(6)}`;
|
||||
}
|
||||
|
||||
return {
|
||||
cost: totalCost,
|
||||
breakdown,
|
||||
};
|
||||
}
|
||||
|
||||
export function calculateRequestCost(
|
||||
provider: string,
|
||||
model: string,
|
||||
usage: Usage,
|
||||
): CostBreakdown | null {
|
||||
switch (provider) {
|
||||
case "anthropic":
|
||||
return calculateAnthropicCost(model, usage);
|
||||
default:
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
|
@ -117,6 +117,11 @@ export default function Details({ interaction }: DetailsProps) {
|
|||
format={(v: number) => v.toFixed(1)}
|
||||
></Cell>
|
||||
</div>
|
||||
{/**summary.costBreakdown && (
|
||||
<pre className="whitespace-pre-wrap px-2 text-sm">
|
||||
{summary.costBreakdown.breakdown}
|
||||
</pre>
|
||||
)*/}
|
||||
</div>
|
||||
<div
|
||||
ref={scrollTop}
|
||||
|
|
|
|||
|
|
@ -1,3 +1,7 @@
|
|||
import {
|
||||
calculateRequestCost,
|
||||
CostBreakdown,
|
||||
} from "core/llm/utils/calculateRequestCost";
|
||||
import { useMemo } from "react";
|
||||
import { LLMInteraction } from "./useLLMLog";
|
||||
|
||||
|
|
@ -62,6 +66,19 @@ export default function useLLMSummary(interaction: LLMInteraction) {
|
|||
: undefined;
|
||||
}
|
||||
|
||||
let costBreakdown: CostBreakdown | null = null;
|
||||
if (
|
||||
interaction.end?.usage &&
|
||||
interaction.start?.provider &&
|
||||
interaction.start?.options?.model
|
||||
) {
|
||||
costBreakdown = calculateRequestCost(
|
||||
interaction.start.provider,
|
||||
interaction.start.options.model,
|
||||
interaction.end.usage,
|
||||
);
|
||||
}
|
||||
|
||||
return {
|
||||
result,
|
||||
type,
|
||||
|
|
@ -71,6 +88,7 @@ export default function useLLMSummary(interaction: LLMInteraction) {
|
|||
promptTokens,
|
||||
generatedTokens,
|
||||
thinkingTokens,
|
||||
costBreakdown,
|
||||
};
|
||||
}, [interaction]);
|
||||
}
|
||||
|
|
|
|||
Loading…
Add table
Reference in a new issue