tokviz 0.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,13 @@
1
+ <!DOCTYPE html>
2
+ <html lang="en">
3
+ <head>
4
+ <meta charset="UTF-8" />
5
+ <meta name="viewport" content="width=device-width, initial-scale=1.0" />
6
+ <title>tokviz</title>
7
+ <script type="module" crossorigin src="/assets/index-SNGqhtM5.js"></script>
8
+ <link rel="stylesheet" crossorigin href="/assets/index-R0O4p4a7.css">
9
+ </head>
10
+ <body>
11
+ <div id="root"></div>
12
+ </body>
13
+ </html>
@@ -0,0 +1,416 @@
1
+ #!/usr/bin/env node
2
+
3
+ // src/server/index.ts
4
+ import express from "express";
5
+ import { createServer } from "http";
6
+ import { WebSocketServer, WebSocket } from "ws";
7
+ import { parseArgs } from "util";
8
+ import { fileURLToPath } from "url";
9
+ import { dirname, join } from "path";
10
+ import { existsSync } from "fs";
11
+ import open from "open";
12
+
13
+ // src/server/otlp.ts
14
+ import protobuf from "protobufjs";
15
+
16
+ // src/server/store.ts
17
+ var Store = class {
18
+ spans = [];
19
+ add(span) {
20
+ this.spans.push(span);
21
+ }
22
+ getAll() {
23
+ return { spans: this.spans };
24
+ }
25
+ };
26
+ var store = new Store();
27
+
28
+ // src/server/proto.ts
29
+ var protoDescriptor = {
30
+ nested: {
31
+ opentelemetry: {
32
+ nested: {
33
+ proto: {
34
+ nested: {
35
+ collector: {
36
+ nested: {
37
+ trace: {
38
+ nested: {
39
+ v1: {
40
+ nested: {
41
+ ExportTraceServiceRequest: {
42
+ fields: {
43
+ resourceSpans: {
44
+ rule: "repeated",
45
+ type: "opentelemetry.proto.trace.v1.ResourceSpans",
46
+ id: 1
47
+ }
48
+ }
49
+ }
50
+ }
51
+ }
52
+ }
53
+ }
54
+ }
55
+ },
56
+ trace: {
57
+ nested: {
58
+ v1: {
59
+ nested: {
60
+ ResourceSpans: {
61
+ fields: {
62
+ resource: {
63
+ type: "opentelemetry.proto.resource.v1.Resource",
64
+ id: 1
65
+ },
66
+ scopeSpans: {
67
+ rule: "repeated",
68
+ type: "ScopeSpans",
69
+ id: 2
70
+ },
71
+ schemaUrl: { type: "string", id: 3 }
72
+ }
73
+ },
74
+ ScopeSpans: {
75
+ fields: {
76
+ scope: {
77
+ type: "opentelemetry.proto.common.v1.InstrumentationScope",
78
+ id: 1
79
+ },
80
+ spans: { rule: "repeated", type: "Span", id: 2 },
81
+ schemaUrl: { type: "string", id: 3 }
82
+ }
83
+ },
84
+ Span: {
85
+ fields: {
86
+ traceId: { type: "bytes", id: 1 },
87
+ spanId: { type: "bytes", id: 2 },
88
+ traceState: { type: "string", id: 3 },
89
+ parentSpanId: { type: "bytes", id: 4 },
90
+ name: { type: "string", id: 5 },
91
+ kind: { type: "SpanKind", id: 6 },
92
+ startTimeUnixNano: { type: "fixed64", id: 7 },
93
+ endTimeUnixNano: { type: "fixed64", id: 8 },
94
+ attributes: {
95
+ rule: "repeated",
96
+ type: "opentelemetry.proto.common.v1.KeyValue",
97
+ id: 9
98
+ },
99
+ droppedAttributesCount: { type: "uint32", id: 10 },
100
+ events: { rule: "repeated", type: "Event", id: 11 },
101
+ droppedEventsCount: { type: "uint32", id: 12 },
102
+ links: { rule: "repeated", type: "Link", id: 13 },
103
+ droppedLinksCount: { type: "uint32", id: 14 },
104
+ status: { type: "Status", id: 15 }
105
+ }
106
+ },
107
+ SpanKind: {
108
+ values: {
109
+ SPAN_KIND_UNSPECIFIED: 0,
110
+ SPAN_KIND_INTERNAL: 1,
111
+ SPAN_KIND_SERVER: 2,
112
+ SPAN_KIND_CLIENT: 3,
113
+ SPAN_KIND_PRODUCER: 4,
114
+ SPAN_KIND_CONSUMER: 5
115
+ }
116
+ },
117
+ Status: {
118
+ fields: {
119
+ message: { type: "string", id: 2 },
120
+ code: { type: "StatusCode", id: 3 }
121
+ }
122
+ },
123
+ StatusCode: {
124
+ values: {
125
+ STATUS_CODE_UNSET: 0,
126
+ STATUS_CODE_OK: 1,
127
+ STATUS_CODE_ERROR: 2
128
+ }
129
+ },
130
+ Event: {
131
+ fields: {
132
+ timeUnixNano: { type: "fixed64", id: 1 },
133
+ name: { type: "string", id: 2 },
134
+ attributes: {
135
+ rule: "repeated",
136
+ type: "opentelemetry.proto.common.v1.KeyValue",
137
+ id: 3
138
+ },
139
+ droppedAttributesCount: { type: "uint32", id: 4 }
140
+ }
141
+ },
142
+ Link: {
143
+ fields: {
144
+ traceId: { type: "bytes", id: 1 },
145
+ spanId: { type: "bytes", id: 2 },
146
+ traceState: { type: "string", id: 3 },
147
+ attributes: {
148
+ rule: "repeated",
149
+ type: "opentelemetry.proto.common.v1.KeyValue",
150
+ id: 4
151
+ },
152
+ droppedAttributesCount: { type: "uint32", id: 5 }
153
+ }
154
+ }
155
+ }
156
+ }
157
+ }
158
+ },
159
+ common: {
160
+ nested: {
161
+ v1: {
162
+ nested: {
163
+ InstrumentationScope: {
164
+ fields: {
165
+ name: { type: "string", id: 1 },
166
+ version: { type: "string", id: 2 },
167
+ attributes: {
168
+ rule: "repeated",
169
+ type: "KeyValue",
170
+ id: 3
171
+ },
172
+ droppedAttributesCount: { type: "uint32", id: 4 }
173
+ }
174
+ },
175
+ KeyValue: {
176
+ fields: {
177
+ key: { type: "string", id: 1 },
178
+ value: { type: "AnyValue", id: 2 }
179
+ }
180
+ },
181
+ AnyValue: {
182
+ oneofs: {
183
+ value: {
184
+ oneof: [
185
+ "stringValue",
186
+ "boolValue",
187
+ "intValue",
188
+ "doubleValue",
189
+ "arrayValue",
190
+ "kvlistValue",
191
+ "bytesValue"
192
+ ]
193
+ }
194
+ },
195
+ fields: {
196
+ stringValue: { type: "string", id: 1 },
197
+ boolValue: { type: "bool", id: 2 },
198
+ intValue: { type: "int64", id: 3 },
199
+ doubleValue: { type: "double", id: 4 },
200
+ arrayValue: { type: "ArrayValue", id: 5 },
201
+ kvlistValue: { type: "KeyValueList", id: 6 },
202
+ bytesValue: { type: "bytes", id: 7 }
203
+ }
204
+ },
205
+ ArrayValue: {
206
+ fields: {
207
+ values: { rule: "repeated", type: "AnyValue", id: 1 }
208
+ }
209
+ },
210
+ KeyValueList: {
211
+ fields: {
212
+ values: { rule: "repeated", type: "KeyValue", id: 1 }
213
+ }
214
+ }
215
+ }
216
+ }
217
+ }
218
+ },
219
+ resource: {
220
+ nested: {
221
+ v1: {
222
+ nested: {
223
+ Resource: {
224
+ fields: {
225
+ attributes: {
226
+ rule: "repeated",
227
+ type: "opentelemetry.proto.common.v1.KeyValue",
228
+ id: 1
229
+ },
230
+ droppedAttributesCount: { type: "uint32", id: 2 }
231
+ }
232
+ }
233
+ }
234
+ }
235
+ }
236
+ }
237
+ }
238
+ }
239
+ }
240
+ }
241
+ }
242
+ };
243
+
244
+ // src/server/otlp.ts
245
+ var root = protobuf.Root.fromJSON(protoDescriptor);
246
+ var ExportTraceServiceRequest = root.lookupType(
247
+ "opentelemetry.proto.collector.trace.v1.ExportTraceServiceRequest"
248
+ );
249
+ function handleTraces(body, contentType) {
250
+ let request;
251
+ if (contentType.includes("application/x-protobuf")) {
252
+ const message = ExportTraceServiceRequest.decode(
253
+ body instanceof Buffer ? new Uint8Array(body) : body
254
+ );
255
+ request = ExportTraceServiceRequest.toObject(message, {
256
+ longs: String,
257
+ bytes: Buffer,
258
+ defaults: true
259
+ });
260
+ } else {
261
+ request = body;
262
+ }
263
+ return extractGenAISpans(request);
264
+ }
265
+ function extractGenAISpans(request) {
266
+ const spans = [];
267
+ for (const resourceSpan of request.resourceSpans || []) {
268
+ for (const scopeSpan of resourceSpan.scopeSpans || []) {
269
+ for (const span of scopeSpan.spans || []) {
270
+ const attrs = extractAttributes(span.attributes || []);
271
+ const hasGenAI = Object.keys(attrs).some(
272
+ (k) => k.startsWith("gen_ai.")
273
+ );
274
+ if (!hasGenAI) continue;
275
+ const inputTokens = toNumber(attrs["gen_ai.usage.input_tokens"]);
276
+ const outputTokens = toNumber(attrs["gen_ai.usage.output_tokens"]);
277
+ const genAISpan = {
278
+ id: toHex(span.spanId),
279
+ traceId: toHex(span.traceId),
280
+ name: span.name || "",
281
+ startTime: nanoToMs(span.startTimeUnixNano),
282
+ endTime: nanoToMs(span.endTimeUnixNano),
283
+ duration: nanoToMs(span.endTimeUnixNano) - nanoToMs(span.startTimeUnixNano),
284
+ model: String(
285
+ attrs["gen_ai.response.model"] || attrs["gen_ai.request.model"] || "unknown"
286
+ ),
287
+ requestModel: attrs["gen_ai.request.model"] != null ? String(attrs["gen_ai.request.model"]) : void 0,
288
+ responseModel: attrs["gen_ai.response.model"] != null ? String(attrs["gen_ai.response.model"]) : void 0,
289
+ inputTokens,
290
+ outputTokens,
291
+ totalTokens: attrs["gen_ai.usage.total_tokens"] != null ? toNumber(attrs["gen_ai.usage.total_tokens"]) : inputTokens + outputTokens,
292
+ cost: toFloat(attrs["gen_ai.usage.cost"]),
293
+ operationName: String(
294
+ attrs["gen_ai.operation.name"] || span.name || ""
295
+ ),
296
+ attributes: attrs
297
+ };
298
+ store.add(genAISpan);
299
+ spans.push(genAISpan);
300
+ }
301
+ }
302
+ }
303
+ return spans;
304
+ }
305
+ function extractAttributes(attributes) {
306
+ const result = {};
307
+ for (const attr of attributes) {
308
+ const key = attr.key;
309
+ const value = attr.value;
310
+ if (!value) continue;
311
+ if (value.stringValue != null) result[key] = value.stringValue;
312
+ else if (value.intValue != null) result[key] = Number(value.intValue);
313
+ else if (value.doubleValue != null) result[key] = value.doubleValue;
314
+ else if (value.boolValue != null) result[key] = value.boolValue;
315
+ }
316
+ return result;
317
+ }
318
+ function toHex(value) {
319
+ if (typeof value === "string") {
320
+ if (/^[0-9a-f]+$/i.test(value)) return value.toLowerCase();
321
+ return Buffer.from(value, "base64").toString("hex");
322
+ }
323
+ if (Buffer.isBuffer(value) || value instanceof Uint8Array) {
324
+ return Buffer.from(value).toString("hex");
325
+ }
326
+ return String(value);
327
+ }
328
+ function nanoToMs(nano) {
329
+ if (typeof nano === "string") {
330
+ return Number(BigInt(nano) / BigInt(1e6));
331
+ }
332
+ if (typeof nano === "number") return nano / 1e6;
333
+ return 0;
334
+ }
335
+ function toNumber(value) {
336
+ if (value == null) return 0;
337
+ const n = Number(value);
338
+ return isNaN(n) ? 0 : n;
339
+ }
340
+ function toFloat(value) {
341
+ if (value == null) return 0;
342
+ const n = parseFloat(String(value));
343
+ return isNaN(n) ? 0 : n;
344
+ }
345
+
346
+ // src/server/index.ts
347
+ var __filename = fileURLToPath(import.meta.url);
348
+ var __dirname = dirname(__filename);
349
+ var { values } = parseArgs({
350
+ options: {
351
+ port: { type: "string", default: "4318" },
352
+ "no-open": { type: "boolean", default: false }
353
+ },
354
+ strict: false
355
+ });
356
+ var port = parseInt(values.port || "4318", 10);
357
+ var app = express();
358
+ var server = createServer(app);
359
+ var wss = new WebSocketServer({ server, path: "/ws" });
360
+ app.use("/v1", express.raw({ type: "*/*", limit: "10mb" }));
361
+ app.post("/v1/traces", (req, res) => {
362
+ try {
363
+ const contentType = req.headers["content-type"] || "";
364
+ const body = contentType.includes("application/json") ? JSON.parse(req.body.toString()) : req.body;
365
+ const spans = handleTraces(body, contentType);
366
+ if (spans.length > 0) {
367
+ broadcast({ type: "spans", data: spans });
368
+ }
369
+ } catch (err) {
370
+ console.error("Error processing traces:", err);
371
+ }
372
+ res.status(200).json({});
373
+ });
374
+ app.post("/v1/metrics", (_req, res) => {
375
+ res.status(200).json({});
376
+ });
377
+ var clientDir = join(__dirname, "..", "client");
378
+ if (existsSync(join(clientDir, "assets"))) {
379
+ app.use(express.static(clientDir));
380
+ app.get("*", (_req, res) => {
381
+ res.sendFile(join(clientDir, "index.html"));
382
+ });
383
+ }
384
+ wss.on("connection", (ws) => {
385
+ ws.send(JSON.stringify({ type: "init", data: store.getAll() }));
386
+ });
387
+ function broadcast(data) {
388
+ const message = JSON.stringify(data);
389
+ wss.clients.forEach((client) => {
390
+ if (client.readyState === WebSocket.OPEN) {
391
+ client.send(message);
392
+ }
393
+ });
394
+ }
395
+ server.on("error", (err) => {
396
+ if (err.code === "EADDRINUSE") {
397
+ console.error(
398
+ `
399
+ Port ${port} is already in use. Try: npx tokviz --port <other-port>
400
+ `
401
+ );
402
+ process.exit(1);
403
+ }
404
+ throw err;
405
+ });
406
+ server.listen(port, () => {
407
+ console.log(`
408
+ tokviz running at http://localhost:${port}
409
+ `);
410
+ console.log(` OTLP endpoint: http://localhost:${port}/v1/traces`);
411
+ console.log(` Set OTEL_EXPORTER_OTLP_ENDPOINT=http://localhost:${port}
412
+ `);
413
+ if (!values["no-open"]) {
414
+ open(`http://localhost:${port}`);
415
+ }
416
+ });
package/package.json ADDED
@@ -0,0 +1,62 @@
1
+ {
2
+ "name": "tokviz",
3
+ "version": "0.1.0",
4
+ "description": "Real-time, local-only web dashboard that visualizes LLM token usage and costs from standard OpenTelemetry data",
5
+ "type": "module",
6
+ "bin": {
7
+ "tokviz": "dist/server/index.js"
8
+ },
9
+ "files": [
10
+ "dist"
11
+ ],
12
+ "scripts": {
13
+ "dev": "concurrently -n server,client \"tsx watch src/server/index.ts --no-open\" \"vite\"",
14
+ "dev:server": "tsx watch src/server/index.ts --no-open",
15
+ "dev:client": "vite",
16
+ "build": "npm run build:client && npm run build:server",
17
+ "build:client": "vite build",
18
+ "build:server": "tsup",
19
+ "start": "node dist/server/index.js",
20
+ "prepublishOnly": "npm run build"
21
+ },
22
+ "keywords": [
23
+ "opentelemetry",
24
+ "otlp",
25
+ "llm",
26
+ "tokens",
27
+ "cost",
28
+ "dashboard",
29
+ "gen-ai",
30
+ "observability"
31
+ ],
32
+ "author": "Waldek Mastykarz",
33
+ "license": "MIT",
34
+ "repository": {
35
+ "type": "git",
36
+ "url": "https://github.com/waldekmastykarz/tokviz.git"
37
+ },
38
+ "engines": {
39
+ "node": ">=18"
40
+ },
41
+ "dependencies": {
42
+ "express": "^4.21.2",
43
+ "open": "^10.1.0",
44
+ "protobufjs": "^7.4.0",
45
+ "ws": "^8.18.0"
46
+ },
47
+ "devDependencies": {
48
+ "@types/express": "^5.0.0",
49
+ "@types/react": "^19.0.0",
50
+ "@types/react-dom": "^19.0.0",
51
+ "@types/ws": "^8.5.13",
52
+ "@vitejs/plugin-react": "^4.3.4",
53
+ "concurrently": "^9.1.0",
54
+ "react": "^19.0.0",
55
+ "react-dom": "^19.0.0",
56
+ "recharts": "^2.15.0",
57
+ "tsup": "^8.4.0",
58
+ "tsx": "^4.19.0",
59
+ "typescript": "^5.7.0",
60
+ "vite": "^6.0.0"
61
+ }
62
+ }