graph-bench 0.1.5 → 0.1.6
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 +39 -4
- package/capture/node/capture.mjs +358 -0
- package/capture/python/graph_bench_capture.py +322 -0
- package/package.json +6 -6
package/README.md
CHANGED
|
@@ -1,22 +1,30 @@
|
|
|
1
1
|
# graph-bench
|
|
2
2
|
|
|
3
|
-
A local development bench for LangGraph projects: watch runs, every model call, cost and cache, and experiment on calls.
|
|
3
|
+
A local development bench for LangGraph projects: watch runs, every model call, cost and cache, and experiment on calls. It attaches to your running Agent Server by URL, the way LangGraph Studio does; a coding agent drives it with the `gbench` CLI and a person watches the same work on a read-only page. Source, issues and the full README: <https://github.com/Ovich/graph-bench>.
|
|
4
4
|
|
|
5
5
|
## Install
|
|
6
6
|
|
|
7
|
+
Pin the version you checked, never "latest":
|
|
8
|
+
|
|
7
9
|
```sh
|
|
8
|
-
npx graph-bench --version
|
|
10
|
+
npx -y graph-bench@0.1.6 --version
|
|
9
11
|
```
|
|
10
12
|
|
|
11
13
|
or install it once and run `gbench`:
|
|
12
14
|
|
|
13
15
|
```sh
|
|
14
|
-
npm install -g graph-bench
|
|
16
|
+
npm install -g graph-bench@0.1.6
|
|
15
17
|
gbench --help
|
|
16
18
|
```
|
|
17
19
|
|
|
18
20
|
npm installs the main package and only the binary for your machine, from its optional dependencies; do not install with `--no-optional` or `--omit=optional`.
|
|
19
21
|
|
|
22
|
+
### Verify what you installed
|
|
23
|
+
|
|
24
|
+
- **Provenance**: the packages are published from this repository's release workflow with npm trusted publishing. `npm audit signatures` in a project that installed them checks the registry signatures and the provenance attestations.
|
|
25
|
+
- **Checksums**: each release's notes on GitHub list the SHA-256 of every platform binary. Compare the binary npm installed (`node_modules/@graph-bench/<os>-<cpu>/bin/`) with `sha256sum` (`shasum -a 256` on macOS, `Get-FileHash` on Windows).
|
|
26
|
+
- **Read the hook before you turn capture on**: the `graph-bench` package carries `capture/node/capture.mjs` and `capture/python/graph_bench_capture.py`, the two small files capture loads into your server, as readable copies of the exact bytes the binary embeds.
|
|
27
|
+
|
|
20
28
|
## Supported platforms
|
|
21
29
|
|
|
22
30
|
| OS | CPU |
|
|
@@ -33,7 +41,34 @@ gbench doctor # check the servers and the bench
|
|
|
33
41
|
gbench --help # every verb
|
|
34
42
|
```
|
|
35
43
|
|
|
36
|
-
|
|
44
|
+
## What capture records
|
|
45
|
+
|
|
46
|
+
By default the bench records nothing of your model calls: it reads what the Agent Server's API and streams give, which never carry a call's tools, `tool_choice`, thinking or effort. **Capture** is the opt-in that adds the exact calls. It is off until you run `gbench capture on` in your project's folder, which shows what it will write and asks yes or no first.
|
|
47
|
+
|
|
48
|
+
- **What is captured**: the full request and response bodies of every model call your server makes (prompts, tool definitions, answers), their timing, and the thread, run, node and task each belongs to.
|
|
49
|
+
- **How**: a small hook (a Node `--import` file, or a Python `.pth` file in the project's virtual environment) loaded into the Agent Server's own process. It is inert unless the variable `GBENCH_CAPTURE_DIR` is set in that process (the Python `.pth` file is read by every process of that virtual environment, tests and a REPL included, but the hook then decides when the HTTP library is imported, and does nothing while the variable is unset), which `gbench capture on` writes into the server's env file: so it covers the server you start with that file and the child processes that inherit the variable, and nothing else on your machine.
|
|
50
|
+
- **Where**: JSON lines under `~/.graph-bench/projects/<hash>/capture/`, then into the folder's records in `~/.graph-bench/projects/<hash>/records.sqlite`, on this machine.
|
|
51
|
+
- **What is redacted**: every request and response header outside this list has its value replaced by `[redacted]` before anything is written, so an API key in a header never reaches a file: `content-type`, `content-length`, `accept`, `accept-encoding`, `anthropic-version`, `anthropic-beta`, `user-agent`, `x-stainless-*`, and on a response `content-encoding`, `request-id`. **Bodies are not redacted**: whatever your prompts contain, they are stored as sent.
|
|
52
|
+
- **Which calls**: those to `api.anthropic.com`, or to any host at a path ending in `/v1/messages`. Calls made by a client the hook cannot see (for example Python's `requests`, `aiohttp` or `urllib`) are not captured; `gbench doctor` says `bypass` when it sees one.
|
|
53
|
+
- **Retention**: 7 days by default (`gbench capture --retention <days>`); older calls, and capture files wholly older, are deleted when the bench's instance starts.
|
|
54
|
+
- **It never leaves this machine**: the hook makes no network call and sends no telemetry; the bench's instance listens on `127.0.0.1` only.
|
|
55
|
+
- **Development servers only**: the hook does nothing when `CI` is set, and `gbench capture on` refuses then. Never turn it on for a deployed server.
|
|
56
|
+
- **Turn it off, delete it**: `gbench capture off` removes exactly what `on` wrote (a line merged into an existing `NODE_OPTIONS` is taken out and the rest of its value restored); `gbench purge` deletes the captured calls and the raw capture files of servers that have ended, `gbench purge <graph_id>` one graph's (a file that also holds other graphs' calls, or one a running server still writes, is left and named), `gbench purge --all` every record of the folder and its lab folders. Each says what it removed.
|
|
57
|
+
|
|
58
|
+
`gbench capture --dry-run` runs the hook's own redaction on a request carrying a made-up API key and prints the record as it would be stored; `gbench doctor` prints, per attached server, whether capture is `active`, `loaded, no model call yet`, `bypass: <reason>` or `off`, and `key redacted: yes` from the same self-test.
|
|
59
|
+
|
|
60
|
+
## Threat model
|
|
61
|
+
|
|
62
|
+
What the bench can read and what could go wrong, plainly.
|
|
63
|
+
|
|
64
|
+
- **The bench is a program you run as yourself.** `gbench` and its instance run with your user's permissions: a compromised build could read any file your user can. That is why the install is pinned, the binaries are checksummed and published with provenance, and the capture hook is readable before you install. The binary does not read a `.env` or `bunfig.toml` from your project, and its instance runs in `~/.graph-bench`, not in your project.
|
|
65
|
+
- **Your API key.** The bench uses a model key only for `gbench resend`, from `GBENCH_ANTHROPIC_API_KEY` in the environment of the shell that starts it; it never writes it to a file. Your server's own key stays in its env file: the hook redacts it from headers but sits inside the process that holds it.
|
|
66
|
+
- **What the hook can see.** Inside your server's process it sees every model call in full, request and response, and whatever your code puts in them: user messages, customer data, secrets pasted into a prompt. It writes the bodies as they are and the headers by allowlist. A hook is code running in your server: read it (it is two short files), keep it to development, and turn it off with `gbench capture off`.
|
|
67
|
+
- **Captured prompts enter an agent's context.** When a coding agent reads a call with `gbench show`, the prompt, the tool results and the answer become part of that agent's context, and so of whatever service the agent runs on. Capture a development server fed with data you would let that agent read, and `gbench purge` afterwards.
|
|
68
|
+
- **Local files.** The records and captures are readable by your user only (mode `0700`/`0600` on POSIX; on Windows, your profile's own access rules). Anything else running as you can read them.
|
|
69
|
+
- **The page and the instance.** They listen on `127.0.0.1` only; the page opens through a one-time link and a session cookie; see [SECURITY.md](SECURITY.md) for the known limits and how to report a vulnerability privately.
|
|
70
|
+
|
|
71
|
+
graph-bench is an independent project, not affiliated with or endorsed by LangChain, Inc. or Anthropic.
|
|
37
72
|
|
|
38
73
|
## License
|
|
39
74
|
|
|
@@ -0,0 +1,358 @@
|
|
|
1
|
+
// graph-bench capture hook for Node, loaded with NODE_OPTIONS=--import "file:///<path>/capture.mjs".
|
|
2
|
+
// It records each model call this process makes (request and response bytes, tags from LangGraph's run context) as
|
|
3
|
+
// JSON lines in <GBENCH_CAPTURE_DIR>/<pid>.jsonl; the lines are described in FORMAT.md next to this file's folder.
|
|
4
|
+
// It makes no network call, keeps every header outside an allowlist as "[redacted]", does nothing when CI is set, and on
|
|
5
|
+
// any error of its own lets the call through untouched (capture-hook#D1-D5, D25).
|
|
6
|
+
import { AsyncLocalStorage } from "node:async_hooks";
|
|
7
|
+
import diagnosticsChannel from "node:diagnostics_channel";
|
|
8
|
+
import { appendFileSync, mkdirSync } from "node:fs";
|
|
9
|
+
import { join } from "node:path";
|
|
10
|
+
|
|
11
|
+
const CAPTURE_DIR = process.env.GBENCH_CAPTURE_DIR;
|
|
12
|
+
const CAPTURE_FILE = CAPTURE_DIR
|
|
13
|
+
? join(CAPTURE_DIR, `${process.pid}.jsonl`)
|
|
14
|
+
: undefined;
|
|
15
|
+
const KEPT_REQUEST_HEADER =
|
|
16
|
+
/^(content-type|content-length|accept|accept-encoding|anthropic-version|anthropic-beta|user-agent|x-stainless-.*)$/i;
|
|
17
|
+
const KEPT_RESPONSE_HEADER =
|
|
18
|
+
/^(content-type|content-length|accept|accept-encoding|anthropic-version|anthropic-beta|user-agent|x-stainless-.*|content-encoding|request-id)$/i;
|
|
19
|
+
|
|
20
|
+
let callsSeen = 0;
|
|
21
|
+
let callsCaptured = 0;
|
|
22
|
+
let firstCallAnnounced = false;
|
|
23
|
+
let bypassAnnounced = false;
|
|
24
|
+
let insideOwnDispatch = false;
|
|
25
|
+
|
|
26
|
+
function writeLine(line) {
|
|
27
|
+
try {
|
|
28
|
+
appendFileSync(
|
|
29
|
+
CAPTURE_FILE,
|
|
30
|
+
`${JSON.stringify({ t: Date.now(), pid: process.pid, ...line })}\n`,
|
|
31
|
+
);
|
|
32
|
+
} catch {}
|
|
33
|
+
}
|
|
34
|
+
const writeStatus = (phase, fields = {}) =>
|
|
35
|
+
writeLine({ type: "status", phase, ...fields });
|
|
36
|
+
|
|
37
|
+
/** Host and path of a model API call: api.anthropic.com, or any host whose path ends in /v1/messages. */
|
|
38
|
+
function isModelCall(host, path) {
|
|
39
|
+
return host === "api.anthropic.com" || path.endsWith("/v1/messages");
|
|
40
|
+
}
|
|
41
|
+
|
|
42
|
+
const headerPairsOf = (headers) =>
|
|
43
|
+
!headers
|
|
44
|
+
? []
|
|
45
|
+
: Array.isArray(headers)
|
|
46
|
+
? Array.from({ length: headers.length >> 1 }, (_, i) => [
|
|
47
|
+
headers[2 * i],
|
|
48
|
+
headers[2 * i + 1],
|
|
49
|
+
])
|
|
50
|
+
: typeof headers.entries === "function"
|
|
51
|
+
? [...headers.entries()]
|
|
52
|
+
: Object.entries(headers);
|
|
53
|
+
|
|
54
|
+
function allowlisted(pairs, allowed) {
|
|
55
|
+
return Object.fromEntries(
|
|
56
|
+
pairs.map(([name, value]) => [
|
|
57
|
+
String(name).toLowerCase(),
|
|
58
|
+
allowed.test(name) ? String(value) : "[redacted]",
|
|
59
|
+
]),
|
|
60
|
+
);
|
|
61
|
+
}
|
|
62
|
+
|
|
63
|
+
const bytesOf = (body) =>
|
|
64
|
+
typeof body === "string"
|
|
65
|
+
? Buffer.from(body)
|
|
66
|
+
: body instanceof Uint8Array
|
|
67
|
+
? Buffer.from(body.buffer, body.byteOffset, body.byteLength)
|
|
68
|
+
: body instanceof ArrayBuffer
|
|
69
|
+
? Buffer.from(body)
|
|
70
|
+
: null;
|
|
71
|
+
|
|
72
|
+
/** LangGraph JS keeps the running node's RunnableConfig in langchain-core's one AsyncLocalStorage. */
|
|
73
|
+
function langGraphTags() {
|
|
74
|
+
try {
|
|
75
|
+
const store =
|
|
76
|
+
globalThis[Symbol.for("ls:tracing_async_local_storage")]?.getStore();
|
|
77
|
+
const config = store?.extra?.[Symbol.for("lc:child_config")];
|
|
78
|
+
if (!config) return {};
|
|
79
|
+
const configurable = config.configurable ?? {};
|
|
80
|
+
const metadata = config.metadata ?? {};
|
|
81
|
+
return {
|
|
82
|
+
thread_id: configurable.thread_id ?? metadata.thread_id,
|
|
83
|
+
run_id: metadata.run_id ?? configurable.run_id,
|
|
84
|
+
assistant_id: metadata.assistant_id ?? configurable.assistant_id,
|
|
85
|
+
node: metadata.langgraph_node,
|
|
86
|
+
checkpoint_ns:
|
|
87
|
+
configurable.checkpoint_ns ?? metadata.langgraph_checkpoint_ns,
|
|
88
|
+
task_id: configurable.__pregel_task_id,
|
|
89
|
+
step: metadata.langgraph_step,
|
|
90
|
+
};
|
|
91
|
+
} catch {
|
|
92
|
+
return {};
|
|
93
|
+
}
|
|
94
|
+
}
|
|
95
|
+
|
|
96
|
+
/** One model call's lines: start, request_body, response, chunk..., done. Each is written as soon as it is known. */
|
|
97
|
+
class CallRecord {
|
|
98
|
+
constructor(layer, method, origin, path, headerPairs) {
|
|
99
|
+
this.id = `${process.pid}-${++callsSeen}`;
|
|
100
|
+
this.bodyParts = undefined;
|
|
101
|
+
this.finished = false;
|
|
102
|
+
const requestHeaders = allowlisted(headerPairs, KEPT_REQUEST_HEADER);
|
|
103
|
+
if (!firstCallAnnounced) {
|
|
104
|
+
firstCallAnnounced = true;
|
|
105
|
+
writeStatus("first_call", { layer });
|
|
106
|
+
}
|
|
107
|
+
writeLine({
|
|
108
|
+
type: "start",
|
|
109
|
+
id: this.id,
|
|
110
|
+
layer,
|
|
111
|
+
method,
|
|
112
|
+
host: origin,
|
|
113
|
+
path,
|
|
114
|
+
request_headers: requestHeaders,
|
|
115
|
+
retry: Number(requestHeaders["x-stainless-retry-count"]) || 0,
|
|
116
|
+
...langGraphTags(),
|
|
117
|
+
});
|
|
118
|
+
}
|
|
119
|
+
requestBody(bytes) {
|
|
120
|
+
this.bodyParts = undefined;
|
|
121
|
+
writeLine({
|
|
122
|
+
type: "request_body",
|
|
123
|
+
id: this.id,
|
|
124
|
+
b64: bytes.toString("base64"),
|
|
125
|
+
});
|
|
126
|
+
}
|
|
127
|
+
response(status, headerPairs) {
|
|
128
|
+
writeLine({
|
|
129
|
+
type: "response",
|
|
130
|
+
id: this.id,
|
|
131
|
+
status,
|
|
132
|
+
response_headers: allowlisted(headerPairs, KEPT_RESPONSE_HEADER),
|
|
133
|
+
});
|
|
134
|
+
}
|
|
135
|
+
chunk(bytes) {
|
|
136
|
+
writeLine({
|
|
137
|
+
type: "chunk",
|
|
138
|
+
id: this.id,
|
|
139
|
+
b64: Buffer.from(bytes).toString("base64"),
|
|
140
|
+
});
|
|
141
|
+
}
|
|
142
|
+
done(error) {
|
|
143
|
+
if (this.finished) return;
|
|
144
|
+
this.finished = true;
|
|
145
|
+
if (this.bodyParts) this.requestBody(Buffer.concat(this.bodyParts));
|
|
146
|
+
callsCaptured++;
|
|
147
|
+
writeLine({
|
|
148
|
+
type: "done",
|
|
149
|
+
id: this.id,
|
|
150
|
+
...(error
|
|
151
|
+
? { error: String(error?.message ?? error).slice(0, 500) }
|
|
152
|
+
: {}),
|
|
153
|
+
});
|
|
154
|
+
}
|
|
155
|
+
}
|
|
156
|
+
|
|
157
|
+
// Layer 1: the undici global dispatcher sees the wire bytes of global fetch and of any fetch on the default dispatcher.
|
|
158
|
+
// The handler is wrapped by a Proxy that speaks both of undici's handler APIs; the original handler always runs first-class.
|
|
159
|
+
const fetchSeenByDispatcher = new AsyncLocalStorage();
|
|
160
|
+
|
|
161
|
+
function wrapHandler(handler, record) {
|
|
162
|
+
const first = (status, headers) =>
|
|
163
|
+
record.response(
|
|
164
|
+
status,
|
|
165
|
+
headerPairsOf(headers).filter(
|
|
166
|
+
([name]) => String(name).toLowerCase() !== "set-cookie",
|
|
167
|
+
),
|
|
168
|
+
);
|
|
169
|
+
const tap = {
|
|
170
|
+
onHeaders: (args) => first(args[0], args[1]),
|
|
171
|
+
onResponseStart: (args) => first(args[1], args[2]),
|
|
172
|
+
onData: (args) => record.chunk(args[0]),
|
|
173
|
+
onResponseData: (args) => record.chunk(args[1]),
|
|
174
|
+
onComplete: () => record.done(),
|
|
175
|
+
onResponseEnd: () => record.done(),
|
|
176
|
+
onError: (args) => record.done(args[0]),
|
|
177
|
+
onResponseError: (args) => record.done(args[1]),
|
|
178
|
+
};
|
|
179
|
+
return new Proxy(handler, {
|
|
180
|
+
get(target, key) {
|
|
181
|
+
const value = Reflect.get(target, key, target);
|
|
182
|
+
if (typeof value !== "function") return value;
|
|
183
|
+
return (...args) => {
|
|
184
|
+
try {
|
|
185
|
+
tap[key]?.(args);
|
|
186
|
+
} catch {}
|
|
187
|
+
return value.apply(target, args);
|
|
188
|
+
};
|
|
189
|
+
},
|
|
190
|
+
});
|
|
191
|
+
}
|
|
192
|
+
|
|
193
|
+
function patchDispatch(dispatcher) {
|
|
194
|
+
const originalDispatch = dispatcher.dispatch.bind(dispatcher);
|
|
195
|
+
dispatcher.dispatch = (options, handler) => {
|
|
196
|
+
try {
|
|
197
|
+
const path = String(options.path).split("?")[0];
|
|
198
|
+
const host = String(
|
|
199
|
+
options.origin ? new URL(String(options.origin)).host : "",
|
|
200
|
+
);
|
|
201
|
+
if (!isModelCall(host.split(":")[0], path))
|
|
202
|
+
return originalDispatch(options, handler);
|
|
203
|
+
const store = fetchSeenByDispatcher.getStore();
|
|
204
|
+
if (store) store.seen = true;
|
|
205
|
+
const record = new CallRecord(
|
|
206
|
+
"dispatcher",
|
|
207
|
+
options.method,
|
|
208
|
+
host,
|
|
209
|
+
path,
|
|
210
|
+
headerPairsOf(options.headers),
|
|
211
|
+
);
|
|
212
|
+
const sentBytes = bytesOf(options.body);
|
|
213
|
+
let forwarded = options;
|
|
214
|
+
if (sentBytes) record.requestBody(sentBytes);
|
|
215
|
+
else if (
|
|
216
|
+
options.body &&
|
|
217
|
+
typeof options.body[Symbol.asyncIterator] === "function"
|
|
218
|
+
) {
|
|
219
|
+
// undici's fetch hands over an async iterable: tee it, the bytes go on unchanged
|
|
220
|
+
const source = options.body;
|
|
221
|
+
record.bodyParts = [];
|
|
222
|
+
forwarded = {
|
|
223
|
+
...options,
|
|
224
|
+
body: (async function* () {
|
|
225
|
+
for await (const piece of source) {
|
|
226
|
+
try {
|
|
227
|
+
record.bodyParts?.push(Buffer.from(piece));
|
|
228
|
+
} catch {}
|
|
229
|
+
yield piece;
|
|
230
|
+
}
|
|
231
|
+
try {
|
|
232
|
+
if (record.bodyParts)
|
|
233
|
+
record.requestBody(Buffer.concat(record.bodyParts));
|
|
234
|
+
} catch {}
|
|
235
|
+
})(),
|
|
236
|
+
};
|
|
237
|
+
}
|
|
238
|
+
insideOwnDispatch = true;
|
|
239
|
+
try {
|
|
240
|
+
return originalDispatch(forwarded, wrapHandler(handler, record));
|
|
241
|
+
} finally {
|
|
242
|
+
insideOwnDispatch = false;
|
|
243
|
+
}
|
|
244
|
+
} catch (error) {
|
|
245
|
+
writeStatus("hook_error", { error: String(error) });
|
|
246
|
+
return originalDispatch(options, handler);
|
|
247
|
+
}
|
|
248
|
+
};
|
|
249
|
+
}
|
|
250
|
+
|
|
251
|
+
// Layer 2: globalThis.fetch, for fetches that never reach the dispatcher (mocks, shims); records only what layer 1 did not see.
|
|
252
|
+
function wrapFetch(originalFetch) {
|
|
253
|
+
return function fetch(input, init) {
|
|
254
|
+
const store = { seen: false };
|
|
255
|
+
const pending = fetchSeenByDispatcher.run(store, () =>
|
|
256
|
+
originalFetch.call(this, input, init),
|
|
257
|
+
);
|
|
258
|
+
return pending.then(async (response) => {
|
|
259
|
+
try {
|
|
260
|
+
const url = new URL(String(input?.url ?? input), "http://unknown");
|
|
261
|
+
if (store.seen || !isModelCall(url.hostname, url.pathname))
|
|
262
|
+
return response;
|
|
263
|
+
const record = new CallRecord(
|
|
264
|
+
"fetch",
|
|
265
|
+
init?.method ?? input?.method ?? "GET",
|
|
266
|
+
url.host,
|
|
267
|
+
url.pathname,
|
|
268
|
+
headerPairsOf(init?.headers ?? input?.headers),
|
|
269
|
+
);
|
|
270
|
+
const sentBytes =
|
|
271
|
+
bytesOf(init?.body) ??
|
|
272
|
+
(input instanceof Request
|
|
273
|
+
? Buffer.from(await input.clone().arrayBuffer())
|
|
274
|
+
: null);
|
|
275
|
+
if (sentBytes) record.requestBody(sentBytes);
|
|
276
|
+
record.response(response.status, [...response.headers]);
|
|
277
|
+
const copy = response.clone();
|
|
278
|
+
(async () => {
|
|
279
|
+
try {
|
|
280
|
+
for await (const piece of copy.body ?? []) record.chunk(piece);
|
|
281
|
+
record.done();
|
|
282
|
+
} catch (error) {
|
|
283
|
+
record.done(error);
|
|
284
|
+
}
|
|
285
|
+
})();
|
|
286
|
+
} catch (error) {
|
|
287
|
+
writeStatus("hook_error", { error: String(error) });
|
|
288
|
+
}
|
|
289
|
+
return response;
|
|
290
|
+
});
|
|
291
|
+
};
|
|
292
|
+
}
|
|
293
|
+
|
|
294
|
+
function install() {
|
|
295
|
+
void globalThis.Headers; // touching this lazy global makes Node load its bundled undici, which creates the default dispatcher
|
|
296
|
+
const dispatcher = globalThis[Symbol.for("undici.globalDispatcher.1")];
|
|
297
|
+
let dispatcherPatched = false;
|
|
298
|
+
if (dispatcher && typeof dispatcher.dispatch === "function") {
|
|
299
|
+
patchDispatch(dispatcher);
|
|
300
|
+
dispatcherPatched = true;
|
|
301
|
+
}
|
|
302
|
+
if (typeof globalThis.fetch === "function")
|
|
303
|
+
globalThis.fetch = wrapFetch(globalThis.fetch);
|
|
304
|
+
// bypass: a model call that no layer above sees
|
|
305
|
+
const announceBypass = (reason, fields) => {
|
|
306
|
+
if (bypassAnnounced) return;
|
|
307
|
+
bypassAnnounced = true;
|
|
308
|
+
writeStatus("bypass", { reason, ...fields });
|
|
309
|
+
};
|
|
310
|
+
diagnosticsChannel.subscribe("http.client.request.start", ({ request }) => {
|
|
311
|
+
try {
|
|
312
|
+
if (isModelCall(String(request.host), String(request.path).split("?")[0]))
|
|
313
|
+
announceBypass("model call through node:http, not captured", {
|
|
314
|
+
host: request.host,
|
|
315
|
+
path: String(request.path).split("?")[0],
|
|
316
|
+
});
|
|
317
|
+
} catch {}
|
|
318
|
+
});
|
|
319
|
+
diagnosticsChannel.subscribe("undici:request:create", ({ request }) => {
|
|
320
|
+
try {
|
|
321
|
+
const path = String(request.path).split("?")[0];
|
|
322
|
+
if (
|
|
323
|
+
!insideOwnDispatch &&
|
|
324
|
+
isModelCall(new URL(String(request.origin)).hostname, path)
|
|
325
|
+
)
|
|
326
|
+
announceBypass(
|
|
327
|
+
"model call on an undici dispatcher other than the global one, not captured",
|
|
328
|
+
{ path },
|
|
329
|
+
);
|
|
330
|
+
} catch {}
|
|
331
|
+
});
|
|
332
|
+
process.on("exit", () => writeStatus("exit", { calls: callsCaptured }));
|
|
333
|
+
writeStatus("load", {
|
|
334
|
+
runtime: `node ${process.version}`,
|
|
335
|
+
cwd: process.cwd(),
|
|
336
|
+
dispatcher: dispatcherPatched,
|
|
337
|
+
});
|
|
338
|
+
}
|
|
339
|
+
|
|
340
|
+
if (CAPTURE_FILE) {
|
|
341
|
+
try {
|
|
342
|
+
// Windows gets no mode: the folder keeps the ACL it inherits (a mode there can leave the folder's own user locked out)
|
|
343
|
+
mkdirSync(
|
|
344
|
+
CAPTURE_DIR,
|
|
345
|
+
process.platform === "win32"
|
|
346
|
+
? { recursive: true }
|
|
347
|
+
: { recursive: true, mode: 0o700 },
|
|
348
|
+
);
|
|
349
|
+
if (process.env.CI)
|
|
350
|
+
writeStatus("load", { inactive: "CI", cwd: process.cwd() });
|
|
351
|
+
else install();
|
|
352
|
+
} catch (error) {
|
|
353
|
+
writeStatus("load", {
|
|
354
|
+
inactive: `hook error: ${error}`,
|
|
355
|
+
cwd: process.cwd(),
|
|
356
|
+
});
|
|
357
|
+
}
|
|
358
|
+
}
|
|
@@ -0,0 +1,322 @@
|
|
|
1
|
+
"""graph-bench capture hook for Python, loaded by a .pth file (`import graph_bench_capture`) in the project's virtual environment.
|
|
2
|
+
|
|
3
|
+
It records each model call this process makes (request and response bytes, tags from LangGraph's run context) as JSON lines
|
|
4
|
+
in <GBENCH_CAPTURE_DIR>/<pid>.jsonl; the lines are described in FORMAT.md next to this file's folder. It makes no network
|
|
5
|
+
call, keeps every header outside an allowlist as "[redacted]", does nothing when CI is set, and on any error of its own
|
|
6
|
+
lets the call through untouched (capture-hook#D1-D5, D25).
|
|
7
|
+
|
|
8
|
+
It patches httpx's and httpx2's transports (the Anthropic SDK and langchain-anthropic use one of them) when they are
|
|
9
|
+
imported, never importing them itself, so a process that never makes a model call pays nothing. The `.pth` loads it before
|
|
10
|
+
a server's env file is applied, so it cannot decide at load whether capture is on: the wrappers ask at each call, and
|
|
11
|
+
while GBENCH_CAPTURE_DIR is unset they do nothing (no file, no status line); the first call after it is set starts the
|
|
12
|
+
capture (capture-hook#D33, D34a).
|
|
13
|
+
"""
|
|
14
|
+
|
|
15
|
+
import atexit
|
|
16
|
+
import base64
|
|
17
|
+
import importlib.abc
|
|
18
|
+
import importlib.util
|
|
19
|
+
import json
|
|
20
|
+
import os
|
|
21
|
+
import re
|
|
22
|
+
import sys
|
|
23
|
+
import threading
|
|
24
|
+
import time
|
|
25
|
+
|
|
26
|
+
KEPT_REQUEST_HEADER = re.compile(
|
|
27
|
+
r"^(content-type|content-length|accept|accept-encoding|anthropic-version|anthropic-beta|user-agent|x-stainless-.*)$", re.I
|
|
28
|
+
)
|
|
29
|
+
KEPT_RESPONSE_HEADER = re.compile(
|
|
30
|
+
r"^(content-type|content-length|accept|accept-encoding|anthropic-version|anthropic-beta|user-agent|x-stainless-.*|content-encoding|request-id)$",
|
|
31
|
+
re.I,
|
|
32
|
+
)
|
|
33
|
+
HTTP_LIBRARIES = ("httpx", "httpx2")
|
|
34
|
+
|
|
35
|
+
_write_lock = threading.Lock()
|
|
36
|
+
_counts = {"seen": 0, "captured": 0, "first_call_announced": False, "bypass_announced": False}
|
|
37
|
+
# the capture's own state: unknown until GBENCH_CAPTURE_DIR is set, then on (a file to write) or off (CI, or a folder it cannot make)
|
|
38
|
+
_capture = {"file": None, "started": False, "on": False}
|
|
39
|
+
|
|
40
|
+
|
|
41
|
+
def _write_line(line):
|
|
42
|
+
try:
|
|
43
|
+
line = {"t": int(time.time() * 1000), "pid": os.getpid(), **line}
|
|
44
|
+
data = (json.dumps(line, default=str) + "\n").encode("utf-8")
|
|
45
|
+
with _write_lock:
|
|
46
|
+
fd = os.open(_capture["file"], os.O_WRONLY | os.O_APPEND | os.O_CREAT, 0o600)
|
|
47
|
+
try:
|
|
48
|
+
os.write(fd, data)
|
|
49
|
+
finally:
|
|
50
|
+
os.close(fd)
|
|
51
|
+
except Exception:
|
|
52
|
+
pass
|
|
53
|
+
|
|
54
|
+
|
|
55
|
+
def _write_status(phase, **fields):
|
|
56
|
+
_write_line({"type": "status", "phase": phase, **fields})
|
|
57
|
+
|
|
58
|
+
|
|
59
|
+
def _capture_is_on():
|
|
60
|
+
"""Whether this call is captured: starts the capture at the first call made with GBENCH_CAPTURE_DIR set."""
|
|
61
|
+
if _capture["started"]:
|
|
62
|
+
return _capture["on"]
|
|
63
|
+
capture_dir = os.environ.get("GBENCH_CAPTURE_DIR")
|
|
64
|
+
if not capture_dir:
|
|
65
|
+
return False
|
|
66
|
+
_capture["started"] = True
|
|
67
|
+
try:
|
|
68
|
+
_capture["file"] = os.path.join(capture_dir, f"{os.getpid()}.jsonl")
|
|
69
|
+
_make_capture_folder(capture_dir)
|
|
70
|
+
if os.environ.get("CI"):
|
|
71
|
+
_write_status("load", inactive="CI", cwd=os.getcwd())
|
|
72
|
+
return False
|
|
73
|
+
atexit.register(lambda: _write_status("exit", calls=_counts["captured"]))
|
|
74
|
+
_write_status("load", runtime="python " + sys.version.split()[0], cwd=os.getcwd(), argv=sys.argv[:2])
|
|
75
|
+
_capture["on"] = True
|
|
76
|
+
except Exception as error:
|
|
77
|
+
_write_status("load", inactive=f"hook error: {error!r}", cwd=os.getcwd())
|
|
78
|
+
return _capture["on"]
|
|
79
|
+
|
|
80
|
+
|
|
81
|
+
def _make_capture_folder(capture_dir):
|
|
82
|
+
"""Windows gets no mode: Python 3.13 turns one into an ACL that locks the folder's own user out."""
|
|
83
|
+
if sys.platform == "win32":
|
|
84
|
+
os.makedirs(capture_dir, exist_ok=True)
|
|
85
|
+
else:
|
|
86
|
+
os.makedirs(capture_dir, mode=0o700, exist_ok=True)
|
|
87
|
+
|
|
88
|
+
|
|
89
|
+
def _is_model_call(host, path):
|
|
90
|
+
"""Host and path of a model API call: api.anthropic.com, or any host whose path ends in /v1/messages."""
|
|
91
|
+
return host == "api.anthropic.com" or path.endswith("/v1/messages")
|
|
92
|
+
|
|
93
|
+
|
|
94
|
+
def _allowlisted(pairs, allowed):
|
|
95
|
+
return {name.lower(): (value if allowed.match(name) else "[redacted]") for name, value in pairs}
|
|
96
|
+
|
|
97
|
+
|
|
98
|
+
def _langgraph_tags():
|
|
99
|
+
"""The running node's RunnableConfig, read only when LangGraph is already loaded in this process."""
|
|
100
|
+
if "langgraph.config" not in sys.modules:
|
|
101
|
+
return {}
|
|
102
|
+
try:
|
|
103
|
+
from langgraph.config import get_config
|
|
104
|
+
|
|
105
|
+
config = get_config()
|
|
106
|
+
configurable, metadata = config.get("configurable") or {}, config.get("metadata") or {}
|
|
107
|
+
return {
|
|
108
|
+
"thread_id": configurable.get("thread_id") or metadata.get("thread_id"),
|
|
109
|
+
"run_id": metadata.get("run_id") or configurable.get("run_id"),
|
|
110
|
+
"assistant_id": metadata.get("assistant_id") or configurable.get("assistant_id"),
|
|
111
|
+
"node": metadata.get("langgraph_node"),
|
|
112
|
+
"checkpoint_ns": configurable.get("checkpoint_ns") or metadata.get("langgraph_checkpoint_ns"),
|
|
113
|
+
"task_id": configurable.get("__pregel_task_id"),
|
|
114
|
+
"step": metadata.get("langgraph_step"),
|
|
115
|
+
}
|
|
116
|
+
except Exception:
|
|
117
|
+
return {}
|
|
118
|
+
|
|
119
|
+
|
|
120
|
+
def _b64(data):
|
|
121
|
+
return base64.b64encode(data).decode()
|
|
122
|
+
|
|
123
|
+
|
|
124
|
+
class CallRecord:
|
|
125
|
+
"""One model call's lines: start, request_body, response, chunk..., done. Each is written as soon as it is known."""
|
|
126
|
+
|
|
127
|
+
def __init__(self, layer, request):
|
|
128
|
+
_counts["seen"] += 1
|
|
129
|
+
self.id = f"{os.getpid()}-{_counts['seen']}"
|
|
130
|
+
self.finished = False
|
|
131
|
+
request_headers = _allowlisted(request.headers.items(), KEPT_REQUEST_HEADER)
|
|
132
|
+
if not _counts["first_call_announced"]:
|
|
133
|
+
_counts["first_call_announced"] = True
|
|
134
|
+
_write_status("first_call", layer=layer)
|
|
135
|
+
try:
|
|
136
|
+
retry = int(request_headers.get("x-stainless-retry-count", 0))
|
|
137
|
+
except ValueError:
|
|
138
|
+
retry = 0
|
|
139
|
+
_write_line(
|
|
140
|
+
{
|
|
141
|
+
"type": "start",
|
|
142
|
+
"id": self.id,
|
|
143
|
+
"layer": layer,
|
|
144
|
+
"method": request.method,
|
|
145
|
+
"host": request.url.netloc.decode() if isinstance(request.url.netloc, bytes) else str(request.url.netloc),
|
|
146
|
+
"path": request.url.path,
|
|
147
|
+
"request_headers": request_headers,
|
|
148
|
+
"retry": retry,
|
|
149
|
+
**_langgraph_tags(),
|
|
150
|
+
}
|
|
151
|
+
)
|
|
152
|
+
try:
|
|
153
|
+
_write_line({"type": "request_body", "id": self.id, "b64": _b64(request.content)})
|
|
154
|
+
except Exception:
|
|
155
|
+
pass # a streamed request body that was not read: not recorded
|
|
156
|
+
|
|
157
|
+
def response(self, response):
|
|
158
|
+
headers = [(k, v) for k, v in response.headers.items() if k.lower() != "set-cookie"]
|
|
159
|
+
_write_line(
|
|
160
|
+
{
|
|
161
|
+
"type": "response",
|
|
162
|
+
"id": self.id,
|
|
163
|
+
"status": response.status_code,
|
|
164
|
+
"response_headers": _allowlisted(headers, KEPT_RESPONSE_HEADER),
|
|
165
|
+
}
|
|
166
|
+
)
|
|
167
|
+
|
|
168
|
+
def chunk(self, data):
|
|
169
|
+
try:
|
|
170
|
+
_write_line({"type": "chunk", "id": self.id, "b64": _b64(bytes(data))})
|
|
171
|
+
except Exception:
|
|
172
|
+
pass
|
|
173
|
+
|
|
174
|
+
def done(self, error=None):
|
|
175
|
+
if self.finished:
|
|
176
|
+
return
|
|
177
|
+
self.finished = True
|
|
178
|
+
_counts["captured"] += 1
|
|
179
|
+
_write_line({"type": "done", "id": self.id, **({"error": repr(error)[:500]} if error is not None else {})})
|
|
180
|
+
|
|
181
|
+
|
|
182
|
+
def _tee_stream(httpx, record, stream, is_async):
|
|
183
|
+
"""Chunks pass through unchanged; their raw (still content-encoded) bytes go to the record."""
|
|
184
|
+
if is_async:
|
|
185
|
+
|
|
186
|
+
class RecordingStream(httpx.AsyncByteStream):
|
|
187
|
+
async def __aiter__(self):
|
|
188
|
+
try:
|
|
189
|
+
async for piece in stream:
|
|
190
|
+
record.chunk(piece)
|
|
191
|
+
yield piece
|
|
192
|
+
record.done()
|
|
193
|
+
except BaseException as error:
|
|
194
|
+
record.done(error)
|
|
195
|
+
raise
|
|
196
|
+
|
|
197
|
+
async def aclose(self):
|
|
198
|
+
try:
|
|
199
|
+
await stream.aclose()
|
|
200
|
+
finally:
|
|
201
|
+
record.done()
|
|
202
|
+
|
|
203
|
+
else:
|
|
204
|
+
|
|
205
|
+
class RecordingStream(httpx.SyncByteStream):
|
|
206
|
+
def __iter__(self):
|
|
207
|
+
try:
|
|
208
|
+
for piece in stream:
|
|
209
|
+
record.chunk(piece)
|
|
210
|
+
yield piece
|
|
211
|
+
record.done()
|
|
212
|
+
except BaseException as error:
|
|
213
|
+
record.done(error)
|
|
214
|
+
raise
|
|
215
|
+
|
|
216
|
+
def close(self):
|
|
217
|
+
try:
|
|
218
|
+
stream.close()
|
|
219
|
+
finally:
|
|
220
|
+
record.done()
|
|
221
|
+
|
|
222
|
+
return RecordingStream()
|
|
223
|
+
|
|
224
|
+
|
|
225
|
+
def _patch_transports(httpx):
|
|
226
|
+
original_sync, original_async = httpx.HTTPTransport.handle_request, httpx.AsyncHTTPTransport.handle_async_request
|
|
227
|
+
|
|
228
|
+
def start_record(request):
|
|
229
|
+
try:
|
|
230
|
+
if _is_model_call(request.url.host, request.url.path) and _capture_is_on():
|
|
231
|
+
return CallRecord(httpx.__name__, request)
|
|
232
|
+
except Exception as error:
|
|
233
|
+
_write_status("hook_error", error=repr(error))
|
|
234
|
+
return None
|
|
235
|
+
|
|
236
|
+
def attach(record, response, is_async):
|
|
237
|
+
try:
|
|
238
|
+
record.response(response)
|
|
239
|
+
response.stream = _tee_stream(httpx, record, response.stream, is_async)
|
|
240
|
+
except Exception as error:
|
|
241
|
+
_write_status("hook_error", error=repr(error))
|
|
242
|
+
|
|
243
|
+
def handle_request(self, request):
|
|
244
|
+
record = start_record(request)
|
|
245
|
+
try:
|
|
246
|
+
response = original_sync(self, request)
|
|
247
|
+
except BaseException as error:
|
|
248
|
+
if record:
|
|
249
|
+
record.done(error)
|
|
250
|
+
raise
|
|
251
|
+
if record:
|
|
252
|
+
attach(record, response, False)
|
|
253
|
+
return response
|
|
254
|
+
|
|
255
|
+
async def handle_async_request(self, request):
|
|
256
|
+
record = start_record(request)
|
|
257
|
+
try:
|
|
258
|
+
response = await original_async(self, request)
|
|
259
|
+
except BaseException as error:
|
|
260
|
+
if record:
|
|
261
|
+
record.done(error)
|
|
262
|
+
raise
|
|
263
|
+
if record:
|
|
264
|
+
attach(record, response, True)
|
|
265
|
+
return response
|
|
266
|
+
|
|
267
|
+
httpx.HTTPTransport.handle_request = handle_request
|
|
268
|
+
httpx.AsyncHTTPTransport.handle_async_request = handle_async_request
|
|
269
|
+
|
|
270
|
+
|
|
271
|
+
def _patch_when_imported(library_name):
|
|
272
|
+
"""Patch the library right after its first import, or now when it is already imported."""
|
|
273
|
+
if library_name in sys.modules:
|
|
274
|
+
_patch_transports(sys.modules[library_name])
|
|
275
|
+
return
|
|
276
|
+
|
|
277
|
+
class PatchAfterImport(importlib.abc.MetaPathFinder):
|
|
278
|
+
def find_spec(self, name, path, target=None):
|
|
279
|
+
if name != library_name:
|
|
280
|
+
return None
|
|
281
|
+
sys.meta_path.remove(self)
|
|
282
|
+
spec = importlib.util.find_spec(name)
|
|
283
|
+
if spec is None or spec.loader is None:
|
|
284
|
+
return spec
|
|
285
|
+
real_exec = spec.loader.exec_module
|
|
286
|
+
|
|
287
|
+
def exec_then_patch(module):
|
|
288
|
+
real_exec(module)
|
|
289
|
+
try:
|
|
290
|
+
_patch_transports(module)
|
|
291
|
+
except Exception as error:
|
|
292
|
+
_write_status("hook_error", error=repr(error))
|
|
293
|
+
|
|
294
|
+
spec.loader.exec_module = exec_then_patch
|
|
295
|
+
return spec
|
|
296
|
+
|
|
297
|
+
sys.meta_path.insert(0, PatchAfterImport())
|
|
298
|
+
|
|
299
|
+
|
|
300
|
+
def _audit(event, args):
|
|
301
|
+
"""A model call through http.client (urllib, requests) never touches httpx: say so, once."""
|
|
302
|
+
try:
|
|
303
|
+
if (
|
|
304
|
+
event == "http.client.send"
|
|
305
|
+
and not _counts["bypass_announced"]
|
|
306
|
+
and re.match(rb"(POST|PUT) \S*/v1/messages[ ?]", args[1][:300])
|
|
307
|
+
and _capture_is_on()
|
|
308
|
+
):
|
|
309
|
+
_counts["bypass_announced"] = True
|
|
310
|
+
_write_status("bypass", reason="model call through http.client, not captured")
|
|
311
|
+
except Exception:
|
|
312
|
+
pass
|
|
313
|
+
|
|
314
|
+
|
|
315
|
+
def _install():
|
|
316
|
+
for library_name in HTTP_LIBRARIES:
|
|
317
|
+
_patch_when_imported(library_name)
|
|
318
|
+
sys.addaudithook(_audit)
|
|
319
|
+
_capture_is_on() # the variable already set at load (a shell's export): the capture starts now, `load` line included
|
|
320
|
+
|
|
321
|
+
|
|
322
|
+
_install()
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "graph-bench",
|
|
3
|
-
"version": "0.1.
|
|
3
|
+
"version": "0.1.6",
|
|
4
4
|
"description": "A local development bench for LangGraph projects: watch runs, every model call, cost and cache, and experiment on calls.",
|
|
5
5
|
"keywords": [
|
|
6
6
|
"langgraph",
|
|
@@ -20,11 +20,11 @@
|
|
|
20
20
|
"gbench": "bin/gbench.cjs"
|
|
21
21
|
},
|
|
22
22
|
"optionalDependencies": {
|
|
23
|
-
"@graph-bench/win32-x64": "0.1.
|
|
24
|
-
"@graph-bench/darwin-x64": "0.1.
|
|
25
|
-
"@graph-bench/darwin-arm64": "0.1.
|
|
26
|
-
"@graph-bench/linux-x64": "0.1.
|
|
27
|
-
"@graph-bench/linux-arm64": "0.1.
|
|
23
|
+
"@graph-bench/win32-x64": "0.1.6",
|
|
24
|
+
"@graph-bench/darwin-x64": "0.1.6",
|
|
25
|
+
"@graph-bench/darwin-arm64": "0.1.6",
|
|
26
|
+
"@graph-bench/linux-x64": "0.1.6",
|
|
27
|
+
"@graph-bench/linux-arm64": "0.1.6"
|
|
28
28
|
},
|
|
29
29
|
"engines": {
|
|
30
30
|
"node": ">=18"
|