-
Notifications
You must be signed in to change notification settings - Fork 121
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
28
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.
+2,519
−98
Open
Changes from all commits
Commits
Show all changes
28 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 9c7f972
fix(docs): make custom_compactor.py example actually run
yelkurdi 3283c20
fix(compaction): re-raise programming errors instead of masking as ba…
yelkurdi d6a421d
docs(context): make ChatContext compaction docstring age-proof
yelkurdi 5a32f76
docs(context): drop caller list from _rebuild_chat_context docstring
yelkurdi 71efb85
refactor(compactor): hoist top-level imports out of function bodies
yelkurdi 1e0cc82
refactor(compactor): avoid wasted slice in LLMSummarizeCompactor.compact
yelkurdi 9e2d361
refactor(compactor): pass precomputed full/pin_end into _async_compact
yelkurdi 441c520
refactor(compactor): pythonic enumerate loop in pin_system
yelkurdi 2165c37
docs(react): note that compactor must return a ChatContext
yelkurdi 11de698
docs(examples): note system-message eviction caveat in TruncateOldest
yelkurdi 8aff6c4
docs(compactor): fix misleading "T = ChatContext" docstring framing
yelkurdi aeff4f1
docs(compactor): add Raises entry for InlineCompactor.compact
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,89 @@ | ||
| # pytest: unit | ||
| """Implementing the Compactor protocol — structural and marker typing. | ||
|
|
||
| The Compactor Protocol is structurally typed: any class with a | ||
| `compact(ctx, *, backend=None) -> ChatContext` method satisfies it. | ||
|
|
||
| Two ways to use a custom compactor with a `ChatContext`: | ||
|
|
||
| - **Pattern 1 (wired into `ChatContext.add`)**: inherit from | ||
| `InlineCompactor` for simple compactors that don't make backend | ||
| calls. Backend-calling compactors should instead be wrapped in | ||
| `ThresholdCompactor` (which gates them by token count) before being | ||
| attached to a `ChatContext`. | ||
| - **Pattern 2 (manual call)**: invoke `compact()` directly between | ||
| turns. Any object satisfying the structural `Compactor` protocol | ||
| works — no inheritance needed. Works for backend-calling compactors | ||
| or any other custom compactor. | ||
| """ | ||
|
|
||
| from mellea.stdlib.components.chat import Message | ||
| from mellea.stdlib.context import ChatContext, Compactor | ||
| from mellea.stdlib.context.chat import _rebuild_chat_context | ||
| from mellea.stdlib.context.compactor import InlineCompactor | ||
|
|
||
|
|
||
| class TruncateOldest(InlineCompactor): | ||
| """Drop only the very first body component each call. | ||
|
|
||
| Smallest possible Pattern-1 compactor — inherits `InlineCompactor` | ||
| so it can be wired directly into `ChatContext`. Each `add()` | ||
| removes the oldest item then appends — net result: the context | ||
| never grows. | ||
|
|
||
| Note: | ||
| `items[1:]` drops index 0 unconditionally, so a leading system | ||
| message gets evicted on the first compaction. This is intentional | ||
| for the smallest-possible-example shape; for the more common | ||
| "keep the system prompt, drop oldest body" behaviour use | ||
| :class:`mellea.stdlib.context.WindowCompactor` with the | ||
| :func:`mellea.stdlib.context.pin_system` predicate instead. | ||
| """ | ||
|
|
||
| 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 bare Compactor protocol is satisfied structurally — no inheritance.""" | ||
|
|
||
| class JustCompact: # no base class — pure structural Compactor | ||
| def compact(self, ctx, *, backend=None): | ||
| return ctx | ||
|
|
||
| c: Compactor = JustCompact() # 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() == "JustCompact" | ||
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.
One caveat worth flagging here:
items[1:]drops element 0 unconditionally, so a leading system message gets evicted on the firstadd(). That's fine for this example sinceTruncateOldestis deliberately the smallest possible compactor, but it's worth a one-line note pointing readers atWindowCompactor/pin_systemif they want the pinned-system variant rather than reaching for this as a starting point.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.
Good catch — added a Note to
TruncateOldest's docstring spelling out thatitems[1:]evicts a leading system message on the first compaction, with a pointer toWindowCompactor+pin_systemfor the keep-the-system-prompt variant. Kept the body of the example as-is since the smallest-possible shape is the point.