nanobridge 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.
- package/README.md +291 -0
- package/bin/nanobridge.js +5 -0
- package/package.json +31 -0
- package/src/api/openai.js +115 -0
- package/src/benchmark/runner.js +48 -0
- package/src/benchmark/stats.js +33 -0
- package/src/chrome/bridge.js +446 -0
- package/src/chrome/detect.js +199 -0
- package/src/chrome/launch.js +214 -0
- package/src/cli.js +196 -0
- package/src/commands/ask.js +179 -0
- package/src/commands/bench.js +79 -0
- package/src/commands/chat.js +194 -0
- package/src/commands/daemon.js +61 -0
- package/src/commands/download.js +71 -0
- package/src/commands/serve.js +56 -0
- package/src/commands/status.js +78 -0
- package/src/daemon/client.js +186 -0
- package/src/daemon/server.js +494 -0
- package/src/daemon/state.js +49 -0
- package/src/utils/errors.js +26 -0
- package/src/utils/files.js +77 -0
- package/src/utils/output.js +59 -0
- package/test/cli.test.js +43 -0
- package/test/daemon.test.js +31 -0
- package/test/detect.test.js +24 -0
- package/test/files.test.js +36 -0
- package/test/openai.test.js +63 -0
- package/test/stats.test.js +29 -0
package/README.md
ADDED
|
@@ -0,0 +1,291 @@
|
|
|
1
|
+
# NanoBridge
|
|
2
|
+
|
|
3
|
+
Use Chrome's built-in on-device AI from your terminal and OpenAI-compatible tools.
|
|
4
|
+
|
|
5
|
+
NanoBridge is a lightweight Node.js CLI & server that bridges Chrome's Built-in AI / on-device language models (`LanguageModel` / Gemini Nano) to your terminal and local developer tools via the Chrome DevTools Protocol (CDP).
|
|
6
|
+
|
|
7
|
+
---
|
|
8
|
+
|
|
9
|
+
## Features
|
|
10
|
+
|
|
11
|
+
- **On-Device Inference**: Runs entirely on your local machine using Chrome's built-in Gemini Nano model.
|
|
12
|
+
- **Zero External AI Services**: No API keys, no third-party model runtimes (no Ollama, no LM Studio), no cloud fallbacks.
|
|
13
|
+
- **Sub-Second Warm Daemon**: Keeps Chrome and model weights warm in RAM for instantaneous response times.
|
|
14
|
+
- **Interactive Chat REPL**: Interactive multi-turn conversation with memory and `/clear`, `/system`, `/history`, `/help` commands.
|
|
15
|
+
- **File Reading & @file Mentions**: Attach local files via `-f / --file` or inline `@filepath` mentions.
|
|
16
|
+
- **OpenAI-Compatible API**: Mounts `/v1/chat/completions` and `/v1/models` for plug-and-play use in **Cursor, Continue, LangChain, OpenAI SDK, Open WebUI, LiteLLM**, and **curl**.
|
|
17
|
+
- **Full Unix Pipe & Stream Support**: First-class streaming output and standard input (`stdin`) piping.
|
|
18
|
+
- **Hardware Acceleration**: Automatic macOS Metal and GPU rasterization flags for maximum inference throughput.
|
|
19
|
+
- **Microsecond Benchmarking**: Measures Chrome startup, session initialization, Time To First Token (TTFT), and generation rate.
|
|
20
|
+
- **Isolated & Safe**: Uses isolated temporary profiles for each execution without interfering with your personal Chrome sessions.
|
|
21
|
+
|
|
22
|
+
---
|
|
23
|
+
|
|
24
|
+
## Installation
|
|
25
|
+
|
|
26
|
+
```bash
|
|
27
|
+
npm install -g nanobridge
|
|
28
|
+
```
|
|
29
|
+
|
|
30
|
+
Or run directly with `npx`:
|
|
31
|
+
|
|
32
|
+
```bash
|
|
33
|
+
npx nanobridge status
|
|
34
|
+
```
|
|
35
|
+
|
|
36
|
+
---
|
|
37
|
+
|
|
38
|
+
## Quick Start
|
|
39
|
+
|
|
40
|
+
### 1. Check AI & Model Status
|
|
41
|
+
|
|
42
|
+
Detect your Chrome version, Built-in AI availability, model readiness, and daemon state:
|
|
43
|
+
|
|
44
|
+
```bash
|
|
45
|
+
nanobridge status
|
|
46
|
+
```
|
|
47
|
+
|
|
48
|
+
Example output:
|
|
49
|
+
|
|
50
|
+
```text
|
|
51
|
+
NanoBridge
|
|
52
|
+
|
|
53
|
+
Chrome 151.0.7922.174
|
|
54
|
+
Platform macOS arm64
|
|
55
|
+
Built-in AI available
|
|
56
|
+
LanguageModel available
|
|
57
|
+
Model ready
|
|
58
|
+
Execution on-device
|
|
59
|
+
Daemon running (PID: 14947, port: 56340)
|
|
60
|
+
```
|
|
61
|
+
|
|
62
|
+
Output as structured JSON:
|
|
63
|
+
|
|
64
|
+
```bash
|
|
65
|
+
nanobridge status --json
|
|
66
|
+
```
|
|
67
|
+
|
|
68
|
+
---
|
|
69
|
+
|
|
70
|
+
### 2. Download Model Components
|
|
71
|
+
|
|
72
|
+
If the model is in a `downloadable` state, trigger the official Chrome model preparation and monitor download progress:
|
|
73
|
+
|
|
74
|
+
```bash
|
|
75
|
+
nanobridge download
|
|
76
|
+
```
|
|
77
|
+
|
|
78
|
+
---
|
|
79
|
+
|
|
80
|
+
### 3. Interactive Chat Mode
|
|
81
|
+
|
|
82
|
+
Start an interactive multi-turn conversation with memory:
|
|
83
|
+
|
|
84
|
+
```bash
|
|
85
|
+
nanobridge chat
|
|
86
|
+
```
|
|
87
|
+
|
|
88
|
+
Inside the interactive chat:
|
|
89
|
+
* `> What dependencies does @package.json have?` — Automatically reads & attaches files mentioned with `@`
|
|
90
|
+
* `/read <filepath>` — Load a file into the conversation context
|
|
91
|
+
* `/clear` — Reset conversation context history & clear screen
|
|
92
|
+
* `/system <prompt>` — Set custom system instructions
|
|
93
|
+
* `/history` — View active conversation turns
|
|
94
|
+
* `/help` — List interactive shortcuts
|
|
95
|
+
* `/exit` or `Ctrl+C` — Exit chat session
|
|
96
|
+
|
|
97
|
+
---
|
|
98
|
+
|
|
99
|
+
### 4. Ask Questions & Prompt the Model
|
|
100
|
+
|
|
101
|
+
#### Quick Prompts & Unix Pipes
|
|
102
|
+
Ask questions directly from your terminal or pipe content:
|
|
103
|
+
|
|
104
|
+
```bash
|
|
105
|
+
# Simple question
|
|
106
|
+
nanobridge ask "Explain Web Workers in one sentence"
|
|
107
|
+
|
|
108
|
+
# Pipe text from any Unix command
|
|
109
|
+
cat README.md | nanobridge ask "Summarize this document in 3 bullet points"
|
|
110
|
+
git diff | nanobridge ask "Generate a conventional commit message for these changes"
|
|
111
|
+
tail -n 50 /var/log/system.log | nanobridge ask "Find any errors or warnings in this log"
|
|
112
|
+
```
|
|
113
|
+
|
|
114
|
+
#### File Reading & Code Context
|
|
115
|
+
Attach local files to your prompts easily:
|
|
116
|
+
|
|
117
|
+
```bash
|
|
118
|
+
# Attach file using -f / --file flag
|
|
119
|
+
nanobridge ask -f package.json "What dependencies are used?"
|
|
120
|
+
|
|
121
|
+
# Attach multiple files
|
|
122
|
+
nanobridge ask -f src/cli.js -f package.json "How is the CLI structured?"
|
|
123
|
+
|
|
124
|
+
# Use inline @file mentions
|
|
125
|
+
nanobridge ask "Review and find bugs in @src/chrome/launch.js"
|
|
126
|
+
```
|
|
127
|
+
|
|
128
|
+
> **Tip**: `nanobridge ask` automatically starts the background daemon on your first query so subsequent questions respond in < 1 second.
|
|
129
|
+
|
|
130
|
+
---
|
|
131
|
+
|
|
132
|
+
### 5. OpenAI-Compatible API Server
|
|
133
|
+
|
|
134
|
+
Start a dedicated OpenAI-compatible local server:
|
|
135
|
+
|
|
136
|
+
```bash
|
|
137
|
+
nanobridge serve --port 8000
|
|
138
|
+
```
|
|
139
|
+
|
|
140
|
+
#### Endpoints Provided
|
|
141
|
+
* `GET /v1/models` — Lists available local models (`gemini-nano`, `chrome`, `gpt-4o-mini` alias)
|
|
142
|
+
* `POST /v1/chat/completions` — Standard chat completions (Supports both **JSON** and **Streaming SSE**)
|
|
143
|
+
* `POST /v1/completions` — Text completions endpoint
|
|
144
|
+
|
|
145
|
+
#### Example: Streaming with `curl`
|
|
146
|
+
```bash
|
|
147
|
+
curl -N http://localhost:8000/v1/chat/completions \
|
|
148
|
+
-H "Content-Type: application/json" \
|
|
149
|
+
-d '{
|
|
150
|
+
"model": "gemini-nano",
|
|
151
|
+
"messages": [
|
|
152
|
+
{"role": "system", "content": "You are a concise assistant."},
|
|
153
|
+
{"role": "user", "content": "What is WebAssembly?"}
|
|
154
|
+
],
|
|
155
|
+
"stream": true
|
|
156
|
+
}'
|
|
157
|
+
```
|
|
158
|
+
|
|
159
|
+
#### Example: Python OpenAI SDK
|
|
160
|
+
```python
|
|
161
|
+
from openai import OpenAI
|
|
162
|
+
|
|
163
|
+
client = OpenAI(
|
|
164
|
+
base_url="http://localhost:8000/v1",
|
|
165
|
+
api_key="nanobridge" # Any string
|
|
166
|
+
)
|
|
167
|
+
|
|
168
|
+
response = client.chat.completions.create(
|
|
169
|
+
model="gemini-nano",
|
|
170
|
+
messages=[
|
|
171
|
+
{"role": "user", "content": "Explain async/await in Python"}
|
|
172
|
+
],
|
|
173
|
+
stream=True
|
|
174
|
+
)
|
|
175
|
+
|
|
176
|
+
for chunk in response:
|
|
177
|
+
content = chunk.choices[0].delta.content
|
|
178
|
+
if content:
|
|
179
|
+
print(content, end="", flush=True)
|
|
180
|
+
print()
|
|
181
|
+
```
|
|
182
|
+
|
|
183
|
+
#### Example: Node.js OpenAI SDK
|
|
184
|
+
```javascript
|
|
185
|
+
import OpenAI from 'openai';
|
|
186
|
+
|
|
187
|
+
const openai = new OpenAI({
|
|
188
|
+
baseURL: 'http://localhost:8000/v1',
|
|
189
|
+
apiKey: 'nanobridge',
|
|
190
|
+
});
|
|
191
|
+
|
|
192
|
+
const stream = await openai.chat.completions.create({
|
|
193
|
+
model: 'gemini-nano',
|
|
194
|
+
messages: [{ role: 'user', content: 'Explain Node.js event loop' }],
|
|
195
|
+
stream: true,
|
|
196
|
+
});
|
|
197
|
+
|
|
198
|
+
for await (const chunk of stream) {
|
|
199
|
+
process.stdout.write(chunk.choices[0]?.delta?.content || '');
|
|
200
|
+
}
|
|
201
|
+
```
|
|
202
|
+
|
|
203
|
+
---
|
|
204
|
+
|
|
205
|
+
### 6. Background Daemon Management
|
|
206
|
+
|
|
207
|
+
NanoBridge can run a warm Chrome background daemon to eliminate the ~2.5s cold-start penalty on every query:
|
|
208
|
+
|
|
209
|
+
```bash
|
|
210
|
+
# Start the background daemon
|
|
211
|
+
nanobridge daemon start
|
|
212
|
+
|
|
213
|
+
# Check daemon status (PID, Port, Uptime)
|
|
214
|
+
nanobridge daemon status
|
|
215
|
+
|
|
216
|
+
# Stop the running background daemon
|
|
217
|
+
nanobridge daemon stop
|
|
218
|
+
# or simply:
|
|
219
|
+
nanobridge stop
|
|
220
|
+
```
|
|
221
|
+
|
|
222
|
+
---
|
|
223
|
+
|
|
224
|
+
### 7. Benchmarking On-Device Performance
|
|
225
|
+
|
|
226
|
+
Measure the exact millisecond latencies of your machine's hardware and Chrome runtime:
|
|
227
|
+
|
|
228
|
+
```bash
|
|
229
|
+
# Single pass
|
|
230
|
+
nanobridge bench
|
|
231
|
+
|
|
232
|
+
# Multi-run statistical benchmark with percentiles (p50, p90, p99)
|
|
233
|
+
nanobridge bench --runs 5
|
|
234
|
+
```
|
|
235
|
+
|
|
236
|
+
Example output:
|
|
237
|
+
|
|
238
|
+
```text
|
|
239
|
+
NanoBridge Benchmark
|
|
240
|
+
|
|
241
|
+
Chrome startup 2412 ms
|
|
242
|
+
Session creation 18 ms
|
|
243
|
+
TTFT 184 ms
|
|
244
|
+
Generation 1205 ms
|
|
245
|
+
Total 3819 ms
|
|
246
|
+
|
|
247
|
+
Output chars 492
|
|
248
|
+
Generation rate 408 chars/s
|
|
249
|
+
```
|
|
250
|
+
|
|
251
|
+
---
|
|
252
|
+
|
|
253
|
+
## Architecture & How It Works
|
|
254
|
+
|
|
255
|
+
```
|
|
256
|
+
┌────────────────────────────────────────────────────────┐
|
|
257
|
+
│ Terminal / User │
|
|
258
|
+
│ nanobridge chat | nanobridge ask | curl │
|
|
259
|
+
└───────────────────────────┬────────────────────────────┘
|
|
260
|
+
│ (HTTP / NDJSON / SSE)
|
|
261
|
+
┌───────────────────────────▼────────────────────────────┐
|
|
262
|
+
│ NanoBridge Daemon (Node.js) │
|
|
263
|
+
│ • Mutex Queue • Self-Healing • OpenAI API Endpoint │
|
|
264
|
+
└───────────────────────────┬────────────────────────────┘
|
|
265
|
+
│ (CDP WebSocket)
|
|
266
|
+
┌───────────────────────────▼────────────────────────────┐
|
|
267
|
+
│ Headless Chromium (Apple Silicon Metal GPU) │
|
|
268
|
+
│ • OptimizationGuideOnDeviceModel (weights.bin) │
|
|
269
|
+
│ • window.LanguageModel API (Gemini Nano) │
|
|
270
|
+
└────────────────────────────────────────────────────────┘
|
|
271
|
+
```
|
|
272
|
+
|
|
273
|
+
1. **CDP Bridge**: Spawns an isolated headless Chrome instance with `--enable-features=PromptAPIForGeminiNano,OptimizationGuideOnDeviceModel` and connects via Chrome DevTools Protocol (CDP).
|
|
274
|
+
2. **Persistent On-Device Session**: Automatically resolves and symlinks the 4.2 GB Gemini Nano weights into the ephemeral profile.
|
|
275
|
+
3. **Low-Latency Streaming**: Listens to real-time token production via CDP events with delta computation and zero-delay TCP socket transport.
|
|
276
|
+
4. **Self-Healing**: Automatically handles macOS sleep/wake cycles, GPU context resets, and request aborts (`Ctrl+C`) without leaking resources.
|
|
277
|
+
|
|
278
|
+
---
|
|
279
|
+
|
|
280
|
+
## Requirements
|
|
281
|
+
|
|
282
|
+
* **macOS, Linux, or Windows**
|
|
283
|
+
* **Google Chrome 128+** (or Chrome Canary / Dev / Beta / Chromium)
|
|
284
|
+
* **Node.js 20.0.0+**
|
|
285
|
+
* On-device Gemini Nano model enabled in Chrome
|
|
286
|
+
|
|
287
|
+
---
|
|
288
|
+
|
|
289
|
+
## License
|
|
290
|
+
|
|
291
|
+
MIT © Ahmet
|
package/package.json
ADDED
|
@@ -0,0 +1,31 @@
|
|
|
1
|
+
{
|
|
2
|
+
"name": "nanobridge",
|
|
3
|
+
"version": "0.1.0",
|
|
4
|
+
"description": "Chrome Built-in AI CLI bridge to on-device language models via CDP",
|
|
5
|
+
"type": "module",
|
|
6
|
+
"bin": {
|
|
7
|
+
"nanobridge": "./bin/nanobridge.js"
|
|
8
|
+
},
|
|
9
|
+
"scripts": {
|
|
10
|
+
"start": "node ./bin/nanobridge.js",
|
|
11
|
+
"test": "node --test test/**/*.test.js"
|
|
12
|
+
},
|
|
13
|
+
"keywords": [
|
|
14
|
+
"chrome",
|
|
15
|
+
"built-in-ai",
|
|
16
|
+
"prompt-api",
|
|
17
|
+
"gemini-nano",
|
|
18
|
+
"cli",
|
|
19
|
+
"cdp",
|
|
20
|
+
"on-device-ai",
|
|
21
|
+
"local-ai"
|
|
22
|
+
],
|
|
23
|
+
"author": "",
|
|
24
|
+
"license": "MIT",
|
|
25
|
+
"engines": {
|
|
26
|
+
"node": ">=20.0.0"
|
|
27
|
+
},
|
|
28
|
+
"dependencies": {
|
|
29
|
+
"ws": "^8.21.3"
|
|
30
|
+
}
|
|
31
|
+
}
|
|
@@ -0,0 +1,115 @@
|
|
|
1
|
+
import crypto from 'node:crypto';
|
|
2
|
+
|
|
3
|
+
export function parseChatMessages(messages = []) {
|
|
4
|
+
let systemPrompt = '';
|
|
5
|
+
const conversationLines = [];
|
|
6
|
+
|
|
7
|
+
for (const msg of messages) {
|
|
8
|
+
const role = (msg.role || 'user').toLowerCase();
|
|
9
|
+
const content = typeof msg.content === 'string' ? msg.content : JSON.stringify(msg.content);
|
|
10
|
+
|
|
11
|
+
if (role === 'system') {
|
|
12
|
+
systemPrompt += (systemPrompt ? '\n\n' : '') + content;
|
|
13
|
+
} else if (role === 'user') {
|
|
14
|
+
conversationLines.push(`User: ${content}`);
|
|
15
|
+
} else if (role === 'assistant') {
|
|
16
|
+
conversationLines.push(`Assistant: ${content}`);
|
|
17
|
+
} else {
|
|
18
|
+
conversationLines.push(`${role}: ${content}`);
|
|
19
|
+
}
|
|
20
|
+
}
|
|
21
|
+
|
|
22
|
+
// If there's only 1 user message and no previous history, pass content directly
|
|
23
|
+
let promptText = '';
|
|
24
|
+
if (conversationLines.length === 1 && conversationLines[0].startsWith('User: ')) {
|
|
25
|
+
promptText = conversationLines[0].slice(6);
|
|
26
|
+
} else {
|
|
27
|
+
promptText = conversationLines.join('\n\n');
|
|
28
|
+
}
|
|
29
|
+
|
|
30
|
+
return {
|
|
31
|
+
systemPrompt: systemPrompt || undefined,
|
|
32
|
+
promptText
|
|
33
|
+
};
|
|
34
|
+
}
|
|
35
|
+
|
|
36
|
+
export function formatModelsList() {
|
|
37
|
+
return {
|
|
38
|
+
object: 'list',
|
|
39
|
+
data: [
|
|
40
|
+
{
|
|
41
|
+
id: 'gemini-nano',
|
|
42
|
+
object: 'model',
|
|
43
|
+
created: 1700000000,
|
|
44
|
+
owned_by: 'chrome-builtin-ai',
|
|
45
|
+
permission: [],
|
|
46
|
+
root: 'gemini-nano',
|
|
47
|
+
parent: null
|
|
48
|
+
},
|
|
49
|
+
{
|
|
50
|
+
id: 'chrome-builtin-ai',
|
|
51
|
+
object: 'model',
|
|
52
|
+
created: 1700000000,
|
|
53
|
+
owned_by: 'chrome-builtin-ai',
|
|
54
|
+
permission: [],
|
|
55
|
+
root: 'chrome-builtin-ai',
|
|
56
|
+
parent: null
|
|
57
|
+
}
|
|
58
|
+
]
|
|
59
|
+
};
|
|
60
|
+
}
|
|
61
|
+
|
|
62
|
+
export function formatChatCompletion({ id, model = 'gemini-nano', content, promptTokens = 0, completionTokens = 0 }) {
|
|
63
|
+
const completionId = id || `chatcmpl-${crypto.randomBytes(8).toString('hex')}`;
|
|
64
|
+
return {
|
|
65
|
+
id: completionId,
|
|
66
|
+
object: 'chat.completion',
|
|
67
|
+
created: Math.floor(Date.now() / 1000),
|
|
68
|
+
model,
|
|
69
|
+
system_fingerprint: 'fp_chrome_builtin_ai',
|
|
70
|
+
choices: [
|
|
71
|
+
{
|
|
72
|
+
index: 0,
|
|
73
|
+
message: {
|
|
74
|
+
role: 'assistant',
|
|
75
|
+
content
|
|
76
|
+
},
|
|
77
|
+
logprobs: null,
|
|
78
|
+
finish_reason: 'stop'
|
|
79
|
+
}
|
|
80
|
+
],
|
|
81
|
+
usage: {
|
|
82
|
+
prompt_tokens: promptTokens || Math.max(1, Math.round(content.length / 4)),
|
|
83
|
+
completion_tokens: completionTokens || Math.max(1, Math.round(content.length / 4)),
|
|
84
|
+
total_tokens: (promptTokens + completionTokens) || Math.max(2, Math.round(content.length / 2))
|
|
85
|
+
}
|
|
86
|
+
};
|
|
87
|
+
}
|
|
88
|
+
|
|
89
|
+
export function formatChatCompletionChunk({ id, model = 'gemini-nano', delta = '', isFirst = false, isLast = false }) {
|
|
90
|
+
const completionId = id || `chatcmpl-${crypto.randomBytes(8).toString('hex')}`;
|
|
91
|
+
|
|
92
|
+
const deltaObj = {};
|
|
93
|
+
if (isFirst) {
|
|
94
|
+
deltaObj.role = 'assistant';
|
|
95
|
+
}
|
|
96
|
+
if (delta) {
|
|
97
|
+
deltaObj.content = delta;
|
|
98
|
+
}
|
|
99
|
+
|
|
100
|
+
return {
|
|
101
|
+
id: completionId,
|
|
102
|
+
object: 'chat.completion.chunk',
|
|
103
|
+
created: Math.floor(Date.now() / 1000),
|
|
104
|
+
model,
|
|
105
|
+
system_fingerprint: 'fp_chrome_builtin_ai',
|
|
106
|
+
choices: [
|
|
107
|
+
{
|
|
108
|
+
index: 0,
|
|
109
|
+
delta: deltaObj,
|
|
110
|
+
logprobs: null,
|
|
111
|
+
finish_reason: isLast ? 'stop' : null
|
|
112
|
+
}
|
|
113
|
+
]
|
|
114
|
+
};
|
|
115
|
+
}
|
|
@@ -0,0 +1,48 @@
|
|
|
1
|
+
import { computeMetricStats } from './stats.js';
|
|
2
|
+
import { debug } from '../utils/output.js';
|
|
3
|
+
|
|
4
|
+
export async function runBenchmark(bridge, options = {}) {
|
|
5
|
+
const runsCount = Math.max(1, options.runs || 1);
|
|
6
|
+
const promptText = options.prompt || 'Explain how the event loop works in JavaScript in two concise paragraphs.';
|
|
7
|
+
debug('bench', `Starting benchmark with ${runsCount} run(s)...`);
|
|
8
|
+
|
|
9
|
+
const results = [];
|
|
10
|
+
|
|
11
|
+
for (let i = 0; i < runsCount; i++) {
|
|
12
|
+
const isWarm = i > 0;
|
|
13
|
+
debug('bench', `Executing benchmark run ${i + 1}/${runsCount} (warm: ${isWarm})...`);
|
|
14
|
+
const runResult = await bridge.benchmarkRun({ promptText, isWarm });
|
|
15
|
+
results.push({
|
|
16
|
+
run: i + 1,
|
|
17
|
+
isWarm,
|
|
18
|
+
...runResult
|
|
19
|
+
});
|
|
20
|
+
}
|
|
21
|
+
|
|
22
|
+
// Aggregate statistics
|
|
23
|
+
const sessionCreateStats = computeMetricStats(results.map((r) => r.sessionCreateMs));
|
|
24
|
+
const ttftStats = computeMetricStats(results.map((r) => r.ttftMs));
|
|
25
|
+
const generationStats = computeMetricStats(results.map((r) => r.generationMs));
|
|
26
|
+
const totalStats = computeMetricStats(results.map((r) => r.totalInferenceMs));
|
|
27
|
+
const charRateStats = computeMetricStats(results.map((r) => r.generationRate));
|
|
28
|
+
const outputCharsStats = computeMetricStats(results.map((r) => r.outputChars));
|
|
29
|
+
|
|
30
|
+
const coldRun = results[0];
|
|
31
|
+
const warmRuns = results.slice(1);
|
|
32
|
+
|
|
33
|
+
return {
|
|
34
|
+
runsCount,
|
|
35
|
+
prompt: promptText,
|
|
36
|
+
runs: results,
|
|
37
|
+
coldRun,
|
|
38
|
+
warmRuns,
|
|
39
|
+
stats: {
|
|
40
|
+
sessionCreateMs: sessionCreateStats,
|
|
41
|
+
ttftMs: ttftStats,
|
|
42
|
+
generationMs: generationStats,
|
|
43
|
+
totalInferenceMs: totalStats,
|
|
44
|
+
generationRateCharsPerSec: charRateStats,
|
|
45
|
+
outputChars: outputCharsStats
|
|
46
|
+
}
|
|
47
|
+
};
|
|
48
|
+
}
|
|
@@ -0,0 +1,33 @@
|
|
|
1
|
+
export function calculatePercentile(values, p) {
|
|
2
|
+
if (!values || values.length === 0) return 0;
|
|
3
|
+
const sorted = [...values].sort((a, b) => a - b);
|
|
4
|
+
if (sorted.length === 1) return sorted[0];
|
|
5
|
+
const index = (p / 100) * (sorted.length - 1);
|
|
6
|
+
const lower = Math.floor(index);
|
|
7
|
+
const upper = Math.ceil(index);
|
|
8
|
+
const weight = index - lower;
|
|
9
|
+
return sorted[lower] * (1 - weight) + sorted[upper] * weight;
|
|
10
|
+
}
|
|
11
|
+
|
|
12
|
+
export function computeMetricStats(values) {
|
|
13
|
+
const valid = (values || []).filter((v) => typeof v === 'number' && !isNaN(v));
|
|
14
|
+
if (valid.length === 0) {
|
|
15
|
+
return { min: 0, max: 0, avg: 0, p50: 0, p95: 0, count: 0 };
|
|
16
|
+
}
|
|
17
|
+
|
|
18
|
+
const sum = valid.reduce((acc, v) => acc + v, 0);
|
|
19
|
+
const avg = sum / valid.length;
|
|
20
|
+
const min = Math.min(...valid);
|
|
21
|
+
const max = Math.max(...valid);
|
|
22
|
+
const p50 = calculatePercentile(valid, 50);
|
|
23
|
+
const p95 = calculatePercentile(valid, 95);
|
|
24
|
+
|
|
25
|
+
return {
|
|
26
|
+
min: Number(min.toFixed(1)),
|
|
27
|
+
max: Number(max.toFixed(1)),
|
|
28
|
+
avg: Number(avg.toFixed(1)),
|
|
29
|
+
p50: Number(p50.toFixed(1)),
|
|
30
|
+
p95: Number(p95.toFixed(1)),
|
|
31
|
+
count: valid.length
|
|
32
|
+
};
|
|
33
|
+
}
|