diff --git a/CHANGELOG.md b/CHANGELOG.md index 5d7c98f..074920a 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -8,6 +8,15 @@ saturate is experimental. Before 1.0, any minor release (0.x) can change the API defaults or the output layout, often with no deprecation period. Pin an exact version (for example `saturate==0.3.4`) if you depend on current behaviour. +## [Unreleased] + +### Added + +- `usage_tokens()` now falls back to `usage.input_tokens` and `usage.output_tokens` when + `prompt_tokens` / `completion_tokens` are absent or `null`, so endpoints such as OpenAI's + `/v1/responses`, Anthropic's `/v1/messages`, and Flide's `/v1/systemone` populate + `Stats.prompt_tokens`, `Stats.completion_tokens`, `tokens_per_sec`, and controller `tok_s`. + ## [0.3.4] - 2026-11-30 Faster single-call `hf://` flushes (`batch_bucket_files` for buckets, single-commit `create_commit` diff --git a/saturate/transport.py b/saturate/transport.py index 53aa474..9287f4a 100644 --- a/saturate/transport.py +++ b/saturate/transport.py @@ -318,13 +318,26 @@ def _row_error(errors: list[str]) -> str: def usage_tokens(body: dict) -> tuple[int, int]: - """(prompt, completion) tokens a response reports. A count that is missing or not an - integer (a server that sends null) is 0: usage is accounting, and a malformed count must not - fail a row whose result is fine, or skip the success and breaker reset that come with it.""" + """(prompt, completion) tokens a response reports. Reads `prompt_tokens`/`completion_tokens` + (OpenAI chat/completions, embeddings) and falls back to `input_tokens`/`output_tokens` + (OpenAI `/v1/responses`, Anthropic `/v1/messages`, Flide `/v1/systemone`). A count that is + missing or not a finite non-negative number (a server that sends null) is 0: usage is + accounting, and a malformed count must not fail a row whose result is fine, or skip the + success and breaker reset that come with it.""" usage = body.get("usage") if not isinstance(usage, dict): return 0, 0 - return _count(usage.get("prompt_tokens")), _count(usage.get("completion_tokens")) + return ( + _token_field(usage, "prompt_tokens", "input_tokens"), + _token_field(usage, "completion_tokens", "output_tokens"), + ) + + +def _token_field(usage: dict, primary: str, fallback: str) -> int: + value = usage.get(primary) + if value is None: + value = usage.get(fallback) + return _count(value) def finish_reasons(body: dict) -> tuple[str, ...]: diff --git a/tests/test_run_stats.py b/tests/test_run_stats.py index d9218d3..8edae40 100644 --- a/tests/test_run_stats.py +++ b/tests/test_run_stats.py @@ -347,3 +347,36 @@ def test_error_counts_across_fail_fast_release_resume_and_retry_errors(stub, tmp assert (retried.rows_processed, retried.rows_failed) == (1, 1) assert retried.error_counts == {"http 400": 1} assert sum(retried.error_counts.values()) == retried.rows_failed + + +def test_input_and_output_tokens_count_in_stats_and_telemetry(stub, tmp_path): + """Endpoints that report usage as input_tokens/output_tokens (e.g. OpenAI /v1/responses, + Anthropic /v1/messages, Flide /v1/systemone) populate Stats tokens, tok/s, and controller + telemetry.""" + stub.latency_s = 0.05 + stub.body_for = lambda req: { + "answers": {"spam": {"type": "noul", "noul": 0.1}}, + "usage": {"input_tokens": 100, "output_tokens": 8}, + } + + data = [{"id": str(i)} for i in range(8)] + stats = pump( + data, + to_request=lambda r: {"model": "m", "messages": [{"role": "user", "content": r["id"]}]}, + parse=lambda r, b: {"spam": b["answers"]["spam"]["noul"]}, + endpoint=stub.endpoint, + output=str(tmp_path), + window=Fixed(2), + id_key="id", + ) + + assert (stats.rows_processed, stats.rows_failed) == (8, 0) + assert stats.prompt_tokens == 800 + assert stats.completion_tokens == 64 + assert stats.tokens_per_sec > 0 + assert stats.finish_reasons == {} + + files = sorted((tmp_path / "__saturate" / "telemetry").glob("telemetry-*.jsonl")) + ticks = [json.loads(line) for f in files for line in f.read_text().splitlines() if line] + assert ticks, "expected at least one telemetry tick" + assert any(t["tok_s"] > 0 for t in ticks) diff --git a/tests/test_transport_retry.py b/tests/test_transport_retry.py index 9f17dfa..32c659c 100644 --- a/tests/test_transport_retry.py +++ b/tests/test_transport_retry.py @@ -562,3 +562,24 @@ def json(self): ) def test_a_token_count_is_a_non_negative_int_or_zero(value, expected): assert transport.usage_tokens({"usage": {"prompt_tokens": value}}) == (expected, 0) + assert transport.usage_tokens({"usage": {"input_tokens": value}}) == (expected, 0) + + +@pytest.mark.internals +@pytest.mark.parametrize( + "usage, expected", + [ + ({"input_tokens": 120, "output_tokens": 8}, (120, 8)), + ({"input_tokens": 120}, (120, 0)), + ({"output_tokens": 8}, (0, 8)), + # prompt/completion take precedence over input/output, including an explicit 0 + ({"prompt_tokens": 50, "completion_tokens": 10, "input_tokens": 999, "output_tokens": 999}, (50, 10)), + ({"prompt_tokens": 0, "completion_tokens": 0, "input_tokens": 999, "output_tokens": 999}, (0, 0)), + # null primary fields fall back to input/output + ({"prompt_tokens": None, "completion_tokens": None, "input_tokens": 42, "output_tokens": 7}, (42, 7)), + # malformed primary values stay 0 instead of silently pulling from fallback + ({"prompt_tokens": "bad", "input_tokens": 42}, (0, 0)), + ], +) +def test_usage_tokens_accepts_input_and_output_tokens(usage, expected): + assert transport.usage_tokens({"usage": usage}) == expected