{"record":{"id":"cf12614d1c45edcd","repo":"BerriAI/litellm","slug":"counttokens-processing-error-e-cf1261","errorCode":null,"errorMessage":"CountTokens processing error: {e}","messagePattern":"CountTokens processing error: (.+?)","errorType":"http","errorClass":"BedrockError","httpStatus":500,"severity":"error","filePath":"litellm/llms/bedrock/count_tokens/handler.py","lineNumber":130,"sourceCode":"            final_response: Final = self.transform_bedrock_response_to_anthropic(bedrock_response)\n\n            verbose_logger.debug(\"Final response: %s\", final_response)\n\n            return final_response\n\n        except BedrockError:\n            # Re-raise Bedrock exceptions as-is\n            raise\n        except httpx.HTTPStatusError as e:\n            # HTTP errors - preserve the actual status code\n            verbose_logger.error(\"HTTP error in CountTokens handler: %s\", e)\n            raise BedrockError(\n                status_code=e.response.status_code,\n                message=e.response.text,\n            )\n        except Exception as e:\n            verbose_logger.error(\"Error in CountTokens handler: %s\", e)\n            raise BedrockError(\n                status_code=500,\n                message=f\"CountTokens processing error: {e}\",\n            )\n","sourceCodeStart":112,"sourceCodeEnd":134,"githubUrl":"https://github.com/BerriAI/litellm/blob/77b7c6c40c0c5aa5fbcb1d6a1825ac39ca8829b8/litellm/llms/bedrock/count_tokens/handler.py#L112-L134","documentation":"The catch-all branch of the count-tokens handler: any exception that is neither a BedrockError nor an httpx.HTTPStatusError (JSON decode failures, transformation bugs, attribute errors) is logged and re-raised as BedrockError(status_code=500, message='CountTokens processing error: {e}'). The status 500 is synthetic — it signals a client-side/litellm-side failure, not necessarily an AWS server error.","triggerScenarios":"AWS returns 200 with a non-JSON body (response.json() raises); the bedrock->anthropic response transformation throws on an unexpected payload shape; programming errors inside the handler (KeyError on a missing field in the parsed response).","commonSituations":"AWS schema changes or new model families whose count-tokens response shape the transformer does not expect; a proxy intercepting responses; empty bodies from interrupted connections; older litellm versions meeting newer AWS response formats.","solutions":["Look at the underlying exception text embedded in the message and the preceding verbose_logger.error line (run with LITELLM_LOG=DEBUG to see it)","Reproduce the raw AWS response (aws bedrock-runtime invoke-model ... for count-tokens) and compare its shape with what litellm expects","Upgrade litellm to the latest release — transformer fixes for new models land frequently","If the payload is non-JSON because of a network intermediary, remove it or fix content-encoding handling"],"exampleFix":"# before\ntry:\n    out = await handler.count_tokens(request)\nexcept BedrockError as e:\n    retry(e)  # wrong: 500 here is synthetic, retrying rarely helps\n\n# after\ntry:\n    out = await handler.count_tokens(request)\nexcept BedrockError as e:\n    if e.message.startswith('CountTokens processing error'):\n        capture_debug_payload(e)   # synthetic 500 -> inspect, report upstream\n    else:\n        raise","handlingStrategy":"try-catch","validationCode":"import json\n\ndef precheck_count_tokens_payload(payload: dict) -> None:\n    # cheap client-side checks that mirror handler expectations\n    assert payload.get('model'), 'model required'\n    if 'messages' in payload:\n        assert isinstance(payload['messages'], list) and payload['messages'], 'messages must be a non-empty list'\n    else:\n        assert len(payload) > 1, 'InvokeModel body needs a content field besides model'","typeGuard":null,"tryCatchPattern":"try:\n    counts = await handler.count_tokens(request)\nexcept BedrockError as e:\n    if e.status_code == 500 and 'CountTokens processing error' in (e.message or ''):\n        # synthetic 500: capture and report, do NOT blind-retry\n        report_to_telemetry({'request': safe_dump(request), 'error': e.message})\n        raise\n    raise","preventionTips":["Pin litellm versions and test count-tokens calls against your models after upgrading","Keep request bodies simple and spec-compliant to avoid transformer edge cases","Log the raw AWS response once in DEBUG mode to correlate with the synthetic 500"],"tags":["bedrock","count-tokens","internal-error","unexpected-exception"],"backgroundTag":"internal-processing-error","analyzedSha":"77b7c6c40c0c5aa5fbcb1d6a1825ac39ca8829b8","analyzedAt":"2026-08-18T11:44:31.656Z","contentChangedAt":null,"schemaVersion":2},"datasetVersion":"2026-09-23T08:17:48.524Z"}