feat: capture and attach usage metadata to assistant messages

Add per-message cost tracking by capturing usage data from LLM API
responses and attaching it to assistant messages when saved to session.

- Update addAssistantMessage to accept usage parameter
- Modify handleToolCalls to pass usage to message creation
- Enhance processStreamingResponse to return usage with model and cost
- Calculate cost in cents and include model name in usage metadata

This enables the control plane cost analysis page to display accurate
per-message costs without client-side token estimation.

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude Sonnet 4.5 <noreply@anthropic.com>
This commit is contained in:
Nate 2025-12-09 14:36:24 -08:00
parent 4ab3cfc47c
commit 7f9ef3694d
3 changed files with 35 additions and 10 deletions

View file

@ -124,7 +124,11 @@ export class ChatHistoryService extends BaseService<ChatHistoryState> {
/**
* Add an assistant message to the history
*/
addAssistantMessage(content: string, toolCalls?: any[]): ChatHistoryItem {
addAssistantMessage(
content: string,
toolCalls?: any[],
usage?: any,
): ChatHistoryItem {
const message: any = {
role: "assistant",
content,
@ -134,6 +138,10 @@ export class ChatHistoryService extends BaseService<ChatHistoryState> {
message.toolCalls = toolCalls;
}
if (usage) {
message.usage = usage;
}
const toolCallStates = toolCalls?.map((tc) => {
const id = tc.id;
const name = tc.function?.name ?? tc.name;

View file

@ -30,6 +30,7 @@ export async function handleToolCalls(
content: string,
callbacks: StreamCallbacks | undefined,
isHeadless: boolean,
usage?: any,
): Promise<boolean> {
const chatHistorySvc = services.chatHistory;
const useService =
@ -38,15 +39,17 @@ export async function handleToolCalls(
if (content) {
if (useService) {
// Service-driven: write assistant message via service
chatHistorySvc.addAssistantMessage(content);
chatHistorySvc.addAssistantMessage(content, undefined, usage);
} else {
// Fallback only when service is unavailable
chatHistory.push(
createHistoryItem({
role: "assistant",
content,
}),
);
const message: any = {
role: "assistant",
content,
};
if (usage) {
message.usage = usage;
}
chatHistory.push(createHistoryItem(message));
}
}
return false;
@ -86,10 +89,14 @@ export async function handleToolCalls(
chatHistorySvc.addAssistantMessage(
assistantMessage.content || "",
assistantMessage.toolCalls,
usage,
);
} else {
// Fallback only when service is unavailable
chatHistory.push(createHistoryItem(assistantMessage, [], toolCallStates));
const messageWithUsage = usage
? { ...assistantMessage, usage }
: assistantMessage;
chatHistory.push(createHistoryItem(messageWithUsage, [], toolCallStates));
}
// First preprocess the tool calls

View file

@ -201,6 +201,7 @@ export async function processStreamingResponse(
finalContent: string; // Added field for final content only
toolCalls: ToolCall[];
shouldContinue: boolean;
usage?: any;
}> {
const {
model,
@ -344,6 +345,12 @@ export async function processStreamingResponse(
});
const totalDuration = responseEndTime - requestStartTime;
// Enhance fullUsage with model and cost for saving to session
if (fullUsage) {
fullUsage.model = model.model;
fullUsage.cost_cents = Math.round(cost * 100); // Convert dollars to cents
}
logger.debug("Stream complete", {
chunkCount,
responseLength: aiResponse.length,
@ -382,6 +389,7 @@ export async function processStreamingResponse(
finalContent: aiResponse,
toolCalls: [],
shouldContinue: false,
usage: fullUsage,
};
}
@ -418,6 +426,7 @@ export async function processStreamingResponse(
finalContent: finalContent,
toolCalls: validToolCalls,
shouldContinue: validToolCalls.length > 0,
usage: fullUsage,
};
}
@ -478,7 +487,7 @@ export async function streamChatResponse(
});
// Get response from LLM
const { content, toolCalls, shouldContinue } =
const { content, toolCalls, shouldContinue, usage } =
await processStreamingResponse({
isHeadless,
chatHistory,
@ -514,6 +523,7 @@ export async function streamChatResponse(
content,
callbacks,
isHeadless,
usage,
);
if (shouldReturn) {