Implementation:AIPexStudio AIPex AIPex applyUsageMetrics
| Knowledge Sources | |
|---|---|
| Domains | Observability, Core |
| Last Updated | 2026-10-24 12:00 GMT |
Overview
Concrete method that extracts token usage from the last model response in an execution, updates the agent metrics snapshot, and triggers persistence and plugin hooks.
Description
The applyUsageMetrics method iterates `result.rawResponses` backwards to find the last response with a `usage` object (representing total tokens for the execution). It sets `promptTokens` from `inputTokens` and `completionTokens` from `outputTokens`, computes `tokensUsed` as their sum, and updates the `AgentMetrics` object in place. After metrics extraction, the session is persisted via `ConversationManager.saveSession`, and `afterResponse` and `onMetrics` plugin hooks are invoked.
Usage
Called internally by `runExecution` after the streaming loop completes. Not called directly by consumers.
Code Reference
Source Location
- Repository: AIPex
- File: packages/core/src/agent/aipex.ts
- Lines: L745-768 (applyUsageMetrics), L818-833 (afterResponse hooks), L847-857 (onMetrics hooks)
Signature
private applyUsageMetrics(
metrics: AgentMetrics,
result: { rawResponses?: Array<{ usage?: UsageShape }> }
): void
private async runAfterResponseHooks(payload: AfterResponsePayload): Promise<void>
private async emitMetricsHooks(payload: MetricsPayload): Promise<void>
interface UsageShape {
inputTokens?: number;
outputTokens?: number;
}
interface AgentMetrics {
tokensUsed: number;
promptTokens: number;
completionTokens: number;
itemCount: number;
maxTurns: number;
duration: number;
startTime: number;
}
Import
// Internal method — not exported. Called by AIPex.runExecution().
I/O Contract
Inputs
| Name | Type | Required | Description |
|---|---|---|---|
| metrics | AgentMetrics | Yes | Mutable metrics object to update in place |
| result.rawResponses | Array<{usage?: UsageShape}> | No | SDK result with usage data |
Outputs
| Name | Type | Description |
|---|---|---|
| returns | void | Updates metrics in place; session persisted; hooks invoked |
Usage Examples
Internal Flow (Illustrative)
// Called internally after streaming completes:
// this.applyUsageMetrics(metrics, result);
// await this.emitMetricsHooks({ metrics, sessionId });
// yield { type: "metrics_update", metrics, sessionId };
// if (session) {
// session.addMetrics(metrics);
// await this.conversationManager.saveSession(session);
// }
// await this.runAfterResponseHooks({ input, finalOutput, metrics, sessionId });