Skip to content

:hedgehog: PostHog is the leading platform for building self-driving products. Our developer tools – AI observability, analytics, session replay, flags, experiments, error tracking, logs, and more – capture all the context agents need to diagnose problems, uncover opportunities, and ship fixes. Steer it all from Slack, web, desktop, or the MCP.

fix(llm-gateway): keep bedrock fallback alive by scrubbing unsupported request shape (#71713)

Chris Volzer081ede0d613e
diff --git a/services/llm-gateway/src/llm_gateway/api/anthropic.py b/services/llm-gateway/src/llm_gateway/api/anthropic.py
index 74218ed94d23..1337c20e462c 100644
--- a/services/llm-gateway/src/llm_gateway/api/anthropic.py
+++ b/services/llm-gateway/src/llm_gateway/api/anthropic.py
@@ -109,13 +109,20 @@ BEDROCK_SUPPORTED_PARAMS: frozenset[str] = frozenset(
"tool_choice",
"thinking",
"metadata",
- # Structured outputs — litellm's bedrock transform converts these to a Bedrock-compatible
- # form, so dropping them would silently disable structured outputs on fallback.
+ # Structured outputs. Kept at the top level, but note Bedrock-hosted Claude rejects the
+ # nested output_config.format schema with a 400 ("output_config.format: Extra inputs are
+ # not permitted"), so that sub-key is stripped separately (strip_structured_output_format);
+ # the rest of output_config (e.g. {"effort": ...}) is accepted and forwarded.
"output_format",
"output_config",
}
)
+# Sub-keys of output_config that Bedrock-hosted Claude rejects even though it accepts output_config
+# itself. Bedrock's error names the nested path (output_config.format), so the whole object can't be
+# dropped without losing supported sub-keys like effort — these are stripped individually instead.
+BEDROCK_UNSUPPORTED_OUTPUT_CONFIG_KEYS: frozenset[str] = frozenset({"format"})
+
# Cap how much of a provider error message we copy into structured logs — provider 5xx bodies can be
# multi-KB HTML error pages (e.g. Cloudflare 520s), and we only need enough to identify the failure.
@@ -170,8 +177,9 @@ def sanitize_for_bedrock(data: dict[str, Any], *, model: str, product: str) -> d
"""Adapt an Anthropic Messages request for the Bedrock path.
Returns a new dict containing only Bedrock-supported top-level params; unsupported params are
- dropped (with a warning + metric) so they can't 400 the request. Nested server-side tools that
- Bedrock doesn't support are stripped too.
+ dropped (with a warning + metric) so they can't 400 the request. Unsupported output_config
+ sub-keys, server-side tool definitions, and any references to them left in the message history
+ or tool_choice are stripped too — Bedrock 400s on all of these.
"""
sanitized: dict[str, Any] = {}
for key, value in data.items():
@@ -181,10 +189,37 @@ def sanitize_for_bedrock(data: dict[str, Any], *, model: str, product: str) -> d
logger.warning("Stripping unsupported param for Bedrock", param=key, model=model, product=product)
BEDROCK_PARAM_STRIPPED.labels(param=key, product=product).inc()
+ strip_structured_output_format(sanitized, model=model, product=product)
strip_server_side_tools(sanitized, model=model, product=product)
+ strip_server_side_tool_uses_from_messages(sanitized, model=model, product=product)
+ reconcile_tool_choice(sanitized, model=model, product=product)
return sanitized
+def strip_structured_output_format(data: dict[str, Any], *, model: str, product: str) -> None:
+ """Drop output_config sub-keys Bedrock rejects (e.g. format), keeping the rest of output_config.
+
+ Bedrock-hosted Claude 400s on output_config.format ("Extra inputs are not permitted") but
+ accepts output_config itself, so we prune just the unsupported sub-keys rather than dropping the
+ whole object — that keeps supported sub-keys like effort working on the fallback.
+ """
+ output_config = data.get("output_config")
+ if not isinstance(output_config, dict):
+ return
+ unsupported = [key for key in output_config if key in BEDROCK_UNSUPPORTED_OUTPUT_CONFIG_KEYS]
+ if not unsupported:
+ return
+
+ cleaned = {key: value for key, value in output_config.items() if key not in BEDROCK_UNSUPPORTED_OUTPUT_CONFIG_KEYS}
+ if cleaned:
+ data["output_config"] = cleaned
+ else:
+ del data["output_config"]
+ for key in unsupported:
+ logger.warning("Stripping unsupported output_config key for Bedrock", key=key, model=model, product=product)
+ BEDROCK_PARAM_STRIPPED.labels(param=f"output_config.{key}", product=product).inc()
+
+
def strip_server_side_tools(data: dict[str, Any], *, model: str, product: str) -> None:
"""Remove Anthropic server-side tools (e.g. web_search) that Bedrock doesn't support.
@@ -212,6 +247,115 @@ def strip_server_side_tools(data: dict[str, Any], *, model: str, product: str) -
del data["tools"]
+def strip_server_side_tool_uses_from_messages(data: dict[str, Any], *, model: str, product: str) -> None:
+ """Remove server-side tool_use / tool_result blocks left in the message history.
+
+ Stripping the server-side tool *definitions* isn't enough: a prior turn's server_tool_use block
+ (or its matching *_tool_result block, e.g. web_search_tool_result) still references a tool no
+ longer in the request, and Bedrock 400s with "Tool '<name>' not found in provided tools". Client
+ tool_use / tool_result blocks (type == "tool_result") are kept — only server-side ones are dropped.
+ A message whose content becomes empty as a result is dropped, then any turns left adjacent by the
+ drop are coalesced so the sequence keeps alternating roles (Bedrock 400s on non-alternating roles).
+ """
+ messages = data.get("messages")
+ if not isinstance(messages, list):
+ return
+
+ new_messages: list[Any] = []
+ stripped = False
+ for message in messages:
+ content = message.get("content") if isinstance(message, dict) else None
+ if not isinstance(content, list):
+ new_messages.append(message)
+ continue
+
+ kept_blocks = [block for block in content if not _is_server_side_tool_block(block)]
+ if len(kept_blocks) == len(content):
+ new_messages.append(message)
+ continue
+
+ stripped = True
+ if kept_blocks:
+ new_messages.append({**message, "content": kept_blocks})
+ # else: content emptied by the strip — drop the message; _coalesce_adjacent_roles below merges
+ # any same-role turns the drop left back-to-back so we don't emit an invalid message sequence.
+
+ if stripped:
+ data["messages"] = _coalesce_adjacent_roles(new_messages)
+ logger.warning("Stripping server-side tool blocks from messages for Bedrock", model=model, product=product)
+ BEDROCK_PARAM_STRIPPED.labels(param="messages.server_tool_blocks", product=product).inc()
+
+
+def _coalesce_adjacent_roles(messages: list[Any]) -> list[Any]:
+ """Merge consecutive same-role messages into one, concatenating their content.
+
+ Dropping an emptied tool-only turn can leave two same-role messages back to back, which Bedrock
+ rejects. A valid input already alternates roles, so this only merges turns made adjacent by a drop.
+ """
+ merged: list[Any] = []
+ for message in messages:
+ prev = merged[-1] if merged else None
+ if isinstance(message, dict) and isinstance(prev, dict) and message.get("role") == prev.get("role"):
+ merged[-1] = {
+ **prev,
+ "content": _content_as_blocks(prev.get("content")) + _content_as_blocks(message.get("content")),
+ }
+ else:
+ merged.append(message)
+ return merged
+
+
+def _content_as_blocks(content: Any) -> list[Any]:
+ """Normalize message content to a block list so two turns can be concatenated."""
+ if isinstance(content, list):
+ return content
+ if isinstance(content, str):
+ return [{"type": "text", "text": content}]
+ return [content]
+
+
+def _is_server_side_tool_block(block: Any) -> bool:
+ """A block Anthropic produces for a server-side tool run, which Bedrock can't validate."""
+ if not isinstance(block, dict):
+ return False
+ block_type = block.get("type")
+ if not isinstance(block_type, str):
+ return False
+ # server_tool_use / mcp_tool_use are the calls; "<tool>_tool_result" are their results. A plain
+ # client "tool_result" (exact match) is kept — only the server-side, type-prefixed ones go.
+ return block_type in ("server_tool_use", "mcp_tool_use") or (
+ block_type.endswith("_tool_result") and block_type != "tool_result"
+ )
+
+
+def reconcile_tool_choice(data: dict[str, Any], *, model: str, product: str) -> None:
+ """Drop a tool_choice that can no longer be satisfied after server-side tools were stripped.
+
+ Bedrock 400s on a tool_choice that names a tool absent from the tools list. When stripping left
+ no tools at all, tool_choice is dropped regardless of type: "any"/"tool" force tool use that
+ can't happen, and even "auto"/"none" are no-ops without tools yet still risk rejection as a
+ tool_choice with nothing to choose from.
+ """
+ tool_choice = data.get("tool_choice")
+ if not isinstance(tool_choice, dict):
+ return
+
+ tools = data.get("tools")
+ tool_names = {tool.get("name") for tool in tools if isinstance(tool, dict)} if isinstance(tools, list) else set()
+
+ if tool_names:
+ drop = tool_choice.get("type") == "tool" and tool_choice.get("name") not in tool_names
+ else:
+ drop = True
+
+ if drop:
+ del data["tool_choice"]
+ logger.warning(
+ "Dropping unsatisfiable tool_choice for Bedrock", tool_choice=tool_choice, model=model, product=product
+ )
+ BEDROCK_PARAM_STRIPPED.labels(param="tool_choice", product=product).inc()
+
+
async def _send_cloudflare_messages(
request_data: dict[str, Any],
user: RateLimitedUser,
diff --git a/services/llm-gateway/tests/test_anthropic.py b/services/llm-gateway/tests/test_anthropic.py
index 33e1f92bc65e..85d55e42e2df 100644
--- a/services/llm-gateway/tests/test_anthropic.py
+++ b/services/llm-gateway/tests/test_anthropic.py
@@ -855,6 +855,209 @@ class TestSanitizeForBedrock:
assert len(result["tools"]) == 1
assert result["tools"][0]["name"] == "read_data"
+ def test_strips_output_config_format_keeps_effort(self) -> None:
+ data: dict[str, Any] = {"model": "m", "output_config": {"effort": "high", "format": {"type": "json_schema"}}}
+ result = self._call(data)
+ assert result["output_config"] == {"effort": "high"}
+
+ def test_drops_output_config_when_only_unsupported_keys(self) -> None:
+ data: dict[str, Any] = {"model": "m", "output_config": {"format": {"type": "json_schema"}}}
+ result = self._call(data)
+ assert "output_config" not in result
+
+ def test_scrubs_server_side_tool_blocks_from_messages(self) -> None:
+ data: dict[str, Any] = {
+ "model": "m",
+ "tools": [{"type": "web_search_20250305", "name": "web_search"}],
+ "messages": [
+ {
+ "role": "assistant",
+ "content": [
+ {"type": "server_tool_use", "id": "srvtoolu_1", "name": "web_search", "input": {"query": "x"}},
+ {"type": "web_search_tool_result", "tool_use_id": "srvtoolu_1", "content": []},
+ {"type": "text", "text": "Here is the answer."},
+ ],
+ }
+ ],
+ }
+ result = self._call(data)
+ assert "tools" not in result
+ assert result["messages"][0]["content"] == [{"type": "text", "text": "Here is the answer."}]
+
+ def test_drops_tool_choice_referencing_stripped_tool(self) -> None:
+ data: dict[str, Any] = {
+ "model": "m",
+ "tools": [{"type": "web_search_20250305", "name": "web_search"}],
+ "tool_choice": {"type": "tool", "name": "web_search"},
+ }
+ result = self._call(data)
+ assert "tool_choice" not in result
+
+ def test_drops_auto_tool_choice_when_all_tools_stripped(self) -> None:
+ # Stripping the only (server-side) tool deletes the tools key entirely; tool_choice must go
+ # with it or Bedrock rejects a tool_choice with nothing to choose from.
+ data: dict[str, Any] = {
+ "model": "m",
+ "tools": [{"type": "web_search_20250305", "name": "web_search"}],
+ "tool_choice": {"type": "auto"},
+ }
+ result = self._call(data)
+ assert "tools" not in result
+ assert "tool_choice" not in result
+
+ def test_increments_metric_for_message_and_tool_choice_strips(self) -> None:
+ from llm_gateway.api.anthropic import sanitize_for_bedrock
+ from llm_gateway.metrics.prometheus import BEDROCK_PARAM_STRIPPED
+
+ def counter(param: str) -> float:
+ return BEDROCK_PARAM_STRIPPED.labels(param=param, product="test")._value.get()
+
+ before = {param: counter(param) for param in ("messages.server_tool_blocks", "tool_choice")}
+ sanitize_for_bedrock(
+ {
+ "model": "m",
+ "tool_choice": {"type": "any"},
+ "messages": [
+ {"role": "assistant", "content": [{"type": "server_tool_use", "name": "web_search", "input": {}}]}
+ ],
+ },
+ model="test-model",
+ product="test",
+ )
+ assert counter("messages.server_tool_blocks") == before["messages.server_tool_blocks"] + 1
+ assert counter("tool_choice") == before["tool_choice"] + 1
+
+
+class TestStripStructuredOutputFormat:
+ """Unit tests for strip_structured_output_format — prunes Bedrock-rejected output_config sub-keys."""
+
+ def _call(self, data: dict[str, Any]) -> None:
+ from llm_gateway.api.anthropic import strip_structured_output_format
+
+ strip_structured_output_format(data, model="test-model", product="test")
+
+ def test_removes_format_keeps_other_keys(self) -> None:
+ data: dict[str, Any] = {"output_config": {"effort": "low", "format": {"type": "json_schema"}}}
+ self._call(data)
+ assert data["output_config"] == {"effort": "low"}
+
+ def test_removes_output_config_when_emptied(self) -> None:
+ data: dict[str, Any] = {"output_config": {"format": {}}}
+ self._call(data)
+ assert "output_config" not in data
+
+ def test_noop_without_unsupported_keys(self) -> None:
+ data: dict[str, Any] = {"output_config": {"effort": "high"}}
+ self._call(data)
+ assert data["output_config"] == {"effort": "high"}
+
+ @pytest.mark.parametrize("output_config", [None, "not-a-dict", 5])
+ def test_noop_when_output_config_absent_or_not_dict(self, output_config: Any) -> None:
+ data: dict[str, Any] = {"model": "m"} if output_config is None else {"output_config": output_config}
+ self._call(data)
+ assert data.get("output_config") == output_config
+
+
+class TestStripServerSideToolUsesFromMessages:
+ """Unit tests for strip_server_side_tool_uses_from_messages — scrubs dangling server-side references."""
+
+ def _call(self, data: dict[str, Any]) -> None:
+ from llm_gateway.api.anthropic import strip_server_side_tool_uses_from_messages
+
+ strip_server_side_tool_uses_from_messages(data, model="test-model", product="test")
+
+ def test_keeps_client_tool_result_blocks(self) -> None:
+ content = [
+ {"type": "tool_result", "tool_use_id": "toolu_1", "content": "ok"},
+ {"type": "text", "text": "done"},
+ ]
+ data: dict[str, Any] = {"messages": [{"role": "user", "content": list(content)}]}
+ self._call(data)
+ assert data["messages"][0]["content"] == content
+
+ @pytest.mark.parametrize(
+ "block",
+ [
+ {"type": "server_tool_use", "name": "web_search", "input": {}},
+ {"type": "web_search_tool_result", "tool_use_id": "srvtoolu_1", "content": []},
+ {"type": "code_execution_tool_result", "tool_use_id": "srvtoolu_2", "content": {}},
+ {"type": "mcp_tool_use", "name": "mcp_thing", "input": {}},
+ ],
+ )
+ def test_strips_server_side_blocks(self, block: dict[str, Any]) -> None:
+ data: dict[str, Any] = {
+ "messages": [{"role": "assistant", "content": [block, {"type": "text", "text": "answer"}]}]
+ }
+ self._call(data)
+ assert data["messages"][0]["content"] == [{"type": "text", "text": "answer"}]
+
+ def test_drops_message_when_content_emptied(self) -> None:
+ data: dict[str, Any] = {
+ "messages": [
+ {"role": "user", "content": "hi"},
+ {"role": "assistant", "content": [{"type": "server_tool_use", "name": "web_search", "input": {}}]},
+ ]
+ }
+ self._call(data)
+ assert data["messages"] == [{"role": "user", "content": "hi"}]
+
+ def test_noop_on_string_content(self) -> None:
+ data: dict[str, Any] = {"messages": [{"role": "user", "content": "just text"}]}
+ self._call(data)
+ assert data["messages"] == [{"role": "user", "content": "just text"}]
+
+ def test_dropping_tool_only_turn_keeps_roles_alternating(self) -> None:
+ # A tool-only assistant turn between two user turns: dropping it must not leave two user
+ # messages back to back (Bedrock 400s on non-alternating roles) — they coalesce into one.
+ data: dict[str, Any] = {
+ "messages": [
+ {"role": "user", "content": "search for X"},
+ {"role": "assistant", "content": [{"type": "server_tool_use", "name": "web_search", "input": {}}]},
+ {"role": "user", "content": [{"type": "text", "text": "and also Y"}]},
+ ]
+ }
+ self._call(data)
+ roles = [message["role"] for message in data["messages"]]
+ assert roles == ["user"]
+ assert data["messages"][0]["content"] == [
+ {"type": "text", "text": "search for X"},
+ {"type": "text", "text": "and also Y"},
+ ]
+
+
+class TestReconcileToolChoice:
+ """Unit tests for reconcile_tool_choice — drops a tool_choice Bedrock can't satisfy."""
+
+ def _call(self, data: dict[str, Any]) -> None:
+ from llm_gateway.api.anthropic import reconcile_tool_choice
+
+ reconcile_tool_choice(data, model="test-model", product="test")
+
+ def test_drops_tool_choice_naming_absent_tool(self) -> None:
+ data: dict[str, Any] = {"tool_choice": {"type": "tool", "name": "web_search"}, "tools": []}
+ self._call(data)
+ assert "tool_choice" not in data
+
+ def test_keeps_tool_choice_naming_present_tool(self) -> None:
+ data: dict[str, Any] = {
+ "tool_choice": {"type": "tool", "name": "read_data"},
+ "tools": [{"name": "read_data"}],
+ }
+ self._call(data)
+ assert data["tool_choice"] == {"type": "tool", "name": "read_data"}
+
+ @pytest.mark.parametrize("choice_type", ["any", "auto", "none"])
+ def test_drops_tool_choice_when_no_tools_remain(self, choice_type: str) -> None:
+ data: dict[str, Any] = {"tool_choice": {"type": choice_type}}
+ self._call(data)
+ assert "tool_choice" not in data
+
+ @pytest.mark.parametrize("choice_type", ["any", "auto", "none"])
+ def test_keeps_non_named_tool_choice_when_tools_remain(self, choice_type: str) -> None:
+ data: dict[str, Any] = {"tool_choice": {"type": choice_type}, "tools": [{"name": "read_data"}]}
+ self._call(data)
+ assert data["tool_choice"] == {"type": choice_type}
+
class TestAnthropicCountTokensEndpoint:
@pytest.fixture