Skip to content

The agent that grows with you

fix(bedrock): Claude reasons over Converse and replays per-model reasoning

Teknium3e31dc223956
diff --git a/agent/bedrock_adapter.py b/agent/bedrock_adapter.py
index e71243109d6..0b5b7ac8817 100644
--- a/agent/bedrock_adapter.py
+++ b/agent/bedrock_adapter.py
@@ -773,17 +773,66 @@ def _parse_tool_args(args) -> Any:
return {}
+def _redacted_reasoning_block(encoded) -> Optional[dict]:
+ redacted = _decode_redacted(encoded)
+ return {"reasoningContent": {"redactedContent": redacted}} if redacted is not None else None
+
+
+def _reasoning_text_block(text, signature) -> dict:
+ reasoning_text = {"text": text if isinstance(text, str) else ""}
+ if isinstance(signature, str) and signature:
+ reasoning_text["signature"] = signature
+ return {"reasoningContent": {"reasoningText": reasoning_text}}
+
+
+# Anthropic Messages block -> Converse block, for turns produced on the AnthropicBedrock path and sent
+# over Converse after the sticky stream-denied fallback (same Claude signatures, Converse union shape).
+_ANTHROPIC_TO_CONVERSE = {
+ "thinking": lambda b, args: _reasoning_text_block(b.get("thinking"), b.get("signature")),
+ "redacted_thinking": lambda b, args: _redacted_reasoning_block(b.get("data")),
+ "text": lambda b, args: {"text": b["text"]} if isinstance(b.get("text"), str) and b["text"].strip() else None,
+ # Input is re-sourced from the redacted tool_calls, never the raw captured block.
+ "tool_use": lambda b, args: _tool_use_block(b.get("id", ""), b.get("name", ""), args.get(b.get("id"), b.get("input", {}))),
+}
+
+
+def _anthropic_ordered_blocks(msg: dict) -> list[dict]:
+ args = {
+ tc.get("id"): _parse_tool_args((tc.get("function") or {}).get("arguments", "{}"))
+ for tc in (msg.get("tool_calls") or []) if isinstance(tc, dict)
+ }
+ converted = (
+ _ANTHROPIC_TO_CONVERSE[b["type"]](b, args)
+ for b in (msg.get("anthropic_content_blocks") or [])
+ if isinstance(b, dict) and b.get("type") in _ANTHROPIC_TO_CONVERSE
+ )
+ return [block for block in converted if block is not None]
+
+
+def _reasoning_details_blocks(msg: dict) -> list[dict]:
+ """Signed and redacted thinking from ``reasoning_details`` (Anthropic shape, or Converse's own redacted
+ capture), in stored order. Converse wants reasoning ahead of toolUse."""
+ blocks = []
+ for d in msg.get("reasoning_details") or []:
+ if not isinstance(d, dict):
+ continue
+ if d.get("type") == "thinking" and d.get("signature"):
+ blocks.append(_reasoning_text_block(d.get("thinking"), d["signature"]))
+ elif d.get("type") == "redacted_thinking" and (block := _redacted_reasoning_block(d.get("data") or d.get("redactedContentBase64"))):
+ blocks.append(block)
+ return blocks
+
+
def _assistant_blocks(msg: dict, content) -> list[dict]:
- """Assistant message → Converse blocks. An ordered ``bedrock_content_blocks`` sidecar is authoritative;
- otherwise redacted thinking from ``reasoning_details`` (byte-for-byte), then text, then tool calls."""
+ """Assistant message → Converse blocks, from the first carrier that yields any: the ordered
+ ``bedrock_content_blocks`` sidecar, the ordered ``anthropic_content_blocks`` sidecar, else thinking
+ from ``reasoning_details`` followed by text, then tool calls."""
ordered_blocks = msg.get("bedrock_content_blocks")
if isinstance(ordered_blocks, list) and (content_blocks := _replay_ordered_blocks(ordered_blocks)):
return content_blocks
- redacted = [
- _decode_redacted(d.get("data") or d.get("redactedContentBase64"))
- for d in (msg.get("reasoning_details") or []) if isinstance(d, dict) and d.get("type") == "redacted_thinking"
- ]
- content_blocks: list[dict] = [{"reasoningContent": {"redactedContent": r}} for r in redacted if r is not None]
+ if content_blocks := _anthropic_ordered_blocks(msg):
+ return content_blocks
+ content_blocks = _reasoning_details_blocks(msg)
if isinstance(content, str) and content.strip():
content_blocks.append({"text": content})
elif isinstance(content, list):
@@ -794,10 +843,67 @@ def _assistant_blocks(msg: dict, content) -> list[dict]:
return content_blocks
-def convert_messages_to_converse(messages: list[dict]) -> tuple[Optional[list[dict]], list[dict]]:
+# Per-model reasoning replay on Converse: (turns before the in-flight tool loop, turns inside it).
+# signed — Claude: everything verbatim, signatures and redactedContent included (AWS: "You must include
+# the signature and all previous messages"; Bedrock ignores older turns server-side for free).
+# strip — DeepSeek-R1 (AWS's multi-turn sample removes reasoningContent) and Kimi K3 (Converse raises
+# InternalServerException "when reasoning content from earlier turns is included"): prior turns
+# lose reasoning, the in-flight loop replays the model's own blocks as captured.
+# unsigned — every other model: prior turns carry readable reasoningText only, since their signatures and
+# redacted blobs may be another model's (a /model switch from Claude) and non-Claude models
+# reject them ("This model doesn't support the reasoningContent.reasoningText.signature field");
+# the in-flight loop was produced by the model now answering and replays as captured.
+_CONVERSE_REPLAY_STRIP_PATTERNS = ("deepseek.r1", "deepseek-r1", "moonshotai.kimi-k3")
+
+
+def _converse_replay_policy(model: Optional[str]) -> str:
+ if model is None:
+ return "signed"
+ if _APPLICATION_PROFILE_ARN_RE.search(model):
+ model = _resolve_inference_profile_model_id(model) # cached; the profile ARN names no model
+ lowered = model.lower()
+ if "claude" in lowered:
+ return "signed"
+ return "strip" if any(p in lowered for p in _CONVERSE_REPLAY_STRIP_PATTERNS) else "unsigned"
+
+
+def _unsigned_reasoning(block: dict) -> Optional[dict]:
+ reasoning = block.get("reasoningContent")
+ if not isinstance(reasoning, dict):
+ return block
+ text = (reasoning.get("reasoningText") or {}).get("text")
+ return {"reasoningContent": {"reasoningText": {"text": text}}} if isinstance(text, str) and text.strip() else None
+
+
+def _verbatim(block: dict) -> dict:
+ return block
+
+
+def _without_reasoning(block: dict) -> Optional[dict]:
+ return None if "reasoningContent" in block else block
+
+
+_REASONING_FILTERS = { # policy -> (before the in-flight tool loop, inside it)
+ "signed": (_verbatim, _verbatim),
+ "strip": (_without_reasoning, _verbatim),
+ "unsigned": (_unsigned_reasoning, _verbatim),
+}
+
+
+def _filter_reasoning(blocks: list[dict], keep) -> list[dict]:
+ return [kept for kept in map(keep, blocks) if kept is not None]
+
+
+def convert_messages_to_converse(
+ messages: list[dict], model: Optional[str] = None,
+) -> tuple[Optional[list[dict]], list[dict]]:
"""OpenAI messages → ``(system_blocks_or_None, converse_messages)``; tool results become ``toolResult``
user blocks. Converse needs strict user/assistant alternation with a user turn first and last:
- same-role neighbours merge, placeholder user turns pad the ends."""
+ same-role neighbours merge, placeholder user turns pad the ends. ``model`` selects the reasoning
+ replay policy for turns before the in-flight tool loop (None replays every carrier verbatim)."""
+ prior_filter, loop_filter = _REASONING_FILTERS[_converse_replay_policy(model)]
+ # Tool results are role "tool" here, so the last role "user" message opens the in-flight tool loop.
+ loop_start = next((i for i in range(len(messages) - 1, -1, -1) if messages[i].get("role") == "user"), -1)
system_blocks: list[dict] = []
converse_msgs: list[dict] = []
@@ -807,7 +913,7 @@ def convert_messages_to_converse(messages: list[dict]) -> tuple[Optional[list[di
else:
converse_msgs.append({"role": role, "content": blocks})
- for msg in messages:
+ for idx, msg in enumerate(messages):
role = msg.get("role", "")
content = msg.get("content")
if role == "system":
@@ -817,7 +923,8 @@ def convert_messages_to_converse(messages: list[dict]) -> tuple[Optional[list[di
append_turn("user", [{"toolResult": {
"toolUseId": msg.get("tool_call_id", ""), "content": [{"text": _safe_text(result_content)}]}}])
elif role == "assistant":
- append_turn("assistant", _assistant_blocks(msg, content) or [dict(_PLACEHOLDER_BLOCK)])
+ blocks = _filter_reasoning(_assistant_blocks(msg, content), prior_filter if idx < loop_start else loop_filter)
+ append_turn("assistant", blocks or [dict(_PLACEHOLDER_BLOCK)])
elif role == "user":
append_turn("user", _convert_content_to_converse(content))
if converse_msgs and converse_msgs[0]["role"] != "user":
@@ -1028,16 +1135,69 @@ def stream_converse_with_callbacks(
# --- High-level API: call Bedrock Converse ---
+def _claude_converse_reasoning(model: str, reasoning_config: dict, max_tokens: Optional[int]) -> tuple[dict, dict]:
+ """Claude thinking over Converse: the same ``thinking``/``output_config`` the AnthropicBedrock path sends,
+ carried in ``additionalModelRequestFields`` (AWS: "pass the thinking and effort parameters inside
+ additionalModelRequestFields"); manual budgets also need temperature 1 and room above the budget."""
+ from agent.anthropic_adapter import _thinking_kwargs
+
+ thinking = _thinking_kwargs(reasoning_config, model, max_tokens or 0)
+ fields = {k: thinking[k] for k in ("thinking", "output_config") if k in thinking}
+ inference: dict[str, Any] = {}
+ if (fields.get("thinking") or {}).get("type") == "enabled":
+ if "claude-3" not in model.lower(): # 3.7 has no interleaved thinking
+ fields["anthropic_beta"] = ["interleaved-thinking-2025-05-14"]
+ inference["temperature"] = thinking.get("temperature", 1)
+ if max_tokens is not None:
+ inference["maxTokens"] = thinking.get("max_tokens", max_tokens)
+ return fields, inference
+
+
+_NOVA_EFFORT = {"minimal": "low", "low": "low", "medium": "medium"} # anything stronger -> "high"
+
+
+def _nova_converse_reasoning(model: str, reasoning_config: dict, max_tokens: Optional[int]) -> tuple[dict, dict]:
+ """Nova 2 ``reasoningConfig`` (off by default). At ``high``, temperature/topP/maxTokens must be unset."""
+ if reasoning_config.get("enabled") is False:
+ return {}, {}
+ effort = _NOVA_EFFORT.get(str(reasoning_config.get("effort", "medium")).lower(), "high")
+ return {"reasoningConfig": {"type": "enabled", "maxReasoningEffort": effort}}, (
+ {"temperature": None, "topP": None, "maxTokens": None} if effort == "high" else {}
+ )
+
+
+_CONVERSE_REASONING_BUILDERS = (
+ (is_anthropic_bedrock_model, _claude_converse_reasoning),
+ (lambda model: "amazon.nova-2-lite" in model.lower(), _nova_converse_reasoning),
+)
+
+
+def _apply_converse_reasoning(kwargs: dict, inference_config: dict, model: str, reasoning_config: dict, max_tokens) -> None:
+ builder = next((b for matches, b in _CONVERSE_REASONING_BUILDERS if matches(model or "")), None)
+ if builder is None:
+ return
+ fields, inference = builder(model, reasoning_config, max_tokens)
+ if fields:
+ kwargs["additionalModelRequestFields"] = fields
+ for key, value in inference.items():
+ if value is None:
+ inference_config.pop(key, None)
+ else:
+ inference_config[key] = value
+
+
def build_converse_kwargs(
model: str, messages: list[dict], tools: Optional[list[dict]] = None, max_tokens: Optional[int] = 4096,
temperature: Optional[float] = None, top_p: Optional[float] = None,
stop_sequences: Optional[list[str]] = None, guardrail_config: Optional[dict] = None,
+ reasoning_config: Optional[dict] = None,
) -> dict[str, Any]:
"""Build kwargs for ``bedrock-runtime.converse()`` / ``converse_stream()``. ``max_tokens=None`` omits
``maxTokens`` (model maximum; default stays 4096). cachePoint markers go on system, tools and the
second-newest message (survives as the tail grows — mirrors Anthropic system_and_3), each only if the
- model supports caching and Bedrock has not rejected that placement."""
- system_prompt, converse_messages = convert_messages_to_converse(messages)
+ model supports caching and Bedrock has not rejected that placement. ``reasoning_config`` becomes the
+ model's ``additionalModelRequestFields`` reasoning switch (Claude ``thinking``, Nova 2 ``reasoningConfig``)."""
+ system_prompt, converse_messages = convert_messages_to_converse(messages, model=model)
cache_at = {p for p in CACHE_POINT_PLACEMENTS if cache_point_allowed(model, p)} if _model_supports_prompt_cache(model) else set()
inference_config: dict[str, Any] = {} if max_tokens is None else {"maxTokens": max_tokens}
kwargs: dict[str, Any] = {"modelId": model, "messages": converse_messages, "inferenceConfig": inference_config}
@@ -1063,6 +1223,8 @@ def build_converse_kwargs(
content.append(dict(_CACHE_POINT))
if guardrail_config:
kwargs["guardrailConfig"] = guardrail_config
+ if reasoning_config and isinstance(reasoning_config, dict):
+ _apply_converse_reasoning(kwargs, inference_config, model, reasoning_config, max_tokens)
if not inference_config:
del kwargs["inferenceConfig"] # optional on the wire; don't send {}
return kwargs
diff --git a/agent/chat_completion_helpers.py b/agent/chat_completion_helpers.py
index 2a31db654a5..55a0a9a3e51 100644
--- a/agent/chat_completion_helpers.py
+++ b/agent/chat_completion_helpers.py
@@ -1424,11 +1424,11 @@ def _build_anthropic_kwargs(agent, api_messages, tools_for_api, reasoning_config
return _merge_nous_portal_messages_extra_body(agent, anthropic_kwargs)
-def _build_bedrock_kwargs(agent, api_messages, tools_for_api):
+def _build_bedrock_kwargs(agent, api_messages, tools_for_api, reasoning_config):
# Bedrock Converse — the adapter converts messages/tools and calls boto3 directly.
return agent._get_transport().build_kwargs(model=agent.model, messages=api_messages, tools=tools_for_api,
max_tokens=agent.max_tokens, region=getattr(agent, "_bedrock_region", None) or "us-east-1",
- guardrail_config=getattr(agent, "_bedrock_guardrail_config", None))
+ guardrail_config=getattr(agent, "_bedrock_guardrail_config", None), reasoning_config=reasoning_config)
def _build_codex_kwargs(agent, api_messages, tools_for_api, reasoning_config, request_overrides, cache_scope_id):
@@ -1562,7 +1562,7 @@ def _build_api_kwargs_for_mode(agent, api_messages: list, tools_for_api: list |
if agent.api_mode == "anthropic_messages":
return _build_anthropic_kwargs(agent, api_messages, tools_for_api, reasoning_config, request_overrides)
if agent.api_mode == "bedrock_converse":
- return _build_bedrock_kwargs(agent, api_messages, tools_for_api)
+ return _build_bedrock_kwargs(agent, api_messages, tools_for_api, reasoning_config)
# Rotation-stable logical cache scope shared by every OpenAI-wire branch
# (memoized on the agent); anthropic/bedrock above don't use it.
cache_scope_id = _prompt_cache_scope_for_agent(agent)
diff --git a/agent/transports/bedrock.py b/agent/transports/bedrock.py
index f8d4e1a35cc..a507c7fe844 100644
--- a/agent/transports/bedrock.py
+++ b/agent/transports/bedrock.py
@@ -26,7 +26,7 @@ class BedrockTransport(ProviderTransport):
def convert_messages(self, messages: list[dict[str, Any]], **kwargs) -> Any:
"""Convert OpenAI messages to Bedrock Converse format."""
from agent.bedrock_adapter import convert_messages_to_converse
- return convert_messages_to_converse(messages)
+ return convert_messages_to_converse(messages, model=kwargs.get("model"))
def convert_tools(self, tools: list[dict[str, Any]]) -> Any:
"""Convert OpenAI tool schemas to Bedrock Converse toolConfig."""
@@ -43,6 +43,7 @@ class BedrockTransport(ProviderTransport):
kwargs = build_converse_kwargs(
model=model, messages=messages, tools=tools, max_tokens=params.get("max_tokens"),
temperature=params.get("temperature"), guardrail_config=params.get("guardrail_config"),
+ reasoning_config=params.get("reasoning_config"),
)
# Sentinel keys for dispatch — agent pops these before the boto3 call
kwargs["__bedrock_converse__"] = True
diff --git a/tests/agent/test_bedrock_converse_reasoning_replay.py b/tests/agent/test_bedrock_converse_reasoning_replay.py
new file mode 100644
index 00000000000..b85c187e2c3
--- /dev/null
+++ b/tests/agent/test_bedrock_converse_reasoning_replay.py
@@ -0,0 +1,85 @@
+"""Claude reasons on Bedrock Converse, and each Converse model gets back only the reasoning it can take.
+
+Converse is the bearer-token Claude path and the sticky fallback after a stream-denied AnthropicBedrock
+error, so a Claude turn captured in Anthropic shape (``anthropic_content_blocks``) must keep its signed
+thinking ahead of its toolUse. AWS docs: Claude needs the signature and all previous messages; DeepSeek-R1's
+sample removes prior reasoning; Kimi K3 raises InternalServerException on prior-turn reasoning; non-Claude
+models reject the ``reasoningText.signature`` field.
+"""
+
+from __future__ import annotations
+
+import copy
+
+import pytest
+
+from agent.transports.bedrock import BedrockTransport
+
+CLAUDE = "us.anthropic.claude-opus-4-8-v1:0"
+
+
+def _anthropic_bedrock_turn(question, sig, tool_id):
+ """A tool turn stored by the AnthropicBedrock path, before the session fell back to Converse."""
+ signed = {"type": "thinking", "thinking": f"plan {sig}", "signature": sig}
+ call = {"id": tool_id, "type": "function", "function": {"name": "read_file", "arguments": '{"path": "a"}'}}
+ return [
+ {"role": "user", "content": question},
+ {"role": "assistant", "content": "", "tool_calls": [call], "reasoning_details": [signed],
+ "anthropic_content_blocks": [signed, {"type": "tool_use", "id": tool_id, "name": "read_file", "input": {"path": "RAW"}}]},
+ {"role": "tool", "tool_call_id": tool_id, "content": "ok"},
+ ]
+
+
+def _history():
+ return _anthropic_bedrock_turn("Q1", "sig_prior", "t1") + [{"role": "assistant", "content": "A1"}] + _anthropic_bedrock_turn("Q2", "sig_loop", "t2")
+
+
+def _reasoning(blocks):
+ return [b["reasoningContent"]["reasoningText"] for b in blocks if "reasoningContent" in b]
+
+
+ "model, prior, loop",
+ [
+ (CLAUDE, [{"text": "plan sig_prior", "signature": "sig_prior"}], [{"text": "plan sig_loop", "signature": "sig_loop"}]),
+ ("us.deepseek.r1-v1:0", [], [{"text": "plan sig_loop", "signature": "sig_loop"}]),
+ ("global.moonshotai.kimi-k3", [], [{"text": "plan sig_loop", "signature": "sig_loop"}]),
+ # Earlier turns may hold another model's signatures: a non-Claude model gets their text only.
+ ("openai.gpt-oss-120b-1:0", [{"text": "plan sig_prior"}], [{"text": "plan sig_loop", "signature": "sig_loop"}]),
+ ],
+)
+def test_converse_replays_each_models_reasoning_contract(model, prior, loop):
+ """Invariant: the in-flight tool loop replays its reasoning ahead of its toolUse with redacted tool
+ input; earlier turns and signatures follow the model's documented contract; history is untouched."""
+ history = _history()
+ before = copy.deepcopy(history)
+ kwargs = BedrockTransport().build_kwargs(model=model, messages=history, reasoning_config={"enabled": True, "effort": "high"})
+
+ assistants = [m["content"] for m in kwargs["messages"] if m["role"] == "assistant"]
+ assert _reasoning(assistants[0]) == prior
+ assert _reasoning(assistants[-1]) == loop
+ assert [next(iter(b)) for b in assistants[-1] if "cachePoint" not in b] == ["reasoningContent", "toolUse"]
+ assert assistants[-1][1]["toolUse"]["input"] == {"path": "a"}
+ assert history == before
+
+
+def test_claude_on_converse_requests_thinking():
+ """Invariant: a reasoning config reaches Claude and Nova 2 as additionalModelRequestFields; models
+ without a documented switch get none."""
+ msgs = [{"role": "user", "content": "hi"}]
+ cfg = {"enabled": True, "effort": "high"}
+ transport = BedrockTransport()
+
+ adaptive = transport.build_kwargs(model=CLAUDE, messages=msgs, reasoning_config=cfg)
+ assert adaptive["additionalModelRequestFields"] == {
+ "thinking": {"type": "adaptive", "display": "summarized"}, "output_config": {"effort": "high"}}
+ manual = transport.build_kwargs(model="anthropic.claude-sonnet-4-5-20250929-v1:0", messages=msgs,
+ max_tokens=4096, reasoning_config=cfg)
+ assert manual["additionalModelRequestFields"]["thinking"] == {"type": "enabled", "budget_tokens": 16000}
+ assert manual["inferenceConfig"]["maxTokens"] > 16000 and manual["inferenceConfig"]["temperature"] == 1
+ nova = transport.build_kwargs(model="us.amazon.nova-2-lite-v1:0", messages=msgs, max_tokens=4096, reasoning_config=cfg)
+ assert nova["additionalModelRequestFields"] == {"reasoningConfig": {"type": "enabled", "maxReasoningEffort": "high"}}
+ assert "maxTokens" not in nova.get("inferenceConfig", {}) # Nova: maxTokens must be unset at high
+ assert "additionalModelRequestFields" not in transport.build_kwargs(
+ model="meta.llama3-70b-instruct-v1:0", messages=msgs, reasoning_config=cfg)
+ assert "additionalModelRequestFields" not in transport.build_kwargs(model=CLAUDE, messages=msgs)
diff --git a/tests/fixtures/provider_wire_snapshot.json b/tests/fixtures/provider_wire_snapshot.json
index ed5fb9a6a5a..aefb6b00734 100644
--- a/tests/fixtures/provider_wire_snapshot.json
+++ b/tests/fixtures/provider_wire_snapshot.json
@@ -4483,6 +4483,15 @@
"high": {
"__bedrock_converse__": true,
"__bedrock_region__": "us-east-1",
+ "additionalModelRequestFields": {
+ "output_config": {
+ "effort": "high"
+ },
+ "thinking": {
+ "display": "summarized",
+ "type": "adaptive"
+ }
+ },
"messages": [
{
"content": [