feat: add memory injection
Description
Python port of #2631
Motivation
The TypeScript SDK ships context injection: a way to fold just-in-time text into the model's input for a single call without persisting it to the durable conversation. The MemoryManager builds on it to surface relevant memories to the model automatically, so the agent doesn't have to spend a tool call searching. Python had neither — MemoryManager (#2740) landed with extraction and search tools but no injection — so the Python MemoryManager could only recall memory reactively via the search_memory tool, never proactively.
This ports the injection primitive to Python and wires it into MemoryManager, bringing the two SDKs to parity. The design follows the TS source: a small, reusable strands.injection engine delivered as an InvokeModelStage.Input middleware, a thin ContextInjector vended plugin for arbitrary content, and a MemoryManager consumer for memory-specific retrieval. Behavior, fail-open semantics, the default <memory> format, the prepend-vs-append fold rule, and trigger policies all mirror the TS implementation.
Ephemerality is the core contract: injected text reaches the model for one call but never enters agent.messages or the session. This falls out of the middleware seam — the engine rewrites the per-call InvokeModelContext.messages (already a defensive copy of agent state), so durable history is untouched.
Memory injection is on by default in both SDKs: if you configure a MemoryManager with stores, the point is to use them, so proactive recall is the obvious-path default rather than a flag you have to discover. Because this also changes the already-shipped TS MemoryManager, it is a behavior change there — see Breaking Changes. Opt out with injection: false / injection=False.
Public API Changes
1. New strands.injection package — shared configuration types for context injection. Delivery primitives are intentionally internal; the public surface is config only:
from strands.injection import InjectionConfig, InjectionContext, InjectionTrigger
2. New ContextInjector vended plugin — folds arbitrary just-in-time text (current time, retrieved docs, request metadata, …) into the model input:
from strands import Agent
from strands.vended_plugins.context_injector import ContextInjector
agent = Agent(
plugins=[
ContextInjector(lambda context: f"<context>{derive(context.messages)}</context>")
]
)
render_content is the only required argument (sync or async; returns the text, or None/"" to skip). Optional keyword-only name (default "strands:context-injector") and trigger ("userTurn" default, "everyTurn", or a predicate over the InjectionContext). A callback that raises fails open — injection is skipped and the model call proceeds.
3. MemoryManager gains an injection option — on by default:
from strands import Agent
from strands.memory import MemoryManager, MemoryInjectionConfig
# Default: inject up to 5 entries on a user turn, rendered as a <memory> block
agent = Agent(plugins=[MemoryManager(stores=[store])])
# Opt out
agent = Agent(plugins=[MemoryManager(stores=[store], injection=False)])
# Or customize retrieval, timing, and formatting
agent = Agent(
plugins=[
MemoryManager(
stores=[store],
injection=MemoryInjectionConfig(
trigger="everyTurn",
max_entries=3,
query=lambda context: derive_query(context.messages),
format=lambda context: render(context.entries),
),
)
]
)
MemoryInjectionConfig extends InjectionConfig. When enabled, MemoryManager derives a query from the conversation (the latest user text on a user turn, else the most recent assistant text), searches its stores, and folds the top entries into the model input. injection defaults to True (False disables it). strands.memory also re-exports InjectionConfig/InjectionContext/InjectionTrigger so injection can be configured from a single import.
The same default flip is applied to the TypeScript MemoryManager (injection?: boolean | MemoryInjectionConfig, now defaulting to enabled) to keep the two SDKs aligned.
One deliberate cross-SDK divergence worth a reviewer's eye: the callback config fields (trigger, render_content, query, format) are typed as Callable | Protocol-with-**kwargs unions rather than the bare Callable the TS side uses. This follows the STYLE_GUIDE's "avoid Callable for extensible interfaces" rule (the Protocol arm lets the calling convention grow keyword arguments later) while the Callable arm keeps the plain-lambda happy path ergonomic under mypy strict — a pure Protocol rejects bare lambdas. This mirrors the existing EdgeCondition pattern in multiagent/graph.py.
Breaking Changes
For the Python MemoryManager, memory injection is new in this PR, so default-on is a fresh default, not a change. For the TypeScript MemoryManager (shipped in #2631), this flips injection from opt-in (false) to opt-out (enabled). Existing TS agents that configure a MemoryManager will now, on each model call, derive a query from the conversation, search their stores, and prepend a <memory> block to the model input — adding tokens and a search round-trip per call, and potentially surfacing irrelevant recall. This is a behavior change under the "pay for play" tenet, called out here for explicit reviewer sign-off; it is not an API-signature break (the field and its type are unchanged).
Migration
// Restore the previous (no-injection) behavior:
new MemoryManager({ stores, injection: false })
# Python equivalent:
MemoryManager(stores=stores, injection=False)
Documentation PR
Follow-up: a docs page for ContextInjector and MemoryManager injection is not included here.
Type of Change
New feature
Testing
How have you tested the change? Verify that the changes do not break functionality or introduce new warnings.
- [ ] I ran
hatch run prepare
Unit tests mirror the TS describe blocks (fold/trigger/query/format/fail-open), plus real-Agent integration tests on both the ContextInjector and MemoryManager paths asserting the injected text reaches the model but never agent.messages.
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.
Assessment: Request Changes
Solid, well-documented port — the ephemerality contract is cleanly modeled on the middleware seam, fail-open semantics are consistent, XML escaping protects the default <memory> format, and the test suite mirrors the TS describe blocks with full-object equality assertions. 135 tests pass and mypy is clean locally.
Two things should be resolved before merge, both around the injection default rather than the implementation itself:
Review themes
-
Default behavior vs. description (blocking): Code defaults
injection=Truewhile the PR description claims it'sFalse/opt-in/non-breaking. Default-on is a real behavior change for existingMemoryManagerusers (extra search + injected context every user turn = latency, token cost, context bloat). The description and code must agree, and the choice should be deliberate. See inline comment onmemory_manager.py:102. -
API review (blocking-ish): This introduces new public primitives — the
strands.injectionpackage, theContextInjectorvended plugin, andMemoryInjectionConfig— plus a default-behavior change to an existing public API. Perteam/API_BAR_RAISING.mdthis is at least a Moderate, arguably Substantial, change (new abstraction customers build on). It needs theapi/needs-reviewlabel and a designated API reviewer; the default-on decision in particular is exactly the kind of "are the defaults the most common/safest?" question bar-raising exists to settle. The PR description is already well-prepared for this (use cases, signatures, exports), which should make the review quick. -
Scope: The PR is titled/scoped as a Python port, but it also flips the TypeScript
MemoryManagerinjection defaultfalse→true(strands-ts/src/memory/memory-manager.ts,types.ts, tests). That's an independent behavior change for TS users and would normally be its own PR; at minimum it should be called out in the description rather than riding along with the port.
Nice work on the fold-rule handling (prepend on a user ask, append after a tool result) and the matching everyTurn tests — that's the subtle part and it's covered.
Assessment: Comment (re-review)
Re-reviewed at efc8b40. Both prior blocking items are resolved, and the public surface is tighter than before. 160 tests pass (up from 135) and mypy is clean locally.
Status of prior feedback
-
Default vs. description (was blocking) — ✅ Resolved. The description now states default-on explicitly, gives the rationale, documents the TS impact as a Breaking Change with a migration snippet, and code/docstrings/
types.pyall agree onTrue. -
Scope / TS default flip (was blocking) — ✅ Resolved. Now called out under "Breaking Changes" with a migration example and a "pay for play" tenet note. Keeping both SDKs aligned in one PR is reasonable now that it's documented.
-
API review — ⚠️ Partially addressed.
efc8b40privatized the delivery primitives (_create_injection_middleware,_resolve_trigger,_is_user_turn,_fold_into_last_user_message,_escape_xml_*), so the public surface is now config-only (InjectionConfig/InjectionContext/InjectionTrigger,ContextInjector,MemoryInjectionConfig) — exactly the right call. The description is also API-review-ready (use cases, signatures, exports, the deliberateCallable | Protocoldivergence). Theapi/needs-reviewlabel is still missing, though: a new customer-facing abstraction plus an opt-in→opt-out default flip on a shipped API is the kind of change bar-raising exists to sign off on. That's the one remaining item — process, not code.
Nice tightening of the public surface in the follow-up commit, and the description rewrite is thorough. Once the api/needs-review label is on and a designated reviewer signs off on the default-on decision, this looks ready from a code standpoint.
Non-blocking nit (don't hold the merge for this) — nice follow-up underscoring the internal functions in efc8b40. The one remaining loose end is the module files themselves:
strands/injection/message_injection.pystrands/injection/xml.py
The functions inside are now _-prefixed (good — from strands.injection.message_injection import fold_into_last_user_message correctly fails), but the module paths still read as public. from strands.injection import message_injection works and exposes the _-prefixed internals with no namespace-level "private" signal.
The repo's own convention is to underscore the module/package, not just its contents — e.g. _middleware/, event_loop/_retry.py, models/_defaults.py, strands/_async.py. Injection is currently the one spot that diverges (functions underscored, files not). Suggestion:
message_injection.py→_message_injection.pyxml.py→_xml.py- update the two relative imports in
memory/memory_manager.pyandvended_plugins/context_injector/plugin.py
Why now rather than later: once released, the module path could become load-bearing for someone, so renaming gets more expensive post-merge. But this is purely a convention/consistency nit — the exported __all__ surface is correct, named-symbol reachability is now fixed, and nothing here is a correctness issue. Totally fine to take it or merge as-is. ✅