{"record":{"id":"266f59c67721513c","repo":"BerriAI/litellm","slug":"error-parsing-chunk-e-received-chunk-chunk","errorCode":null,"errorMessage":"Error parsing chunk: {e},\nReceived chunk: {chunk}","messagePattern":"Error parsing chunk: (.+?),\nReceived chunk: (.+?)","errorType":"exception","errorClass":"RuntimeError","httpStatus":null,"severity":"error","filePath":"litellm/llms/anthropic/chat/handler.py","lineNumber":1141,"sourceCode":"\n                if str_line.startswith(\"data:\"):\n                    result = self._parse_sse_data(str_line)\n                    if result is not None:\n                        return result\n                    # If None, continue loop to get more chunks for accumulation\n                else:\n                    return GenericStreamingChunk(\n                        text=\"\",\n                        is_finished=False,\n                        finish_reason=\"\",\n                        usage=None,\n                        index=0,\n                        tool_use=None,\n                    )\n            except StopIteration:\n                raise StopIteration\n            except ValueError as e:\n                raise RuntimeError(f\"Error parsing chunk: {e},\\nReceived chunk: {chunk}\")\n\n    # Async iterator\n    def __aiter__(self):\n        self.async_response_iterator = self.streaming_response.__aiter__()\n        return self\n\n    async def __anext__(self):\n        while True:\n            try:\n                chunk = await self.async_response_iterator.__anext__()\n            except StopAsyncIteration:\n                # If we have accumulated JSON when stream ends, try to parse it\n                if self.accumulated_json:\n                    try:\n                        data_json = json.loads(self.accumulated_json)\n                        self.accumulated_json = \"\"\n                        return self.chunk_parser(chunk=data_json)\n                    except json.JSONDecodeError:","sourceCodeStart":1123,"sourceCodeEnd":1159,"githubUrl":"https://github.com/BerriAI/litellm/blob/6c2dcb801bf2b75c18f1bb24140e7cf57465cc4d/litellm/llms/anthropic/chat/handler.py#L1123-L1159","documentation":"RuntimeError from the sync Anthropic stream iterator's parsing stage: after a raw line is successfully fetched, converting it into a GenericStreamingChunk raised a ValueError, and the handler re-raises it as RuntimeError including both the error and the raw chunk. The '\nReceived chunk:' part is the debugging gold — it shows the exact payload that could not be parsed.","triggerScenarios":"Sync streaming where a 'data:' line's JSON parses but its shape is unexpected (missing fields the parser expects, unexpected event type), or where the chunk text is not valid JSON (e.g. 'data: [DONE]' style payloads from an OpenAI-format upstream served under an anthropic/ model prefix).","commonSituations":"Pointing anthropic/ models at OpenAI-compatible or mock servers; API format drift after an Anthropic API version change; gateways that append trailers or rewrite events; testing with recorded/replayed SSE fixtures that were truncated.","solutions":["Look at 'Received chunk:' in the message to see the exact malformed payload and identify its origin (OpenAI-style, HTML, truncated).","If the chunk looks like OpenAI SSE ('\"choices\": [...]'), remove the anthropic/ prefix or fix the model routing so the OpenAI transformation is used.","If the chunk is truncated JSON, check for proxy buffering/read-timeout settings that cut the stream early.","Reproduce with stream=False against the same endpoint to inspect the full response body.","Catch RuntimeError around stream consumption and degrade gracefully (keep partial content, surface the error to the user)."],"exampleFix":"# before\nresult = \"\".join(c.choices[0].delta.content or \"\" for c in resp)\n\n# after\nresult = []\ntry:\n    for c in resp:\n        if c.choices and c.choices[0].delta.content:\n            result.append(c.choices[0].delta.content)\nexcept RuntimeError as e:\n    log.warning(\"anthropic stream parse failure: %s\", e)\nprint(\"\".join(result))","handlingStrategy":"try-catch","validationCode":null,"typeGuard":null,"tryCatchPattern":"collected = []\ntry:\n    for chunk in stream:\n        collected.append(chunk)\nexcept RuntimeError as e:\n    if \"Error parsing chunk\" in str(e):\n        log.error(\"unparseable frame: %s\", e)  # includes raw chunk\n        return merge_partial(collected)  # graceful degradation\n    raise","preventionTips":["Verify endpoint speaks Anthropic SSE before switching model prefixes.","Replay recorded Anthropic SSE fixtures in integration tests.","Treat 'Received chunk:' content as the primary debugging clue."],"tags":["anthropic","streaming","chunk-parsing","sse"],"backgroundTag":null,"analyzedSha":"6c2dcb801bf2b75c18f1bb24140e7cf57465cc4d","analyzedAt":"2026-08-15T07:12:03.035Z","schemaVersion":2},"datasetVersion":"2026-08-15T22:17:37.221Z"}