Repository navigation
Description
What are you really trying to do?
Run a Strands TemporalAgent with a long conversation history and have it behave like a plain Strands Agent when the model rejects the prompt as too long: the conversation manager trims the history and the model call is retried.
Describe the bug
When a model provider rejects a prompt as too long it raises strands.types.exceptions.ContextWindowOverflowException. A plain Strands Agent catches that in _execute_event_loop_cycle, calls conversation_manager.reduce_context(...) (the default SlidingWindowConversationManager drops the oldest messages) and runs the cycle again.
Under TemporalAgent the model call runs in an activity. StrandsFailureConverter turns the exception into a non-retryable ApplicationError(type="ContextWindowOverflowException"), and TemporalModel.stream in python/strands_agents/src/temporalio/strands_agents/_temporal_model.py lets the resulting ActivityError propagate. Strands only catches ContextWindowOverflowException, so the recovery never runs and the workflow fails after a single model call, however much of the history could have been trimmed.
The comment on _TERMINAL_EXCEPTIONS in _failure_converter.py says TemporalAgent.invoke_async rewraps these as StrandsWorkflowError on the workflow side. I could not find any such rewrap, and StrandsWorkflowError does not exist anywhere in the package, so I think the comment is stale.
Minimal Reproduction
Runs against main @ 5e91c26 with the plugin installed from the checkout (cd python/strands_agents && make sync, then .venv/bin/python repro.py). The model is a stand-in that rejects any prompt longer than 3 messages, so no credentials are needed. The same model is run through a plain Agent first as the control.
import asyncio
import uuid
from datetime import timedelta
from typing import Any
from strands import Agent
from strands.models import Model
from strands.types.exceptions import ContextWindowOverflowException
from temporalio import workflow
from temporalio.client import Client, WorkflowFailureError
from temporalio.strands_agents import StrandsPlugin, TemporalAgent
from temporalio.testing import WorkflowEnvironment
from temporalio.worker import Worker
HISTORY = [
{"role": "user", "content": [{"text": "q1"}]},
{"role": "assistant", "content": [{"text": "a1"}]},
{"role": "user", "content": [{"text": "q2"}]},
{"role": "assistant", "content": [{"text": "a2"}]},
]
SEEN: list[int] = []
class SmallContextModel(Model):
"""Pretends the context window only fits 3 messages."""
def update_config(self, **_: Any) -> None: ...
def get_config(self) -> dict[str, Any]:
return {}
def structured_output(self, *a: Any, **k: Any):
raise NotImplementedError
async def stream(self, messages, *_a, **_k):
SEEN.append(len(messages))
if len(messages) > 3:
raise ContextWindowOverflowException("prompt is too long")
yield {"messageStart": {"role": "assistant"}}
yield {"contentBlockDelta": {"delta": {"text": "ok"}}}
yield {"contentBlockStop": {}}
yield {"messageStop": {"stopReason": "end_turn"}}
@workflow.defn
class W:
@workflow.run
async def run(self) -> str:
agent = TemporalAgent(
model="small",
messages=[dict(m) for m in HISTORY],
callback_handler=None,
start_to_close_timeout=timedelta(seconds=10),
)
return str(await agent.invoke_async("q3"))
async def main() -> None:
result = await Agent(
model=SmallContextModel(), messages=[dict(m) for m in HISTORY], callback_handler=None
).invoke_async("q3")
print("plain Agent:", repr(str(result)), "model saw message counts", SEEN)
SEEN.clear()
async with await WorkflowEnvironment.start_local() as env:
config = env.client.config()
config["plugins"] = [StrandsPlugin(models={"small": SmallContextModel})]
client = Client(**config)
async with Worker(client, task_queue="q", workflows=[W]):
try:
result = await client.execute_workflow(
W.run, id=f"wf-{uuid.uuid4()}", task_queue="q", execution_timeout=timedelta(seconds=30)
)
print("TemporalAgent:", repr(result), "model saw message counts", SEEN)
except WorkflowFailureError as e:
chain, c = [], e
while c is not None:
chain.append(f"{type(c).__name__}: {str(c)[:40]}")
c = c.__cause__
print("TemporalAgent: workflow failed, model saw message counts", SEEN)
print(" " + " <- ".join(chain))
if __name__ == "__main__":
asyncio.run(main())Output on main:
plain Agent: 'ok\n' model saw message counts [5, 3]
TemporalAgent: workflow failed, model saw message counts [5]
WorkflowFailureError: Workflow execution failed <- ActivityError: Activity task failed <- ApplicationError: ContextWindowOverflowException: prompt i
Expected: TemporalAgent behaves like the plain Agent (second model call sees 3 messages, result 'ok\n').
Environment/Versions
- OS and processor: macOS, arm64
- Temporal Version: temporalio 1.34.0 (local dev server via
WorkflowEnvironment.start_local(): Temporal CLI 1.9.1, Server 1.32.0), temporalio-strands-agents frommain@ 5e91c26, strands-agents 1.56.0, Python 3.14.7 - Are you using Docker or Kubernetes or building Temporal from source? No
Additional context
I have a fix ready. TemporalModel.stream catches the ActivityError, and when its cause is an ApplicationError of type ContextWindowOverflowException it raises ContextWindowOverflowException (chained from the ActivityError) so Strands handles it as it would without Temporal. The retry is deterministic workflow code: each model call is its own activity, so the failed attempt and the retried one are separate events in the history and replay is unaffected.
One thing that change needs: if the conversation manager cannot reduce the context any further, Strands re-raises ContextWindowOverflowException out of invoke_async. In workflow code a plain exception like that fails the workflow task, which is retried indefinitely, whereas before this change the same case failed the workflow. So the fix also lists ContextWindowOverflowException in the plugin's workflow_failure_exception_types, the way the other Python plugins register their error types. With only the TemporalModel change, the always-overflowing variant of the script above ends in TimeoutError: Workflow timed out instead of a prompt failure.
I kept this to the overflow case. The other exceptions the converter marks non-retryable (MaxTokensReachedException, StructuredOutputException, SessionException) have no recovery path in the Strands event loop, so there is nothing for the workflow to retry with; they keep reaching the workflow as an ActivityError. The fix also corrects the stale StrandsWorkflowError comment. I will open a PR for it.
Activity