feat: port agentic context management to python
Description
Ports the agentic context-management feature from strands-ts (#2754) to strands-py.
Motivation
The TypeScript SDK shipped an "agentic" context strategy that hands this control to the model: it injects compression tools the model can call, and feeds it live token-usage telemetry so it can decide when to compress. This change brings that capability to the Python SDK at parity.
Public API Changes
context_manager now accepts "agentic" in addition to "auto":
from strands import Agent
# The model manages its own context via injected tools.
agent = Agent(context_manager="agentic")
In agentic mode the agent gains three model-callable tools and a token-usage middleware:
summarize_context— fold the oldest messages into a model-generated summarytruncate_context— drop the oldest messages outrightpin_context— pin/unpin messages so they survive compression
Before each model call, a <context-status> block is appended to the conversation so the model can see how much of the window it has used:
<context-status>
<used>50,000 / 200,000 tokens (25.0%)</used>
<remaining>~150,000 tokens</remaining>
</context-status>
Unlike "auto", agentic mode does not enable proactive compression — the model drives compression itself, and the underlying SummarizingConversationManager remains only as a reactive overflow safety net. It also offloads tool results at a higher threshold (8k vs 1.5k tokens), since the model is responsible for managing its own inline context.
Implementation notes
Two structural decisions worth surfacing for review:
- Shared compression primitives. Mirroring the TS layout, the tool-pair-safe split/trim helpers, summary generation, and pin utilities now live in a
conversation_manager/compression/package. The existing summarizing and sliding-window managers were refactored onto these shared helpers. This refactor is behavior-preserving — notably, the sliding-window manager keeps its Python-only "fall back to a tool-pair boundary" path, which has no TS equivalent and was deliberately not collapsed into the sharedfind_valid_trim_point. - Fully internal surface. The pin utilities and agentic tools/middleware are intentionally not exported from any public
__init__.py; they're reachable only by full module path. The sole re-export is theDEFAULT_SUMMARIZATION_PROMPTconstant (kept for backward compatibility on its original module).
Related Issues
Ports the feature added to strands-ts in #2754.
Documentation PR
None in this PR — docs for the agentic strategy are tracked separately.
Type of Change
New feature
Testing
Unit tests cover the three tools, the shared compression helpers, and the token-usage middleware (including full agent-loop integration against a mocked model). Integration tests under tests_integ/ exercise the feature end-to-end against Bedrock — verifying the model actually invokes the compression tools, that pinning protects messages from truncation, and that the agent stays coherent after compressing its own history. The existing conversation-manager and pin test suites pass unchanged, confirming the refactor introduced no regressions.
- [x] I ran
hatch run prepare
Checklist
- [x] I have read the CONTRIBUTING document
- [x] I have reviewed and understand every line of code in this PR, including any generated by AI tools, and I can explain why it works
- [x] My change is focused and reasonably small; I have split unrelated work into separate PRs
- [x] I have added any necessary tests that prove my fix is effective or my feature works
- [ ] I have updated the documentation accordingly
- [ ] I have added an appropriate example to the documentation to outline the feature, or no new docs are needed
- [x] My changes generate no new warnings
- [x] Any dependent changes have been merged and published
By submitting this pull request, I confirm that you can use, modify, copy, and redistribute this contribution, under the terms of your choice.
/strands review
@agent-of-mkmeral review the PR. Especially confirm
- parity with TS agentic mode.
- no regressions in existing conversation manager refactor
- python conventions, no construct of agentic mode is exported. The feature is fully internal; following internal guidelines
Assessment: Comment
Clean, well-structured port. The shared compression/ package is a tidy way to dedupe the split/trim/summary primitives across the reactive managers and the new agentic tools, and the refactor is behavior-preserving — the full conversation-manager and pin suites pass unchanged (147 tests green locally), and ruff/mypy are clean on the changed paths. Two input-validation gaps in pin_context/summarize_context are worth tightening (inline). Addressing your three explicit asks:
1. Parity with TS agentic mode
Strong parity. Tool semantics, the <context-status> block format, middleware copy-on-write behavior, the constants, and collect_preserved/find_valid_trim_point logic all match strands-ts. The one divergence is input validation: TS enforces bounds declaratively in Zod (min(0)/min(1)/min(2)/min(0.1).max(0.8)), whereas the Python @tool schemas generated from type hints carry no such bounds. The practical fallout is the negative-index issue flagged inline — pin_context(select=[-1]) silently pins the last message instead of erroring.
2. No regressions in the conversation-manager refactor
Confirmed. SummarizingConversationManager and SlidingWindowConversationManager now delegate to the shared helpers; the sliding-window manager correctly retains its Python-only _find_tool_pair_trim_point fallback (no TS equivalent), and the thin _adjust_split_point_for_tool_pairs wrapper preserves the subclass/test override surface. The existing suites — including the pin tests — pass without modification beyond the import-path updates.
3. Python conventions / fully-internal surface
Confirmed internal. The tools, middleware, and pin utilities are reachable only by full module path; no new public __init__ exports, and DEFAULT_SUMMARIZATION_PROMPT remains re-exported on its original module for backward compat. Logging style, type annotations, and Google-style docstrings all follow strands-py/AGENTS.md.
One process note: this adds "agentic" to the public ContextManagerStrategy literal, which is a customer-facing API surface change. The PR description has excellent API docs (use cases, signatures, examples), but there's no api/needs-review label — per team/API_BAR_RAISING.md this looks like a "Moderate" change that warrants a quick API-reviewer sign-off. Worth confirming with a maintainer.
Nicely done overall — the integration tests exercising real tool invocation and pin-survival are a great touch.
@notowen333 — TL;DR: Parity with TS is strong w/ one validation divergence; no regressions (147 tests pass); surface fully internal; reproduced a negative-index pin_context bug; one minor API-bar-raising note. (The automated github-actions review above at 20:16:55Z is also mine — re-posting directly now that I'm unblocked.) Details below.
1. Parity with TS agentic mode — ✅ strong, one divergence
Tool semantics, the <context-status> block format, middleware copy-on-write, the constants, and collect_preserved/find_valid_trim_point all match strands-ts. The only divergence is input validation: TS enforces bounds declaratively in Zod (select min(0), last-N min(1), keepRecent.min(2), summaryRatio.min(0.1).max(0.8)), whereas the Python @tool schemas generated from type hints carry no lower/upper bounds.
2. No regressions in the conversation-manager refactor — ✅ confirmed
Ran tests/strands/agent/conversation_manager/, test_conversation_manager.py, and test_pin_message.py → 147 passed unchanged. SlidingWindowConversationManager correctly keeps its Python-only _find_tool_pair_trim_point fallback (no TS equivalent), and the thin _adjust_split_point_for_tool_pairs wrapper preserves the subclass/test override surface.
3. Fully-internal surface — ✅ confirmed
grep of all __init__.py shows no leaks of agentic / summarize_context / truncate_context / pin_context; everything is reachable only by full module path. Only DEFAULT_SUMMARIZATION_PROMPT remains re-exported on its original module for backward compat.
Bug I independently reproduced (matches the inline finding)
pin_context(select=[-1]) returns "Pinned 1 message(s)." and silently pins the last message instead of erroring, because of Python list-index semantics — TS guards this at the schema level. Suggested fix: bound both ends, e.g. candidate_indices = [i for i in select if 0 <= i < len(messages)], and clamp the last-N / keep_recent paths the same way.
Process note (API bar-raising)
This adds "agentic" to the public ContextManagerStrategy literal — a customer-facing API surface change. The PR description has great API docs, but there's no api/needs-review label; per team/API_BAR_RAISING.md this reads as a "Moderate" change worth a quick API-reviewer sign-off.
Nicely done overall — the integration tests exercising real tool invocation and pin-survival are a great touch.
Re-review — refactor: lift agentic mode to context_manager package; address PR feedback ✅
Re-reviewed the latest commit (2f426ed). Both items I flagged are resolved, and the package restructure is clean. Approve from my side.
Negative-index / input-bounds fixes — verified by execution
Reproduced the previously-broken cases against the new code:
| Input | Before | Now |
|---|---|---|
pin_context(select=[-1]) |
"Pinned 1 message(s)." (silently pinned last msg) |
"All indices out of range (conversation has 5 messages)." — nothing pinned |
pin_context(select=-1) (int) |
wrapped via list semantics | "No matching messages found." — clamped to 0, nothing pinned |
The fixes match what TS enforces declaratively in Zod:
- list branch →
[i for i in select if 0 <= i < len(messages)] - int branch →
count = min(max(0, select), len(messages)) summarize_context/truncate_contextnow clampkeep_recenttomax(_MIN_MESSAGES_FOR_COMPRESSION, ...)
Nice touch adding dedicated regression tests (test_rejects_negative_indices, test_pins_valid_indices_and_drops_negative_ones, test_clamps_to_conversation_length) — exactly the right place to lock this in.
Package restructure (conversation_manager/modes → context_manager) — sound
- Layering is clean: the new top-level
context_managerpackage depends one-way on the sharedagent.conversation_manager.compressionprimitives; no cycle. agent.pykeeps the agentic imports function-local inside thecontext_manager == "agentic"branch, so the package only loads when the mode is active and there's no import cycle withagent.- TS mirror moved in lockstep (
strands-ts/src/context-manager/modes/agentic/), preserving cross-SDK parity. - Surface remains fully internal — no new public
__init__exports.
Validation
- 149 tests pass (
conversation_manager/,test_conversation_manager.py,test_pin_message.py) — up from 147, reflecting the new regression tests. ruff+mypyclean acrosscontext_manager/,conversation_manager/, andagent.py.
The only remaining open item is non-blocking and out of your hands: the "agentic" addition to the public ContextManagerStrategy literal could use a maintainer's API-bar-raising sign-off (api/needs-review). Thanks for the quick turnaround on the fixes! 🚀
@notowen333 — re-confirmed against the latest commit 2f426ed (the context_manager package lift). All three asks pass; approving:
- Parity with TS agentic mode — ✅ Tool semantics,
<context-status>format, middleware copy-on-write, constants, andcollect_preserved/find_valid_trim_pointall matchstrands-ts. The one prior divergence (input bounds) is now closed: list branch[i for i in select if 0 <= i < len(messages)], int branchmin(max(0, select), len(messages)), andkeep_recentclamped — mirroring the Zod guards. TS mirror moved in lockstep (context-manager/modes/agentic/). - No regressions — ✅ 149 tests pass (up from 147 via the new
test_rejects_negative_indices/test_clamps_to_conversation_lengthregression tests);ruff+mypyclean. Sliding-window manager keeps its Python-only_find_tool_pair_trim_pointfallback; override surface preserved. - Fully internal — ✅ New top-level
context_managerpackage depends one-way on the sharedcompressionprimitives (no cycle);agent.pykeeps agentic imports function-local to the== "agentic"branch; no new public__init__exports.
Full execution-verified detail is in my re-review just above (21:23:55Z). Only non-blocking item is out of your hands: the "agentic" addition to the public ContextManagerStrategy literal could use a maintainer's api/needs-review sign-off. Great turnaround 🚀
Re-review — commit 4efbf06 (drop empty __init__.py from context_manager namespace package) ✅
Reviewed the latest commit addressing @lizradway's feedback to remove the three empty __init__.py files. Still approving — the change is safe and correctly verified the one real risk (namespace-package packaging/discovery).
Namespace-package packaging — verified by building a wheel
The concern with removing __init__.py is that context_manager/ becomes a PEP 420 namespace package, which build tools can silently drop. Confirmed it's packaged correctly:
- Wheel build (
python -m build --wheel) includes the module:
Hatchling packages by directory path (strands/context_manager/modes/agentic/agentic_context.pypackages = ["src/strands"]), so the namespace dirs are preserved in the distributable. - Runtime imports resolve:
import strands.context_manager.modes.agentic→_NamespacePath([...]), and the full-path tool imports (summarize_context/truncate_context/pin_context/create_token_usage_middleware) all work. Agentconstructs fine with the agentic branch intact.
Validation
- 149 tests pass (
conversation_manager/,test_conversation_manager.py,test_pin_message.py) — unchanged. ruffclean on all changed paths.mypy ./srcresolves the namespace package with no issues on PR-touched files. (The 36 errors that surface are all pre-existing in unrelateda2a/fastapioptional-dependency modules, none incontext_manager/conversation_manager/agent.py.)
This is the right call — keeping zero-export __init__.py files around would just be dead scaffolding. The only remaining open item is unchanged and out of your hands: a maintainer's api/needs-review sign-off on the "agentic" literal addition. 🚀
Codecov Report
:x: Patch coverage is 91.06383% with 21 lines in your changes missing coverage. Please review.
:loudspeaker: Thoughts on this report? Let us know!
Re-review — commit bd73525 (rename context_manager → internal _context_manager package) ✅
Reviewed the latest commit, which reverts the namespace-package approach in favor of the established _middleware convention: underscore-prefixed package name + restored __init__.py files marked "Internal only. Do not export.". Still approving — this is a cleaner, more idiomatic way to signal "internal" than the namespace-package route, and it's consistent with how the codebase already marks private packages.
Public API unchanged — verified
The rename is purely internal. The customer-facing kwarg stays context_manager, and the literal is still ContextManagerStrategy = Literal["auto", "agentic"]. agent.py keeps the agentic imports function-local inside the context_manager == "agentic" branch, now pointing at .._context_manager.modes.agentic.agentic_context. Agent(context_manager="agentic") constructs cleanly and registers all three tools (summarize_context, truncate_context, pin_context).
Fully internal — confirmed
_context_manageris not instrands.__all__; reachable only by full module path.- All three
__init__.pyfiles carry the"Internal only. Do not export."marker. - No stale
strands.context_managerreferences anywhere insrc/tests/tests_integ— the rename is complete and consistent (test imports usestrands._context_manager...). - The
context_managermatches inbidi/are unrelated (a log string + an async-context-manager variable), not the package.
Packaging + validation
- Wheel build includes all four files (the three
__init__.pymarkers +agentic_context.py) understrands/_context_manager/. - 179 tests pass: 149 (
conversation_manager/,test_conversation_manager.py,test_pin_message.py) + 30 (test_agentic_context.py). ruffclean on changed paths;mypyclean on_context_manager/andagent.py.
Good call switching to the underscore convention — it matches _middleware and makes the "internal" intent obvious at the package level. No remaining concerns from me; the only open item is still the non-blocking maintainer api/needs-review sign-off on the "agentic" literal. 🚀
@notowen333 — re-confirmed against the latest head bd73525 (the context_manager → internal _context_manager rename, plus the earlier 4efbf06 __init__.py cleanup and @lizradway's feedback). All three asks still pass; approving:
- Parity with TS agentic mode — ✅ Tool semantics,
<context-status>format, middleware copy-on-write, constants, andcollect_preserved/find_valid_trim_pointall matchstrands-ts; the input-bounds fixes from2f426edstill mirror the Zod guards. The rename is internal-only — customer-facing kwarg stayscontext_managerand the literal staysContextManagerStrategy = Literal["auto", "agentic"]. - No regressions — ✅ 179 tests pass (149 conversation-manager/pin + 30
test_agentic_context.py);ruffclean,mypyclean on_context_manager/+agent.py. Sliding-window fallback and override surface preserved. - Fully internal — ✅
_context_manageris underscore-prefixed (matching the_middlewareconvention), not instrands.__all__, reachable only by full module path; all three__init__.pycarry"Internal only. Do not export.";agent.pykeeps agentic imports function-local to the== "agentic"branch. No stalestrands.context_managerreferences remain.
Good call switching to the _-prefix convention over the PEP-420 namespace-package route — it makes the internal intent obvious at the package level. Full execution-verified detail is in the re-reviews above (4efbf06 @ 23:13Z, bd73525 @ 13:23Z).
Two non-blocking items, neither a regression:
- Coverage: codecov flags 91% patch coverage — the uncovered lines are mostly error/edge branches in
agentic_context.pyandcompression/context_compression.py. Worth a couple of targeted tests on those branches, but not a blocker. - API sign-off: the
"agentic"literal addition still wants a maintainer'sapi/needs-reviewperteam/API_BAR_RAISING.md— out of your hands. Nice iteration 🚀
Re-review — commit 0b2b608 (sort imports in agentic test files) + codecov follow-up ✅
Reviewed the latest commit (0b2b608, "style: sort imports in agentic test files after _context_manager rename") and the codecov report. Still approving — the import sort is clean and the only outstanding item is non-blocking test coverage.
Import sort + regression check
ruff checkpasses on all three agentic test files (test_agentic_context.py,test_context_compression.py,test_token_usage_middleware.py) — imports correctly grouped stdlib → third-party → first-party, with the newstrands._context_manager...path sorted into place.- 149 tests pass (
conversation_manager/,test_conversation_manager.py,test_pin_message.py);mypyclean on_context_manager/,compression/, andagent.py. No regressions from the rename or the sort.
Codecov 91% patch coverage — mostly defensive branches, a few worth a test
Reproduced the patch coverage locally (66 agentic/compression tests pass). Breaking down the flagged misses by whether they're material:
agentic_context.py (94%) — uncovered lines are mostly error-return strings and the _matches_pin_filter unreachable fallback, but two are genuinely testable behaviors:
121-122— theContextWindowOverflowExceptionhandler insummarize_context(the "no valid split boundary found" message). A test passing a conversation whosekeep_recentlands mid-tool-call would cover this real user-facing path.- The
unpinaction branch inpin_context(281/284) —pin_contextis only exercised withaction="pin"; a round-trip pin→unpin test would close this and lock in the unpin semantics.
context_compression.py (87%) — 137-142 is the tool-pair boundary advancement in the trim-point search (skip a toolUse not followed by a toolResult). This is core tool-pair-safety logic, not an error branch — worth a direct test with a dangling toolUse at the trim boundary. The remaining misses (189 RuntimeError on empty model response, 212 unreachable filter fallback) are fine to leave.
None of these block — the happy paths and the previously-fixed input-bounds cases are well covered — but the three above (summarize_context overflow, unpin, dangling-toolUse trim) are behavior rather than dead defensive code, so a few targeted tests would be a nice tightening.
No remaining concerns from me. The two open items are both non-blocking: (1) the optional coverage nits above, and (2) the unchanged maintainer api/needs-review sign-off on the public "agentic" literal. Thanks for the continued cleanup 🚀
@notowen333 — this is now merged (14:11:59Z) with @lizradway's maintainer approval, so the API-bar-raising item I'd flagged is resolved. Final confirmation against the merged state (head 0b2b608):
- Parity with TS agentic mode — ✅ All primitives (tool semantics,
<context-status>format, middleware copy-on-write, constants,collect_preserved/find_valid_trim_point) matchstrands-ts; input-bounds fixes mirror the Zod guards; TS mirror moved in lockstep. - No regressions — ✅ 179 tests pass (149 conversation-manager/pin + 30 agentic);
ruff/mypyclean; sliding-window fallback + override surface preserved. - Fully internal — ✅
_context_manageris underscore-prefixed, not instrands.__all__, reachable only by full module path; all__init__.pymarked "Internal only. Do not export."; agentic imports function-local inagent.py. No stale references.
Only residual (non-blocking, post-merge follow-up if desired): the codecov 91% patch gap — three branches are real behavior worth a targeted test (summarize_context overflow handler, pin_context unpin round-trip, dangling-toolUse trim boundary in context_compression.py); the rest are defensive/unreachable. Happy to open a small follow-up PR for those if you'd like. Nice work landing this 🚀