File size: 7,068 Bytes
fc69895
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
import { collectDefaultMetrics, Counter, Registry, Summary } from "prom-client";
import { logger } from "$lib/server/logger";
import { config } from "$lib/server/config";
import { createServer, type Server as HttpServer } from "http";
import { onExit } from "./exitHandler";

type ModelLabel = "model";
type ToolLabel = "tool";

interface Metrics {
	model: {
		conversationsTotal: Counter<ModelLabel>;
		messagesTotal: Counter<ModelLabel>;
		tokenCountTotal: Counter<ModelLabel>;
		timePerOutputToken: Summary<ModelLabel>;
		timeToFirstToken: Summary<ModelLabel>;
		latency: Summary<ModelLabel>;
		votesPositive: Counter<ModelLabel>;
		votesNegative: Counter<ModelLabel>;
	};
	webSearch: {
		requestCount: Counter;
		pageFetchCount: Counter;
		pageFetchCountError: Counter;
		pageFetchDuration: Summary;
		embeddingDuration: Summary;
	};
	tool: {
		toolUseCount: Counter<ToolLabel>;
		toolUseCountError: Counter<ToolLabel>;
		toolUseDuration: Summary<ToolLabel>;
		timeToChooseTools: Summary<ModelLabel>;
	};
}

export class MetricsServer {
	private static instance: MetricsServer | undefined;
	private readonly enabled: boolean;
	private readonly register: Registry;
	private readonly metrics: Metrics;
	private httpServer: HttpServer | undefined;

	private constructor() {
		this.enabled = config.METRICS_ENABLED === "true";
		this.register = new Registry();

		if (this.enabled) {
			collectDefaultMetrics({ register: this.register });
		}

		this.metrics = this.createMetrics();

		if (this.enabled) {
			this.startStandaloneServer();
		}
	}

	public static getInstance(): MetricsServer {
		if (!MetricsServer.instance) {
			MetricsServer.instance = new MetricsServer();
		}
		return MetricsServer.instance;
	}

	public static getMetrics(): Metrics {
		return MetricsServer.getInstance().metrics;
	}

	public static isEnabled(): boolean {
		return config.METRICS_ENABLED === "true";
	}

	public async render(): Promise<string> {
		if (!this.enabled) {
			return "";
		}

		return this.register.metrics();
	}

	private createMetrics(): Metrics {
		const labelNames: ModelLabel[] = ["model"];
		const toolLabelNames: ToolLabel[] = ["tool"];

		const noopRegistry = new Registry();

		const registry = this.enabled ? this.register : noopRegistry;

		return {
			model: {
				conversationsTotal: new Counter<ModelLabel>({
					name: "model_conversations_total",
					help: "Total number of conversations",
					labelNames,
					registers: [registry],
				}),
				messagesTotal: new Counter<ModelLabel>({
					name: "model_messages_total",
					help: "Total number of messages",
					labelNames,
					registers: [registry],
				}),
				tokenCountTotal: new Counter<ModelLabel>({
					name: "model_token_count_total",
					help: "Total number of tokens emitted by the model",
					labelNames,
					registers: [registry],
				}),
				timePerOutputToken: new Summary<ModelLabel>({
					name: "model_time_per_output_token_ms",
					help: "Per-token latency in milliseconds",
					labelNames,
					registers: [registry],
					maxAgeSeconds: 5 * 60,
					ageBuckets: 5,
				}),
				timeToFirstToken: new Summary<ModelLabel>({
					name: "model_time_to_first_token_ms",
					help: "Time to first token in milliseconds",
					labelNames,
					registers: [registry],
					maxAgeSeconds: 5 * 60,
					ageBuckets: 5,
				}),
				latency: new Summary<ModelLabel>({
					name: "model_latency_ms",
					help: "Total time to complete a response in milliseconds",
					labelNames,
					registers: [registry],
					maxAgeSeconds: 5 * 60,
					ageBuckets: 5,
				}),
				votesPositive: new Counter<ModelLabel>({
					name: "model_votes_positive_total",
					help: "Total number of positive votes on model messages",
					labelNames,
					registers: [registry],
				}),
				votesNegative: new Counter<ModelLabel>({
					name: "model_votes_negative_total",
					help: "Total number of negative votes on model messages",
					labelNames,
					registers: [registry],
				}),
			},
			webSearch: {
				requestCount: new Counter({
					name: "web_search_request_count",
					help: "Total number of web search requests",
					registers: [registry],
				}),
				pageFetchCount: new Counter({
					name: "web_search_page_fetch_count",
					help: "Total number of web search page fetches",
					registers: [registry],
				}),
				pageFetchCountError: new Counter({
					name: "web_search_page_fetch_count_error",
					help: "Total number of web search page fetch errors",
					registers: [registry],
				}),
				pageFetchDuration: new Summary({
					name: "web_search_page_fetch_duration_ms",
					help: "Duration of web search page fetches in milliseconds",
					registers: [registry],
					maxAgeSeconds: 5 * 60,
					ageBuckets: 5,
				}),
				embeddingDuration: new Summary({
					name: "web_search_embedding_duration_ms",
					help: "Duration of web search embeddings in milliseconds",
					registers: [registry],
					maxAgeSeconds: 5 * 60,
					ageBuckets: 5,
				}),
			},
			tool: {
				toolUseCount: new Counter<ToolLabel>({
					name: "tool_use_count",
					help: "Total number of tool invocations",
					labelNames: toolLabelNames,
					registers: [registry],
				}),
				toolUseCountError: new Counter<ToolLabel>({
					name: "tool_use_count_error",
					help: "Total number of tool invocation errors",
					labelNames: toolLabelNames,
					registers: [registry],
				}),
				toolUseDuration: new Summary<ToolLabel>({
					name: "tool_use_duration_ms",
					help: "Duration of tool invocations in milliseconds",
					labelNames: toolLabelNames,
					registers: [registry],
					maxAgeSeconds: 30 * 60,
					ageBuckets: 5,
				}),
				timeToChooseTools: new Summary<ModelLabel>({
					name: "time_to_choose_tools_ms",
					help: "Time spent selecting tools in milliseconds",
					labelNames,
					registers: [registry],
					maxAgeSeconds: 5 * 60,
					ageBuckets: 5,
				}),
			},
		};
	}

	private startStandaloneServer() {
		const port = Number(config.METRICS_PORT || "5565");

		if (!Number.isInteger(port) || port < 0 || port > 65535) {
			logger.warn(`Invalid METRICS_PORT value: ${config.METRICS_PORT}`);
			return;
		}

		this.httpServer = createServer(async (req, res) => {
			if (req.method !== "GET") {
				res.statusCode = 405;
				res.end("Method Not Allowed");
				return;
			}

			try {
				const payload = await this.render();
				res.setHeader("Content-Type", "text/plain; version=0.0.4");
				res.end(payload);
			} catch (error) {
				logger.error(error, "Failed to render metrics");
				res.statusCode = 500;
				res.end("Failed to render metrics");
			}
		});

		this.httpServer.listen(port, () => {
			logger.info(`Metrics server listening on port ${port}`);
		});

		onExit(async () => {
			if (!this.httpServer) return;
			logger.info("Shutting down metrics server...");
			await new Promise<void>((resolve, reject) => {
				this.httpServer?.close((err) => {
					if (err) {
						reject(err);
						return;
					}
					resolve();
				});
			}).catch((error) => logger.error(error, "Failed to close metrics server"));
			this.httpServer = undefined;
		});
	}
}