Principle:AIPexStudio AIPex Metrics And Persistence
| Knowledge Sources | |
|---|---|
| Domains | Observability, State_Management |
| Last Updated | 2026-10-24 12:00 GMT |
Overview
A pattern for extracting token usage metrics from AI model responses, accumulating them across turns, and persisting conversation state for later resumption.
Description
AI agent systems need to track resource consumption (input/output tokens, duration, item count) for cost analysis and UI feedback. Metrics are extracted from the last model response in an execution (which contains the total token count for that turn), stored in a metrics snapshot, and emitted as an event for UI and plugin consumers. Conversation state—the full session history—is persisted to a storage adapter after each execution, enabling session resumption via a session ID. Plugin hooks (`onMetrics`, `afterResponse`) allow extensions to react to completed turns for logging, analytics, or side effects.
Usage
Use this principle when the agent needs to maintain conversation history across sessions, report token usage to the UI, or allow plugins to observe completed responses. It is essential for any multi-session agent application.
Theoretical Basis
1. Extract usage from result.rawResponses (last response with usage data)
2. Update metrics: promptTokens, completionTokens, tokensUsed
3. Emit metrics_update event
4. Session.addMetrics(metrics)
5. ConversationManager.saveSession(session)
6. Run afterResponse hooks (plugins)