optimize(llmcore): decouple trim_messages_history token estimator from cap calc (closes #750) - #765
Open
Kailigithub wants to merge 1 commit into
Conversation
…m cap calc (closes lsdefine#750) Extract the legacy `3 chars/token` heuristic from `trim_messages_history()` into a single named function `estimate_context_tokens()`. Default behaviour is byte-identical with the prior code (same `cost()/3` formula), so this PR is observably a refactor — the only user-visible change is the debug log now reports both the char count (`ctx`) and a token estimate (`tokens_est`) side-by-side. Two extension points so future model-aware estimators don't have to fork the trim path: * `sess.token_estimator(messages) -> int` — full override callable. * `sess.token_chars_per_token` (float, default 3) — multiplier on the message-char sum; lets a session flip the heuristic without writing a custom callable. Both hooks are opt-in and bug-tolerant (zero / negative / unparsable values fall back to the module default; a raised exception is swallowed and the path falls through to the multiplier branch). `trim_messages_history()` itself still uses the char-based gate (`cost(history) <= context_win * 3`) so all downstream consumers — `frontends/cost_tracker.py`, `frontends/tui_v3.py`, `frontends/tuiapp_v2.py` and the hub — keep reading `STATS['ctx']` in chars exactly as before. `cost_tracker.py` still hardcodes `*3` for its own display; that's left as a follow-up to keep this PR scope to "minimum change" per the issue. Test recipe (`tests/test_llmcore_estimate_context_tokens.py`, 18 cases): * `python3 -m unittest discover -s tests -p 'test_*.py' -v` -> 18/18 OK. Refs: lsdefine#750
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
What
Extract the legacy
3 chars/tokenheuristic fromtrim_messages_history()into a single named functionestimate_context_tokens(). Default behaviour is byte-identical with the prior code (samecost()/3formula), so this PR is observably a refactor — the only user-visible change is the debug log now reports both the char count (ctx) and a token estimate (tokens_est) side-by-side.Why
Issue #750 documents that today's
/3heuristic lives insidetrim_messages_history()and is wrong for CJK/code/JSON content. There is no single place to swap it without forking the trim path. The issue's "minimum change" plan is exactly this PR:How
trim_messages_history()keeps its char-based gate (cost(history) <= context_win * 3) so all downstream consumers —frontends/cost_tracker.py,frontends/tui_v3.py,frontends/tuiapp_v2.py, the hub — keep readingSTATS['ctx']in chars exactly as before. The estimator is wired intoSTATS['tokens_est']and the existing debug print.Extension points (opt-in)
sess.token_estimator(msgs)sess.token_chars_per_tokenNone,0, negative, or unparsable values fall back to the default.Both hooks are bug-tolerant so a misconfigured session can never crash the trim path.
Tests
tests/test_llmcore_estimate_context_tokens.py— 18 cases, all passing underpython3 -m unittest discover -s tests -p 'test_*.py':EstimateContextTokensDefaultHeuristicTestsint(char_count / 3)behaviour for empty / English / CJK / multi-message / non-serialisable histories.EstimateContextTokensCharsPerTokenOverrideTeststoken_chars_per_tokenaccepts strings, falls back on garbage / zero / negative / None.EstimateContextTokensCallableOverrideTeststoken_estimatorcallable wins over the multiplier, swallows exceptions, clamps negatives.TrimMessagesHistoryBehaviorPreservedTeststokens_estnot the gate.Out of scope (intentional)
frontends/cost_tracker.pyhas its own copy of the*3heuristic (context_window_chars()). The issue explicitly excludes this from the first PR; it can be a follow-up that points atDEFAULT_CHARS_PER_TOKEN.compress_history_tags()'smax_len=800field truncation (also called out in the issue as a separate follow-up).Risk
Low.
STATS['ctx']still reports the same char count, the trim gate uses the same condition, and the only new output is a debug-only~N tokens estannotation in the trim log. All 18 tests pass.Closes #750