The fastest, litest AI Gateway. Rust core with Python SDK. Call 100+ LLM APIs in OpenAI (or native) format with cost tracking, guardrails, load balancing, and logging [Bedrock, Azure, OpenAI, Anthropic, OpenAI, VertexAI, vLLM, Nvidia NIM]
Python ai-gatewayanthropicazure-openaibedrockgatewaylangchainlitellmllmllm-gatewayllmopsmcp-gatewayopenaiopenai-proxyrustrust-aivertex-ai
fix(bedrock): handle concatenated JSON in tool call arguments (#20742)
Neel Harsola4256c547c2e3
diff --git a/litellm/litellm_core_utils/prompt_templates/common_utils.py b/litellm/litellm_core_utils/prompt_templates/common_utils.pyindex b1c2d0a52f5..cdddee4e54e 100644--- a/litellm/litellm_core_utils/prompt_templates/common_utils.py+++ b/litellm/litellm_core_utils/prompt_templates/common_utils.py@@ -1272,3 +1272,59 @@ def parse_tool_call_arguments()raise ValueError(error_message) from e+++def split_concatenated_json_objects(raw: str) -> List[Dict[str, Any]]:+ """+ Split a string that contains one or more concatenated JSON objects into+ a list of parsed dicts.++ LLM providers (notably Bedrock Claude Sonnet 4.5) sometimes return+ multiple tool-call argument objects concatenated in a single+ ``arguments`` string, e.g.::++ '{"command":["curl",...]}{"command":["curl",...]}{"command":["curl",...]}'++ ``json.loads()`` fails on this with ``JSONDecodeError: Extra data``.+ This helper uses ``json.JSONDecoder.raw_decode()`` to walk the string+ and extract each JSON object individually.++ Returns+ -------+ list[dict]+ A list of parsed dicts – one per JSON object found. If *raw* is+ empty or whitespace-only, an empty list is returned.++ Raises+ ------+ json.JSONDecodeError+ If the string contains text that cannot be parsed as JSON at all.+ """+ import json++ raw = raw.strip()+ if not raw:+ return []++ decoder = json.JSONDecoder()+ results: List[Dict[str, Any]] = []+ idx = 0+ length = len(raw)++ while idx < length:+ # Skip whitespace between objects+ while idx < length and raw[idx] in " \t\n\r":+ idx += 1+ if idx >= length:+ break++ obj, end_idx = decoder.raw_decode(raw, idx)+ if isinstance(obj, dict):+ results.append(obj)+ else:+ # Non-dict JSON value – wrap in empty dict (Bedrock requires+ # toolUse.input to be an object).+ results.append({})+ idx = end_idx++ return resultsdiff --git a/litellm/litellm_core_utils/prompt_templates/factory.py b/litellm/litellm_core_utils/prompt_templates/factory.pyindex f9ecd78ff1c..c907ed32b95 100644--- a/litellm/litellm_core_utils/prompt_templates/factory.py+++ b/litellm/litellm_core_utils/prompt_templates/factory.py@@ -3287,25 +3287,68 @@ def _convert_to_bedrock_tool_call_invoke(- extract name- extract id"""+ from litellm.litellm_core_utils.prompt_templates.common_utils import (+ split_concatenated_json_objects,+ )try:_parts_list: List[BedrockContentBlock] = []for tool in tool_calls:if "function" in tool:- id = tool["id"]+ tool_id = tool["id"]name = tool["function"].get("name", "")arguments = tool["function"].get("arguments", "")- arguments_dict = json.loads(arguments) if arguments else {}- # Ensure arguments_dict is always a dict (Bedrock requires toolUse.input to be an object)- # When some providers return arguments: '""' (JSON-encoded empty string), json.loads returns ""- if not isinstance(arguments_dict, dict):- arguments_dict = {}+if not arguments or not arguments.strip():arguments_dict = {}else:- arguments_dict = json.loads(arguments)+ try:+ arguments_dict = json.loads(arguments)+ # Ensure arguments_dict is always a dict+ # (Bedrock requires toolUse.input to be an object).+ # Some providers return arguments: '""' which+ # json.loads decodes to a bare string.+ if not isinstance(arguments_dict, dict):+ arguments_dict = {}+ except json.JSONDecodeError:+ # The model may return multiple JSON objects+ # concatenated in a single arguments string, e.g.+ # '{"cmd":"a"}{"cmd":"b"}{"cmd":"c"}'+ # Split them and emit one toolUse block per object.+ # Fixes: https://github.com/BerriAI/litellm/issues/20543+ parsed_objects = split_concatenated_json_objects(+ arguments+ )+ if parsed_objects:+ # First object keeps the original tool id.+ for obj_idx, obj in enumerate(parsed_objects):+ block_id = (+ tool_id+ if obj_idx == 0+ else f"{tool_id}_{obj_idx}"+ )+ bedrock_tool = BedrockToolUseBlock(+ input=obj, name=name, toolUseId=block_id+ )+ _parts_list.append(+ BedrockContentBlock(toolUse=bedrock_tool)+ )+ # cache_control applies to the whole original+ # tool call; attach after the last split block.+ if tool.get("cache_control", None) is not None:+ _parts_list.append(+ BedrockContentBlock(+ cachePoint=CachePointBlock(+ type="default"+ )+ )+ )+ continue+ # Fallback: no objects extracted — use empty dict.+ arguments_dict = {}+bedrock_tool = BedrockToolUseBlock(- input=arguments_dict, name=name, toolUseId=id+ input=arguments_dict, name=name, toolUseId=tool_id)bedrock_content_block = BedrockContentBlock(toolUse=bedrock_tool)_parts_list.append(bedrock_content_block)diff --git a/tests/test_litellm/litellm_core_utils/prompt_templates/test_litellm_core_utils_prompt_templates_common_utils.py b/tests/test_litellm/litellm_core_utils/prompt_templates/test_litellm_core_utils_prompt_templates_common_utils.pyindex 980693aa73a..f566f91841d 100644--- a/tests/test_litellm/litellm_core_utils/prompt_templates/test_litellm_core_utils_prompt_templates_common_utils.py+++ b/tests/test_litellm/litellm_core_utils/prompt_templates/test_litellm_core_utils_prompt_templates_common_utils.py@@ -12,6 +12,7 @@ sys.path.insert(from litellm.litellm_core_utils.prompt_templates.common_utils import (get_format_from_file_id,handle_any_messages_to_chat_completion_str_messages_conversion,+ split_concatenated_json_objects,update_messages_with_model_file_ids,)@@ -143,3 +144,58 @@ def test_convert_prefix_message_to_non_prefix_messages():},{"role": "assistant", "content": "value"},]+++# ── split_concatenated_json_objects tests ──+++def test_split_concatenated_json_single_object():+ """A single valid JSON object is returned as a one-element list."""+ result = split_concatenated_json_objects('{"location": "Boston"}')+ assert result == [{"location": "Boston"}]+++def test_split_concatenated_json_multiple_objects():+ """+ Multiple JSON objects concatenated without separators are split correctly.+ This is the exact pattern from issue #20543 where Bedrock Claude Sonnet 4.5+ returns concatenated JSON in a single tool call arguments string.+ """+ raw = (+ '{"command": ["curl", "-i", "http://localhost:9009"]}'+ '{"command": ["curl", "-i", "http://localhost:9009/robots.txt"]}'+ '{"command": ["curl", "-i", "http://localhost:9009/sitemap.xml"]}'+ )+ result = split_concatenated_json_objects(raw)+ assert len(result) == 3+ assert result[0] == {"command": ["curl", "-i", "http://localhost:9009"]}+ assert result[1] == {"command": ["curl", "-i", "http://localhost:9009/robots.txt"]}+ assert result[2] == {"command": ["curl", "-i", "http://localhost:9009/sitemap.xml"]}+++def test_split_concatenated_json_with_whitespace():+ """Objects separated by whitespace are handled correctly."""+ raw = '{"a": 1} {"b": 2}\n{"c": 3}'+ result = split_concatenated_json_objects(raw)+ assert len(result) == 3+ assert result[0] == {"a": 1}+ assert result[1] == {"b": 2}+ assert result[2] == {"c": 3}+++def test_split_concatenated_json_empty_string():+ """Empty or whitespace-only strings return an empty list."""+ assert split_concatenated_json_objects("") == []+ assert split_concatenated_json_objects(" ") == []+++def test_split_concatenated_json_non_dict_value():+ """Non-dict JSON values (e.g. arrays, strings) are replaced with {}."""+ result = split_concatenated_json_objects('[1, 2, 3]')+ assert result == [{}]+++def test_split_concatenated_json_invalid_raises():+ """Completely invalid JSON raises JSONDecodeError."""+ with pytest.raises(json.JSONDecodeError):+ split_concatenated_json_objects("not json at all")diff --git a/tests/test_litellm/litellm_core_utils/prompt_templates/test_litellm_core_utils_prompt_templates_factory.py b/tests/test_litellm/litellm_core_utils/prompt_templates/test_litellm_core_utils_prompt_templates_factory.pyindex e87233a52a3..707b5bdc777 100644--- a/tests/test_litellm/litellm_core_utils/prompt_templates/test_litellm_core_utils_prompt_templates_factory.py+++ b/tests/test_litellm/litellm_core_utils/prompt_templates/test_litellm_core_utils_prompt_templates_factory.py@@ -8,6 +8,7 @@ from litellm.litellm_core_utils.prompt_templates.factory import (BAD_MESSAGE_ERROR_STR,BedrockConverseMessagesProcessor,BedrockImageProcessor,+ _convert_to_bedrock_tool_call_invoke,ollama_pt,)@@ -1590,3 +1591,153 @@ def test_bedrock_tools_unpack_defs_no_oom_with_nested_refs():# Verify $defs have been removed (Bedrock doesn't support them)tool_schema = result[0]["toolSpec"].get("inputSchema", {}).get("json", {})assert "$defs" not in tool_schema, "$defs should be removed after expansion"+++# ── _convert_to_bedrock_tool_call_invoke tests ──+++def test_bedrock_tool_call_invoke_normal_single_tool():+ """Normal single tool call with valid JSON arguments."""+ tool_calls = [+ {+ "id": "call_abc123",+ "type": "function",+ "function": {+ "name": "get_weather",+ "arguments": '{"location": "Boston, MA"}',+ },+ }+ ]+ result = _convert_to_bedrock_tool_call_invoke(tool_calls)+ assert len(result) == 1+ assert result[0]["toolUse"]["toolUseId"] == "call_abc123"+ assert result[0]["toolUse"]["name"] == "get_weather"+ assert result[0]["toolUse"]["input"] == {"location": "Boston, MA"}+++def test_bedrock_tool_call_invoke_empty_arguments():+ """Tool call with empty arguments produces an empty dict input."""+ tool_calls = [+ {+ "id": "call_empty",+ "type": "function",+ "function": {"name": "do_something", "arguments": ""},+ }+ ]+ result = _convert_to_bedrock_tool_call_invoke(tool_calls)+ assert len(result) == 1+ assert result[0]["toolUse"]["input"] == {}+++def test_bedrock_tool_call_invoke_concatenated_json():+ """+ Tool call whose arguments contain multiple concatenated JSON objects+ (the bug from issue #20543) is split into separate Bedrock toolUse blocks.++ Bedrock Claude Sonnet 4.5 sometimes returns multiple tool call arguments+ concatenated in a single string like:+ '{"command":["curl",...]}{"command":["curl",...]}{"command":["curl",...]}'+ """+ tool_calls = [+ {+ "id": "tooluse_L7I3TewYAUhoheJZQEuwVN",+ "type": "function",+ "function": {+ "name": "shell",+ "arguments": (+ '{"command": ["curl", "-i", "http://localhost:9009", "-m", "10"]}'+ '{"command": ["curl", "-i", "http://localhost:9009/robots.txt", "-m", "5"]}'+ '{"command": ["curl", "-i", "http://localhost:9009/sitemap.xml", "-m", "5"]}'+ ),+ },+ }+ ]+ result = _convert_to_bedrock_tool_call_invoke(tool_calls)++ # Should produce 3 separate toolUse blocks+ assert len(result) == 3++ # First block keeps original tool id+ assert result[0]["toolUse"]["toolUseId"] == "tooluse_L7I3TewYAUhoheJZQEuwVN"+ assert result[0]["toolUse"]["name"] == "shell"+ assert result[0]["toolUse"]["input"] == {+ "command": ["curl", "-i", "http://localhost:9009", "-m", "10"]+ }++ # Subsequent blocks get suffixed ids+ assert result[1]["toolUse"]["toolUseId"] == "tooluse_L7I3TewYAUhoheJZQEuwVN_1"+ assert result[1]["toolUse"]["name"] == "shell"+ assert result[1]["toolUse"]["input"] == {+ "command": ["curl", "-i", "http://localhost:9009/robots.txt", "-m", "5"]+ }++ assert result[2]["toolUse"]["toolUseId"] == "tooluse_L7I3TewYAUhoheJZQEuwVN_2"+ assert result[2]["toolUse"]["name"] == "shell"+ assert result[2]["toolUse"]["input"] == {+ "command": ["curl", "-i", "http://localhost:9009/sitemap.xml", "-m", "5"]+ }+++def test_bedrock_tool_call_invoke_concatenated_json_with_cache_control():+ """+ When a tool call has cache_control AND concatenated JSON arguments,+ the cachePoint block is appended after the last split block.+ """+ tool_calls = [+ {+ "id": "call_cached",+ "type": "function",+ "cache_control": {"type": "default"},+ "function": {+ "name": "shell",+ "arguments": '{"a": 1}{"b": 2}',+ },+ }+ ]+ result = _convert_to_bedrock_tool_call_invoke(tool_calls)++ # 2 toolUse blocks + 1 cachePoint block+ assert len(result) == 3+ assert "toolUse" in result[0]+ assert "toolUse" in result[1]+ assert "cachePoint" in result[2]+++def test_bedrock_tool_call_invoke_non_dict_arguments():+ """Arguments that parse to a non-dict (e.g. '""') produce empty dict input."""+ tool_calls = [+ {+ "id": "call_non_dict",+ "type": "function",+ "function": {"name": "tool", "arguments": '""'},+ }+ ]+ result = _convert_to_bedrock_tool_call_invoke(tool_calls)+ assert len(result) == 1+ assert result[0]["toolUse"]["input"] == {}+++def test_bedrock_tool_call_invoke_multiple_normal_tools():+ """Multiple separate tool calls (normal parallel calling) work correctly."""+ tool_calls = [+ {+ "id": "call_1",+ "type": "function",+ "function": {+ "name": "get_weather",+ "arguments": '{"city": "NYC"}',+ },+ },+ {+ "id": "call_2",+ "type": "function",+ "function": {+ "name": "get_weather",+ "arguments": '{"city": "LA"}',+ },+ },+ ]+ result = _convert_to_bedrock_tool_call_invoke(tool_calls)+ assert len(result) == 2+ assert result[0]["toolUse"]["toolUseId"] == "call_1"+ assert result[1]["toolUse"]["toolUseId"] == "call_2"