-
Notifications
You must be signed in to change notification settings - Fork 120
feat: context compaction strategies for the react loop #996
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
yelkurdi
wants to merge
16
commits into
generative-computing:main
Choose a base branch
from
yelkurdi:context_compaction_for_react
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
Show all changes
16 commits
Select commit
Hold shift + click to select a range
048071d
feat: add context compaction strategies for react framework
yelkurdi a6462d9
refactor: express compaction threshold as token count
yelkurdi 1e28704
Fix mot.generation.usage
ramon-astudillo 4e5d16b
refactor: relocate compaction module into frameworks package
yelkurdi 2440155
docs: add Args/Returns sections to react_compaction compact overrides
yelkurdi d7c5d15
feat(compaction): per-turn Compactor protocol for ChatContext + ReACT
yelkurdi 6f6cb12
docs: fix stale references to ChatContext default and compaction exam…
yelkurdi 45b4ee8
feat(compaction): InlineCompactor marker + required default_backend o…
yelkurdi 4baf4e5
fix(session): track interaction_count out-of-band; doc compaction sem…
yelkurdi 2846181
fix(compaction): make LLMSummarizeCompactor backend errors non-fatal
yelkurdi 0acb4fc
docs: stronger warning on _run_coro_blocking event-loop blocking
yelkurdi 25288b3
fix(compaction): make LLMSummarizeCompactor rendering loss-aware
yelkurdi 206b533
refactor(compaction): skip empty ModelOutputThunks instead of renderi…
yelkurdi 44c7929
chore(compaction): set silence_context_type_warning on internal aact …
yelkurdi dd4829c
feat(compaction): expose model_options on LLMSummarizeCompactor
yelkurdi 298ee27
chore(docs): normalize source docstring backticks in context package
yelkurdi 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
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,63 @@ | ||
| # pytest: unit | ||
| """Implementing the Compactor protocol — anything with ``compact()`` works. | ||
|
|
||
| The protocol is structurally typed: a class with a ``compact(ctx, *, | ||
| backend=None) -> ChatContext`` method is a valid Compactor. No | ||
| inheritance is required. | ||
| """ | ||
|
|
||
| from mellea.stdlib.components.chat import Message | ||
| from mellea.stdlib.context import ChatContext, Compactor | ||
| from mellea.stdlib.context.chat import _rebuild_chat_context | ||
|
|
||
|
|
||
| class TruncateOldest: | ||
| """Drop only the very first body component each call. | ||
|
|
||
| Demonstrates the smallest possible Compactor implementation. Pattern | ||
| 1 (wired into ``ChatContext``) means each ``add()`` removes the | ||
| oldest item then appends — net result: the context never grows. | ||
| """ | ||
|
|
||
| def compact(self, ctx, *, backend=None): | ||
| items = ctx.as_list() | ||
| if len(items) <= 1: | ||
| return ctx | ||
| return _rebuild_chat_context(items[1:], compactor=ctx._compactor) | ||
|
|
||
|
|
||
| def pattern_1_wired_into_context(): | ||
| """Pattern 1: compactor lives on the context, runs in ``add()``.""" | ||
| ctx = ChatContext(compactor=TruncateOldest()) | ||
| for i in range(4): | ||
| ctx = ctx.add(Message("user", f"msg {i}")) | ||
| return [m.content for m in ctx.as_list()] | ||
| # → ['msg 3'] (oldest dropped before each append) | ||
|
|
||
|
|
||
| def pattern_2_manual_call(): | ||
| """Pattern 2: caller invokes ``compact()`` directly between turns.""" | ||
| ctx = ChatContext(window_size=10_000) # permissive — no auto-compaction | ||
| for i in range(5): | ||
| ctx = ctx.add(Message("user", f"msg {i}")) | ||
| truncated = TruncateOldest().compact(ctx) | ||
| return [m.content for m in truncated.as_list()] | ||
|
|
||
|
|
||
| def structural_typing_check(): | ||
| """The Compactor protocol is satisfied structurally, no inheritance.""" | ||
| c: Compactor = TruncateOldest() # mypy-checked Protocol assignment | ||
| return type(c).__name__ | ||
|
|
||
|
|
||
| if __name__ == "__main__": | ||
| for fn in [pattern_1_wired_into_context, pattern_2_manual_call]: | ||
| print(f"--- {fn.__name__} ---") | ||
| print(fn()) | ||
| print(f"structural typing: {structural_typing_check()} satisfies Compactor") | ||
|
|
||
|
|
||
| def test_custom_compactor_examples(): | ||
| assert pattern_1_wired_into_context() == ["msg 3"] | ||
| assert pattern_2_manual_call() == ["msg 1", "msg 2", "msg 3", "msg 4"] | ||
| assert structural_typing_check() == "TruncateOldest" | ||
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,237 @@ | ||
| # pytest: unit | ||
| """Compose the ReACT loop with a sync `Compactor`. | ||
|
|
||
| Two integration points are available, and they're complementary: | ||
|
|
||
| 1. **Per-add** — the `ChatContext`'s own compactor runs every time the | ||
| ReACT loop appends a Message, ToolMessage, or thunk. This is fine | ||
| for cheap strategies like `WindowCompactor`. | ||
| 2. **Per-turn** — pass `compactor=` to ``react(...)`` to invoke a | ||
| compactor once per ReACT iteration after the tool observation. Use | ||
| it for heavier strategies that should fire at turn boundaries | ||
| instead of on every component append. | ||
|
|
||
| In both cases use ``pin_react_initiator`` (from | ||
| ``mellea.stdlib.components.react``) so the goal and tool registration | ||
| survive compaction. | ||
|
|
||
| This example exercises the wiring end-to-end against a fake backend so | ||
| no LLM is required. | ||
| """ | ||
|
|
||
| from __future__ import annotations | ||
|
|
||
| import asyncio | ||
| from collections.abc import Sequence | ||
| from dataclasses import dataclass | ||
|
|
||
| from mellea.backends.tools import MelleaTool | ||
| from mellea.core.backend import Backend, BaseModelSubclass | ||
| from mellea.core.base import ( | ||
| C, | ||
| CBlock, | ||
| Component, | ||
| Context, | ||
| GenerateLog, | ||
| ModelOutputThunk, | ||
| ModelToolCall, | ||
| ) | ||
| from mellea.stdlib.components.react import ( | ||
| MELLEA_FINALIZER_TOOL, | ||
| ReactInitiator, | ||
| _mellea_finalize_tool, | ||
| pin_react_initiator, | ||
| ) | ||
| from mellea.stdlib.context import ChatContext, WindowCompactor | ||
| from mellea.stdlib.frameworks.react import react | ||
|
|
||
| # --------------------------------------------------------------------------- # | ||
| # Fake backend so the example runs without an LLM # | ||
| # --------------------------------------------------------------------------- # | ||
|
|
||
|
|
||
| @dataclass | ||
| class _ScriptedTurn: | ||
| value: str | ||
| tool_calls: dict[str, ModelToolCall] | None = None | ||
|
|
||
|
|
||
| class ScriptedBackend(Backend): | ||
| """Returns pre-scripted responses; no real model is called.""" | ||
|
|
||
| def __init__(self, script: list[_ScriptedTurn]) -> None: | ||
| self._script = iter(script) | ||
|
|
||
| async def _generate_from_context( | ||
| self, | ||
| action: Component[C] | CBlock, | ||
| ctx: Context, | ||
| *, | ||
| format: type[BaseModelSubclass] | None = None, | ||
| model_options: dict | None = None, | ||
| tool_calls: bool = False, | ||
| ) -> tuple[ModelOutputThunk[C], Context]: | ||
| turn = next(self._script) | ||
| mot: ModelOutputThunk = ModelOutputThunk( | ||
| value=turn.value, tool_calls=turn.tool_calls | ||
| ) | ||
| mot._generate_log = GenerateLog(is_final_result=True) | ||
| return mot, ctx.add(action).add(mot) | ||
|
|
||
| async def generate_from_raw( | ||
| self, | ||
| actions: Sequence[Component[C] | CBlock], | ||
| ctx: Context, | ||
| *, | ||
| format: type[BaseModelSubclass] | None = None, | ||
| model_options: dict | None = None, | ||
| tool_calls: bool = False, | ||
| ) -> list[ModelOutputThunk]: | ||
| raise NotImplementedError | ||
|
|
||
|
|
||
| def _tool(name: str, return_value: str = "ok") -> MelleaTool: | ||
| def _fn() -> str: | ||
| return return_value | ||
|
|
||
| return MelleaTool.from_callable(_fn, name=name) | ||
|
|
||
|
|
||
| def _tool_call(tool_name: str, tool: MelleaTool, thought: str) -> _ScriptedTurn: | ||
| tc = ModelToolCall(name=tool_name, func=tool, args={}) | ||
| return _ScriptedTurn(value=thought, tool_calls={tool_name: tc}) | ||
|
|
||
|
|
||
| def _final(answer: str) -> _ScriptedTurn: | ||
| finalizer = MelleaTool.from_callable(_mellea_finalize_tool, MELLEA_FINALIZER_TOOL) | ||
| tc = ModelToolCall( | ||
| name=MELLEA_FINALIZER_TOOL, func=finalizer, args={"answer": answer} | ||
| ) | ||
| return _ScriptedTurn(value="", tool_calls={MELLEA_FINALIZER_TOOL: tc}) | ||
|
|
||
|
|
||
| # --------------------------------------------------------------------------- # | ||
| # Pattern A — per-add compaction wired into the ChatContext # | ||
| # --------------------------------------------------------------------------- # | ||
|
|
||
|
|
||
| async def per_add_compaction(): | ||
| """A `WindowCompactor(pin_react_initiator)` on the ChatContext compacts | ||
| on every ``add()`` — Messages, ToolMessages, thunks. The ReactInitiator | ||
| stays pinned across the whole loop. | ||
| """ | ||
| search = _tool("search") | ||
| backend = ScriptedBackend( | ||
| [ | ||
| _tool_call("search", search, "step 1"), | ||
| _tool_call("search", search, "step 2"), | ||
| _tool_call("search", search, "step 3"), | ||
| _final("done"), | ||
| ] | ||
| ) | ||
| ctx = ChatContext( | ||
| compactor=WindowCompactor(size=3, pin_predicate=pin_react_initiator) | ||
| ) | ||
| result, ctx = await react( | ||
| goal="find info", context=ctx, backend=backend, tools=[search], loop_budget=10 | ||
| ) | ||
| return ( | ||
| result.value, | ||
| any(isinstance(c, ReactInitiator) for c in ctx.as_list()), | ||
| len(ctx.as_list()), | ||
| ) | ||
|
|
||
|
|
||
| # --------------------------------------------------------------------------- # | ||
| # Pattern B — per-turn compaction passed to react() # | ||
| # --------------------------------------------------------------------------- # | ||
|
|
||
|
|
||
| async def per_turn_compaction(): | ||
| """Pass ``compactor=`` to ``react`` for once-per-turn invocation. | ||
|
|
||
| Use a permissive ``ChatContext`` (large window) so the per-add path is | ||
| effectively disabled — only the per-turn hook drives compaction. | ||
| """ | ||
| search = _tool("search") | ||
| backend = ScriptedBackend( | ||
| [ | ||
| _tool_call("search", search, "step 1"), | ||
| _tool_call("search", search, "step 2"), | ||
| _tool_call("search", search, "step 3"), | ||
| _final("done"), | ||
| ] | ||
| ) | ||
| result, ctx = await react( | ||
| goal="find info", | ||
| context=ChatContext(window_size=10_000), | ||
| backend=backend, | ||
| tools=[search], | ||
| loop_budget=10, | ||
| compactor=WindowCompactor(size=2, pin_predicate=pin_react_initiator), | ||
| ) | ||
| return (result.value, any(isinstance(c, ReactInitiator) for c in ctx.as_list())) | ||
|
|
||
|
|
||
| # --------------------------------------------------------------------------- # | ||
| # Pattern C — LLM-driven summarisation # | ||
| # --------------------------------------------------------------------------- # | ||
|
|
||
|
|
||
| async def llm_summarize_compaction(): | ||
| """Wire :class:`LLMSummarizeCompactor` into ``react()``. | ||
|
|
||
| ``LLMSummarizeCompactor`` implements the sync :class:`Compactor` | ||
| protocol — its ``compact`` method internally orchestrates the async | ||
| backend call (running it on a worker thread when invoked from inside | ||
| an event loop). From ``react()``'s perspective it's just another | ||
| sync compactor. | ||
|
|
||
| To keep the scripted backend simple, this example sets ``keep_n`` | ||
| large enough that summarisation never fires (no LLM call is needed). | ||
| Real usage would pair it with ``ThresholdCompactor`` so it only | ||
| activates once the conversation crosses a token budget. See | ||
| ``TestLLMSummarizeCompactor`` in ``test/stdlib/test_compactor.py`` for | ||
| unit tests that exercise the actual summary path. | ||
| """ | ||
| from mellea.stdlib.context import LLMSummarizeCompactor | ||
|
|
||
| search = _tool("search") | ||
| backend = ScriptedBackend([_tool_call("search", search, "step 1"), _final("done")]) | ||
| result, ctx = await react( | ||
| goal="find info", | ||
| context=ChatContext(window_size=10_000), | ||
| backend=backend, | ||
| tools=[search], | ||
| loop_budget=10, | ||
| # keep_n=1000 → no summarisation triggers in this short script; | ||
| # the example just shows the async compactor is wired correctly. | ||
| compactor=LLMSummarizeCompactor( | ||
| default_backend=backend, keep_n=1000, pin_predicate=pin_react_initiator | ||
| ), | ||
| ) | ||
| return (result.value, any(isinstance(c, ReactInitiator) for c in ctx.as_list())) | ||
|
|
||
|
|
||
| if __name__ == "__main__": | ||
| print(f"per_add_compaction: {asyncio.run(per_add_compaction())}") | ||
| print(f"per_turn_compaction: {asyncio.run(per_turn_compaction())}") | ||
| print(f"llm_summarize_compact: {asyncio.run(llm_summarize_compaction())}") | ||
|
|
||
|
|
||
| def test_per_add_compaction(): | ||
| answer, has_initiator, _length = asyncio.run(per_add_compaction()) | ||
| assert answer == "done" | ||
| assert has_initiator | ||
|
|
||
|
|
||
| def test_per_turn_compaction(): | ||
| answer, has_initiator = asyncio.run(per_turn_compaction()) | ||
| assert answer == "done" | ||
| assert has_initiator | ||
|
|
||
|
|
||
| def test_llm_summarize_compaction(): | ||
| answer, has_initiator = asyncio.run(llm_summarize_compaction()) | ||
| assert answer == "done" | ||
| assert has_initiator |
Oops, something went wrong.
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.
Hey — I think this example actually crashes when
pattern_1_wired_into_context()runs:TruncateOldestdoesn't inheritInlineCompactor, and the new guard inchat.py:52-58raisesTypeErroron construction. The# pytest: unitannotation means it'll show up in the default CI run too, so worth catching before merge.One-line fix:
Totally tangential thought, take it or leave it — the example imports
_rebuild_chat_contextand readsctx._compactor, which is whatWindowCompactordoes internally too, so it's an honest reflection of reality. Just wondering whether it's worth promoting_rebuild_chat_contextto public (rebuild_chat_context) so the "look how easy it is to write your own" framing holds together. Happy to file a follow-up if that's out of scope here.