BerriAI/litellm · error · BedrockError

CountTokens processing error

Error message

CountTokens processing error: {e}

What it means

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.

Solutions

  1. 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)
  2. Reproduce the raw AWS response (aws bedrock-runtime invoke-model ... for count-tokens) and compare its shape with what litellm expects
  3. Upgrade litellm to the latest release — transformer fixes for new models land frequently
  4. If the payload is non-JSON because of a network intermediary, remove it or fix content-encoding handling

Example fix

# before
try:
    out = await handler.count_tokens(request)
except BedrockError as e:
    retry(e)  # wrong: 500 here is synthetic, retrying rarely helps

# after
try:
    out = await handler.count_tokens(request)
except BedrockError as e:
    if e.message.startswith('CountTokens processing error'):
        capture_debug_payload(e)   # synthetic 500 -> inspect, report upstream
    else:
        raise
Defensive patterns

Strategy: try-catch

Validate before calling

import json

def precheck_count_tokens_payload(payload: dict) -> None:
    # cheap client-side checks that mirror handler expectations
    assert payload.get('model'), 'model required'
    if 'messages' in payload:
        assert isinstance(payload['messages'], list) and payload['messages'], 'messages must be a non-empty list'
    else:
        assert len(payload) > 1, 'InvokeModel body needs a content field besides model'

Try / catch

try:
    counts = await handler.count_tokens(request)
except BedrockError as e:
    if e.status_code == 500 and 'CountTokens processing error' in (e.message or ''):
        # synthetic 500: capture and report, do NOT blind-retry
        report_to_telemetry({'request': safe_dump(request), 'error': e.message})
        raise
    raise

Prevention

When it happens

Trigger: 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).

Common situations: 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.

Related errors


AI-assisted analysis of BerriAI/litellm@77b7c6c40c (2026-08-18). Data as JSON: /api/errors/cf12614d1c45edcd. Report an issue: GitHub.

Appendix: source

Thrown at litellm/llms/bedrock/count_tokens/handler.py:130

            final_response: Final = self.transform_bedrock_response_to_anthropic(bedrock_response)

            verbose_logger.debug("Final response: %s", final_response)

            return final_response

        except BedrockError:
            # Re-raise Bedrock exceptions as-is
            raise
        except httpx.HTTPStatusError as e:
            # HTTP errors - preserve the actual status code
            verbose_logger.error("HTTP error in CountTokens handler: %s", e)
            raise BedrockError(
                status_code=e.response.status_code,
                message=e.response.text,
            )
        except Exception as e:
            verbose_logger.error("Error in CountTokens handler: %s", e)
            raise BedrockError(
                status_code=500,
                message=f"CountTokens processing error: {e}",
            )

View on GitHub (pinned to 77b7c6c40c)