| 100 | }); |
| 101 | |
| 102 | export class UiTelemetryService extends EventEmitter { |
| 103 | #metrics: SessionMetrics = createInitialMetrics(); |
| 104 | #lastPromptTokenCount = 0; |
| 105 | |
| 106 | addEvent(event: UiEvent) { |
| 107 | switch (event['event.name']) { |
| 108 | case EVENT_API_RESPONSE: |
| 109 | this.processApiResponse(event); |
| 110 | break; |
| 111 | case EVENT_API_ERROR: |
| 112 | this.processApiError(event); |
| 113 | break; |
| 114 | case EVENT_TOOL_CALL: |
| 115 | this.processToolCall(event); |
| 116 | break; |
| 117 | default: |
| 118 | // We should not emit update for any other event metric. |
| 119 | return; |
| 120 | } |
| 121 | |
| 122 | this.emit('update', { |
| 123 | metrics: this.#metrics, |
| 124 | lastPromptTokenCount: this.#lastPromptTokenCount, |
| 125 | }); |
| 126 | } |
| 127 | |
| 128 | getMetrics(): SessionMetrics { |
| 129 | return this.#metrics; |
| 130 | } |
| 131 | |
| 132 | getLastPromptTokenCount(): number { |
| 133 | return this.#lastPromptTokenCount; |
| 134 | } |
| 135 | |
| 136 | resetLastPromptTokenCount(): void { |
| 137 | this.#lastPromptTokenCount = 0; |
| 138 | this.emit('update', { |
| 139 | metrics: this.#metrics, |
| 140 | lastPromptTokenCount: this.#lastPromptTokenCount, |
| 141 | }); |
| 142 | } |
| 143 | |
| 144 | private getOrCreateModelMetrics(modelName: string): ModelMetrics { |
| 145 | if (!this.#metrics.models[modelName]) { |
| 146 | this.#metrics.models[modelName] = createInitialModelMetrics(); |
| 147 | } |
| 148 | return this.#metrics.models[modelName]; |
| 149 | } |
| 150 | |
| 151 | private processApiResponse(event: ApiResponseEvent) { |
| 152 | const modelMetrics = this.getOrCreateModelMetrics(event.model); |
| 153 | |
| 154 | modelMetrics.api.totalRequests++; |
| 155 | modelMetrics.api.totalLatencyMs += event.duration_ms; |
| 156 | |
| 157 | modelMetrics.tokens.prompt += event.input_token_count; |
| 158 | modelMetrics.tokens.candidates += event.output_token_count; |
| 159 | modelMetrics.tokens.total += event.total_token_count; |
nothing calls this directly
no test coverage detected