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(agentcore): handle JSON responses from agents using sync return (#23165)
michelligabrielec47f77a34866
diff --git a/litellm/llms/bedrock/chat/agentcore/transformation.py b/litellm/llms/bedrock/chat/agentcore/transformation.pyindex fe7d4b194a2..560fadad7c5 100644--- a/litellm/llms/bedrock/chat/agentcore/transformation.py+++ b/litellm/llms/bedrock/chat/agentcore/transformation.py@@ -334,24 +334,67 @@ class AmazonAgentCoreConfig(BaseConfig, BaseAWSLLM):"""Parse direct JSON response (non-streaming).- JSON response structure:- {- "result": {- "role": "assistant",- "content": [{"text": "..."}]- }- }- """- result = response_json.get("result", {})+ Supports multiple agent response schemas:+ 1. {"result": {"role": "assistant", "content": [{"text": "..."}]}} - standard AgentCore+ 2. {"response": [{"text": "..."}]} - Strands agent format+ 3. {"result": "plain text"} or {"response": "plain text"} - simple string+ 4. Fallback: raw JSON as content string+ """+ # Guard: if json.loads() returned a non-dict (e.g. array or primitive),+ # skip strategy matching and fall back to raw JSON string+ if not isinstance(response_json, dict):+ verbose_logger.warning(+ "AgentCore: JSON response is not a dict. "+ "Returning raw JSON as content."+ )+ return AgentCoreParsedResponse(+ content=json.dumps(response_json),+ usage=None,+ final_message=None,+ )- # Extract content using the same helper as SSE parsing- content = self._extract_content_from_message(result) # type: ignore+ # Strategy 1: {"result": {"content": [{"text": "..."}]}} - standard AgentCore format+ if "result" in response_json and isinstance(response_json["result"], dict):+ result = response_json["result"]+ content = self._extract_content_from_message(result) # type: ignore+ return AgentCoreParsedResponse(+ content=content,+ usage=None,+ final_message=result, # type: ignore+ )++ # Strategy 2: {"response": [{"text": "..."}]} - Strands agent content blocks+ if "response" in response_json and isinstance(+ response_json["response"], list+ ):+ content = self._extract_content_from_message(+ {"content": response_json["response"]} # type: ignore+ )+ return AgentCoreParsedResponse(+ content=content,+ usage=None,+ final_message=None,+ )- # JSON responses don't include usage data+ # Strategy 3: string values - {"result": "text"} or {"response": "text"}+ for key in ("result", "response"):+ val = response_json.get(key)+ if isinstance(val, str):+ return AgentCoreParsedResponse(+ content=val,+ usage=None,+ final_message=None,+ )++ # Strategy 4: fallback - return raw JSON as content+ verbose_logger.warning(+ f"AgentCore: Could not extract content from JSON response keys "+ f"{list(response_json.keys())}. Returning raw JSON as content."+ )return AgentCoreParsedResponse(- content=content,+ content=json.dumps(response_json),usage=None,- final_message=result, # type: ignore+ final_message=None,)def _get_parsed_response(@@ -589,7 +632,64 @@ class AmazonAgentCoreConfig(BaseConfig, BaseAWSLLM):additional_args={"complete_input_dict": data},)- # Wrap the generator in CustomStreamWrapper+ # Check if response is JSON (agent used sync return) instead of SSE+ content_type = response.headers.get("content-type", "").lower()+ if "application/json" in content_type:+ verbose_logger.debug(+ "AgentCore streaming: received JSON response instead of SSE, "+ "converting to single-chunk stream"+ )+ try:+ body = response.read()+ response_json = json.loads(body)+ except (json.JSONDecodeError, Exception) as e:+ raise BedrockError(+ status_code=response.status_code,+ message=f"AgentCore: Failed to read/parse JSON response body: {e}",+ )+ parsed = self._parse_json_response(response_json)++ def _json_as_sync_stream():+ # Content chunk+ content_chunk = ModelResponseStream(+ id=f"chatcmpl-{uuid.uuid4()}",+ created=0,+ model=model,+ object="chat.completion.chunk",+ )+ content_chunk.choices = [+ StreamingChoices(+ finish_reason=None,+ index=0,+ delta=Delta(content=parsed["content"], role="assistant"),+ )+ ]+ yield content_chunk++ # Stop sentinel chunk (matches SSE path convention)+ stop_chunk = ModelResponseStream(+ id=f"chatcmpl-{uuid.uuid4()}",+ created=0,+ model=model,+ object="chat.completion.chunk",+ )+ stop_chunk.choices = [+ StreamingChoices(+ finish_reason="stop",+ index=0,+ delta=Delta(),+ )+ ]+ yield stop_chunk++ return CustomStreamWrapper(+ completion_stream=_json_as_sync_stream(),+ model=model,+ custom_llm_provider="bedrock",+ logging_obj=logging_obj,+ )++ # SSE stream (text/event-stream or default) - use existing SSE parserreturn CustomStreamWrapper(completion_stream=self._stream_agentcore_response_sync(response, model),model=model,@@ -746,7 +846,64 @@ class AmazonAgentCoreConfig(BaseConfig, BaseAWSLLM):additional_args={"complete_input_dict": data},)- # Wrap the async generator in CustomStreamWrapper+ # Check if response is JSON (agent used sync return) instead of SSE+ content_type = response.headers.get("content-type", "").lower()+ if "application/json" in content_type:+ verbose_logger.debug(+ "AgentCore streaming: received JSON response instead of SSE, "+ "converting to single-chunk stream"+ )+ try:+ body = await response.aread()+ response_json = json.loads(body)+ except (json.JSONDecodeError, Exception) as e:+ raise BedrockError(+ status_code=response.status_code,+ message=f"AgentCore: Failed to read/parse JSON response body: {e}",+ )+ parsed = self._parse_json_response(response_json)++ async def _json_as_async_stream() -> AsyncGenerator[ModelResponseStream, None]:+ # Content chunk+ content_chunk = ModelResponseStream(+ id=f"chatcmpl-{uuid.uuid4()}",+ created=0,+ model=model,+ object="chat.completion.chunk",+ )+ content_chunk.choices = [+ StreamingChoices(+ finish_reason=None,+ index=0,+ delta=Delta(content=parsed["content"], role="assistant"),+ )+ ]+ yield content_chunk++ # Stop sentinel chunk (matches SSE path convention)+ stop_chunk = ModelResponseStream(+ id=f"chatcmpl-{uuid.uuid4()}",+ created=0,+ model=model,+ object="chat.completion.chunk",+ )+ stop_chunk.choices = [+ StreamingChoices(+ finish_reason="stop",+ index=0,+ delta=Delta(),+ )+ ]+ yield stop_chunk++ return CustomStreamWrapper(+ completion_stream=_json_as_async_stream(),+ model=model,+ custom_llm_provider="bedrock",+ logging_obj=logging_obj,+ )++ # SSE stream (text/event-stream or default) - use existing SSE parserreturn CustomStreamWrapper(completion_stream=self._stream_agentcore_response(response, model),model=model,diff --git a/tests/test_litellm/llms/bedrock/chat/agentcore/test_agentcore_transformation.py b/tests/test_litellm/llms/bedrock/chat/agentcore/test_agentcore_transformation.pyindex b122a083718..acb55a97399 100644--- a/tests/test_litellm/llms/bedrock/chat/agentcore/test_agentcore_transformation.py+++ b/tests/test_litellm/llms/bedrock/chat/agentcore/test_agentcore_transformation.py@@ -1,20 +1,22 @@"""-Unit tests for Bedrock AgentCore transformation — Accept header fix.+Unit tests for Bedrock AgentCore transformation.-Verifies that AmazonAgentCoreConfig.sign_request() sets the-Accept: application/json, text/event-stream header required by-MCP servers on Bedrock AgentCore.+Tests:+- Accept header fix (sign_request sets Accept: application/json, text/event-stream)+- JSON response parsing fallback chain (_parse_json_response supports multiple schemas)+- Streaming Content-Type fallback (JSON responses converted to single-chunk streams)"""import jsonimport osimport sys+import httpximport pytestsys.path.insert(0, os.path.abspath("../../../../../.."))-from unittest.mock import MagicMock, patch+from unittest.mock import MagicMock, Mock, patchimport litellmfrom litellm.llms.bedrock.chat.agentcore.transformation import AmazonAgentCoreConfig@@ -81,3 +83,237 @@ class TestAgentCoreAcceptHeader:headers = mock_post.call_args.kwargs["headers"]assert "Accept" in headersassert headers["Accept"] == "application/json, text/event-stream"+++class TestAgentCoreJsonResponseParsing:+ """Tests for _parse_json_response fallback chain."""++ @pytest.fixture+ def config(self):+ return AmazonAgentCoreConfig()++ def test_parse_json_standard_agentcore_format(self, config):+ """Strategy 1: standard {"result": {"content": [{"text": "..."}]}} format."""+ response_json = {+ "result": {+ "role": "assistant",+ "content": [{"text": "Hello from standard format"}],+ }+ }+ parsed = config._parse_json_response(response_json)+ assert parsed["content"] == "Hello from standard format"+ assert parsed["usage"] is None+ assert parsed["final_message"] == response_json["result"]++ def test_parse_json_strands_format(self, config):+ """Strategy 2: Strands {"response": [{"text": "..."}]} format."""+ response_json = {+ "response": [+ {"text": "Based on my research, "},+ {"text": "iOS 18.2 was released."},+ ]+ }+ parsed = config._parse_json_response(response_json)+ assert parsed["content"] == "Based on my research, iOS 18.2 was released."+ assert parsed["usage"] is None+ assert parsed["final_message"] is None++ def test_parse_json_string_result(self, config):+ """Strategy 3: plain string {"result": "text"} format."""+ response_json = {"result": "Simple text response"}+ parsed = config._parse_json_response(response_json)+ assert parsed["content"] == "Simple text response"+ assert parsed["usage"] is None++ def test_parse_json_string_response(self, config):+ """Strategy 3: plain string {"response": "text"} format."""+ response_json = {"response": "Another text response"}+ parsed = config._parse_json_response(response_json)+ assert parsed["content"] == "Another text response"+ assert parsed["usage"] is None++ def test_parse_json_unknown_format_fallback(self, config):+ """Strategy 4: unknown keys fall back to raw JSON."""+ response_json = {"custom_key": "custom_value", "data": [1, 2, 3]}+ parsed = config._parse_json_response(response_json)+ assert parsed["content"] == json.dumps(response_json)+ assert parsed["usage"] is None+ assert parsed["final_message"] is None++ def test_parse_json_non_dict_response(self, config):+ """Guard: non-dict JSON (e.g. array) falls back to raw JSON string."""+ response_json = [{"text": "array response"}]+ parsed = config._parse_json_response(response_json)+ assert parsed["content"] == json.dumps(response_json)+ assert parsed["usage"] is None+ assert parsed["final_message"] is None++ def test_parse_json_empty_content_in_result(self, config):+ """Standard format with empty content list - preserves existing behavior."""+ response_json = {+ "result": {+ "role": "assistant",+ "content": [],+ }+ }+ parsed = config._parse_json_response(response_json)+ assert parsed["content"] == ""+ assert parsed["final_message"] == response_json["result"]+++class TestAgentCoreNonStreamingJsonFormats:+ """Tests for _get_parsed_response with different JSON formats (non-streaming path)."""++ @pytest.fixture+ def config(self):+ return AmazonAgentCoreConfig()++ def test_get_parsed_response_strands_json(self, config):+ """+ Non-streaming path: _get_parsed_response routes application/json+ to _parse_json_response which handles the Strands format.+ """+ mock_response = Mock(spec=httpx.Response)+ mock_response.headers = {"content-type": "application/json"}+ mock_response.json.return_value = {+ "response": [{"text": "Strands agent response via non-streaming"}]+ }+ parsed = config._get_parsed_response(mock_response)+ assert parsed["content"] == "Strands agent response via non-streaming"+ assert parsed["usage"] is None++ def test_get_parsed_response_raw_json_fallback(self, config):+ """+ Non-streaming path: unknown JSON schema falls back to raw JSON string.+ """+ response_json = {"output": "some value"}+ mock_response = Mock(spec=httpx.Response)+ mock_response.headers = {"content-type": "application/json"}+ mock_response.json.return_value = response_json+ parsed = config._get_parsed_response(mock_response)+ assert parsed["content"] == json.dumps(response_json)+++class TestAgentCoreStreamingJsonFallback:+ """Tests for streaming Content-Type check (JSON -> single-chunk stream)."""++ def test_sync_streaming_with_json_response(self):+ """+ When stream=True but the agent returns Content-Type: application/json,+ content is extracted and returned instead of silently returning empty.+ Exercises the full path through litellm.completion().+ """+ from litellm.llms.custom_httpx.http_handler import HTTPHandler++ client = HTTPHandler()+ json_body = {"response": [{"text": "Strands sync response"}]}++ mock_response = Mock(spec=httpx.Response)+ mock_response.status_code = 200+ mock_response.headers = {"content-type": "application/json"}+ mock_response.read.return_value = json.dumps(json_body).encode()++ with patch.object(client, "post", return_value=mock_response):+ response = litellm.completion(+ model="bedrock/agentcore/arn:aws:bedrock-agentcore:us-west-2:888602223428:runtime/test_agent",+ messages=[{"role": "user", "content": "test"}],+ stream=True,+ client=client,+ )++ # Collect content across all chunks+ # CustomStreamWrapper yields content chunk(s) + a synthetic stop chunk+ content = ""+ for chunk in response:+ if chunk.choices[0].delta.content:+ content += chunk.choices[0].delta.content++ assert content == "Strands sync response"++ async def test_async_streaming_with_json_response(self):+ """+ Async streaming: same Content-Type: application/json fallback via+ litellm.acompletion(stream=True).+ """+ from unittest.mock import AsyncMock++ from litellm.llms.custom_httpx.http_handler import AsyncHTTPHandler++ client = AsyncHTTPHandler()+ json_body = {"response": [{"text": "Strands async response"}]}++ mock_response = Mock(spec=httpx.Response)+ mock_response.status_code = 200+ mock_response.headers = {"content-type": "application/json"}+ mock_response.aread = AsyncMock(+ return_value=json.dumps(json_body).encode()+ )++ with patch.object(+ client, "post", new_callable=AsyncMock, return_value=mock_response+ ):+ response = await litellm.acompletion(+ model="bedrock/agentcore/arn:aws:bedrock-agentcore:us-west-2:888602223428:runtime/test_agent",+ messages=[{"role": "user", "content": "test"}],+ stream=True,+ client=client,+ )++ # Collect content across all chunks+ content = ""+ async for chunk in response:+ if chunk.choices[0].delta.content:+ content += chunk.choices[0].delta.content++ assert content == "Strands async response"++ def test_sync_streaming_malformed_json_raises_error(self):+ """+ When stream=True and Content-Type is application/json but the body+ is malformed JSON, an error is raised with a descriptive message+ (not a raw JSONDecodeError).+ """+ from litellm.llms.custom_httpx.http_handler import HTTPHandler++ client = HTTPHandler()++ mock_response = Mock(spec=httpx.Response)+ mock_response.status_code = 200+ mock_response.headers = {"content-type": "application/json"}+ mock_response.read.return_value = b"not valid json {{"++ with patch.object(client, "post", return_value=mock_response):+ with pytest.raises(Exception, match="Failed to read/parse JSON response body"):+ litellm.completion(+ model="bedrock/agentcore/arn:aws:bedrock-agentcore:us-west-2:888602223428:runtime/test_agent",+ messages=[{"role": "user", "content": "test"}],+ stream=True,+ client=client,+ )++ async def test_async_streaming_malformed_json_raises_error(self):+ """+ Async mirror: malformed JSON body raises a structured error, not a+ raw JSONDecodeError.+ """+ from unittest.mock import AsyncMock++ from litellm.llms.custom_httpx.http_handler import AsyncHTTPHandler++ client = AsyncHTTPHandler()++ mock_response = Mock(spec=httpx.Response)+ mock_response.status_code = 200+ mock_response.headers = {"content-type": "application/json"}+ mock_response.aread = AsyncMock(return_value=b"not valid json {{")++ with patch.object(+ client, "post", new_callable=AsyncMock, return_value=mock_response+ ):+ with pytest.raises(Exception, match="Failed to read/parse JSON response body"):+ await litellm.acompletion(+ model="bedrock/agentcore/arn:aws:bedrock-agentcore:us-west-2:888602223428:runtime/test_agent",+ messages=[{"role": "user", "content": "test"}],+ stream=True,+ client=client,+ )