-
Notifications
You must be signed in to change notification settings - Fork 52.6k
feat(agent): re-budget context compressor when a router swaps the backend #37720
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Open
iamfoz
wants to merge
1
commit into
NousResearch:main
Choose a base branch
from
iamfoz:feat/adaptive-context-window
base: main
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
Open
Changes from all commits
Commits
File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
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
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,94 @@ | ||
| """Track response.model changes across LLM calls so the context | ||
| compressor can rebudget to the actual backend's context length. | ||
|
|
||
| Many OpenAI-compatible endpoints expose router-style model ids such as | ||
| ``openrouter/auto`` or ``:free``-suffixed names where the concrete | ||
| backend selected per request varies (Llama 3.3, Qwen, DeepSeek, etc.). | ||
| Each backend has its own context window. Without observing the live | ||
| ``response.model`` value, Hermes keeps its compressor calibrated to | ||
| whatever the operator configured at startup, which is usually wrong | ||
| for whichever backend the router actually picked. | ||
|
|
||
| This module is a tiny state machine: it remembers the last observed | ||
| model id and reports back when it changes. It does *not* perform the | ||
| ``context_length`` lookup (``agent.model_metadata`` already owns that) | ||
| and it does *not* mutate the compressor. The caller decides what to do | ||
| with the change signal. | ||
| """ | ||
| from __future__ import annotations | ||
|
|
||
| import logging | ||
| import time | ||
|
|
||
| logger = logging.getLogger(__name__) | ||
|
|
||
|
|
||
| class AdaptiveContextTracker: | ||
| """Stateful observer that fires when ``response.model`` changes. | ||
|
|
||
| Typical use:: | ||
|
|
||
| tracker = AdaptiveContextTracker() | ||
| new_model = tracker.observe(getattr(response, "model", None)) | ||
| if new_model is not None: | ||
| ctx = get_model_context_length(new_model, ...) | ||
| compressor.update_model(model=new_model, context_length=ctx, ...) | ||
| """ | ||
|
|
||
| def __init__(self) -> None: | ||
| self._last_seen: str | None = None | ||
| self._last_changed_at: float = 0.0 | ||
| self._change_count: int = 0 | ||
|
|
||
| def observe(self, response_model: str | None) -> str | None: | ||
| """Record the model id reported by an LLM response. | ||
|
|
||
| Returns the new id when it differs from the previously seen | ||
| value, so callers know to rebudget. Returns ``None`` on the | ||
| first observation, when the value is unchanged, or when the | ||
| input is missing/non-string (defensive: response objects in | ||
| some adapters may not carry ``model``). | ||
| """ | ||
| if not response_model or not isinstance(response_model, str): | ||
| return None | ||
| if self._last_seen is None: | ||
| # First observation: adopt silently. The agent was already | ||
| # configured with some model id at startup; this is the | ||
| # baseline against which subsequent changes are detected. | ||
| self._last_seen = response_model | ||
| return None | ||
| if response_model == self._last_seen: | ||
| return None | ||
| previous = self._last_seen | ||
| self._last_seen = response_model | ||
| self._last_changed_at = time.monotonic() | ||
| self._change_count += 1 | ||
| logger.info( | ||
| "adaptive-context: backend changed %r -> %r (change #%d)", | ||
| previous, response_model, self._change_count, | ||
| ) | ||
| return response_model | ||
|
|
||
| @property | ||
| def last_seen(self) -> str | None: | ||
| return self._last_seen | ||
|
|
||
| @property | ||
| def change_count(self) -> int: | ||
| return self._change_count | ||
|
|
||
| def summary(self) -> dict: | ||
| """Snapshot of tracker state for UX surfaces (e.g. /usage). | ||
|
|
||
| Returns a plain dict so callers don't have to reach into | ||
| private attributes. ``seconds_since_last_change`` is ``None`` | ||
| until the first transition is observed. | ||
| """ | ||
| seconds_since: float | None = None | ||
| if self._change_count > 0 and self._last_changed_at > 0: | ||
| seconds_since = max(0.0, time.monotonic() - self._last_changed_at) | ||
| return { | ||
| "last_seen": self._last_seen, | ||
| "change_count": self._change_count, | ||
| "seconds_since_last_change": seconds_since, | ||
| } | ||
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
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
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
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
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
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
| Original file line number | Diff line number | Diff line change |
|---|---|---|
|
|
@@ -413,6 +413,9 @@ gateway: | |
| breakdown_cat_subagent_definitions: "Subagent definitions" | ||
| breakdown_cat_memory: "Memory" | ||
| breakdown_cat_conversation: "Conversation" | ||
| label_adaptive_context_pending: "Adaptive ctx: enabled (no responses observed yet)" | ||
|
Collaborator
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Adding English catalog keys requires matching entries in every |
||
| label_adaptive_context_baseline: "Adaptive ctx: enabled - baseline: `{model}`" | ||
| label_adaptive_context_changes: "Adaptive ctx: enabled - last seen: `{model}` ({count} backend changes)" | ||
| header_session_info: "📊 **Session Info**" | ||
| label_messages: "Messages: {count}" | ||
| label_estimated_context: "Estimated context: ~{count} tokens" | ||
|
|
||
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
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,111 @@ | ||
| """Unit tests for agent.adaptive_context.AdaptiveContextTracker. | ||
|
|
||
| The tracker is intentionally minimal - it observes model ids and | ||
| reports the new id only on change. These tests pin the boundary | ||
| behaviours so the run_agent integration can rely on them. | ||
| """ | ||
| from __future__ import annotations | ||
|
|
||
| import pytest | ||
|
|
||
| from agent.adaptive_context import AdaptiveContextTracker | ||
|
|
||
|
|
||
| def test_first_observation_returns_none_and_records_baseline(): | ||
| t = AdaptiveContextTracker() | ||
| assert t.observe("meta-llama/llama-3.3-70b-instruct:free") is None | ||
| assert t.last_seen == "meta-llama/llama-3.3-70b-instruct:free" | ||
| assert t.change_count == 0 | ||
|
|
||
|
|
||
| def test_same_model_returns_none(): | ||
| t = AdaptiveContextTracker() | ||
| t.observe("model-a") | ||
| assert t.observe("model-a") is None | ||
| assert t.observe("model-a") is None | ||
| assert t.change_count == 0 | ||
|
|
||
|
|
||
| def test_change_returns_new_model_and_increments(): | ||
| t = AdaptiveContextTracker() | ||
| t.observe("model-a") | ||
| new = t.observe("model-b") | ||
| assert new == "model-b" | ||
| assert t.last_seen == "model-b" | ||
| assert t.change_count == 1 | ||
|
|
||
|
|
||
| def test_multiple_changes_increment_counter(): | ||
| t = AdaptiveContextTracker() | ||
| t.observe("a") | ||
| assert t.observe("b") == "b" | ||
| assert t.observe("c") == "c" | ||
| assert t.observe("c") is None | ||
| assert t.observe("d") == "d" | ||
| assert t.change_count == 3 | ||
|
|
||
|
|
||
| def test_router_to_concrete_backend_transition_fires_once(): | ||
| # Realistic scenario: first call returns a concrete backend, second | ||
| # call returns a *different* concrete backend (the router picked | ||
| # someone else). The tracker should fire on the second. | ||
| t = AdaptiveContextTracker() | ||
| assert t.observe("meta-llama/llama-3.3-70b-instruct:free") is None | ||
| fired = t.observe("qwen/qwen-2.5-72b-instruct:free") | ||
| assert fired == "qwen/qwen-2.5-72b-instruct:free" | ||
| assert t.change_count == 1 | ||
|
|
||
|
|
||
| @pytest.mark.parametrize("bad", [None, "", 0, False, 42, [], {}, object()]) | ||
| def test_invalid_inputs_return_none_without_changing_state(bad): | ||
| t = AdaptiveContextTracker() | ||
| t.observe("model-a") # seed | ||
| snapshot_last = t.last_seen | ||
| snapshot_count = t.change_count | ||
| assert t.observe(bad) is None | ||
| assert t.last_seen == snapshot_last | ||
| assert t.change_count == snapshot_count | ||
|
|
||
|
|
||
| def test_invalid_input_as_first_observation_does_not_seed(): | ||
| t = AdaptiveContextTracker() | ||
| assert t.observe(None) is None | ||
| assert t.observe("") is None | ||
| assert t.last_seen is None | ||
| # A subsequent valid observation should still be treated as the baseline | ||
| assert t.observe("first-real") is None | ||
| assert t.last_seen == "first-real" | ||
| assert t.change_count == 0 | ||
|
|
||
|
|
||
| def test_summary_fresh_tracker(): | ||
| t = AdaptiveContextTracker() | ||
| s = t.summary() | ||
| assert s == { | ||
| "last_seen": None, | ||
| "change_count": 0, | ||
| "seconds_since_last_change": None, | ||
| } | ||
|
|
||
|
|
||
| def test_summary_after_baseline_only(): | ||
| t = AdaptiveContextTracker() | ||
| t.observe("model-a") | ||
| s = t.summary() | ||
| assert s["last_seen"] == "model-a" | ||
| assert s["change_count"] == 0 | ||
| # No change yet, so no elapsed-since-change figure | ||
| assert s["seconds_since_last_change"] is None | ||
|
|
||
|
|
||
| def test_summary_after_change_includes_elapsed(): | ||
| t = AdaptiveContextTracker() | ||
| t.observe("model-a") | ||
| t.observe("model-b") | ||
| s = t.summary() | ||
| assert s["last_seen"] == "model-b" | ||
| assert s["change_count"] == 1 | ||
| assert isinstance(s["seconds_since_last_change"], float) | ||
| assert s["seconds_since_last_change"] >= 0.0 | ||
| # Sanity: a brand-new change should be sub-second | ||
| assert s["seconds_since_last_change"] < 5.0 |
Oops, something went wrong.
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.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
This first concrete backend is recorded but deliberately returns
None, so the caller never callsupdate_modelfor it. When a configured router consistently returns this backend, adaptive re-budgeting never happens. Return a change signal when this first observed backend differs from the compressor's configured model, and cover that stable-router case.