Compress tool outputs, logs, files, and RAG chunks before they reach the LLM. 20% fewer tokens for coding agents, 60-95% fewer tokens for JSON, same answers. Library, proxy, MCP server.
Python agentaianthropicclaude-codecompressioncontext-engineeringcontext-windowcursorfastapilangchainllmmcpopenaiprompt-engineeringproxypythonragtoken-optimizationtokenstypescript
fix(tokenizers): use o200k_base for gpt-4.1/gpt-4.5/o4 families (#2108)
Abhay Singh6979b5245eb3
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex bb71d3f99..fd77ce059 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -102,6 +102,7 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0### Bug Fixes+* **tokenizers:** use `o200k_base` for the gpt-4.1 / gpt-4.5 / o4 families in `get_encoding_for_model`. `gpt-4.1*` and `gpt-4.5*` matched the broad `gpt-4` prefix and were encoded with `cl100k_base`, and `o4*` matched no prefix and fell through to the `cl100k_base` default — all three use `o200k_base`, so their token counts were computed with the wrong vocabulary. Added explicit `gpt-4.1`/`gpt-4.5` prefixes ahead of `gpt-4` and an `o4` prefix; `gpt-4` and `gpt-3.5` snapshots still resolve to `cl100k_base`.* **cache/ccr:** stop counting a successful eviction as a retrieval in the compression feedback learner, which inverted the learning signal. When an entry is evicted without ever being retrieved, `CompressionStore` emits a synthetic `retrieval_type="eviction_success"` event to mark that the compression was sufficient (the LLM never needed the original). `CompressionFeedback.record_retrieval` had no branch for it, so — because the type is not `"full"` — it was counted as a *search retrieval*, inflating the tool's `retrieval_rate`/`search_rate`. `get_compression_hints` reads a high retrieval rate as "compressing too aggressively" and backs off, so a compression that actually worked pushed the learner toward *less* compression (a standalone repro scores one successful eviction as a 100% retrieval rate). The event is now recognized and left out of the retrieval counters; the compression is still counted by `record_compression` at store time, so a never-retrieved entry correctly yields a low retrieval rate. Genuine retrievals are unaffected.* **proxy/anthropic:** don't launder a non-2xx upstream into HTTP 200 when enterprise security scans the response. On the non-streaming `/v1/messages` path the response-scan branch rebuilt the reply as `httpx.Response(status_code=200)` and returned it without checking the upstream status, so a rate-limit (429), overloaded (529), or other 4xx error whose JSON body was scanned reached the client as an HTTP 200 — the client's retry/backoff never fired and an error looked like success. The branch is now gated on a 200 upstream, matching the sibling CCR/cache/buffered-stream blocks in the same handler; non-2xx responses fall through and keep their real status.* **learn:** classify timeout and connection tool failures correctly instead of as generic runtime errors. In `classify_error` the generic `RUNTIME_ERROR` pattern (`Traceback|Exception:|Error:`) was checked before the dedicated `TIMEOUT` and `CONNECTION_ERROR` patterns. Because every Python exception repr is `XxxError: ...`, a `TimeoutError: ...` or `ConnectionError: ...` matched the catch-all first and was miscategorized as `RUNTIME_ERROR`, leaving those two categories unreachable for the common colon-repr form (they only fired for tokenless phrasings like `deadline exceeded`). The `TIMEOUT` and `CONNECTION_ERROR` patterns are now checked before the generic catch-all; tokenless generic errors still classify as `RUNTIME_ERROR`.diff --git a/headroom/tokenizers/tiktoken_counter.py b/headroom/tokenizers/tiktoken_counter.pyindex 728a098cf..91065e40f 100644--- a/headroom/tokenizers/tiktoken_counter.py+++ b/headroom/tokenizers/tiktoken_counter.py@@ -176,11 +176,18 @@ def get_encoding_for_model(model: str) -> str:# o200k_base instead of cl100k_base for unknown gpt-4 snapshots.for prefix, encoding in (("gpt-4o", "o200k_base"),+ # gpt-4.1 / gpt-4.5 use o200k_base and MUST precede the "gpt-4" prefix,+ # which they would otherwise match and be mis-encoded as cl100k_base.+ ("gpt-4.1", "o200k_base"),+ ("gpt-4.5", "o200k_base"),("gpt-4-turbo", "cl100k_base"),("gpt-4", "cl100k_base"),("gpt-3.5", "cl100k_base"),("o1", "o200k_base"),("o3", "o200k_base"),+ # o4 reasoning models use o200k_base; without this they fell through to+ # the cl100k_base default.+ ("o4", "o200k_base"),):if model.startswith(prefix):return encodingdiff --git a/tests/test_tokenizers.py b/tests/test_tokenizers.pyindex b0b6bcfe9..7b76bb699 100644--- a/tests/test_tokenizers.py+++ b/tests/test_tokenizers.py@@ -51,6 +51,22 @@ class TestTiktokenCounter:# gpt-4-turbo snapshots use cl100k_base.assert get_encoding_for_model("gpt-4-turbo-2099") == "cl100k_base"+ def test_gpt41_and_o4_families_use_o200k(self):+ """gpt-4.1 / gpt-4.5 / o4 use o200k_base, not cl100k_base.++ Regression: gpt-4.1* and gpt-4.5* matched the broad "gpt-4" prefix and+ resolved to cl100k_base, and o4* matched no prefix and fell to the+ cl100k_base default — both wrong encodings for those models.+ """+ from headroom.tokenizers.tiktoken_counter import get_encoding_for_model++ assert get_encoding_for_model("gpt-4.1") == "o200k_base"+ assert get_encoding_for_model("gpt-4.1-mini") == "o200k_base"+ assert get_encoding_for_model("gpt-4.5-preview") == "o200k_base"+ assert get_encoding_for_model("o4-mini") == "o200k_base"+ # A plain gpt-4 snapshot must still use cl100k_base (not shadowed).+ assert get_encoding_for_model("gpt-4-0613") == "cl100k_base"+def test_count_text_empty(self):"""Test counting empty text."""counter = TiktokenCounter()