@drakonkat/ai-helper 1.1.1 → 1.2.3
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/ARCHITECTURE.md +14 -3
- package/CHANGELOG.md +9 -0
- package/README.md +483 -26
- package/docs/benchmark.md +373 -0
- package/package.json +17 -5
- package/scripts/bench-proxy.js +111 -0
- package/scripts/build.js +16 -0
- package/src/benchmark/fixtures.js +162 -0
- package/src/benchmark/live.js +207 -0
- package/src/benchmark/measurement.js +180 -0
- package/src/benchmark/quality-fixtures.js +95 -0
- package/src/benchmark/quality.js +206 -0
- package/src/benchmark/report.js +162 -0
- package/src/benchmark/runner.js +287 -0
- package/src/codex-config.js +247 -0
- package/src/codex-routing.js +132 -0
- package/src/config.js +19 -1
- package/src/index.js +158 -26
- package/src/manager.js +233 -15
- package/src/proxy-interceptor.example.mjs +33 -0
- package/src/proxy-presets.js +235 -0
- package/src/proxy-stats.js +64 -0
- package/src/proxy-worker.js +17 -0
- package/src/proxy.js +313 -0
- package/src/request-images.js +69 -0
- package/src/service-updates.js +68 -0
- package/src/tui.js +370 -162
- package/src/update.js +41 -0
- package/src/utils/metrics.js +39 -12
- package/src/utils/process.js +92 -146
- package/src/utils/versions.js +165 -0
|
@@ -0,0 +1,373 @@
|
|
|
1
|
+
# Benchmark dei flow del proxy
|
|
2
|
+
|
|
3
|
+
Il benchmark confronta **gli stessi input** attraverso i preset reali `none`,
|
|
4
|
+
`headroom`, `rtk`, `pxpipe`, `headroom-pxpipe`, `rtk-pxpipe`,
|
|
5
|
+
`rtk-headroom-pxpipe`. Non legge né azzera
|
|
6
|
+
le statistiche del proxy quotidiano e non cambia client, configurazioni o servizi.
|
|
7
|
+
`none` viene sempre aggiunto come baseline. Il preset `rtk-headroom-pxpipe`
|
|
8
|
+
esegue **RTK → Headroom → pxpipe** sul risultato dello stadio precedente; i tre
|
|
9
|
+
stadi sono riportati separatamente. La doppia compressione può perdere fatti:
|
|
10
|
+
Headroom non può recuperare informazioni già eliminate da RTK. Il nuovo preset
|
|
11
|
+
non viene selezionato automaticamente nel proxy quotidiano.
|
|
12
|
+
|
|
13
|
+
## Avvio rapido
|
|
14
|
+
|
|
15
|
+
Richiede Node.js compatibile con il progetto e dipendenze installate. Il runner
|
|
16
|
+
si esegue dal checkout con Node, non nel binario Bun compilato.
|
|
17
|
+
|
|
18
|
+
```powershell
|
|
19
|
+
# Smoke test senza Headroom, RTK o provider esterni
|
|
20
|
+
npm run bench:proxy -- --presets none,pxpipe --formats responses --warmup 0 --repetitions 1
|
|
21
|
+
|
|
22
|
+
# Tutti i sette flow; Headroom deve essere già disponibile a questo indirizzo
|
|
23
|
+
npm run bench:proxy -- --headroom-url http://127.0.0.1:8787 --repetitions 5 --warmup 1
|
|
24
|
+
|
|
25
|
+
# Stessi casi Responses attraverso HTTP e WebSocket
|
|
26
|
+
npm run bench:proxy -- --presets none,rtk,pxpipe,rtk-pxpipe --formats responses --transports http,ws
|
|
27
|
+
|
|
28
|
+
# Elenca oppure esporta il corpus per modificarlo
|
|
29
|
+
npm run bench:proxy -- --list
|
|
30
|
+
npm run bench:proxy -- --formats responses --export-fixtures my-fixtures.json
|
|
31
|
+
npm run bench:proxy -- --fixtures my-fixtures.json --out benchmark-results/my-experiment
|
|
32
|
+
|
|
33
|
+
# Test automatici del sistema (nessuna chiamata a provider reali)
|
|
34
|
+
npm run test:benchmark
|
|
35
|
+
```
|
|
36
|
+
|
|
37
|
+
RTK richiede un eseguibile con `rtk pipe` su PATH. Headroom usa esclusivamente
|
|
38
|
+
`POST /v1/compress`, in `lossy_inline`, con eventuale `HEADROOM_PROXY_TOKEN`.
|
|
39
|
+
Il runner non avvia/installa questi servizi: se mancano, registra **errori** per
|
|
40
|
+
i flow interessati, continua gli altri e termina con codice 2.
|
|
41
|
+
Le chiamate reali possono incrementare le metriche interne di Headroom/RTK e
|
|
42
|
+
scaldare le loro cache; restano invece isolate le statistiche del proxy aih gestito.
|
|
43
|
+
|
|
44
|
+
**Pxpipe nel benchmark è opt-in sui modelli del corpus**, anche se il gate di
|
|
45
|
+
default del proxy normale li escluderebbe. Questo serve a esercitare davvero i
|
|
46
|
+
flow con immagini: non è una garanzia di supporto o qualità del modello. Con
|
|
47
|
+
`--models` si può specificare l'allowlist esatta da testare; i `model_excluded`
|
|
48
|
+
rimangono visibili in `stageReasons`. Nessuna configurazione di produzione cambia.
|
|
49
|
+
|
|
50
|
+
`--rtk-filter` applica un filtro fisso a tutti i tool output: usarlo soltanto su
|
|
51
|
+
un corpus omogeneo compatibile. Senza flag viene usata l'autodetection.
|
|
52
|
+
|
|
53
|
+
## Cosa viene misurato
|
|
54
|
+
|
|
55
|
+
### Replay offline (default)
|
|
56
|
+
|
|
57
|
+
Ogni preset ha un proxy reale su una porta loopback effimera, con un collector
|
|
58
|
+
locale come upstream. Il collector osserva il payload effettivamente inoltrato.
|
|
59
|
+
Non vengono effettuate chiamate LLM. Headroom, se selezionato, riceve i testi da
|
|
60
|
+
comprimere: un `--headroom-url` remoto comporta l'invio a quel servizio.
|
|
61
|
+
|
|
62
|
+
Il corpus integrato contiene **30 fixture sintetiche**, 10 scenari per Responses,
|
|
63
|
+
Chat Completions e Anthropic Messages: build, test, stack trace, log, grep, git,
|
|
64
|
+
JSON, output breve e contesto statico denso. Non contiene dati di lavoro reali.
|
|
65
|
+
|
|
66
|
+
- Ordine di casi e flow randomizzato con seed riproducibile.
|
|
67
|
+
- Default: 1 round di warmup e 3 misurati per caso/flow/trasporto.
|
|
68
|
+
- Warmup conservati nei record ma esclusi dalle aggregazioni.
|
|
69
|
+
- HTTP misura il round-trip fino al collector, inclusa la trasformazione.
|
|
70
|
+
- WS usa una nuova connessione per campione Responses e misura separatamente
|
|
71
|
+
handshake (`connectionMs`) e round-trip del messaggio (`durationMs`).
|
|
72
|
+
- `firstRequest` identifica la prima richiesta al proxy del benchmark, **non**
|
|
73
|
+
un vero avvio a freddo di RTK, Headroom, librerie o cache del provider.
|
|
74
|
+
- `meta.startup` misura l'inizializzazione dei proxy. Non equivale al tempo di
|
|
75
|
+
avvio di processi esterni; per misurarlo serve una campagna separata controllata.
|
|
76
|
+
|
|
77
|
+
I risultati sono separati per **modello, protocollo e trasporto**, anche per
|
|
78
|
+
categoria nel JSON. Headroom riceve solo tool text per Responses, ma i messaggi
|
|
79
|
+
per Chat/Messages: non bisogna confrontare percentuali di scope diversi.
|
|
80
|
+
|
|
81
|
+
### Conteggio uniforme
|
|
82
|
+
|
|
83
|
+
I conteggi dichiarati da Headroom/RTK/pxpipe sono conservati in `stages` soltanto
|
|
84
|
+
come diagnostica. La metrica comune viene ricalcolata prima e dopo il proxy:
|
|
85
|
+
|
|
86
|
+
- testo e struttura JSON canonica: tokenizer `o200k_base` identico per ogni flow;
|
|
87
|
+
- tool text: conteggio separato dei soli risultati testuali;
|
|
88
|
+
- immagini PNG: dimensioni IHDR e profilo vision della versione pxpipe installata
|
|
89
|
+
per famiglie OpenAI riconosciute con detail esplicito `high`/`original`;
|
|
90
|
+
- base64, dati cifrati e media non vengono conteggiati come testo;
|
|
91
|
+
- modello/dettaglio/formato immagine non misurabile, media opachi o resize non
|
|
92
|
+
modellato ⇒ totale **null / sconosciuto**, mai zero. `knownTokens` è soltanto
|
|
93
|
+
il subtotale noto della stima locale, non una garanzia sul consumo del provider.
|
|
94
|
+
|
|
95
|
+
Questi sono **token stimati**, non l'esatta serializzazione del provider né una
|
|
96
|
+
fattura. Per le immagini Anthropic/Gemini non viene inventato un costo OpenAI.
|
|
97
|
+
Il trasferimento di testo in immagini non è considerato un risparmio totale del
|
|
98
|
+
100%: `toolText` resta diagnostico, mentre il totale include il costo vision o è
|
|
99
|
+
sconosciuto. `imageMeasurements` e `warnings` spiegano le approssimazioni.
|
|
100
|
+
|
|
101
|
+
La percentuale aggregata è ponderata:
|
|
102
|
+
|
|
103
|
+
```text
|
|
104
|
+
100 × (somma token prima − somma token dopo) / somma token prima
|
|
105
|
+
```
|
|
106
|
+
|
|
107
|
+
Non è la media delle percentuali. Errori, output invariati, risparmi negativi e
|
|
108
|
+
costi sconosciuti rimangono visibili. La copertura indica quante richieste hanno
|
|
109
|
+
un confronto completo; un totale parziale non può vincere la selezione automatica.
|
|
110
|
+
|
|
111
|
+
### Qualità offline
|
|
112
|
+
|
|
113
|
+
Ogni fixture dichiara fatti che devono sopravvivere: codice di errore, file/riga,
|
|
114
|
+
valori JSON, identificatore del test, ecc. Vengono controllati anche modello,
|
|
115
|
+
nomi dei tool e coppie call/result native presenti nell'originale.
|
|
116
|
+
|
|
117
|
+
Gli esiti sono `pass`, `fail`, `indeterminate`, `unscored`. Se un fatto non è più
|
|
118
|
+
testo ma potrebbero contenerlo le immagini, l'esito è `indeterminate`: nessun OCR
|
|
119
|
+
o modello ha verificato che sia leggibile. Il runner **non dichiara un vincitore
|
|
120
|
+
di qualità sulla base del solo replay offline**. La presenza delle stringhe è
|
|
121
|
+
un controllo di conservazione, non una prova di comprensione o correttezza.
|
|
122
|
+
|
|
123
|
+
## Valutazione live, esplicita e potenzialmente a pagamento
|
|
124
|
+
|
|
125
|
+
### Suite qualità e richieste con immagini native
|
|
126
|
+
|
|
127
|
+
`--suite core` resta il default storico: 30 fixture, 10 per protocollo.
|
|
128
|
+
`--suite quality` aggiunge un corpus **opt-in di 12 casi Responses**, destinato
|
|
129
|
+
anche al confronto Astra/Fable. `--suite all` unisce i due corpora (42 fixture
|
|
130
|
+
prima dei filtri/modelli). Il file passato con `--fixtures` è alternativo a
|
|
131
|
+
`--suite`: non viene mescolato implicitamente con casi integrati.
|
|
132
|
+
|
|
133
|
+
La suite qualità contiene:
|
|
134
|
+
|
|
135
|
+
- 2 casi con regole in istruzioni lunghe, non nel tool output: recupero di un
|
|
136
|
+
fatto e rispetto della priorità delle istruzioni rispetto a una nota del tool;
|
|
137
|
+
- 2 diagnostici di build, in fondo e in mezzo a output rumoroso, con risposta
|
|
138
|
+
JSON esatta comprendente errore, file, riga, colonna ed exit code;
|
|
139
|
+
- 1 campo assente per verificare l'astensione invece dell'invenzione di un valore;
|
|
140
|
+
- 7 casi con PNG nativi: singolo, multiplo/ordine, storico più allegato corrente,
|
|
141
|
+
risultato di tool, testo contraddittorio, detail low e controllo breve.
|
|
142
|
+
|
|
143
|
+
I PNG sono pixel deterministici di pannelli sintetici con codici leggibili,
|
|
144
|
+
senza metadati testuali o URL che contengano la soluzione. Sono **test di OCR e
|
|
145
|
+
associazione**, non una valutazione generale di foto, diagrammi o screenshot.
|
|
146
|
+
Le risposte attese e `evaluation.evidence` restano fuori da `body`, quindi non
|
|
147
|
+
vengono inviate ai modelli. Nessuna immagine remota viene scaricata dal benchmark.
|
|
148
|
+
|
|
149
|
+
```powershell
|
|
150
|
+
# Ispezionare/esportare i 12 input prima di usarli; nessuna chiamata LLM
|
|
151
|
+
node scripts/bench-proxy.js --suite quality --formats responses --list
|
|
152
|
+
node scripts/bench-proxy.js --suite quality --formats responses --export-fixtures quality-fixtures.json
|
|
153
|
+
|
|
154
|
+
# Replay offline: 12 casi × 2 modelli × 4 flow = 96 campioni
|
|
155
|
+
npm run bench:models -- --suite quality --presets none,headroom,headroom-pxpipe,headroom-pxpipe-native-bypass --repetitions 1 --warmup 0
|
|
156
|
+
```
|
|
157
|
+
|
|
158
|
+
Gli alias **solo benchmark** `pxpipe-native-bypass`,
|
|
159
|
+
`headroom-pxpipe-native-bypass`, `rtk-pxpipe-native-bypass` e
|
|
160
|
+
`rtk-headroom-pxpipe-native-bypass` usano la ricetta reale corrispondente, ma
|
|
161
|
+
saltano **solo pxpipe** quando la richiesta originale contiene immagini native.
|
|
162
|
+
Il rilevamento avviene prima di RTK/Headroom, comprende contenuti multimodali e
|
|
163
|
+
risultati di tool; ignora schemi, metadata e JSON citato come testo. Lo stadio
|
|
164
|
+
registra `native_images_present`, non un risparmio vision inventato.
|
|
165
|
+
|
|
166
|
+
Gli alias non sono inclusi nei 7 flow di default e non cambiano la configurazione
|
|
167
|
+
quotidiana. I flow senza suffisso mantengono il comportamento precedente.
|
|
168
|
+
Headroom/RTK restano attivi dove applicabili: il bypass di pxpipe **non è una
|
|
169
|
+
garanzia** che un altro stadio preservi l'allegato. Anche questo viene verificato.
|
|
170
|
+
Con tutti gli 11 flow e i 2 modelli, la suite qualità richiede **264 campioni per
|
|
171
|
+
round**; aggiungere `--live` li renderebbe altrettanti tentativi provider.
|
|
172
|
+
|
|
173
|
+
Nuovi controlli e campi del report:
|
|
174
|
+
|
|
175
|
+
- `answerChecks.exact`: uguaglianza case-sensitive, ignorando soltanto whitespace
|
|
176
|
+
iniziale/finale; niente spiegazioni aggiuntive;
|
|
177
|
+
- `answerChecks.jsonEquals`: JSON valido, nessun fence o prosa, stesso oggetto o
|
|
178
|
+
array atteso, stessi tipi/valori e nessuna chiave extra; ordine delle chiavi
|
|
179
|
+
irrilevante, chiavi duplicate rifiutate anche con escape Unicode;
|
|
180
|
+
- `answerChecks.maxChars`: tetto alla lunghezza, combinabile con gli altri check;
|
|
181
|
+
- `imageIntegrity`: hash del contenuto e di tutti gli attributi delle immagini
|
|
182
|
+
native, molteplicità, ordine relativo, raggruppamento e associazione a ruolo,
|
|
183
|
+
call ID e testo co-locato. Indici assoluti possono cambiare quando vengono
|
|
184
|
+
inseriti messaggi sintetici. Un cambio del testo co-locato viene segnalato in
|
|
185
|
+
modo conservativo, anche se una valutazione umana potrebbe ritenerlo innocuo;
|
|
186
|
+
- `addedOrChanged` conta immagini nuove **o native modificate**, non le presume
|
|
187
|
+
tutte correttamente generate. `nativeImagesRetained` non è un punteggio vision;
|
|
188
|
+
- `evidence` distingue risposte ancora disponibili nel testo da casi che
|
|
189
|
+
richiedono immagini native o renderizzate. Non è una validazione OCR.
|
|
190
|
+
|
|
191
|
+
Il selettore esclude un candidato con perdita/alterazione degli allegati anche
|
|
192
|
+
se la risposta supera i controlli. Nei casi dichiarati `rendered_context`, se
|
|
193
|
+
pxpipe si applica ma lascia la risposta nel testo (per esempio nella factsheet),
|
|
194
|
+
segnala `vision_evidence_not_discriminating`: quel pass non prova lettura delle
|
|
195
|
+
immagini. Una vera valutazione live rimane necessaria; il replay offline non
|
|
196
|
+
produce punteggi di comprensione visiva né sceglie un vincitore.
|
|
197
|
+
|
|
198
|
+
### GPT-6 Astra e Fable 5.1 sullo stesso corpus
|
|
199
|
+
|
|
200
|
+
Il comando dedicato seleziona gli ID del gateway `gpt-6-astra` e
|
|
201
|
+
`anthropic/claude-fable-5-1`, sul medesimo protocollo Responses:
|
|
202
|
+
|
|
203
|
+
```powershell
|
|
204
|
+
# Replay offline: 20 fixture × 7 flow = 140 campioni
|
|
205
|
+
npm run bench:models -- --repetitions 1 --warmup 0
|
|
206
|
+
|
|
207
|
+
# Smoke live: al massimo 140 chiamate complessive, senza retry del runner
|
|
208
|
+
npm run bench:models -- --live --responses-stream --upstream http://127.0.0.1:10100 --repetitions 1 --warmup 0 --max-live-calls 140 --stop-on-error
|
|
209
|
+
|
|
210
|
+
# Solo baseline e nuova combinazione: 10 casi × 2 flow × 2 modelli = 40 chiamate
|
|
211
|
+
npm run bench:models -- --presets none,rtk-headroom-pxpipe --live --responses-stream --upstream http://127.0.0.1:10100 --repetitions 1 --warmup 0 --max-live-calls 40
|
|
212
|
+
```
|
|
213
|
+
|
|
214
|
+
Richiede un gateway che supporti **entrambi i modelli via Responses**; un endpoint
|
|
215
|
+
Anthropic diretto non accetta questa combinazione. `--compare-models` permette
|
|
216
|
+
altre liste ed è distinto da `--models`, che controlla solo l'allowlist pxpipe.
|
|
217
|
+
I report mantengono baseline, latenza, qualità e usage **separati per modello**;
|
|
218
|
+
il limite chiamate si applica all'intera matrice, non a ciascun modello.
|
|
219
|
+
|
|
220
|
+
I costi vision locali per questi modelli non vengono ricavati arbitrariamente
|
|
221
|
+
da profili più vecchi: dove non supportati restano sconosciuti. La misura di
|
|
222
|
+
riferimento nel test live è l'usage restituito dal gateway/provider.
|
|
223
|
+
|
|
224
|
+
Gli upstream ChatGPT/Codex possono richiedere `stream: true` anche quando OCX
|
|
225
|
+
accetta sintatticamente il non-stream. Usare `--responses-stream`: il runner
|
|
226
|
+
consuma SSE fino all'evento terminale. Se il terminale omette l'output (come può
|
|
227
|
+
accadere con Astra), ricostruisce il testo dagli item finalizzati
|
|
228
|
+
`response.output_item.done`; l'usage proviene sempre dal terminale. I soli delta
|
|
229
|
+
non bastano a dichiarare una risposta completa. Stream
|
|
230
|
+
troncati o senza evento terminale restano errori, non risposte completate.
|
|
231
|
+
|
|
232
|
+
### Endpoint e credenziali
|
|
233
|
+
|
|
234
|
+
```powershell
|
|
235
|
+
# Impostare BENCH_API_KEY nell'ambiente, senza inserirla nella command line.
|
|
236
|
+
# L'upstream è la radice PRIMA di /v1: il percorso viene dalla fixture.
|
|
237
|
+
npm run bench:proxy -- --live --upstream http://127.0.0.1:10100 --api-key-env BENCH_API_KEY --formats responses --model gpt-5.5 --repetitions 3 --warmup 0
|
|
238
|
+
```
|
|
239
|
+
|
|
240
|
+
Scegliere un modello effettivamente supportato dal proprio upstream. Per un
|
|
241
|
+
endpoint Anthropic usare `--formats anthropic` e un modello Anthropic. Un corpus
|
|
242
|
+
multiformato live richiede un upstream che accetti tutti i protocolli selezionati.
|
|
243
|
+
Le credenziali sono opzionali per gateway locali che non le richiedono; non
|
|
244
|
+
vengono mai cercate automaticamente negli account o nei file dell'utente.
|
|
245
|
+
|
|
246
|
+
Il collector inoltra al provider **il payload realmente trasformato dal proxy**.
|
|
247
|
+
Con `--upstream http://127.0.0.1:10100` la catena è quindi
|
|
248
|
+
`runner → proxy privato del preset → collector privato → OCX`, **non** il proxy
|
|
249
|
+
quotidiano `rtk-pxpipe → OCX`. Il runner usa l'upstream esplicito, non quello del
|
|
250
|
+
client Codex; impostarlo invece alla porta del proxy quotidiano reintrodurrebbe
|
|
251
|
+
la doppia trasformazione. Le istanze proxy sono private, mentre OCX e il servizio
|
|
252
|
+
Headroom rimangono condivisi e non vengono riavviati o riconfigurati.
|
|
253
|
+
Ogni fixture pone una domanda con risposta nota contenuta nel tool output;
|
|
254
|
+
`answerChecks` valuta la risposta reale. I report includono:
|
|
255
|
+
|
|
256
|
+
- qualità della risposta per campione e tasso di pass;
|
|
257
|
+
- durata totale proxy + collector + provider, e durata del solo provider;
|
|
258
|
+
- input/output/cache read/cache write/reasoning dichiarati dal provider;
|
|
259
|
+
- risposta completa o troncata, tool aggiuntivi richiesti dal modello.
|
|
260
|
+
|
|
261
|
+
Per Anthropic l'input normalizzato comprende input non-cached + letture/scritture
|
|
262
|
+
cache, evitando di confrontare scope diversi. Campi non restituiti restano null.
|
|
263
|
+
Di default streaming viene disabilitato; `--responses-stream` lo abilita solo per
|
|
264
|
+
Responses. Le Responses hanno `store: false` e non usano background jobs,
|
|
265
|
+
Chat usa una singola completion, e le risposte
|
|
266
|
+
richiedono il limite `--max-output-tokens` (default 256). Il gateway/provider può
|
|
267
|
+
ignorarlo: l'adapter ChatGPT di OCX osservato rimuove `max_output_tokens`, quindi
|
|
268
|
+
non è una garanzia di budget. Vengono utilizzati bearer
|
|
269
|
+
auth per OpenAI-compatible e `x-api-key` per Anthropic; redirect sono bloccati.
|
|
270
|
+
|
|
271
|
+
**Non è un agente autonomo:** nessun tool viene eseguito, nessun retry o follow-up
|
|
272
|
+
automatico. Tool richiesti e risposte incomplete squalificano il candidato. La
|
|
273
|
+
modalità live accetta solo definizioni di tool function/client, non tool eseguiti
|
|
274
|
+
dal provider come web search o code interpreter. La
|
|
275
|
+
qualità misurata riguarda queste domande/fixture, non una completa attività di
|
|
276
|
+
coding. Per valutare task agentici servono sessioni controllate con repository
|
|
277
|
+
identico, test di accettazione e conteggio di tutte le riletture/retry; questo
|
|
278
|
+
runner non pretende di coprirli.
|
|
279
|
+
|
|
280
|
+
Warmup live **consumano token**. Il numero massimo pianificato di chiamate è:
|
|
281
|
+
|
|
282
|
+
```text
|
|
283
|
+
casi applicabili × flow (incluso none) × (warmup + repetitions)
|
|
284
|
+
```
|
|
285
|
+
|
|
286
|
+
Il numero viene mostrato prima delle chiamate; `--max-live-calls` (default 200)
|
|
287
|
+
blocca piani più grandi prima di inviare richieste. Per una campagna più ampia,
|
|
288
|
+
aumentare esplicitamente questo limite oppure ridurre corpus/rounds.
|
|
289
|
+
Il limite conta i tentativi HTTP del runner: eventuali retry o fallback interni
|
|
290
|
+
del gateway non sono sotto il suo controllo e vanno verificati nei log di OCX.
|
|
291
|
+
|
|
292
|
+
Non c'è controllo della cache remota: fissare modello/versioni/configurazioni e
|
|
293
|
+
ripetere le campagne. Ordine randomizzato riduce, ma non elimina, il bias della
|
|
294
|
+
cache e del carico. Una richiesta annullata può comunque essere fatturata senza
|
|
295
|
+
restituire usage: i report non rappresentano una fattura completa. L'abort del
|
|
296
|
+
campione viene propagato alla fetch del provider; non è una garanzia che il
|
|
297
|
+
provider interrompa il proprio lavoro.
|
|
298
|
+
|
|
299
|
+
## Fixture proprie
|
|
300
|
+
|
|
301
|
+
Esportare il corpus è il modo più semplice per partire. Il file deve essere un
|
|
302
|
+
array JSON di richieste standalone, già sanificate, senza header o credenziali.
|
|
303
|
+
Esempio minimo:
|
|
304
|
+
|
|
305
|
+
```json
|
|
306
|
+
[
|
|
307
|
+
{
|
|
308
|
+
"id": "incident-01",
|
|
309
|
+
"category": "logs",
|
|
310
|
+
"format": "responses",
|
|
311
|
+
"path": "/v1/responses",
|
|
312
|
+
"body": {
|
|
313
|
+
"model": "gpt-5.5",
|
|
314
|
+
"input": [
|
|
315
|
+
{"type":"function_call","call_id":"c1","name":"read_log","arguments":"{}"},
|
|
316
|
+
{"type":"function_call_output","call_id":"c1","output":"INFO ready\nERROR E_QUEUE_FULL at worker.ts:18"},
|
|
317
|
+
{"role":"user","content":"Return the error code and source location."}
|
|
318
|
+
]
|
|
319
|
+
},
|
|
320
|
+
"checks": {"toolIncludes":["E_QUEUE_FULL","worker.ts:18"]},
|
|
321
|
+
"answerChecks": {"includes":["E_QUEUE_FULL","worker.ts:18"],"excludes":["no errors"]}
|
|
322
|
+
}
|
|
323
|
+
]
|
|
324
|
+
```
|
|
325
|
+
|
|
326
|
+
`checks.toolIncludes` cerca solo nei risultati dei tool; `requestIncludes` nel
|
|
327
|
+
testo nativo della richiesta. Le stringhe devono esistere già nell'originale.
|
|
328
|
+
`answerChecks.includes/excludes` sono confronti letterali case-sensitive, non un
|
|
329
|
+
LLM judge; `exact`, `jsonEquals` e `maxChars` consentono controlli più rigorosi.
|
|
330
|
+
Non inserire le risposte nella domanda. Omettere `answerChecks` lascia
|
|
331
|
+
la risposta non valutata, e impedisce una raccomandazione live. Le fixture
|
|
332
|
+
integrate includono definizioni/coppie dei tool complete; rispettare i vincoli
|
|
333
|
+
del proprio provider nelle fixture personalizzate. Non usare riferimenti a
|
|
334
|
+
stato remoto (`previous_response_id`) per un confronto standalone riproducibile.
|
|
335
|
+
|
|
336
|
+
## Report e decisioni
|
|
337
|
+
|
|
338
|
+
Ogni esecuzione crea una directory nuova, normalmente sotto `benchmark-results/`
|
|
339
|
+
(gitignored), senza sovrascrivere run precedenti:
|
|
340
|
+
|
|
341
|
+
- `report.md`: riepilogo leggibile e candidati;
|
|
342
|
+
- `report.json`: manifest/versioni/hash, tutti i campioni, aggregazioni e decisioni;
|
|
343
|
+
- `results.csv`: righe importabili in fogli di calcolo;
|
|
344
|
+
- `records.jsonl`: append progressivo, disponibile anche dopo un'interruzione.
|
|
345
|
+
|
|
346
|
+
Non vengono salvati prompt/output/credenziali di default; i valori attesi delle
|
|
347
|
+
asserzioni sono sostituiti con hash. Gli identificatori delle fixture/modelli e
|
|
348
|
+
gli endpoint configurati restano nel manifest: evitare segreti nei nomi/path.
|
|
349
|
+
`--save-payloads` abilita esplicitamente una sottodirectory con originali,
|
|
350
|
+
trasformati e risposte live, utile per ispezionare le regressioni e potenzialmente
|
|
351
|
+
**sensibile**. Non caricarla automaticamente su servizi esterni.
|
|
352
|
+
|
|
353
|
+
La selezione considera solo run live completi, campioni abbinati alla baseline,
|
|
354
|
+
senza errori, con usage completo e risposte valutate/complete. Soglie configurabili:
|
|
355
|
+
|
|
356
|
+
- `--max-quality-drop 0`: nessuna diminuzione ammessa del pass rate (punti percentuali);
|
|
357
|
+
- `--max-latency-regression 25`: aumento massimo del p95 rispetto a `none` (%).
|
|
358
|
+
|
|
359
|
+
Tra i candidati ammissibili, la **frontiera di Pareto** elenca quelli non dominati
|
|
360
|
+
su risparmio input dichiarato dal provider, p95 e pass rate. Non sceglie un peso
|
|
361
|
+
arbitrario tra qualità e velocità, non equipara token risparmiati a denaro e non
|
|
362
|
+
afferma significatività statistica. Con pochi campioni usare i risultati come
|
|
363
|
+
segnale esplorativo, poi aumentare corpus/ripetizioni e verificare le regressioni.
|
|
364
|
+
|
|
365
|
+
Il manifest registra seed, hash corpus, versioni locali di Node/RTK/pxpipe/tokenizer,
|
|
366
|
+
URL e configurazione scelta. `headroomLocalCli` **non certifica** la versione o i
|
|
367
|
+
flag di un servizio Headroom remoto: fissarli/annotarli esternamente per confronti
|
|
368
|
+
tra macchine o date diverse.
|
|
369
|
+
|
|
370
|
+
Exit code: **0** run completato senza errori di richiesta; **2** errori o
|
|
371
|
+
interruzione; **1** opzioni/setup non validi. Una regressione di qualità non
|
|
372
|
+
cambia da sola l'exit code: consultare `decisions`. Nessuna modifica è applicata
|
|
373
|
+
automaticamente al flow del proxy in uso.
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@drakonkat/ai-helper",
|
|
3
|
-
"version": "1.
|
|
3
|
+
"version": "1.2.3",
|
|
4
4
|
"description": "Zero-config background service manager, auto-discovery daemon & dashboard launcher for AI agent ecosystems (pxpipe, ocx, agentmemory, headroom)",
|
|
5
5
|
"main": "src/index.js",
|
|
6
6
|
"module": "src/index.js",
|
|
@@ -12,13 +12,16 @@
|
|
|
12
12
|
"files": [
|
|
13
13
|
"bin",
|
|
14
14
|
"src",
|
|
15
|
+
"scripts/build.js",
|
|
16
|
+
"scripts/bench-proxy.js",
|
|
17
|
+
"docs/benchmark.md",
|
|
15
18
|
"README.md",
|
|
16
19
|
"LICENSE",
|
|
17
20
|
"ARCHITECTURE.md",
|
|
18
21
|
"CHANGELOG.md"
|
|
19
22
|
],
|
|
20
23
|
"engines": {
|
|
21
|
-
"node": ">=
|
|
24
|
+
"node": ">=20.19.0"
|
|
22
25
|
},
|
|
23
26
|
"publishConfig": {
|
|
24
27
|
"access": "public"
|
|
@@ -34,8 +37,11 @@
|
|
|
34
37
|
"scripts": {
|
|
35
38
|
"start": "node ./bin/cli.js",
|
|
36
39
|
"dev": "node ./bin/cli.js",
|
|
37
|
-
"test": "bun test",
|
|
38
|
-
"
|
|
40
|
+
"test": "bun test test/aih.test.js test/metrics.test.js test/discovery.test.js test/tui-pipeline.test.js test/tui-versions.test.js test/versions.test.js test/repositories.test.js test/service-updates.test.js && node --test test/proxy.test.js test/codex-config.test.js test/codex-routing.test.js test/codex-manager.test.js test/benchmark-live.test.js test/benchmark-measurement.test.js test/benchmark-quality.test.js test/benchmark-report.test.js test/benchmark-runner.test.js test/benchmark-multimodal.test.js",
|
|
41
|
+
"bench:proxy": "node scripts/bench-proxy.js",
|
|
42
|
+
"bench:models": "node scripts/bench-proxy.js --compare-models gpt-6-astra,anthropic/claude-fable-5-1 --formats responses",
|
|
43
|
+
"test:benchmark": "node --test test/benchmark-live.test.js test/benchmark-measurement.test.js test/benchmark-quality.test.js test/benchmark-report.test.js test/benchmark-runner.test.js test/benchmark-multimodal.test.js",
|
|
44
|
+
"build": "bun run scripts/build.js",
|
|
39
45
|
"install-bin": "bun run scripts/install-bin.js"
|
|
40
46
|
},
|
|
41
47
|
"keywords": [
|
|
@@ -53,5 +59,11 @@
|
|
|
53
59
|
"developer-tools"
|
|
54
60
|
],
|
|
55
61
|
"author": "Mauro",
|
|
56
|
-
"license": "MIT"
|
|
62
|
+
"license": "MIT",
|
|
63
|
+
"dependencies": {
|
|
64
|
+
"gpt-tokenizer": "3.4.0",
|
|
65
|
+
"pxpipe-proxy": "0.13.2",
|
|
66
|
+
"toml-eslint-parser": "1.0.3",
|
|
67
|
+
"ws": "^8.21.3"
|
|
68
|
+
}
|
|
57
69
|
}
|
|
@@ -0,0 +1,111 @@
|
|
|
1
|
+
#!/usr/bin/env node
|
|
2
|
+
import { parseArgs } from "node:util";
|
|
3
|
+
import { readFile, mkdir, writeFile, appendFile, readdir } from "node:fs/promises";
|
|
4
|
+
import { resolve, join } from "node:path";
|
|
5
|
+
import { randomBytes } from "node:crypto";
|
|
6
|
+
import { fileURLToPath } from "node:url";
|
|
7
|
+
import { runBenchmark, prepareBenchmark, BENCHMARK_PRESETS, SUPPORTED_BENCHMARK_PRESETS } from "../src/benchmark/runner.js";
|
|
8
|
+
import { buildReport, reportCsv, reportMarkdown } from "../src/benchmark/report.js";
|
|
9
|
+
|
|
10
|
+
const HELP = `Usage: node scripts/bench-proxy.js [options]
|
|
11
|
+
|
|
12
|
+
Offline by default: private loopback proxies and real compressors; no provider call.
|
|
13
|
+
--presets LIST ${SUPPORTED_BENCHMARK_PRESETS.join(",")}
|
|
14
|
+
Default: ${BENCHMARK_PRESETS.join(",")}; none always included
|
|
15
|
+
--suite NAME core (default), quality (12 stronger Responses cases), all
|
|
16
|
+
--formats LIST responses,chat,anthropic (default: all)
|
|
17
|
+
--transports LIST http,ws (default: http; WS only for Responses)
|
|
18
|
+
--fixtures FILE JSON array of custom fixtures instead of built-in corpus
|
|
19
|
+
--export-fixtures FILE Write built-in fixtures as editable JSON, without running
|
|
20
|
+
--model NAME Override model identically for every fixture/flow
|
|
21
|
+
--compare-models LIST Replay each fixture for every model (mutually exclusive with --model)
|
|
22
|
+
--repetitions N Measured rounds (default: 3)
|
|
23
|
+
--warmup N Unscored rounds (default: 1; live warmups also cost tokens)
|
|
24
|
+
--seed N Reproducible randomized order (default: 42)
|
|
25
|
+
--headroom-url URL Compression service (default: http://127.0.0.1:8787)
|
|
26
|
+
--rtk-filter NAME Fixed filter for matching corpora only (default: auto)
|
|
27
|
+
--models LIST pxpipe allowlist (default: all fixture models, benchmark-only opt-in)
|
|
28
|
+
--timeout-ms N Per-request limit (default: 120000)
|
|
29
|
+
--max-body-bytes N Payload/response limit (default: 67108864)
|
|
30
|
+
--out DIR New output directory (default: benchmark-results/<run-id>)
|
|
31
|
+
--save-payloads Opt-in originals/transformed payloads and live answers; may contain sensitive data
|
|
32
|
+
--live EXPLICITLY enable potentially billable provider calls
|
|
33
|
+
--responses-stream Request SSE for Responses (required by ChatGPT/Codex upstreams)
|
|
34
|
+
--upstream URL Live provider root BEFORE /v1, e.g. http://127.0.0.1:10100
|
|
35
|
+
--api-key-env NAME Environment variable holding credentials (never written to reports)
|
|
36
|
+
--max-output-tokens N Live answer cap (default: 256; no tool execution or retries)
|
|
37
|
+
--max-live-calls N Refuse live plans above this call count (default: 200, including warmups)
|
|
38
|
+
--stop-on-error Stop after the first request error (useful for live smoke checks)
|
|
39
|
+
--max-quality-drop N Allowed answer pass-rate drop in percentage points (default: 0)
|
|
40
|
+
--max-latency-regression N Allowed p95 increase in percent (default: 25)
|
|
41
|
+
--list Print built-in fixture IDs without running
|
|
42
|
+
--help Show help
|
|
43
|
+
|
|
44
|
+
Reports: report.json, records.jsonl, results.csv, report.md. Managed config/aih proxy stats are untouched.
|
|
45
|
+
Exit 0 completed without request errors; 2 request errors/interruption; 1 invalid setup.
|
|
46
|
+
Offline runs never claim a semantic-quality winner. See docs/benchmark.md.
|
|
47
|
+
`;
|
|
48
|
+
|
|
49
|
+
export async function main(argv = process.argv.slice(2)) {
|
|
50
|
+
const strings = ["presets", "suite", "formats", "transports", "fixtures", "export-fixtures", "model", "compare-models", "repetitions", "warmup", "seed", "headroom-url", "rtk-filter", "models", "timeout-ms", "max-body-bytes", "out", "upstream", "api-key-env", "max-output-tokens", "max-live-calls", "max-quality-drop", "max-latency-regression"];
|
|
51
|
+
const booleans = ["help", "list", "save-payloads", "live", "responses-stream", "stop-on-error"];
|
|
52
|
+
const { values } = parseArgs({ args: argv, options: { ...Object.fromEntries(strings.map(s => [s, { type: "string" }])), ...Object.fromEntries(booleans.map(s => [s, { type: "boolean" }])) }, strict: true, allowPositionals: false });
|
|
53
|
+
if (values.help) { console.log(HELP); return 0; }
|
|
54
|
+
const list = name => values[name] === undefined ? undefined : values[name].split(",").map(s => s.trim());
|
|
55
|
+
const numeric = name => values[name] === undefined ? undefined : Number(values[name]);
|
|
56
|
+
const formats = list("formats");
|
|
57
|
+
if (formats && (formats.some(f => !["responses", "chat", "anthropic"].includes(f)) || new Set(formats).size !== formats.length)) throw new Error("Invalid formats list");
|
|
58
|
+
if (values.fixtures && values.suite) throw new Error("Use --fixtures OR --suite, not both");
|
|
59
|
+
const preview = values.list || values["export-fixtures"] ? prepareBenchmark({ model: values.model, compareModels: list("compare-models"), formats, suite: values.suite, presets: ["none"] }).fixtures : null;
|
|
60
|
+
if (values.list) { console.log(preview.map(f => `${f.id}\t${f.format}\t${f.category}`).join("\n")); return 0; }
|
|
61
|
+
if (values["export-fixtures"]) {
|
|
62
|
+
const file = resolve(values["export-fixtures"]);
|
|
63
|
+
await writeFile(file, JSON.stringify(preview, null, 2) + "\n", { flag: "wx" });
|
|
64
|
+
console.log(`Fixtures exported to ${file}`); return 0;
|
|
65
|
+
}
|
|
66
|
+
if (values["api-key-env"] && !values.live) throw new Error("--api-key-env requires --live");
|
|
67
|
+
const apiKey = values["api-key-env"] ? process.env[values["api-key-env"]] : undefined;
|
|
68
|
+
if (values["api-key-env"] && !apiKey) throw new Error("Credential environment variable is missing or empty");
|
|
69
|
+
const thresholds = { maxQualityDrop: numeric("max-quality-drop") ?? 0, maxLatencyRegression: numeric("max-latency-regression") ?? 25 };
|
|
70
|
+
if (Object.values(thresholds).some(n => !Number.isFinite(n) || n < 0)) throw new Error("Thresholds must be nonnegative numbers");
|
|
71
|
+
const fixtures = values.fixtures ? JSON.parse(await readFile(resolve(values.fixtures), "utf8")) : undefined;
|
|
72
|
+
const options = { presets: list("presets"), suite: values.suite, formats, transports: list("transports"), fixtures, model: values.model, compareModels: list("compare-models"),
|
|
73
|
+
repetitions: numeric("repetitions"), warmup: numeric("warmup"), seed: numeric("seed"),
|
|
74
|
+
headroomUrl: values["headroom-url"], rtkFilter: values["rtk-filter"], models: values.models,
|
|
75
|
+
timeoutMs: numeric("timeout-ms"), maxBodyBytes: numeric("max-body-bytes"), live: values.live,
|
|
76
|
+
upstream: values.upstream, apiKey, responsesStream: values["responses-stream"], maxOutputTokens: numeric("max-output-tokens"), maxLiveCalls: numeric("max-live-calls") };
|
|
77
|
+
const prepared = prepareBenchmark(options); // Validate before creating/reserving any output files.
|
|
78
|
+
const directory = resolve(values.out || join("benchmark-results", `${new Date().toISOString().replace(/[:.]/g, "-")}-${randomBytes(3).toString("hex")}`));
|
|
79
|
+
await mkdir(directory, { recursive: true });
|
|
80
|
+
if ((await readdir(directory)).length) throw new Error("Output directory must be empty; choose a new run directory");
|
|
81
|
+
// Reserve a new run; never overwrite a previous benchmark's measurements.
|
|
82
|
+
await writeFile(join(directory, "records.jsonl"), "", { flag: "wx" });
|
|
83
|
+
if (values["save-payloads"]) await mkdir(join(directory, "payloads"));
|
|
84
|
+
const controller = new AbortController();
|
|
85
|
+
const interrupt = () => controller.abort();
|
|
86
|
+
process.once("SIGINT", interrupt);
|
|
87
|
+
if (values.live) console.error(`LIVE benchmark: up to ${prepared.cases.length * prepared.options.presets.length * (prepared.options.repetitions + prepared.options.warmup)} potentially billable provider calls, including warmups. No automatic retries or tool execution.`);
|
|
88
|
+
try {
|
|
89
|
+
const run = await runBenchmark({ ...options, signal: controller.signal,
|
|
90
|
+
onRecord: async row => {
|
|
91
|
+
await appendFile(join(directory, "records.jsonl"), JSON.stringify(row) + "\n");
|
|
92
|
+
if (row.status === "error") {
|
|
93
|
+
console.error(`${row.preset} / ${row.caseId}: ${row.error}`);
|
|
94
|
+
if (values["stop-on-error"]) controller.abort();
|
|
95
|
+
}
|
|
96
|
+
},
|
|
97
|
+
onPayload: values["save-payloads"] ? async payload => writeFile(join(directory, "payloads", `${payload.sequence}.json`), JSON.stringify(payload) + "\n", { flag: "wx" }) : undefined,
|
|
98
|
+
});
|
|
99
|
+
const report = buildReport(run, thresholds);
|
|
100
|
+
await writeFile(join(directory, "report.json"), JSON.stringify(report, null, 2) + "\n", { flag: "wx" });
|
|
101
|
+
await writeFile(join(directory, "results.csv"), reportCsv(report), { flag: "wx" });
|
|
102
|
+
await writeFile(join(directory, "report.md"), reportMarkdown(report), { flag: "wx" });
|
|
103
|
+
console.log(reportMarkdown(report));
|
|
104
|
+
console.log(`Reports saved to ${directory}`);
|
|
105
|
+
return report.meta.completed && !report.records.some(r => r.status === "error") ? 0 : 2;
|
|
106
|
+
} finally { process.removeListener("SIGINT", interrupt); }
|
|
107
|
+
}
|
|
108
|
+
|
|
109
|
+
if (process.argv[1] && resolve(process.argv[1]) === fileURLToPath(import.meta.url)) {
|
|
110
|
+
main().then(code => { process.exitCode = code; }).catch(error => { console.error(`Benchmark: ${error.message}`); process.exitCode = 1; });
|
|
111
|
+
}
|
package/scripts/build.js
ADDED
|
@@ -0,0 +1,16 @@
|
|
|
1
|
+
import { resolve } from "node:path";
|
|
2
|
+
|
|
3
|
+
// Embed a Node worker so the compiled CLI uses the same proxy transport as npm.
|
|
4
|
+
const root = resolve(import.meta.dir, "..");
|
|
5
|
+
const outfile = process.argv[2] || resolve(root, "dist", process.platform === "win32" ? "aih.exe" : "aih");
|
|
6
|
+
const worker = await Bun.build({
|
|
7
|
+
entrypoints: [resolve(root, "src/proxy-worker.js")], target: "node", format: "esm", minify: true,
|
|
8
|
+
});
|
|
9
|
+
if (!worker.success) throw new AggregateError(worker.logs, "Proxy worker build failed");
|
|
10
|
+
const result = await Bun.build({
|
|
11
|
+
entrypoints: [resolve(root, "src/index.js")], minify: true,
|
|
12
|
+
compile: { outfile },
|
|
13
|
+
define: { AIH_PROXY_WORKER_SOURCE: JSON.stringify(await worker.outputs[0].text()) },
|
|
14
|
+
});
|
|
15
|
+
if (!result.success) throw new AggregateError(result.logs, "CLI build failed");
|
|
16
|
+
console.log(`Built ${outfile} (proxy worker requires Node.js 20.19+ on PATH)`);
|