Repository navigation
Description
Summary
TemporalAgent replaces the agent's model with TemporalModel, whose get_config() returns {}
because the real model lives on the Worker. Strands reads two settings from the model in Workflow
code: context_window_limit, which proactive compression and context_manager="auto" divide by,
and model_id, which its agent and model spans record as gen_ai.request.model. Through the
plugin both are missing, so compression divides by Strands' 200,000-token fallback for every model
and the spans have no model id. Strands logs context_window_limit not set on model, using default, although the Worker's model has it.
With a model whose window is larger than 200,000 tokens (gpt-4.1, or the plugin's default
Bedrock model with 1,000,000), the agent drops earlier turns that a native agent keeps; with a
smaller one (gpt-4o), it keeps turns a native agent drops and sends a larger request.
Versions
temporalio-strands-agents 0.1.0 and main at 6a7330a (TemporalModel.get_config() still
returns {}); also temporalio.contrib.strands in temporalio 1.33.0. strands-agents 1.56.0 (1.51.0 at 1.33.0),
openai 2.54.0, Python 3.13.16, Temporal CLI 1.9.1.
Reproduction
One file. A recording httpx.MockTransport behind the real OpenAIModel reports 150,000 input
tokens for gpt-4.1 and 100,000 for gpt-4o on the first turn. It runs two turns natively with
SlidingWindowConversationManager(proactive_compression=True), then the same two turns in a
Workflow (unsandboxed so it fits in one file) on a Worker with StrandsPlugin(models=...). It
prints the user turns of each second request and exits 0 when the defect shows.
reproduce.py
"""Proactive compression in a TemporalAgent ignores the chosen model's context window.
Strands compresses a conversation before a model call once the projected input reaches
70% of agent.model.context_window_limit, which it derives from the model id
(gpt-4.1: 1,047,576 tokens; gpt-4o: 128,000). Through StrandsPlugin, agent.model is a
TemporalModel whose config is empty, so the limit falls back to 200,000 for every model.
The fake reports the first turn's input tokens; the second request shows whether the
first turn was trimmed.
"""
import asyncio
import json
import shutil
import uuid
from datetime import timedelta
import httpx
from strands import Agent
from strands.agent.conversation_manager import SlidingWindowConversationManager
from strands.models.openai import OpenAIModel
from temporalio import workflow
from temporalio.strands_agents import StrandsPlugin, TemporalAgent
from temporalio.testing import WorkflowEnvironment
from temporalio.worker import Worker
SEEN: list[dict] = []
FIRST_TURN_INPUT_TOKENS = {"gpt-4.1": 150_000, "gpt-4o": 100_000}
async def fake_api(request: httpx.Request) -> httpx.Response:
body = json.loads(request.content)
users = [p["text"] for m in body["messages"] if m["role"] == "user" for p in m["content"]]
SEEN.append({"model": body["model"], "user_messages": users})
tokens = FIRST_TURN_INPUT_TOKENS[body["model"]] if users[-1] == "turn 1" else 1
chunks = [
{"choices": [{"index": 0, "delta": {"role": "assistant", "content": "ok"}, "finish_reason": None}]},
{"choices": [{"index": 0, "delta": {}, "finish_reason": "stop"}]},
{"choices": [], "usage": {"prompt_tokens": tokens, "completion_tokens": 1, "total_tokens": tokens + 1}},
]
sse = "".join("data: " + json.dumps({"id": "c1", "object": "chat.completion.chunk", "created": 0,
"model": body["model"], **c}) + "\n\n" for c in chunks)
return httpx.Response(200, headers={"content-type": "text/event-stream"}, content=(sse + "data: [DONE]\n\n").encode())
class KeepOpen(httpx.AsyncClient):
async def aclose(self) -> None: # OpenAIModel closes its client after each request
return None
def model(model_id: str) -> OpenAIModel:
return OpenAIModel(model_id=model_id, client_args={
"api_key": "key", "base_url": "http://fake-openai.test/v1", "max_retries": 0,
"http_client": KeepOpen(transport=httpx.MockTransport(fake_api))})
def compressing() -> SlidingWindowConversationManager:
return SlidingWindowConversationManager(proactive_compression=True)
async def two_turns(agent: Agent) -> None:
await agent.invoke_async("turn 1")
await agent.invoke_async("turn 2")
# Unsandboxed so the Workflow can live in this one file; the sandboxed feature check gives the same result.
@workflow.defn(sandboxed=False)
class TwoTurnWorkflow:
@workflow.run
async def run(self, model_name: str) -> None:
await two_turns(TemporalAgent(model=model_name, conversation_manager=compressing(), callback_handler=None,
start_to_close_timeout=timedelta(seconds=10)))
async def main() -> None:
models = list(FIRST_TURN_INPUT_TOKENS)
for m in models:
agent = Agent(model=model(m), conversation_manager=compressing(), callback_handler=None)
await two_turns(agent)
print("native ", json.dumps({"context_window_limit": agent.model.context_window_limit, "second_request": SEEN[-1]}))
plugin = StrandsPlugin(models={m: (lambda m=m: model(m)) for m in models})
async with await WorkflowEnvironment.start_local(plugins=[plugin], dev_server_existing_path=shutil.which("temporal")) as env:
async with Worker(env.client, task_queue="tq", workflows=[TwoTurnWorkflow]):
for m in models:
await env.client.execute_workflow(TwoTurnWorkflow.run, m, id=f"two-turn-{uuid.uuid4()}", task_queue="tq")
limit = TemporalAgent(model=m).model.context_window_limit
print("plugin ", json.dumps({"context_window_limit": limit, "second_request": SEEN[-1]}))
n41, n4o, p41, p4o = (s["user_messages"] for s in SEEN[1::2])
assert n41 == ["turn 1", "turn 2"] and p41 == ["turn 2"] # 1M window: plugin drops the first turn, native keeps it
assert n4o == ["turn 2"] and p4o == ["turn 1", "turn 2"] # 128k window: native compresses, plugin does not
print("ASSERTIONS PASSED (they require the defective outcome)")
if __name__ == "__main__":
asyncio.run(main())Output on 0.1.0 and main:
native {"context_window_limit": 1047576, "second_request": {"model": "gpt-4.1", "user_messages": ["turn 1", "turn 2"]}}
native {"context_window_limit": 128000, "second_request": {"model": "gpt-4o", "user_messages": ["turn 2"]}}
plugin {"context_window_limit": null, "second_request": {"model": "gpt-4.1", "user_messages": ["turn 2"]}}
plugin {"context_window_limit": null, "second_request": {"model": "gpt-4o", "user_messages": ["turn 1", "turn 2"]}}
ASSERTIONS PASSED (they require the defective outcome)
The plugin lines print the limit of a new TemporalAgent built outside a Workflow, so they show
null with or without a fix; the second requests are the decisive part.
Expected
The plugin agent keeps or drops turns as the native agent does: turn 1, turn 2 for gpt-4.1 and
turn 2 for gpt-4o. agent.model.get_config() in Workflow code has the model's
context_window_limit and model_id, and Strands' spans carry the model id.
Proposed fix
Before an agent's first invocation, read the Worker model's model_id and context_window_limit
with a new Activity (strands_get_model_config, same Activity options as the model call) and
return them from TemporalModel.get_config() and a config property, which Strands' tracing reads.
Return only those two fields, since a provider config can hold credentials or clients. Load them
inside Strands' invocation guard, before the agent span starts (the fix overrides
_convert_prompt_to_messages, which stream_async awaits there), so Strands still rejects,
deduplicates or aborts overlapping invocations as it does natively. The Activity is a new command, so gate it with workflow.patched(...):
runs whose agents first ran before the change keep the empty config.
This is a breaking change for code that worked around the defect by scaling
compression_threshold by window / 200,000: that code must remove the scaling, or it compresses
too early. Every agent run also schedules one more Activity, and Workers that run the model
Activities need the new version.
A PR follows with this change, a regression test in tests/test_model.py (it fails on main and
passes with the change), updated Activity lists in the existing tests, and a README note.
The TypeScript plugin has the same defect (#157); its fix (#158) uses the same design.
Activity