argus-bench 0.1.0__tar.gz

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 The ARGUS authors
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
@@ -0,0 +1,45 @@
1
+ Metadata-Version: 2.3
2
+ Name: argus-bench
3
+ Version: 0.1.0
4
+ Summary: Record every model call (what the model saw, what it said) of an agent run in one unified JSONL format, for any inference library.
5
+ Author: The ARGUS authors
6
+ License: MIT
7
+ Keywords: agents,benchmark,llm,logging,rollouts,sglang,vllm
8
+ Classifier: Intended Audience :: Science/Research
9
+ Classifier: License :: OSI Approved :: MIT License
10
+ Classifier: Programming Language :: Python :: 3
11
+ Classifier: Topic :: Scientific/Engineering :: Artificial Intelligence
12
+ Requires-Python: >=3.9
13
+ Provides-Extra: test
14
+ Requires-Dist: openai; extra == 'test'
15
+ Requires-Dist: pytest; extra == 'test'
16
+ Description-Content-Type: text/markdown
17
+
18
+ # argus-bench
19
+
20
+ Record every model call of an agent run, whatever inference library runs the model, in one plain JSON Lines file.
21
+ For each call it stores what the model was shown and what it produced.
22
+
23
+ ```
24
+ pip install argus-bench
25
+ ```
26
+
27
+ ```python
28
+ import argus_bench
29
+ argus_bench.record_to("rollout.jsonl", revision="<full model commit hash>", library="vllm 0.23.0 (server)",
30
+ dtype="bfloat16", quantization="none", chat_template="default")
31
+ # ... run your agent as usual: every OpenAI-SDK chat call (vLLM, SGLang, llama.cpp, Ollama, LiteLLM, LangChain; sync, async, streaming) is recorded
32
+ ```
33
+
34
+ Model runs inside your own process (transformers, vLLM `LLM`, SGLang `Engine`, llama-cpp-python)? One call after each generation:
35
+
36
+ ```python
37
+ argus_bench.log(messages, generated_text, tools=tools, model="Qwen/Qwen3-1.7B", sampling={"temperature": 0.7, "top_p": 0.95})
38
+ ```
39
+
40
+ Agent you cannot edit, or one that runs in a container? Set `ARGUS_BENCH_LOG=/path/rollout.jsonl` in its environment.
41
+ Check the result with `argus-bench check rollout.jsonl`.
42
+
43
+ * [docs/USAGE.md](docs/USAGE.md): how to record with every supported way of running a model
44
+ * [docs/FORMAT.md](docs/FORMAT.md): the exact file format, so you can produce it without this package
45
+ * [docs/TESTED.md](docs/TESTED.md): what has and has not been tested
@@ -0,0 +1,28 @@
1
+ # argus-bench
2
+
3
+ Record every model call of an agent run, whatever inference library runs the model, in one plain JSON Lines file.
4
+ For each call it stores what the model was shown and what it produced.
5
+
6
+ ```
7
+ pip install argus-bench
8
+ ```
9
+
10
+ ```python
11
+ import argus_bench
12
+ argus_bench.record_to("rollout.jsonl", revision="<full model commit hash>", library="vllm 0.23.0 (server)",
13
+ dtype="bfloat16", quantization="none", chat_template="default")
14
+ # ... run your agent as usual: every OpenAI-SDK chat call (vLLM, SGLang, llama.cpp, Ollama, LiteLLM, LangChain; sync, async, streaming) is recorded
15
+ ```
16
+
17
+ Model runs inside your own process (transformers, vLLM `LLM`, SGLang `Engine`, llama-cpp-python)? One call after each generation:
18
+
19
+ ```python
20
+ argus_bench.log(messages, generated_text, tools=tools, model="Qwen/Qwen3-1.7B", sampling={"temperature": 0.7, "top_p": 0.95})
21
+ ```
22
+
23
+ Agent you cannot edit, or one that runs in a container? Set `ARGUS_BENCH_LOG=/path/rollout.jsonl` in its environment.
24
+ Check the result with `argus-bench check rollout.jsonl`.
25
+
26
+ * [docs/USAGE.md](docs/USAGE.md): how to record with every supported way of running a model
27
+ * [docs/FORMAT.md](docs/FORMAT.md): the exact file format, so you can produce it without this package
28
+ * [docs/TESTED.md](docs/TESTED.md): what has and has not been tested
@@ -0,0 +1 @@
1
+ import os; os.environ.get("ARGUS_BENCH_LOG") and __import__("argus_bench._auto", fromlist=["start"]).start()
@@ -0,0 +1,105 @@
1
+ # The rollout file format
2
+
3
+ Everything `argus-bench` writes is one plain text file in **JSON Lines** format: UTF-8, one JSON object per line, append-only.
4
+ You do not need the package to produce it. Any program that writes this format is a valid submission.
5
+
6
+ The file holds one **rollout** (one agent run). It consists of header lines followed by one **record per model call**.
7
+
8
+ ## Header line
9
+
10
+ ```json
11
+ {"header": {"argus_bench": "0.1.0", "python": "3.12.7", "started": 1794397938.55,
12
+ "rollout_id": "task-17-run-3", "revision": "c1899de289a04d12100db370d81485cdf75e47ca",
13
+ "library": "vllm 0.23.0 (server)", "dtype": "bfloat16", "quantization": "none", "chat_template": "default"}}
14
+ ```
15
+
16
+ A line is a header line if its only key is `header`. Several header lines may exist (one per process that wrote to the file); readers merge them.
17
+ Put every fact about the *run* here, not in the records.
18
+
19
+ | key | meaning | required |
20
+ |---|---|---|
21
+ | `rollout_id` | your identifier for this rollout | recommended |
22
+ | `revision` | the full 40-character Hugging Face commit hash of the weights (not a branch, not a short hash) | yes, if the model is on the Hub |
23
+ | `library` | inference library and version, and how it was run (`vllm 0.23.0 (server)`, `transformers 5.22 (in-process)`, ...) | yes |
24
+ | `dtype` | numeric precision the model ran in (`bfloat16`, `float16`, `float32`) | yes |
25
+ | `quantization` | `"none"`, or what was used (`"gguf-q4_k_m"`, `"awq"`, `"fp8"`, ...) | yes |
26
+ | `chat_template` | `"default"` if the library used the model's own chat template, else a name or hash of the template you used | yes |
27
+ | `argus_bench`, `python`, `started`, `openai_sdk` | written automatically by the package; leave out if you write the file yourself | no |
28
+
29
+ Any additional keys are allowed.
30
+
31
+ ## Record line (one per model call)
32
+
33
+ ```json
34
+ {"t": 1794397941.88,
35
+ "model": "Qwen/Qwen3-1.7B",
36
+ "messages": [{"role": "system", "content": "You are a shell agent."},
37
+ {"role": "user", "content": "List the files and tell me how many there are."}],
38
+ "tools": [{"type": "function", "function": {"name": "bash", "description": "Run a shell command",
39
+ "parameters": {"type": "object", "properties": {"command": {"type": "string"}}, "required": ["command"]}}}],
40
+ "sampling": {"temperature": 0.7, "top_p": 0.95, "top_k": 20, "max_tokens": 300, "seed": 7},
41
+ "output": {"reasoning_content": "The user wants...", "content": "",
42
+ "tool_calls": [{"id": "call_1", "name": "bash", "arguments": "{\"command\": \"ls\"}"}]},
43
+ "finish_reason": "tool_calls",
44
+ "env_state": {"step": 1}}
45
+ ```
46
+
47
+ | field | type | meaning |
48
+ |---|---|---|
49
+ | `t` | number | unix time (seconds) of the call |
50
+ | `model` | string | the model name that was asked for (`Qwen/Qwen3-1.7B`) |
51
+ | `messages` | list | **the complete input the model was shown for this call**, OpenAI chat format (see below). Never a diff against the previous call. |
52
+ | `tools` | list or null | the tool definitions the model was given, OpenAI function-tool format |
53
+ | `sampling` | object | every sampling setting that was in effect and that you know: `temperature`, `top_p`, `top_k`, `min_p`, `max_tokens`, `seed`, `repetition_penalty`, `presence_penalty`, `frequency_penalty`, `stop`. Leave out what you did not set. |
54
+ | `output` | object | what the model produced, see below. Must contain at least one of its keys. |
55
+ | `finish_reason` | string | `stop`, `length` (cut off by the token limit), `tool_calls`, ... as your library reports it. Recommended; it matters for `length`. |
56
+ | `env_state` | any JSON | optional: state of the environment at the start of this call (see below) |
57
+ | `stream` | boolean | optional: `true` if the call was streamed (the package sets it) |
58
+ | `source` | string | optional: set by the package (`openai-sdk`) |
59
+
60
+ ### `messages`
61
+
62
+ OpenAI chat format, in the order the model saw them, including everything the agent added since the last call:
63
+
64
+ ```json
65
+ [{"role": "system", "content": "..."},
66
+ {"role": "user", "content": "..."},
67
+ {"role": "assistant", "content": "", "tool_calls": [{"id": "call_1", "type": "function", "function": {"name": "bash", "arguments": "{\"command\": \"ls\"}"}}]},
68
+ {"role": "tool", "tool_call_id": "call_1", "content": "a.txt\nb.txt"}]
69
+ ```
70
+
71
+ The assistant turns inside `messages` are the model's earlier outputs as the agent resent them. Write them the way they were sent to the model,
72
+ including any rewriting the agent did (e.g. reasoning removed, content trimmed).
73
+
74
+ ### `output`
75
+
76
+ What the model produced in *this* call, as separate fields. Leave out empty ones.
77
+
78
+ | key | meaning |
79
+ |---|---|
80
+ | `content` | the visible text. If your server does not split reasoning from text, put everything the model wrote here, exactly as generated (including any `<think>...</think>`). |
81
+ | `reasoning_content` | the reasoning text, only if your server returned it separately |
82
+ | `tool_calls` | list of `{"id": ..., "name": ..., "arguments": ...}`. `arguments` is the **string** the model produced, kept as-is even if it is not valid JSON. If your library does not parse tool calls, leave them inside `content` as raw text. |
83
+
84
+ Write the model's text exactly as it came out. Do not trim, normalise, pretty-print or re-serialise it.
85
+
86
+ ## Rules
87
+
88
+ 1. One record per model call, in call order. If a call returns several choices (`n > 1`), write one record per choice.
89
+ 2. A streamed call is one record: the final assembled message.
90
+ 3. Every record is self-contained (`messages` is the whole input). **Context compaction needs no special handling**: after the agent compacts,
91
+ the next record simply has a shorter or different `messages`. There is no compaction marker.
92
+ 4. Calls that failed with an error (no output) are not recorded.
93
+ 5. Subagents, parallel branches and several processes may write into the same file; each record stands on its own. Write each line with a single
94
+ write call so lines from different processes do not interleave.
95
+ 6. `env_state` is whatever you declare it to be (a dict of facts, a hash, a file path). It is opaque, self-reported and should stay small;
96
+ keep large state in a separate file and record the path or hash.
97
+
98
+ ## Minimal valid file
99
+
100
+ ```
101
+ {"header": {"library": "my-engine 1.0", "revision": "c1899de289a04d12100db370d81485cdf75e47ca", "dtype": "bfloat16", "quantization": "none", "chat_template": "default"}}
102
+ {"model": "Qwen/Qwen3-1.7B", "messages": [{"role": "user", "content": "Hi"}], "sampling": {"temperature": 0.7}, "output": {"content": "Hello!"}, "finish_reason": "stop"}
103
+ ```
104
+
105
+ Check a file with `argus-bench check rollout.jsonl` (needs the package; no model, no network).
@@ -0,0 +1,134 @@
1
+ # Using argus-bench
2
+
3
+ ```
4
+ pip install argus-bench # pure Python, no dependencies
5
+ ```
6
+
7
+ Pick the row that matches how your agent calls the model. All of them write the same file ([FORMAT.md](FORMAT.md)).
8
+
9
+ | how the model is run | what you do |
10
+ |---|---|
11
+ | a server with an OpenAI-compatible API (vLLM, SGLang, llama.cpp / llama-cpp-python server, Ollama, LM Studio, TGI, LiteLLM proxy, a hosted API) and the agent uses the `openai` Python package (directly, or through LiteLLM, LangChain, ...) | [A. one line, `record_to`](#a-openai-compatible-server) |
12
+ | same, but the agent is a program you cannot edit, or runs in another process or container | [B. environment variable](#b-agent-you-cannot-edit-subprocess-container) |
13
+ | the model runs inside your own Python process (transformers, vLLM `LLM`, SGLang `Engine`, llama-cpp-python, your own loop) | [C. `log()` after each generation](#c-model-runs-in-your-process) |
14
+ | anything else (another language, raw HTTP, another SDK) | [D. write the file yourself](#d-anything-else) |
15
+
16
+ Always declare what you know about the run: `revision` (full commit hash), `library`, `dtype`, `quantization`, `chat_template`, `rollout_id`.
17
+ `argus-bench check` warns about missing ones.
18
+
19
+ ## A. OpenAI-compatible server
20
+
21
+ Add this before the agent starts, in the process that makes the model calls:
22
+
23
+ ```python
24
+ import argus_bench
25
+ argus_bench.record_to("rollout.jsonl",
26
+ rollout_id="task-17-run-3",
27
+ revision="<full 40-char hf commit hash of the weights>",
28
+ library="vllm 0.23.0 (server)", dtype="bfloat16", quantization="none", chat_template="default")
29
+ ```
30
+
31
+ Everything the `openai` package sends to `/chat/completions` from then on is recorded: `client.chat.completions.create`, `with_raw_response`,
32
+ sync, async and streaming, and libraries built on the SDK (LiteLLM, LangChain, Agents SDK). Your code gets the normal responses back, unchanged.
33
+ Nothing else about how you start or call the server changes.
34
+
35
+ Notes:
36
+ * The model server does not need any flag or plugin.
37
+ * It hooks one internal function of the `openai` package. Capture tests pass on openai 1.6.1 up to 3.x. If a future version breaks the hook,
38
+ `record_to` prints a warning, and at program exit another warning appears if no call was recorded.
39
+ * Only `/chat/completions` is recorded. The Responses API is not.
40
+ * The server must return reasoning in `reasoning_content` (vLLM: `--reasoning-parser`, SGLang: `--reasoning-parser`) to have it recorded separately.
41
+ Otherwise it stays inside `content`, which is fine.
42
+
43
+ ## B. Agent you cannot edit (subprocess, container)
44
+
45
+ Install `argus-bench` in the Python environment the agent runs in and set environment variables for its process:
46
+
47
+ ```
48
+ ARGUS_BENCH_LOG=/path/rollout.jsonl
49
+ ARGUS_BENCH_META='{"revision": "<hash>", "library": "vllm 0.23.0 (server)", "dtype": "bfloat16", "quantization": "none", "chat_template": "default"}'
50
+ ```
51
+
52
+ Every Python process started with those variables records its `openai` calls to the file (the package ships a `.pth` file that starts the
53
+ recording at interpreter start-up). Several processes can write to the same file. Processes that make no model call write nothing.
54
+ This is the same as route A, so the same notes apply.
55
+
56
+ ## C. Model runs in your process
57
+
58
+ Call `argus_bench.log(messages, output, ...)` after each generation. `messages` is the full chat input the model got; `output` is the generated
59
+ text, or a dict `{"content", "reasoning_content", "tool_calls"}`.
60
+
61
+ ```python
62
+ argus_bench.record_to("rollout.jsonl", revision="<hash>", library="transformers 5.22 (in-process)", dtype="bfloat16",
63
+ quantization="none", chat_template="default", rollout_id="task-17-run-3")
64
+ ```
65
+
66
+ **transformers**
67
+ ```python
68
+ ids = tok.apply_chat_template(messages, tools=tools, add_generation_prompt=True, return_tensors="pt", return_dict=True).to(model.device)
69
+ gen = model.generate(**ids, do_sample=True, temperature=0.7, top_p=0.95, top_k=20, max_new_tokens=300)
70
+ text = tok.decode(gen[0, ids["input_ids"].shape[1]:], skip_special_tokens=True)
71
+ argus_bench.log(messages, text, tools=tools, model="Qwen/Qwen3-1.7B",
72
+ sampling={"temperature": 0.7, "top_p": 0.95, "top_k": 20, "max_tokens": 300})
73
+ ```
74
+
75
+ **vLLM offline (`LLM`)**
76
+ ```python
77
+ sp = SamplingParams(temperature=0.7, top_p=0.95, top_k=20, max_tokens=300, seed=7)
78
+ out = llm.chat(messages, sp, tools=tools)[0].outputs[0]
79
+ argus_bench.log(messages, out.text, tools=tools, model="Qwen/Qwen3-1.7B",
80
+ sampling={"temperature": 0.7, "top_p": 0.95, "top_k": 20, "max_tokens": 300, "seed": 7},
81
+ finish_reason=out.finish_reason)
82
+ ```
83
+
84
+ **SGLang `Engine`**
85
+ ```python
86
+ ids = tok.apply_chat_template(messages, tools=tools, add_generation_prompt=True, tokenize=True, return_dict=True)["input_ids"]
87
+ o = engine.generate(input_ids=list(ids), sampling_params={"temperature": 0.7, "top_p": 0.95, "top_k": 20, "max_new_tokens": 300})
88
+ argus_bench.log(messages, o["text"], tools=tools, model="Qwen/Qwen3-1.7B",
89
+ sampling={"temperature": 0.7, "top_p": 0.95, "top_k": 20, "max_tokens": 300})
90
+ ```
91
+
92
+ **llama-cpp-python (`Llama`)**
93
+ ```python
94
+ r = llm.create_chat_completion(messages=messages, tools=tools, temperature=0.7, top_p=0.95, max_tokens=300)
95
+ m = r["choices"][0]["message"]
96
+ argus_bench.log(messages, {"content": m.get("content"), "tool_calls": [{"id": t["id"], "name": t["function"]["name"], "arguments": t["function"]["arguments"]} for t in m.get("tool_calls", [])]},
97
+ tools=tools, model="Qwen/Qwen3-1.7B", sampling={"temperature": 0.7, "top_p": 0.95, "max_tokens": 300}, finish_reason=r["choices"][0]["finish_reason"])
98
+ ```
99
+
100
+ If your code does not parse tool calls or reasoning, pass the raw generated text as `output`; do not strip or reformat it.
101
+ Extra keyword arguments to `log` (such as `finish_reason=`) are written into the record.
102
+
103
+ ## D. Anything else
104
+
105
+ Write the JSON Lines file yourself. [FORMAT.md](FORMAT.md) is the full specification and has a minimal example.
106
+
107
+ ## Environment state (optional)
108
+
109
+ If you want to record what the environment looked like at each call, declare it once:
110
+
111
+ ```python
112
+ argus_bench.env_state(lambda: {"files": sorted(os.listdir(workdir)), "git_head": git_head()}) # function, called at the start of every model call
113
+ argus_bench.env_state({"task": "fix-bug-12"}) # or a fixed value
114
+ ```
115
+
116
+ The value ends up as `env_state` on every record. It is evaluated in the process that called `record_to`, so that process must be able to see the
117
+ environment (read the files, or ask the sandbox). With route B (environment variables) there is no code to declare it in, so use a function that
118
+ reads a state file your harness keeps up to date, or pass `env_state=` to `log`.
119
+
120
+ ## Check your file
121
+
122
+ ```
123
+ argus-bench check rollout.jsonl
124
+ rollout.jsonl: 4 calls {"models": ["Qwen/Qwen3-1.7B"], "calls_extending_previous": 2, "calls_with_new_context (compaction / new thread)": 1}
125
+ OK
126
+ ```
127
+
128
+ It reports problems (no messages, empty output), warnings (missing header declarations, tool-call arguments that are not valid JSON,
129
+ missing sampling settings) and how many calls continue the previous call's input vs. start a new context (compaction, a new conversation, or a
130
+ parallel thread). No model and no network needed. Exit code 1 if there are problems.
131
+
132
+ ## What was tested
133
+
134
+ See [TESTED.md](TESTED.md).
@@ -0,0 +1,27 @@
1
+ [build-system]
2
+ requires = ["hatchling>=1.21,<1.27"]
3
+ build-backend = "hatchling.build"
4
+
5
+ [project]
6
+ name = "argus-bench"
7
+ version = "0.1.0"
8
+ description = "Record every model call (what the model saw, what it said) of an agent run in one unified JSONL format, for any inference library."
9
+ readme = "README.md"
10
+ license = { text = "MIT" }
11
+ authors = [{ name = "The ARGUS authors" }]
12
+ keywords = ["llm", "rollouts", "logging", "agents", "vllm", "sglang", "benchmark"]
13
+ classifiers = ["License :: OSI Approved :: MIT License", "Programming Language :: Python :: 3", "Intended Audience :: Science/Research", "Topic :: Scientific/Engineering :: Artificial Intelligence"]
14
+ requires-python = ">=3.9"
15
+ dependencies = []
16
+
17
+ [project.optional-dependencies]
18
+ test = ["pytest", "openai"]
19
+
20
+ [project.scripts]
21
+ argus-bench = "argus_bench.cli:main"
22
+
23
+ [tool.hatch.build.targets.wheel]
24
+ packages = ["src/argus_bench"]
25
+
26
+ [tool.hatch.build.targets.wheel.force-include]
27
+ "argus_bench.pth" = "argus_bench.pth"
@@ -0,0 +1,327 @@
1
+ """argus_bench: write down what a model was shown and what it said, one JSON line per model call.
2
+
3
+ import argus_bench
4
+ argus_bench.record_to("rollout.jsonl") # every OpenAI-SDK chat call from here on is logged (sync, async, streaming)
5
+
6
+ argus_bench.log(messages, output, tools=tools, model="Qwen/Qwen3-1.7B") # anything else: one call, two values
7
+
8
+ No model, library or server specific flags. Nothing to configure per library. Check the file with `argus-bench check rollout.jsonl`.
9
+ If the agent runs in another process or container and you cannot edit its code, set ARGUS_BENCH_LOG=/path/rollout.jsonl in its environment instead
10
+ (optionally ARGUS_BENCH_META='{"revision": "..."}'); the installed package then starts recording in every Python process there.
11
+ """
12
+ import functools
13
+ import inspect
14
+ import json
15
+ import os
16
+ import platform
17
+ import threading
18
+ import time
19
+ import warnings
20
+ import atexit
21
+
22
+ __version__ = "0.1.0"
23
+ __all__ = ["record_to", "log", "env_state", "stop"]
24
+
25
+ SAMPLING_KEYS = ("temperature", "top_p", "top_k", "min_p", "max_tokens", "max_completion_tokens", "seed", "repetition_penalty",
26
+ "presence_penalty", "frequency_penalty", "stop")
27
+ _S = {"path": None, "lock": threading.Lock(), "meta": {}, "n": 0, "env": None, "hooked": False}
28
+
29
+
30
+ # ------------------------------------------------------------------ writing
31
+ def _jsonable(x):
32
+ if hasattr(x, "model_dump"):
33
+ return x.model_dump(exclude_none=True)
34
+ if isinstance(x, dict):
35
+ return {k: _jsonable(v) for k, v in x.items()}
36
+ if isinstance(x, (list, tuple)):
37
+ return [_jsonable(v) for v in x]
38
+ if isinstance(x, (str, int, float, bool)) or x is None:
39
+ return x
40
+ return str(x)
41
+
42
+
43
+ def _write(rec):
44
+ if not _S["path"]:
45
+ return
46
+ _S["n"] += 1
47
+ with _S["lock"]:
48
+ h = _S.pop("header", None)
49
+ data = (json.dumps(_jsonable(h), ensure_ascii=False) + "\n" if h else "") + json.dumps(_jsonable(rec), ensure_ascii=False) + "\n"
50
+ fd = os.open(_S["path"], os.O_WRONLY | os.O_APPEND | os.O_CREAT, 0o644) # one write() call: lines from several processes never interleave
51
+ try:
52
+ os.write(fd, data.encode("utf-8"))
53
+ finally:
54
+ os.close(fd)
55
+
56
+
57
+ def record_to(path, _quiet=False, **meta):
58
+ """Start appending one record per model call to `path`. `meta` goes in the header. Declare what you can:
59
+ revision="<full hf commit hash>", rollout_id="...", library="vllm 0.23", quantization="none" | "gguf-q4_k_m" | ...,
60
+ chat_template="default" | "<name or hash of a custom template>", dtype="bfloat16"."""
61
+ _S["path"], _S["meta"], _S["n"], _S["quiet"] = os.fspath(path), meta, 0, _quiet
62
+ header = {"header": {"argus_bench": __version__, "python": platform.python_version(), "started": time.time(), **meta}}
63
+ try:
64
+ import openai
65
+ header["header"]["openai_sdk"] = openai.__version__
66
+ except ImportError:
67
+ pass
68
+ _S["header"] = header # written together with the first record, so processes that make no model call leave no trace
69
+ _patch_openai()
70
+
71
+
72
+ def stop():
73
+ _S["path"] = None
74
+
75
+
76
+ def env_state(state):
77
+ """Declare the environment state to attach to every following call, as a JSON-able value or a zero-argument function.
78
+ A function is called at the START of each model call (so state that changes between calls is captured when the OpenAI hook is used);
79
+ with log() it is called when you log. Pass None to stop. Keep it small: put big state in a file and record its path or hash here."""
80
+ _S["env"] = state
81
+
82
+
83
+ def _env():
84
+ e = _S["env"]
85
+ if e is None:
86
+ return None, False
87
+ try:
88
+ return (e() if callable(e) else e), True
89
+ except Exception as ex:
90
+ return f"env_state error: {ex!r}", True
91
+
92
+
93
+ def _no_calls_warning():
94
+ if _S["path"] and _S["n"] == 0 and not _S.get("quiet"):
95
+ warnings.warn(f"argus_bench: record_to({_S['path']!r}) was called but no model call was recorded. Is the model called through the "
96
+ "openai Python SDK /chat/completions in this process? Otherwise call argus_bench.log(...) yourself.", stacklevel=1)
97
+
98
+
99
+ atexit.register(_no_calls_warning)
100
+
101
+
102
+ def _norm_output(output):
103
+ if isinstance(output, str):
104
+ return {"content": output}
105
+ out = dict(output)
106
+ return {k: v for k, v in out.items() if v not in (None, "", [])}
107
+
108
+
109
+ def log(messages, output, tools=None, model=None, sampling=None, **extra):
110
+ """Log one model call. `messages`: the chat messages the model was given (OpenAI format). `output`: the generated text, or a dict with
111
+ content / reasoning_content / tool_calls. `sampling`: temperature, top_p, ... if you know them. Without a prior record_to(), call
112
+ argus_bench.record_to(path) first. An `env_state=` keyword overrides the value set with argus_bench.env_state()."""
113
+ if "env_state" not in extra:
114
+ v, on = _env()
115
+ if on:
116
+ extra["env_state"] = v
117
+ _write({"t": time.time(), "model": model, "messages": messages, "tools": tools, "sampling": sampling or {},
118
+ "output": _norm_output(output), **extra})
119
+
120
+
121
+ # ------------------------------------------------------------------ OpenAI SDK hook
122
+ def _request_fields(kw):
123
+ s = {k: kw[k] for k in SAMPLING_KEYS if kw.get(k) is not None}
124
+ for k, v in (kw.get("extra_body") or {}).items():
125
+ if k in SAMPLING_KEYS:
126
+ s[k] = v
127
+ rec = {"model": kw.get("model"), "messages": kw.get("messages"), "tools": kw.get("tools") or None, "sampling": s}
128
+ if "__env_state" in kw:
129
+ rec["env_state"] = kw["__env_state"]
130
+ return rec
131
+
132
+
133
+ def _msg_output(m):
134
+ extra = getattr(m, "model_extra", None) or {}
135
+ out = {"content": getattr(m, "content", None), "reasoning_content": extra.get("reasoning_content") or extra.get("reasoning")}
136
+ calls = getattr(m, "tool_calls", None)
137
+ if calls:
138
+ out["tool_calls"] = [{"id": c.id, "name": c.function.name, "arguments": c.function.arguments} for c in calls]
139
+ return _norm_output(out)
140
+
141
+
142
+ def _log_completion(kw, res):
143
+ for ch in getattr(res, "choices", None) or []:
144
+ _write({"t": time.time(), **_request_fields(kw), "output": _msg_output(ch.message), "finish_reason": ch.finish_reason,
145
+ "source": "openai-sdk"})
146
+
147
+
148
+ class _Acc:
149
+ """Rebuilds the final message from streamed chunks."""
150
+
151
+ def __init__(self, kw):
152
+ self.kw, self.content, self.reasoning, self.calls, self.finish, self.done = kw, [], [], {}, None, False
153
+
154
+ def add(self, chunk):
155
+ for ch in getattr(chunk, "choices", None) or []:
156
+ d = ch.delta
157
+ extra = getattr(d, "model_extra", None) or {}
158
+ if d.content:
159
+ self.content.append(d.content)
160
+ r = extra.get("reasoning_content") or extra.get("reasoning")
161
+ if r:
162
+ self.reasoning.append(r)
163
+ for tc in d.tool_calls or []:
164
+ c = self.calls.setdefault(tc.index, {"id": None, "name": "", "arguments": ""})
165
+ c["id"] = tc.id or c["id"]
166
+ if tc.function:
167
+ c["name"] += tc.function.name or ""
168
+ c["arguments"] += tc.function.arguments or ""
169
+ self.finish = ch.finish_reason or self.finish
170
+
171
+ def flush(self):
172
+ if self.done:
173
+ return
174
+ self.done = True
175
+ out = _norm_output({"content": "".join(self.content), "reasoning_content": "".join(self.reasoning),
176
+ "tool_calls": [self.calls[i] for i in sorted(self.calls)]})
177
+ _write({"t": time.time(), **_request_fields(self.kw), "output": out, "finish_reason": self.finish, "source": "openai-sdk", "stream": True})
178
+
179
+
180
+ class _TeeStream:
181
+ """Behaves like the SDK's Stream: iterable, an iterator (LiteLLM calls next()), a context manager, closable."""
182
+
183
+ def __init__(self, stream, kw):
184
+ self._s, self._it, self._a = stream, None, _Acc(kw)
185
+
186
+ def __iter__(self):
187
+ return self
188
+
189
+ def __next__(self):
190
+ if self._it is None:
191
+ self._it = iter(self._s)
192
+ try:
193
+ chunk = next(self._it)
194
+ except BaseException:
195
+ self._a.flush()
196
+ raise
197
+ self._a.add(chunk)
198
+ return chunk
199
+
200
+ def __enter__(self):
201
+ self._s.__enter__()
202
+ return self
203
+
204
+ def __exit__(self, *a):
205
+ self._a.flush()
206
+ return self._s.__exit__(*a)
207
+
208
+ def close(self):
209
+ self._a.flush()
210
+ return self._s.close()
211
+
212
+ def __del__(self):
213
+ try:
214
+ self._a.flush() # consumer stopped early without closing: still log what the model produced
215
+ except Exception:
216
+ pass
217
+
218
+ def __getattr__(self, name):
219
+ return getattr(self._s, name)
220
+
221
+
222
+ class _TeeAsyncStream(_TeeStream):
223
+ def __aiter__(self):
224
+ return self
225
+
226
+ async def __anext__(self):
227
+ if self._it is None:
228
+ self._it = self._s.__aiter__()
229
+ try:
230
+ chunk = await self._it.__anext__()
231
+ except BaseException:
232
+ self._a.flush()
233
+ raise
234
+ self._a.add(chunk)
235
+ return chunk
236
+
237
+ async def __aenter__(self):
238
+ await self._s.__aenter__()
239
+ return self
240
+
241
+ async def __aexit__(self, *a):
242
+ self._a.flush()
243
+ return await self._s.__aexit__(*a)
244
+
245
+ async def close(self):
246
+ self._a.flush()
247
+ return await self._s.close()
248
+
249
+
250
+ def _handle(kw, res):
251
+ """Log a parsed result (ChatCompletion or Stream) and return what the caller should get back."""
252
+ if kw.get("stream"):
253
+ return (_TeeAsyncStream if hasattr(res, "__aiter__") else _TeeStream)(res, kw)
254
+ _log_completion(kw, res)
255
+ return res
256
+
257
+
258
+ def _wrap_result(body, res, is_async):
259
+ """Log the parsed result (ChatCompletion or Stream); handle `with_raw_response`, where the parsed object only exists after .parse()."""
260
+ if hasattr(res, "parse") and not hasattr(res, "choices"):
261
+ parse, cache = res.parse, []
262
+
263
+ def parse_logged(*a, **k):
264
+ r = parse(*a, **k)
265
+ if inspect.isawaitable(r):
266
+ async def finish():
267
+ if not cache:
268
+ cache.append(_handle(body, await r))
269
+ return cache[0]
270
+ return finish()
271
+ if not cache:
272
+ cache.append(_handle(body, r))
273
+ return cache[0]
274
+ res.parse = parse_logged
275
+ return res
276
+ return _handle(body, res)
277
+
278
+
279
+ def _chat_body(args, kw):
280
+ options = kw.get("options") or (args[1] if len(args) > 1 else None)
281
+ url = str(getattr(options, "url", "") or "")
282
+ body = getattr(options, "json_data", None)
283
+ if not (url.rstrip("/").endswith("/chat/completions") and isinstance(body, dict)):
284
+ return None
285
+ return {**body, **(getattr(options, "extra_json", None) or {})} # extra_body fields (top_k, min_p, ...) are merged into the request
286
+
287
+
288
+ def _patch_openai():
289
+ """Patch the SDK's single HTTP entry point, so every way of calling chat completions is covered: client.chat.completions.create,
290
+ with_raw_response, client.post(...) (LiteLLM), LangChain, the Agents SDK's chat-completions model, sync / async / streaming."""
291
+ try:
292
+ import openai
293
+ except ImportError:
294
+ return # no openai SDK: only log() is available
295
+ try:
296
+ from openai._base_client import AsyncAPIClient, SyncAPIClient
297
+ assert callable(SyncAPIClient.request) and callable(AsyncAPIClient.request)
298
+ except Exception:
299
+ warnings.warn(f"argus_bench: cannot hook openai {getattr(openai, '__version__', '?')} (its internals changed). "
300
+ "Calls through the SDK will NOT be recorded; use argus_bench.log(...) instead.", stacklevel=3)
301
+ return
302
+ if getattr(SyncAPIClient.request, "_argus_bench", False):
303
+ return
304
+ sync_request, async_request = SyncAPIClient.request, AsyncAPIClient.request
305
+
306
+ @functools.wraps(sync_request)
307
+ def request(self, *args, **kw):
308
+ body = _chat_body(args, kw)
309
+ if body is not None:
310
+ v, on = _env()
311
+ if on:
312
+ body["__env_state"] = v
313
+ res = sync_request(self, *args, **kw)
314
+ return _wrap_result(body, res, False) if body is not None else res
315
+
316
+ @functools.wraps(async_request)
317
+ async def arequest(self, *args, **kw):
318
+ body = _chat_body(args, kw)
319
+ if body is not None:
320
+ v, on = _env()
321
+ if on:
322
+ body["__env_state"] = v
323
+ res = await async_request(self, *args, **kw)
324
+ return _wrap_result(body, res, True) if body is not None else res
325
+
326
+ request._argus_bench = arequest._argus_bench = True
327
+ SyncAPIClient.request, AsyncAPIClient.request = request, arequest
@@ -0,0 +1,15 @@
1
+ """Started by argus_bench.pth in every Python process whose environment has ARGUS_BENCH_LOG set."""
2
+ import json
3
+ import os
4
+
5
+
6
+ def start():
7
+ path = os.environ.get("ARGUS_BENCH_LOG")
8
+ if not path:
9
+ return
10
+ try:
11
+ meta = json.loads(os.environ.get("ARGUS_BENCH_META") or "{}")
12
+ except ValueError:
13
+ meta = {}
14
+ import argus_bench
15
+ argus_bench.record_to(path, _quiet=True, **meta)
@@ -0,0 +1,73 @@
1
+ """Structural check of a rollout file. No model needed."""
2
+ import json
3
+
4
+
5
+ def load(path):
6
+ header, recs = {}, []
7
+ for i, line in enumerate(open(path), 1):
8
+ if not line.strip():
9
+ continue
10
+ try:
11
+ obj = json.loads(line)
12
+ except json.JSONDecodeError as e:
13
+ raise ValueError(f"{path}:{i}: not valid JSON ({e})")
14
+ if "header" in obj:
15
+ header.update(obj["header"])
16
+ else:
17
+ recs.append(obj)
18
+ return header, recs
19
+
20
+
21
+ def _same(a, b):
22
+ return json.dumps(a, sort_keys=True, default=str) == json.dumps(b, sort_keys=True, default=str)
23
+
24
+
25
+ def check(path):
26
+ """Returns (problems, warnings, info)."""
27
+ header, recs = load(path)
28
+ problems, warnings, info = [], [], {}
29
+ if not recs:
30
+ return ["no model calls in file"], [], {}
31
+ for i, r in enumerate(recs):
32
+ w = f"call {i}"
33
+ if not r.get("messages"):
34
+ problems.append(f"{w}: no messages")
35
+ out = r.get("output") or {}
36
+ if not (out.get("content") or out.get("tool_calls") or out.get("reasoning_content")):
37
+ problems.append(f"{w}: empty output")
38
+ for tc in out.get("tool_calls") or []:
39
+ a = tc.get("arguments")
40
+ if isinstance(a, str):
41
+ try:
42
+ json.loads(a)
43
+ except json.JSONDecodeError:
44
+ warnings.append(f"{w}: tool call '{tc.get('name')}' has arguments that are not valid JSON (kept as-is)")
45
+ models = {r.get("model") for r in recs}
46
+ if None in models or "" in models:
47
+ warnings.append("some calls have no `model`; pass model=... to log()")
48
+ if not header.get("revision"):
49
+ warnings.append("no model revision in the header: use record_to(path, revision='<full hf commit hash>')")
50
+ if not header.get("library"):
51
+ warnings.append("no `library` in the header (e.g. library='vllm 0.23.0 (server)')")
52
+ if not header.get("dtype"):
53
+ warnings.append("no `dtype` in the header (e.g. dtype='bfloat16')")
54
+ if not header.get("quantization"):
55
+ warnings.append("no `quantization` declared in the header (e.g. quantization='none')")
56
+ if not header.get("chat_template"):
57
+ warnings.append("no `chat_template` declared in the header (e.g. chat_template='default')")
58
+ if not any(r.get("sampling") for r in recs):
59
+ warnings.append("no sampling settings recorded (temperature/top_p/...)")
60
+ # how the context evolved: extension of the previous call, or something else (e.g. compaction, a new thread)
61
+ ext = other = 0
62
+ prev = None
63
+ for r in recs:
64
+ if prev is not None:
65
+ base = prev["messages"] + [{"role": "assistant"}]
66
+ if len(r["messages"]) >= len(base) and all(_same(a, b) for a, b in zip(prev["messages"], r["messages"])):
67
+ ext += 1
68
+ else:
69
+ other += 1
70
+ prev = r
71
+ info = {"calls": len(recs), "models": sorted(m for m in models if m), "calls_extending_previous": ext,
72
+ "calls_with_new_context (compaction / new thread)": other, "header": header}
73
+ return problems, warnings, info
@@ -0,0 +1,28 @@
1
+ import argparse
2
+ import json
3
+ import sys
4
+
5
+ from .check import check
6
+
7
+
8
+ def main(argv=None):
9
+ ap = argparse.ArgumentParser(prog="argus-bench")
10
+ sub = ap.add_subparsers(dest="cmd", required=True)
11
+ c = sub.add_parser("check", help="check that a rollout file is well-formed")
12
+ c.add_argument("files", nargs="+")
13
+ a = ap.parse_args(argv)
14
+ bad = False
15
+ for f in a.files:
16
+ problems, warnings, info = check(f)
17
+ print(f"{f}: {info.get('calls', 0)} calls {json.dumps({k: v for k, v in info.items() if k != 'header' and k != 'calls'})}")
18
+ for p in problems:
19
+ print(" PROBLEM:", p); bad = True
20
+ for w in warnings:
21
+ print(" warning:", w)
22
+ if not problems:
23
+ print(" OK")
24
+ return 1 if bad else 0
25
+
26
+
27
+ if __name__ == "__main__":
28
+ sys.exit(main())
@@ -0,0 +1,211 @@
1
+ import asyncio
2
+ import inspect
3
+ import json
4
+
5
+ import httpx
6
+ import openai
7
+ import pytest
8
+
9
+ import argus_bench
10
+ from argus_bench.check import check, load
11
+
12
+ MSGS = [{"role": "system", "content": "sys"}, {"role": "user", "content": "hi"}]
13
+ TOOLS = [{"type": "function", "function": {"name": "bash", "description": "run", "parameters": {"type": "object", "properties": {}}}}]
14
+
15
+
16
+ def completion(content="hello", reasoning=None, calls=None):
17
+ msg = {"role": "assistant", "content": content}
18
+ if reasoning:
19
+ msg["reasoning_content"] = reasoning
20
+ if calls:
21
+ msg["tool_calls"] = [{"id": "c1", "type": "function", "function": {"name": "bash", "arguments": json.dumps(calls)}}]
22
+ return {"id": "x", "object": "chat.completion", "created": 0, "model": "m",
23
+ "choices": [{"index": 0, "message": msg, "finish_reason": "tool_calls" if calls else "stop"}]}
24
+
25
+
26
+ def sse(chunks):
27
+ return "".join(f"data: {json.dumps(c)}\n\n" for c in chunks) + "data: [DONE]\n\n"
28
+
29
+
30
+ def chunk(delta, finish=None):
31
+ return {"id": "x", "object": "chat.completion.chunk", "created": 0, "model": "m", "choices": [{"index": 0, "delta": delta, "finish_reason": finish}]}
32
+
33
+
34
+ def handler(request):
35
+ body = json.loads(request.content)
36
+ if body.get("stream"):
37
+ chunks = [chunk({"role": "assistant", "reasoning_content": "th"}), chunk({"reasoning_content": "ink"}), chunk({"content": "hel"}),
38
+ chunk({"content": "lo"}), chunk({"tool_calls": [{"index": 0, "id": "c9", "type": "function", "function": {"name": "bash", "arguments": '{"command"'}}]}),
39
+ chunk({"tool_calls": [{"index": 0, "function": {"arguments": ': "ls"}'}}]}, "tool_calls")]
40
+ return httpx.Response(200, headers={"content-type": "text/event-stream"}, content=sse(chunks))
41
+ return httpx.Response(200, json=completion("hello", reasoning="think", calls={"command": "ls"}))
42
+
43
+
44
+ @pytest.fixture
45
+ def out(tmp_path):
46
+ p = tmp_path / "r.jsonl"
47
+ argus_bench.record_to(p, revision="abc")
48
+ yield p
49
+ argus_bench.stop()
50
+
51
+
52
+ def test_sync(out):
53
+ c = openai.OpenAI(base_url="http://x/v1", api_key="k", http_client=httpx.Client(transport=httpx.MockTransport(handler)))
54
+ r = c.chat.completions.create(model="m", messages=MSGS, tools=TOOLS, temperature=0.7, seed=1, extra_body={"top_k": 20})
55
+ assert r.choices[0].message.content == "hello" # the user still gets the normal response
56
+ header, recs = load(out)
57
+ assert header["revision"] == "abc" and len(recs) == 1
58
+ rec = recs[0]
59
+ assert rec["messages"] == MSGS and rec["tools"] == TOOLS and rec["model"] == "m"
60
+ assert rec["sampling"] == {"temperature": 0.7, "seed": 1, "top_k": 20}
61
+ assert rec["output"]["reasoning_content"] == "think" and rec["output"]["tool_calls"][0]["name"] == "bash"
62
+
63
+
64
+ def test_stream_sync(out):
65
+ c = openai.OpenAI(base_url="http://x/v1", api_key="k", http_client=httpx.Client(transport=httpx.MockTransport(handler)))
66
+ seen = [ch for ch in c.chat.completions.create(model="m", messages=MSGS, stream=True)]
67
+ assert len(seen) == 6 # all chunks still reach the caller
68
+ _, recs = load(out)
69
+ o = recs[0]["output"]
70
+ assert o["content"] == "hello" and o["reasoning_content"] == "think" and recs[0]["stream"] is True
71
+ assert o["tool_calls"] == [{"id": "c9", "name": "bash", "arguments": '{"command": "ls"}'}]
72
+
73
+
74
+ def test_stream_context_manager_and_early_close(out):
75
+ c = openai.OpenAI(base_url="http://x/v1", api_key="k", http_client=httpx.Client(transport=httpx.MockTransport(handler)))
76
+ with c.chat.completions.create(model="m", messages=MSGS, stream=True) as s:
77
+ for i, ch in enumerate(s):
78
+ if i == 3:
79
+ break
80
+ _, recs = load(out)
81
+ assert len(recs) == 1 and recs[0]["output"]["content"].startswith("hel") # partial output is still logged
82
+
83
+
84
+ def test_async_and_async_stream(out):
85
+ async def go():
86
+ c = openai.AsyncOpenAI(base_url="http://x/v1", api_key="k", http_client=httpx.AsyncClient(transport=httpx.MockTransport(handler)))
87
+ await c.chat.completions.create(model="m", messages=MSGS)
88
+ s = await c.chat.completions.create(model="m", messages=MSGS, stream=True)
89
+ return [ch async for ch in s]
90
+ assert len(asyncio.run(go())) == 6
91
+ _, recs = load(out)
92
+ assert len(recs) == 2 and recs[1]["output"]["content"] == "hello" and recs[1]["stream"]
93
+
94
+
95
+ def test_log_primitive_and_check(tmp_path):
96
+ p = tmp_path / "x.jsonl"
97
+ argus_bench.record_to(p, revision="abc")
98
+ argus_bench.log(MSGS, "hello", model="m", sampling={"temperature": 0.6})
99
+ argus_bench.log(MSGS + [{"role": "assistant", "content": "hello"}, {"role": "user", "content": "more"}], {"content": "ok", "tool_calls": [{"name": "bash", "arguments": "{bad"}]}, model="m")
100
+ argus_bench.log([MSGS[0], {"role": "user", "content": "summary of the conversation"}], "fresh", model="m") # compaction
101
+ argus_bench.stop()
102
+ problems, warnings, info = check(p)
103
+ assert not problems
104
+ assert any("not valid JSON" in w for w in warnings)
105
+ assert info["calls_extending_previous"] == 1 and info["calls_with_new_context (compaction / new thread)"] == 1
106
+
107
+
108
+ def test_check_flags_empty_and_missing(tmp_path):
109
+ p = tmp_path / "bad.jsonl"
110
+ p.write_text(json.dumps({"messages": [], "output": {}}) + "\n")
111
+ problems, _, _ = check(p)
112
+ assert any("no messages" in x for x in problems) and any("empty output" in x for x in problems)
113
+
114
+
115
+ def test_patch_is_idempotent(tmp_path):
116
+ argus_bench.record_to(tmp_path / "a.jsonl")
117
+ argus_bench.record_to(tmp_path / "b.jsonl")
118
+ c = openai.OpenAI(base_url="http://x/v1", api_key="k", http_client=httpx.Client(transport=httpx.MockTransport(handler)))
119
+ c.chat.completions.create(model="m", messages=MSGS)
120
+ argus_bench.stop()
121
+ assert len(load(tmp_path / "b.jsonl")[1]) == 1 and not (tmp_path / "a.jsonl").exists()
122
+
123
+
124
+ def test_raw_response_path_used_by_litellm_and_langchain(out):
125
+ c = openai.OpenAI(base_url="http://x/v1", api_key="k", http_client=httpx.Client(transport=httpx.MockTransport(handler)))
126
+ raw = c.chat.completions.with_raw_response.create(model="m", messages=MSGS)
127
+ r = raw.parse()
128
+ assert r.choices[0].message.content == "hello" and raw.parse() is r # same object on repeated parse, logged once
129
+ s = c.chat.completions.with_raw_response.create(model="m", messages=MSGS, stream=True).parse()
130
+ assert len([ch for ch in s]) == 6
131
+ _, recs = load(out)
132
+ assert len(recs) == 2 and recs[1]["stream"] and recs[1]["output"]["content"] == "hello"
133
+
134
+
135
+ def test_raw_response_async(out):
136
+ async def go():
137
+ c = openai.AsyncOpenAI(base_url="http://x/v1", api_key="k", http_client=httpx.AsyncClient(transport=httpx.MockTransport(handler)))
138
+ async def parsed(raw):
139
+ r = raw.parse()
140
+ return await r if inspect.isawaitable(r) else r
141
+ raw = await c.chat.completions.with_raw_response.create(model="m", messages=MSGS)
142
+ await parsed(raw)
143
+ raw2 = await c.chat.completions.with_raw_response.create(model="m", messages=MSGS, stream=True)
144
+ return [ch async for ch in await parsed(raw2)]
145
+ assert len(asyncio.run(go())) == 6
146
+ assert len(load(out)[1]) == 2
147
+
148
+
149
+ def test_env_state_function_evaluated_per_call(out):
150
+ c = openai.OpenAI(base_url="http://x/v1", api_key="k", http_client=httpx.Client(transport=httpx.MockTransport(handler)))
151
+ state = {"n": 0}
152
+ argus_bench.env_state(lambda: {"files": state["n"]})
153
+ c.chat.completions.create(model="m", messages=MSGS)
154
+ state["n"] = 3
155
+ c.chat.completions.create(model="m", messages=MSGS, stream=True).__next__()
156
+ argus_bench.log(MSGS, "x", model="m")
157
+ argus_bench.log(MSGS, "y", model="m", env_state="explicit")
158
+ argus_bench.env_state(None)
159
+ c.chat.completions.create(model="m", messages=MSGS)
160
+ _, recs = load(out)
161
+ assert [r.get("env_state") for r in recs] == [{"files": 0}, {"files": 3}, {"files": 3}, "explicit", None]
162
+ assert "__env_state" not in json.dumps(recs)
163
+
164
+
165
+ def test_warns_when_nothing_recorded(tmp_path):
166
+ argus_bench.record_to(tmp_path / "e.jsonl")
167
+ with pytest.warns(UserWarning, match="no model call was recorded"):
168
+ argus_bench._no_calls_warning()
169
+ argus_bench.stop()
170
+
171
+
172
+ def test_check_warns_on_undeclared_quantization_and_template(tmp_path):
173
+ p = tmp_path / "q.jsonl"
174
+ argus_bench.record_to(p, revision="abc")
175
+ argus_bench.log(MSGS, "hello", model="m", sampling={"temperature": 1})
176
+ argus_bench.stop()
177
+ _, warnings_, _ = check(p)
178
+ assert any("quantization" in w for w in warnings_) and any("chat_template" in w for w in warnings_)
179
+
180
+
181
+ def test_subprocess_agent_records_via_env_var_without_code_changes(tmp_path):
182
+ import os, subprocess, sys, textwrap
183
+ script = tmp_path / "agent.py" # an "agent" that knows nothing about argus_bench
184
+ script.write_text(textwrap.dedent("""
185
+ import httpx, json, openai
186
+ h = lambda r: httpx.Response(200, json={"id": "x", "object": "chat.completion", "created": 0, "model": "m",
187
+ "choices": [{"index": 0, "message": {"role": "assistant", "content": "hi from child"}, "finish_reason": "stop"}]})
188
+ c = openai.OpenAI(base_url="http://x/v1", api_key="k", http_client=httpx.Client(transport=httpx.MockTransport(h)))
189
+ c.chat.completions.create(model="m", messages=[{"role": "user", "content": "hi"}])
190
+ """))
191
+ log = tmp_path / "sub.jsonl"
192
+ env = {**os.environ, "ARGUS_BENCH_LOG": str(log), "ARGUS_BENCH_META": json.dumps({"revision": "r1", "quantization": "none"})}
193
+ subprocess.run([sys.executable, str(script)], env=env, check=True)
194
+ subprocess.run([sys.executable, "-c", "pass"], env=env, check=True) # a process that makes no call leaves nothing behind
195
+ header, recs = load(log)
196
+ assert header["revision"] == "r1" and len(recs) == 1 and recs[0]["output"]["content"] == "hi from child"
197
+
198
+
199
+ def test_many_processes_do_not_interleave_lines(tmp_path):
200
+ import subprocess, sys, textwrap, os
201
+ log = tmp_path / "many.jsonl"
202
+ code = textwrap.dedent("""
203
+ import argus_bench, sys
204
+ argus_bench.record_to(sys.argv[1], _quiet=True)
205
+ for i in range(30):
206
+ argus_bench.log([{"role": "user", "content": "x" * 20000}], "y" * 20000, model="m")
207
+ """)
208
+ ps = [subprocess.Popen([sys.executable, "-c", code, str(log)]) for _ in range(4)]
209
+ assert all(p.wait() == 0 for p in ps)
210
+ _, recs = load(log) # load() raises on any torn line
211
+ assert len(recs) == 120