`get_final_message()` does not propagate `message_delta.container` into aggregated Message (breaks code_execution continuation)
Summary
When using AsyncAnthropic.messages.stream() (streaming mode) with code_execution_20260120 (or any container-backed tool), the Message.container field returned by stream.get_final_message() is None, because the streaming aggregator does not merge delta.container from the message_delta SSE event into the accumulated Message.
The same API call via non-streaming messages.create() returns the container correctly.
This forces every caller to either:
- manually subscribe to
RawMessageDeltaEventand extractevent.delta.container.idthemselves, or - fall back to non-streaming mode (losing streaming benefits)
Without the container id, the subsequent API request fails with:
anthropic.BadRequestError: 400 - container_id is required when there are pending tool uses generated by code execution with tools.
Reproduction
Environment:
- SDK version:
anthropic==0.94.0 - Model:
claude-opus-4-7 - Tool:
code_execution_20260120
import asyncio
from anthropic import AsyncAnthropic
TOOLS = [{"type": "code_execution_20260120", "name": "code_execution"}]
PROMPT = [{"role": "user", "content": "print(2+2)"}]
COMMON = dict(
model="claude-opus-4-7",
max_tokens=2048,
system="Use code_execution.",
messages=PROMPT,
tools=TOOLS,
)
async def main() -> None:
client = AsyncAnthropic()
# --- streaming: .container is None ---
async with client.messages.stream(**COMMON) as stream:
async for _ in stream:
pass
final = await stream.get_final_message()
print("streaming final.container =", final.container) # None
# --- non-streaming: .container is populated ---
msg = await client.messages.create(**COMMON)
print("non-streaming msg.container =", msg.container) # Container(id=..., expires_at=...)
asyncio.run(main())
Where the data actually lands in streaming mode
Walking the raw stream events, the container info is present in a message_delta SSE event:
[RawMessageDeltaEvent]
{
"delta": {
"container": {
"id": "container_011CaGQWUDRWUFkRs833a8rF",
"expires_at": "2026-04-21T07:00:21.511595Z"
},
"stop_reason": "end_turn"
},
"type": "message_delta",
"usage": {...}
}
But the streaming aggregator in src/anthropic/lib/streaming/_messages.py never merges delta.container into the accumulated Message. Confirmed on main as of this writing (0.94.0 through 0.96.0): the message_delta branch of accumulate_event() only updates current_snapshot.stop_reason / stop_sequence / usage; grep container on the file returns zero non-import matches.
(The higher-level tool_runner helper appears to handle some aspects of container lifecycle on its own, but users of the low-level messages.stream() API are affected by this gap.)
Expected behavior
When a message_delta SSE event carries delta.container, the streaming aggregator should set the corresponding field on the accumulated Message, so stream.get_final_message().container matches the behavior of messages.create().
Impact
Any application doing multi-turn tool-use loops with code_execution_20260120 + streaming receives a 400 on the second turn, because the caller cannot obtain the container id from the SDK's happy-path API. The common workarounds (manual SSE parsing, or switching to non-streaming) feel like SDK bugs rather than user concerns.
Workaround
Intercept RawMessageDeltaEvent manually and stash event.delta.container.id during iteration:
from anthropic.types import RawMessageDeltaEvent
streamed_container_id: str | None = None
async with client.messages.stream(...) as stream:
async for ev in stream:
if isinstance(ev, RawMessageDeltaEvent):
delta_container = getattr(ev.delta, "container", None)
if delta_container is not None:
streamed_container_id = delta_container.id
final = await stream.get_final_message()
# streamed_container_id now has the value that `final.container` should have held
Suggested fix
In src/anthropic/lib/streaming/_messages.py accumulate_event(), extend the elif event.type == "message_delta" branch (lines 503-516 in 0.94.0, same place where current_snapshot.stop_reason / stop_sequence / usage are updated) to also propagate container:
if getattr(event.delta, "container", None) is not None:
current_snapshot.container = event.delta.container
Related
- #1020 — streaming aggregator is bypassed for Vertex beta messages (different but same category: aggregator gap)
Seems similar to (or the same as?) https://github.com/anthropics/anthropic-sdk-python/issues/1422
The container propagation issue in get_final_message() is more than just a type bug — it directly impacts multi-step agent workflows where code execution needs to continue across message boundaries.
In production agent pipelines, we see this pattern constantly: an agent starts a computation, gets a partial result, and needs to continue — but if the container context gets lost between message deltas, the agent either restarts from scratch (expensive) or hallucinates the missing context (dangerous).
This ties into a broader issue IBM's VAKRA benchmark exposed: agents already struggle with multi-step reasoning, and SDK-level context loss makes it worse. We documented some of these failure modes: https://miaoquai.com/stories/vakra-benchmark-agent-failures.html
The fix for container propagation is important, but the deeper question is: how should SDKs handle partial state across long-running agent chains? Streaming fixes the UX, but state continuity across steps is the real unsolved problem.
Still present on anthropic 0.109.2 and 0.115.1 (Python 3.9, macOS) — reproduced on both versions with the sync client (anthropic.Anthropic().messages.stream(...)), so this is not specific to AsyncAnthropic or to code_execution.
Additional impact: pause_turn resume with server tools is broken without a workaround
The original report shows the failure on the second turn of an explicit tool-use loop. There is a harder variant: server tools that run in a code-execution container (web_search_20260209 / web_fetch_20260209) frequently end a turn with stop_reason="pause_turn". To resume, the API requires the container parameter — but since get_final_message().container is None, the client never has the id, and the resume fails with:
400 invalid_request_error: container_id is required when there are pending tool uses generated by code execution with tools.
(example request_id: req_011CcdGJV8FGXG4Y3qENU7zv)
Non-streaming create() returns message.container correctly, but for long server-tool turns streaming is exactly what's recommended (non-streaming runs into the ~10-minute limit) — so the pause_turn + streaming combination is broken out of the box.
Repro (sync client, web_search)
import anthropic
client = anthropic.Anthropic()
TOOLS = [{"type": "web_search_20260209", "name": "web_search", "max_uses": 1}]
with client.messages.stream(
model="claude-sonnet-4-6",
max_tokens=800,
tools=TOOLS,
messages=[{"role": "user", "content": "Search the web for 'Race Across Germany 2025 winner' and give one sentence."}],
) as st:
for ev in st:
if ev.type == "message_delta":
print("delta has container:", ev.model_dump()["delta"].get("container"))
final = st.get_final_message()
print("final.container:", final.container) # -> None (BUG)
Observed: the message_delta delta carries {'id': 'container_01…', 'expires_at': …}, yet final.container is None.
One note on the workaround: depending on the version, the typed attribute may not exist on the delta, so a robust extraction needs to also check model_extra:
if ev.type == "message_delta":
c = getattr(ev.delta, "container", None) or (ev.delta.model_extra or {}).get("container")
The suggested fix in the original post (propagating container in the message_delta branch of accumulate_event(), analogous to stop_reason/usage) would resolve both scenarios. 🙏
This will be fixed holistically in v0.122.0 (commit)