Skip to content

fix(count_tokens)!: answer 400 for Vertex partner models without a count API and OpenAI-shaped provider errors on /v1/responses/input_tokens - #47163

Merged
mateo-berri merged 13 commits into
mainfrom
litellm_count_tokens_partner_400_and_responses_error_shape
Oct 17, 2026
Merged

mateo-berri merged 13 commits into
mainfrom
litellm_count_tokens_partner_400_and_responses_error_shape

Conversation

@mateo-berri

@mateo-berri mateo-berri commented Oct 17, 2026 •

Copy link
Copy Markdown
Contributor

Breaking change: clients matching token_counting_error or a string code on Responses count errors should match the OpenAI type instead, and Vertex partner counts that answered 500 or 404 now answer 400

TLDR

Problem this solves:

  • Vertex GLM token counts answer a 500 "Unknown partner model"
  • /v1/responses/input_tokens provider errors arrive as raw JSON stuffed in message

How it solves it:

  • Vertex partner models without a count API now answer 400 naming the model, unless the deployment sets its own custom_tokenizer
  • Responses count errors pass the provider's OpenAI error through as is

Replaces #46990 with the same commits

Intentional product change: the error shapes in the breaking change note above

User Flow

Before: an app that sizes prompts gets a 500 on Vertex GLM and an unreadable Responses count error

  1. They send POST https://litellm-domain/v1/messages/count_tokens with "model": "vertex-glm-5.2" and a normal Messages body
  2. It answers 500 api_error "Unknown partner model: zai-org/glm-5.2-maas"
  3. They send POST https://litellm-domain/v1/responses/input_tokens for an OpenAI model with a function tool missing its name
  4. It answers 400 with OpenAI's error JSON as a string in error.message and type: token_counting_error

After: the same calls answer plain 400s that say what is wrong

  1. They send POST https://litellm-domain/v1/messages/count_tokens with "model": "vertex-glm-5.2" and a normal Messages body
  2. It answers 400 invalid_request_error "LiteLLM does not support counting tokens for Vertex AI model zai-org/glm-5.2-maas."
  3. They send POST https://litellm-domain/v1/responses/input_tokens for an OpenAI model with a function tool missing its name
  4. It answers OpenAI's own 400, "Missing required parameter: 'tools[0].name'." with param: tools[0].name

Linear ticket

Part of LIT-9564

Cases from the customer's test this PR leaves out

Each case compares the count with /v1/messages usage

Case State Reason
Vertex Claude flat counts Fixed since 1.100.0 #43900
o3 over inference Does not reproduce within 0.5%
Kimi K2.6 Does not reproduce within 0.4%
grok-4-1 with a tool Open, -5.6% tool framing
DeepSeek V4 with a tool Open, -9.1% tool framing
Databricks qwen3.5 with a tool Open, -9.3% tool framing
deepseek-r1 400 by design needs #46777
Vertex GLM, all six 400 now needs #46777
PDF documents Open adapter defect
Databricks inkling, glm, kimi-k3 Not tested not served to us
Vertex Claude, Responses function tool Open, 400 follow-up filed
large_user prompt Not run marked slow, skipped
Why tool framing and PDFs stay open

Tool framing means the provider's chat template adds about 210 tokens whenever a request carries tools, and the local count does not, so a per-request constant like #46777's cannot close it. The PDF defect is that /v1/messages sends an Anthropic document block to OpenAI-shaped providers as an image_url with data:application/pdf, which o3, Kimi, grok and DeepSeek V4 Pro reject with 400 and DeepSeek V4 Flash and GLM silently ignore. Both are tracked as their own follow-ups. #46777 (open) turns a 400 "can't count this model" into a configured estimate, which is what the GLM 400 here is shaped for

Decisions

A Vertex partner model with no count that matches inference answers 400 rather than a silent local count. The ticket measured the local tokenizer 54% to 426% off for GLM, so a confident wrong number is worse than an error the caller can act on, and #46777's fallback lets an operator opt into an estimate on purpose

A deployment that sets model_info.custom_tokenizer skips that 400 for a messages body and counts with its tokenizer, since the operator chose that count on purpose and /utils/token_counter already honors it. A contents-only body keeps the 400, because the local count cannot read contents. With zai-org/GLM-5.2 the customer's own test is within 0.2% on its baseline and system rows and within 3.2% to 4.7% on its tool rows whenever GLM inference counts the tool. It still fails the PDF rows, because GLM inference ignores the document that the tokenizer counts as base64 text. GLM inference itself is not stable on the tool rows: the same large_tool body billed 2222 input tokens in one run and 1137 in the next, so no count can match it every time

It answers 400 rather than calling Vertex. GLM has no count endpoint (publishers/zai-org/models/glm-5.2-maas:countTokens answers 404) and Mistral's :countTokens answers 400 "countTokens is infeasible", so calling them only adds a round trip to a known failure. gpt-oss and Gemma MaaS do answer :countTokens, but both gave 4 tokens and 16 billable characters for a prompt gpt-oss inference billed as 71 tokens, a raw text count with no chat template, so they get the 400 too. The message says LiteLLM, not Vertex, cannot count them, since that is what is true for every model the gate covers (sweep in the gist). 400 matches what Bedrock answers for the same "this model can't be counted" meaning, and #46777 treats 400 and 404 alike

The publishers left on Vertex's count route are Anthropic (claude) and Meta (llama, meta/). Mistral and codestral leave it, since publishers/mistralai/models/count-tokens:rawPredict answers 404 for every Mistral model tried, including three whose inference answers 200 on the same project (sweep in the gist). Meta stays unverified because the QA project has no Meta access, and its route is unchanged from main. Every other Vertex partner prefix (mistral, codestral, zai-org, deepseek-ai, qwen, openai/gpt-oss, minimaxai, moonshotai, jamba, google/gemma) gets the 400 instead of a 500 or a 404, on /v1/messages/count_tokens, /v1/responses/input_tokens, /utils/token_counter and the Google countTokens route alike

On /v1/responses/input_tokens, a provider error that already is an OpenAI error object passes through with its four standard fields (message, type, param, code), since that is the shape the route promises, and any extra key drops. Any other provider error (Anthropic, Google, Bedrock, plain text) keeps its unwrapped message, a prefix like BedrockException - dropped, and takes the type the proxy gives that status elsewhere (invalid_request_error for most 4xx and internal_server_error for 5xx, where OpenAI says server_error), with param and code null, following the route's own 400s. The old param: "model" pointed callers at the wrong field

Only provider count errors are reshaped. Every other error on the route, like token_counting_disabled, keeps the proxy's usual error handling, and the reshaped answer adds the call id and closes the trace span through the global handler's own helpers

Pre-Submission checklist

Please complete all items before asking a LiteLLM maintainer to review your PR

  • I have added meaningful tests
  • The handful of test files covering my change pass locally, e.g. uv run pytest tests/unit/<your_test_file>.py -v. Leave the suites (make test-unit-*, make test-unit) to CI: it finishes in ~15 minutes where a laptop takes an hour or more
  • My PR passes all required CI/CD checks (e.g., lint, schema.d.ts sync check, etc.)
  • My PR's scope is as isolated as possible; it only solves 1 specific problem
  • Every automated review on my PR's latest commit has finished, and I have addressed or replied to each of its findings before requesting a maintainer review

Delays in PR merge?

If you're seeing a delay in your PR being merged, ping the LiteLLM Team on Slack (#pr-review).

Screenshots / Proof of Fix

Last updated: 2bed82a, a merge of #46990's commits. QA and /live-pr-risk ran on 1288a94, the last commit with a product diff

Case Before After
Vertex GLM, Messages count 500 "Unknown partner model" 400 "does not support counting"
Vertex GLM, other count routes 500 400
Vertex Mistral, count routes 404 400
Vertex gpt-oss, Messages count 500 400
Vertex GLM with custom_tokenizer 500 200
OpenAI nameless tool, Responses count OpenAI JSON in message OpenAI's own error
Bedrock, Vertex Claude, Gemini errors, Responses count JSON in message plain message
Requests that should not change same same
Customer's test, Vertex Claude rows pass pass
Customer's test, Vertex GLM rows fail, count 500 fail, count 400
Customer's test, GLM with its own tokenizer fail, count 500 most text rows pass

Real provider calls, one proxy each

config.yaml and proxy command

Each leg ran one proxy (2 workers, no database) with the same config and curl steps, only the commit differing, against real Vertex AI, Gemini, OpenAI and Bedrock (project id redacted), plus one OpenAI SDK check

python litellm/proxy/proxy_cli.py --config config.yaml --port $PORT --num_workers 2

model_list:
  - model_name: vertex-mistral-medium-3
    litellm_params:
      model: vertex_ai/mistral-medium-3
      vertex_location: us-central1
  - model_name: vertex-glm-5.2
    litellm_params:
      model: vertex_ai/zai-org/glm-5.2-maas
      vertex_location: global
  - model_name: vertex-glm-5.2-own-tokenizer
    litellm_params:
      model: vertex_ai/zai-org/glm-5.2-maas
      vertex_location: global
    model_info:
      custom_tokenizer:
        identifier: zai-org/GLM-5.2
        revision: main
  - model_name: vertex-gpt-oss-120b
    litellm_params:
      model: vertex_ai/openai/gpt-oss-120b-maas
      vertex_location: us-central1
  - model_name: claude-sonnet-4-5-vertex
    litellm_params:
      model: vertex_ai/claude-sonnet-4-5
      vertex_location: global
  - model_name: deepseek-r1
    litellm_params:
      model: bedrock/us.deepseek.r1-v1:0
      aws_region_name: us-east-1
  - model_name: gpt-6-luna
    litellm_params:
      model: openai/gpt-6-luna
      api_key: os.environ/OPENAI_API_KEY
  - model_name: gemini-typo
    litellm_params:
      model: gemini/gemini-typo
      api_key: os.environ/GEMINI_API_KEY
litellm_settings:
  drop_params: true

Before (aa32e4c)

Steps and output, 14 cases

Vertex GLM, Messages count

  1. Send the request
curl -s -w '\n[%{http_code}]\n' http://localhost:$PORT/v1/messages/count_tokens -H "Authorization: Bearer $LITELLM_MASTER_KEY" -H 'Content-Type: application/json' -d '{"model":"vertex-glm-5.2","messages":[{"role":"user","content":"Return exactly OK."}]}'
  1. Observe
{"type":"error","error":{"type":"api_error","message":"Unknown partner model: zai-org/glm-5.2-maas"}}
[500]

Vertex Mistral, both count routes

  1. Send the request
curl -s -w '\n[%{http_code}]\n' http://localhost:$PORT/v1/messages/count_tokens -H "Authorization: Bearer $LITELLM_MASTER_KEY" -H 'Content-Type: application/json' -d '{"model":"vertex-mistral-medium-3","messages":[{"role":"user","content":"Return exactly OK."}]}'
  1. Observe
{"type":"error","error":{"type":"not_found_error","message":"{\n  \"error\": {\n    \"code\": 404,\n    \"message\": \"Publisher model `projects/<project>/locations/us-central1/publishers/mistralai/models/count-tokens` was not found or your project does not have access to it. Ensure you are using a valid model name and that the model is available in the specified region. For more information, see: https://docs.cloud.google.com/gemini-enterprise-agent-platform/resources/locations.\",\n    \"status\": \"NOT_FOUND\"\n  }\n}\n"}}
[404]
  1. Send the request
curl -s -w '\n[%{http_code}]\n' http://localhost:$PORT/v1/responses/input_tokens -H "Authorization: Bearer $LITELLM_MASTER_KEY" -H 'Content-Type: application/json' -d '{"model":"vertex-mistral-medium-3","input":"Return exactly OK."}'
  1. Observe
{"error":{"message":"{\n  \"error\": {\n    \"code\": 404,\n    \"message\": \"Publisher model `projects/<project>/locations/us-central1/publishers/mistralai/models/count-tokens` was not found or your project does not have access to it. Ensure you are using a valid model name and that the model is available in the specified region. For more information, see: https://docs.cloud.google.com/gemini-enterprise-agent-platform/resources/locations.\",\n    \"status\": \"NOT_FOUND\"\n  }\n}\n","type":"token_counting_error","param":"model","code":"404"}}
[404]
  1. Send the request
curl -s -w '\n[%{http_code}]\n' http://localhost:$PORT/v1/messages -H "Authorization: Bearer $LITELLM_MASTER_KEY" -H 'Content-Type: application/json' -d '{"model":"vertex-mistral-medium-3","max_tokens":64,"messages":[{"role":"user","content":"Return exactly OK."}]}'
  1. Observe
{"id":"807307f8c6b64cc8a0b7039025a66ee2","type":"message","role":"assistant","model":"vertex-mistral-medium-3","stop_sequence":null,"usage":{"input_tokens":7,"output_tokens":2},"content":[{"type":"text","text":"OK"}],"stop_reason":"end_turn","stop_details":null}
[200]

Vertex gpt-oss, Messages count

  1. Send the request
curl -s -w '\n[%{http_code}]\n' http://localhost:$PORT/v1/messages/count_tokens -H "Authorization: Bearer $LITELLM_MASTER_KEY" -H 'Content-Type: application/json' -d '{"model":"vertex-gpt-oss-120b","messages":[{"role":"user","content":"Return exactly OK."}]}'
  1. Observe
{"type":"error","error":{"type":"api_error","message":"Unknown partner model: openai/gpt-oss-120b-maas"}}
[500]
  1. Send the request
curl -s -w '\n[%{http_code}]\n' http://localhost:$PORT/v1/messages -H "Authorization: Bearer $LITELLM_MASTER_KEY" -H 'Content-Type: application/json' -d '{"model":"vertex-gpt-oss-120b","max_tokens":256,"messages":[{"role":"user","content":"Return exactly OK."}]}'
  1. Observe
{"id":"a601b493-6493-45f2-8fb1-c122e73f8171","type":"message","role":"assistant","model":"vertex-gpt-oss-120b","stop_sequence":null,"usage":{"input_tokens":71,"output_tokens":23},"content":[{"type":"thinking","thinking":"We need to respond with exactly \"OK\". No extra.","signature":null},{"type":"text","text":"OK"}],"stop_reason":"end_turn","stop_details":null}
[200]

OpenAI tool without a name, Responses count

  1. Send the request
curl -s -w '\n[%{http_code}]\n' http://localhost:$PORT/v1/responses/input_tokens -H "Authorization: Bearer $LITELLM_MASTER_KEY" -H 'Content-Type: application/json' -d '{"model":"gpt-6-luna","input":"hi","tools":[{"type":"function"}]}'
  1. Observe
{"error":{"message":"{\n  \"error\": {\n    \"message\": \"Missing required parameter: 'tools[0].name'.\",\n    \"type\": \"invalid_request_error\",\n    \"param\": \"tools[0].name\",\n    \"code\": \"missing_required_parameter\"\n  }\n}","type":"token_counting_error","param":"model","code":"400"}}
[400]
  1. The same request through the OpenAI Python SDK (openai 2.33.0), reading the error fields the SDK hands the app
import os

from openai import BadRequestError, OpenAI

client = OpenAI(base_url=f"http://localhost:{os.environ['PORT']}/v1", api_key=os.environ["LITELLM_MASTER_KEY"])
try:
    client.responses.input_tokens.count(model="gpt-6-luna", input="hi", tools=[{"type": "function"}])
except BadRequestError as e:
    print(f"status={e.status_code} type={e.type} param={e.param} code={e.code}")
    print(f"message={e.message}")
status=400 type=token_counting_error param=model code=400
message=Error code: 400 - {'error': {'message': '{\n  "error": {\n    "message": "Missing required parameter: \'tools[0].name\'.",\n    "type": "invalid_request_error",\n    "param": "tools[0].name",\n    "code": "missing_required_parameter"\n  }\n}', 'type': 'token_counting_error', 'param': 'model', 'code': '400'}}

Vertex GLM, Responses count

  1. Send the request
curl -s -w '\n[%{http_code}]\n' http://localhost:$PORT/v1/responses/input_tokens -H "Authorization: Bearer $LITELLM_MASTER_KEY" -H 'Content-Type: application/json' -d '{"model":"vertex-glm-5.2","input":"Return exactly OK."}'
  1. Observe
{"error":{"message":"Unknown partner model: zai-org/glm-5.2-maas","type":"token_counting_error","param":"model","code":"500"}}
[500]

Vertex GLM, Google countTokens

  1. Send the request
curl -s -w '\n[%{http_code}]\n' http://localhost:$PORT/v1beta/models/vertex-glm-5.2:countTokens -H "Authorization: Bearer $LITELLM_MASTER_KEY" -H 'Content-Type: application/json' -d '{"contents":[{"role":"user","parts":[{"text":"Return exactly OK."}]}]}'
  1. Observe
{"error":{"code":500,"message":"Unknown partner model: zai-org/glm-5.2-maas","status":"INTERNAL"}}
[500]

Bedrock deepseek-r1, Responses count

  1. Send the request
curl -s -w '\n[%{http_code}]\n' http://localhost:$PORT/v1/responses/input_tokens -H "Authorization: Bearer $LITELLM_MASTER_KEY" -H 'Content-Type: application/json' -d '{"model":"deepseek-r1","input":"Return exactly OK."}'
  1. Observe
{"error":{"message":"{\"message\":\"The provided model doesn't support counting tokens.\"}","type":"token_counting_error","param":"model","code":"400"}}
[400]

Vertex Claude Responses tool, Responses count

  1. Send the request
curl -s -w '\n[%{http_code}]\n' http://localhost:$PORT/v1/responses/input_tokens -H "Authorization: Bearer $LITELLM_MASTER_KEY" -H 'Content-Type: application/json' -d '{"model":"claude-sonnet-4-5-vertex","input":"hi","tools":[{"type":"function","name":"noop","parameters":{"type":"object","properties":{}}}]}'
  1. Observe
{"error":{"message":"{\"type\":\"error\",\"error\":{\"type\":\"invalid_request_error\",\"message\":\"tools.0: Input tag 'function' found using 'type' does not match any of the expected tags: 'bash_20250124', 'browser_toolset_20260801', 'computer_toolset_20260801', 'custom', 'memory_20250818', 'text_editor_20250124', 'text_editor_20250429', 'text_editor_20250728', 'tool_search_tool_bm25', 'tool_search_tool_bm25_20251119', 'tool_search_tool_regex', 'tool_search_tool_regex_20251119', 'web_search_20250305'\"},\"request_id\":\"req_vrtx_011Cg77sK8s9ZjT77ij8VbGk\"}","type":"token_counting_error","param":"model","code":"400"}}
[400]

Gemini error, Responses count

  1. Send the request
curl -s -w '\n[%{http_code}]\n' http://localhost:$PORT/v1/responses/input_tokens -H "Authorization: Bearer $LITELLM_MASTER_KEY" -H 'Content-Type: application/json' -d '{"model":"gemini-typo","input":"Return exactly OK."}'
  1. Observe
{"error":{"message":"litellm.APIError: Google Gen AI Studio API error: 404 - {\n  \"error\": {\n    \"code\": 404,\n    \"message\": \"models/gemini-typo is not found for API version v1beta, or is not supported for countTokens. Call ModelService.ListModels to see the list of available models and their supported methods.\",\n    \"status\": \"NOT_FOUND\"\n  }\n}\n","type":"token_counting_error","param":"model","code":"404"}}
[404]

Vertex GLM, /utils/token_counter

  1. Send the request
curl -s -w '\n[%{http_code}]\n' http://localhost:$PORT/utils/token_counter?call_endpoint=true -H "Authorization: Bearer $LITELLM_MASTER_KEY" -H 'Content-Type: application/json' -d '{"model":"vertex-glm-5.2","messages":[{"role":"user","content":"Return exactly OK."}]}'
  1. Observe
{"error":{"message":"Unknown partner model: zai-org/glm-5.2-maas","type":"token_counting_error","param":"model","code":"500"}}
[500]

Vertex GLM with its own custom_tokenizer, count routes

  1. Send the request
curl -s -w '\n[%{http_code}]\n' http://localhost:$PORT/v1/messages/count_tokens -H "Authorization: Bearer $LITELLM_MASTER_KEY" -H 'Content-Type: application/json' -d '{"model":"vertex-glm-5.2-own-tokenizer","messages":[{"role":"user","content":"Return exactly OK."}]}'
  1. Observe
{"type":"error","error":{"type":"api_error","message":"Unknown partner model: zai-org/glm-5.2-maas"}}
[500]
  1. Send the request
curl -s -w '\n[%{http_code}]\n' http://localhost:$PORT/v1/responses/input_tokens -H "Authorization: Bearer $LITELLM_MASTER_KEY" -H 'Content-Type: application/json' -d '{"model":"vertex-glm-5.2-own-tokenizer","input":"Return exactly OK."}'
  1. Observe
{"error":{"message":"Unknown partner model: zai-org/glm-5.2-maas","type":"token_counting_error","param":"model","code":"500"}}
[500]
  1. Send the request
curl -s -w '\n[%{http_code}]\n' http://localhost:$PORT/v1beta/models/vertex-glm-5.2-own-tokenizer:countTokens -H "Authorization: Bearer $LITELLM_MASTER_KEY" -H 'Content-Type: application/json' -d '{"contents":[{"role":"user","parts":[{"text":"Return exactly OK."}]}]}'
  1. Observe
{"error":{"code":500,"message":"Unknown partner model: zai-org/glm-5.2-maas","status":"INTERNAL"}}
[500]
  1. Send the request
curl -s -w '\n[%{http_code}]\n' http://localhost:$PORT/utils/token_counter?call_endpoint=true -H "Authorization: Bearer $LITELLM_MASTER_KEY" -H 'Content-Type: application/json' -d '{"model":"vertex-glm-5.2-own-tokenizer","contents":[{"role":"user","parts":[{"text":"Return exactly OK."}]}]}'
  1. Observe
{"error":{"message":"Unknown partner model: zai-org/glm-5.2-maas","type":"token_counting_error","param":"model","code":"500"}}
[500]

Requests that should not change

  1. Send the request
curl -s -w '\n[%{http_code}]\n' http://localhost:$PORT/v1/responses/input_tokens -H "Authorization: Bearer $LITELLM_MASTER_KEY" -H 'Content-Type: application/json' -d '{"input":"hi"}'
  1. Observe
{"error":{"message":"Missing required parameter: 'model'.","type":"invalid_request_error","param":"model","code":"missing_required_parameter"}}
[400]
  1. Send the request
curl -s -w '\n[%{http_code}]\n' http://localhost:$PORT/v1/responses/input_tokens -H "Authorization: Bearer $LITELLM_MASTER_KEY" -H 'Content-Type: application/json' -d '{"model":"gpt-6-luna","input":"Return exactly OK."}'
  1. Observe
{"object":"response.input_tokens","input_tokens":10}
[200]
  1. Send the request
curl -s -w '\n[%{http_code}]\n' http://localhost:$PORT/v1/responses/input_tokens -H "Authorization: Bearer $LITELLM_MASTER_KEY" -H 'Content-Type: application/json' -d '{"model":"claude-sonnet-4-5-vertex","input":"Return exactly OK."}'
  1. Observe
{"object":"response.input_tokens","input_tokens":11}
[200]
  1. Send the request
curl -s -w '\n[%{http_code}]\n' http://localhost:$PORT/v1/messages/count_tokens -H "Authorization: Bearer $LITELLM_MASTER_KEY" -H 'Content-Type: application/json' -d '{"model":"claude-sonnet-4-5-vertex","messages":[{"role":"user","content":"Return exactly OK."}]}'
  1. Observe
{"input_tokens":11}
[200]
  1. Send the request
curl -s -w '\n[%{http_code}]\n' http://localhost:$PORT/v1/messages/count_tokens -H "Authorization: Bearer $LITELLM_MASTER_KEY" -H 'Content-Type: application/json' -d '{"model":"deepseek-r1","messages":[{"role":"user","content":"Return exactly OK."}]}'
  1. Observe
{"type":"error","error":{"type":"invalid_request_error","message":"The provided model doesn't support counting tokens."}}
[400]
  1. Send the request
curl -s -w '\n[%{http_code}]\n' http://localhost:$PORT/v1/messages -H "Authorization: Bearer $LITELLM_MASTER_KEY" -H 'Content-Type: application/json' -d '{"model":"vertex-glm-5.2","max_tokens":256,"messages":[{"role":"user","content":"Return exactly OK."}]}'
  1. Observe
{"id":"93bf8854-6efe-483a-a7d1-4252e7ff5961","type":"message","role":"assistant","model":"vertex-glm-5.2","stop_sequence":null,"usage":{"input_tokens":16,"output_tokens":82},"content":[{"type":"thinking","thinking":"1.  Analyze the Request: The user wants the response to be exactly \"OK\".\n2.  Identify Constraints: \"Return exactly OK.\" -> No other text, no punctuation (unless considered part of \"OK\", but standard is just the two letters), no conversational filler.\n3.  Formulate Output: OK\n4.  Verify: Does it match exactly? Yes.","signature":null},{"type":"text","text":"OK"}],"stop_reason":"end_turn","stop_details":null}
[200]

Customer's six shapes, count vs inference

  1. For each of the six shapes, build the body with the customer's request builder, send it to /v1/messages/count_tokens, then send it with "max_tokens": 256 to /v1/messages and compare input_tokens (builder and runner): PORT=$PORT ./run_cases.sh vertex-glm-5.2 claude-sonnet-4-5-vertex
vertex-glm-5.2             baseline                 inf=1105 count=None diff=- FAIL count 500: {"type": "error", "error": {"type": "api_error", "message": "Unknown partner model: zai-org/glm-5.2-maas"}}
vertex-glm-5.2             large_system             inf=2102 count=None diff=- FAIL count 500: {"type": "error", "error": {"type": "api_error", "message": "Unknown partner model: zai-org/glm-5.2-maas"}}
vertex-glm-5.2             large_tool               inf=2225 count=None diff=- FAIL count 500: {"type": "error", "error": {"type": "api_error", "message": "Unknown partner model: zai-org/glm-5.2-maas"}}
vertex-glm-5.2             large_system_and_tool    inf=3222 count=None diff=- FAIL count 500: {"type": "error", "error": {"type": "api_error", "message": "Unknown partner model: zai-org/glm-5.2-maas"}}
vertex-glm-5.2             pdf_base64_1_page        inf=138 count=None diff=- FAIL count 500: {"type": "error", "error": {"type": "api_error", "message": "Unknown partner model: zai-org/glm-5.2-maas"}}
vertex-glm-5.2             pdf_base64_12_pages      inf=405 count=None diff=- FAIL count 500: {"type": "error", "error": {"type": "api_error", "message": "Unknown partner model: zai-org/glm-5.2-maas"}}
claude-sonnet-4-5-vertex   baseline                 inf=1105 count=1105 diff=+0.00 PASS
claude-sonnet-4-5-vertex   large_system             inf=2108 count=2108 diff=+0.00 PASS
claude-sonnet-4-5-vertex   large_tool               inf=2633 count=2633 diff=+0.00 PASS
claude-sonnet-4-5-vertex   large_system_and_tool    inf=3637 count=3637 diff=+0.00 PASS
claude-sonnet-4-5-vertex   pdf_base64_1_page        inf=2687 count=2687 diff=+0.00 PASS
claude-sonnet-4-5-vertex   pdf_base64_12_pages      inf=30740 count=30740 diff=+0.00 PASS

Customer's test_count_tokens.py

  1. Run the customer's own test_count_tokens.py from the ticket, unchanged, with a stand-in for its unshared base_integration_test harness that lists models from /model/info and posts with the master key (stand-in): LITELLM_BASE_URL=http://127.0.0.1:$PORT pytest test_count_tokens.py -k test_count_tokens_matches_inference --models 'vertex-glm-5.2*' --models claude-sonnet-4-5-vertex -s
model | case | status | count_tokens | inference | diff% | error
claude-sonnet-4-5-vertex | baseline | pass | 1104 | 1104 | 0.0 | 
claude-sonnet-4-5-vertex | large_system | pass | 2104 | 2104 | 0.0 | 
claude-sonnet-4-5-vertex | large_tool | pass | 2639 | 2639 | 0.0 | 
claude-sonnet-4-5-vertex | large_system_and_tool | pass | 3636 | 3636 | 0.0 | 
claude-sonnet-4-5-vertex | pdf_base64_1_page | pass | 2688 | 2688 | 0.0 | 
claude-sonnet-4-5-vertex | pdf_base64_12_pages | pass | 30738 | 30738 | 0.0 | 
vertex-glm-5.2 | baseline | fail | None | 1104 | None | 500 count_tokens: Unknown partner model: zai-org/glm-5.2-maas
vertex-glm-5.2 | large_system | fail | None | 2104 | None | 500 count_tokens: Unknown partner model: zai-org/glm-5.2-maas
vertex-glm-5.2 | large_tool | fail | None | 2225 | None | 500 count_tokens: Unknown partner model: zai-org/glm-5.2-maas
vertex-glm-5.2 | large_system_and_tool | fail | None | 2138 | None | 500 count_tokens: Unknown partner model: zai-org/glm-5.2-maas
vertex-glm-5.2 | pdf_base64_1_page | fail | None | 137 | None | 500 count_tokens: Unknown partner model: zai-org/glm-5.2-maas
vertex-glm-5.2 | pdf_base64_12_pages | fail | None | 402 | None | 500 count_tokens: Unknown partner model: zai-org/glm-5.2-maas
vertex-glm-5.2-own-tokenizer | baseline | fail | None | 1105 | None | 500 count_tokens: Unknown partner model: zai-org/glm-5.2-maas
vertex-glm-5.2-own-tokenizer | large_system | fail | None | 2104 | None | 500 count_tokens: Unknown partner model: zai-org/glm-5.2-maas
vertex-glm-5.2-own-tokenizer | large_tool | fail | None | 1137 | None | 500 count_tokens: Unknown partner model: zai-org/glm-5.2-maas
vertex-glm-5.2-own-tokenizer | large_system_and_tool | fail | None | 2136 | None | 500 count_tokens: Unknown partner model: zai-org/glm-5.2-maas
vertex-glm-5.2-own-tokenizer | pdf_base64_1_page | fail | None | 141 | None | 500 count_tokens: Unknown partner model: zai-org/glm-5.2-maas
vertex-glm-5.2-own-tokenizer | pdf_base64_12_pages | fail | None | 401 | None | 500 count_tokens: Unknown partner model: zai-org/glm-5.2-maas
18 passed, 3 skipped, 9 deselected in 28.30s

After (1288a94)

Steps and output, 14 cases

Vertex GLM, Messages count

  1. Send the request
curl -s -w '\n[%{http_code}]\n' http://localhost:$PORT/v1/messages/count_tokens -H "Authorization: Bearer $LITELLM_MASTER_KEY" -H 'Content-Type: application/json' -d '{"model":"vertex-glm-5.2","messages":[{"role":"user","content":"Return exactly OK."}]}'
  1. Observe
{"type":"error","error":{"type":"invalid_request_error","message":"LiteLLM does not support counting tokens for Vertex AI model zai-org/glm-5.2-maas."}}
[400]

Vertex Mistral, both count routes

  1. Send the request
curl -s -w '\n[%{http_code}]\n' http://localhost:$PORT/v1/messages/count_tokens -H "Authorization: Bearer $LITELLM_MASTER_KEY" -H 'Content-Type: application/json' -d '{"model":"vertex-mistral-medium-3","messages":[{"role":"user","content":"Return exactly OK."}]}'
  1. Observe
{"type":"error","error":{"type":"invalid_request_error","message":"LiteLLM does not support counting tokens for Vertex AI model mistral-medium-3."}}
[400]
  1. Send the request
curl -s -w '\n[%{http_code}]\n' http://localhost:$PORT/v1/responses/input_tokens -H "Authorization: Bearer $LITELLM_MASTER_KEY" -H 'Content-Type: application/json' -d '{"model":"vertex-mistral-medium-3","input":"Return exactly OK."}'
  1. Observe
{"error":{"message":"LiteLLM does not support counting tokens for Vertex AI model mistral-medium-3.","type":"invalid_request_error","param":null,"code":null}}
[400]
  1. Send the request
curl -s -w '\n[%{http_code}]\n' http://localhost:$PORT/v1/messages -H "Authorization: Bearer $LITELLM_MASTER_KEY" -H 'Content-Type: application/json' -d '{"model":"vertex-mistral-medium-3","max_tokens":64,"messages":[{"role":"user","content":"Return exactly OK."}]}'
  1. Observe
{"id":"7b7f0999a12f490f8c3c4c723ee02121","type":"message","role":"assistant","model":"vertex-mistral-medium-3","stop_sequence":null,"usage":{"input_tokens":7,"output_tokens":2},"content":[{"type":"text","text":"OK"}],"stop_reason":"end_turn","stop_details":null}
[200]

Vertex gpt-oss, Messages count

  1. Send the request
curl -s -w '\n[%{http_code}]\n' http://localhost:$PORT/v1/messages/count_tokens -H "Authorization: Bearer $LITELLM_MASTER_KEY" -H 'Content-Type: application/json' -d '{"model":"vertex-gpt-oss-120b","messages":[{"role":"user","content":"Return exactly OK."}]}'
  1. Observe
{"type":"error","error":{"type":"invalid_request_error","message":"LiteLLM does not support counting tokens for Vertex AI model openai/gpt-oss-120b-maas."}}
[400]
  1. Send the request
curl -s -w '\n[%{http_code}]\n' http://localhost:$PORT/v1/messages -H "Authorization: Bearer $LITELLM_MASTER_KEY" -H 'Content-Type: application/json' -d '{"model":"vertex-gpt-oss-120b","max_tokens":256,"messages":[{"role":"user","content":"Return exactly OK."}]}'
  1. Observe
{"id":"21969bd1-acdf-4b6f-8d6a-ff129dd619fb","type":"message","role":"assistant","model":"vertex-gpt-oss-120b","stop_sequence":null,"usage":{"input_tokens":71,"output_tokens":55},"content":[{"type":"thinking","thinking":"The user asks: \"Return exactly OK.\" So answer should be \"OK\". No extra punctuation? Probably exactly \"OK\". Should not include any extra whitespace or newline? Just \"OK\". I should output \"OK\".","signature":null},{"type":"text","text":"OK"}],"stop_reason":"end_turn","stop_details":null}
[200]

OpenAI tool without a name, Responses count

  1. Send the request
curl -s -w '\n[%{http_code}]\n' http://localhost:$PORT/v1/responses/input_tokens -H "Authorization: Bearer $LITELLM_MASTER_KEY" -H 'Content-Type: application/json' -d '{"model":"gpt-6-luna","input":"hi","tools":[{"type":"function"}]}'
  1. Observe
{"error":{"message":"Missing required parameter: 'tools[0].name'.","type":"invalid_request_error","param":"tools[0].name","code":"missing_required_parameter"}}
[400]
  1. The same request through the OpenAI Python SDK (openai 2.33.0), reading the error fields the SDK hands the app
import os

from openai import BadRequestError, OpenAI

client = OpenAI(base_url=f"http://localhost:{os.environ['PORT']}/v1", api_key=os.environ["LITELLM_MASTER_KEY"])
try:
    client.responses.input_tokens.count(model="gpt-6-luna", input="hi", tools=[{"type": "function"}])
except BadRequestError as e:
    print(f"status={e.status_code} type={e.type} param={e.param} code={e.code}")
    print(f"message={e.message}")
status=400 type=invalid_request_error param=tools[0].name code=missing_required_parameter
message=Error code: 400 - {'error': {'message': "Missing required parameter: 'tools[0].name'.", 'type': 'invalid_request_error', 'param': 'tools[0].name', 'code': 'missing_required_parameter'}}

Vertex GLM, Responses count

  1. Send the request
curl -s -w '\n[%{http_code}]\n' http://localhost:$PORT/v1/responses/input_tokens -H "Authorization: Bearer $LITELLM_MASTER_KEY" -H 'Content-Type: application/json' -d '{"model":"vertex-glm-5.2","input":"Return exactly OK."}'
  1. Observe
{"error":{"message":"LiteLLM does not support counting tokens for Vertex AI model zai-org/glm-5.2-maas.","type":"invalid_request_error","param":null,"code":null}}
[400]

Vertex GLM, Google countTokens

  1. Send the request
curl -s -w '\n[%{http_code}]\n' http://localhost:$PORT/v1beta/models/vertex-glm-5.2:countTokens -H "Authorization: Bearer $LITELLM_MASTER_KEY" -H 'Content-Type: application/json' -d '{"contents":[{"role":"user","parts":[{"text":"Return exactly OK."}]}]}'
  1. Observe
{"error":{"code":400,"message":"LiteLLM does not support counting tokens for Vertex AI model zai-org/glm-5.2-maas.","status":"INVALID_ARGUMENT"}}
[400]

Bedrock deepseek-r1, Responses count

  1. Send the request
curl -s -w '\n[%{http_code}]\n' http://localhost:$PORT/v1/responses/input_tokens -H "Authorization: Bearer $LITELLM_MASTER_KEY" -H 'Content-Type: application/json' -d '{"model":"deepseek-r1","input":"Return exactly OK."}'
  1. Observe
{"error":{"message":"The provided model doesn't support counting tokens.","type":"invalid_request_error","param":null,"code":null}}
[400]

Vertex Claude Responses tool, Responses count

  1. Send the request
curl -s -w '\n[%{http_code}]\n' http://localhost:$PORT/v1/responses/input_tokens -H "Authorization: Bearer $LITELLM_MASTER_KEY" -H 'Content-Type: application/json' -d '{"model":"claude-sonnet-4-5-vertex","input":"hi","tools":[{"type":"function","name":"noop","parameters":{"type":"object","properties":{}}}]}'
  1. Observe
{"error":{"message":"tools.0: Input tag 'function' found using 'type' does not match any of the expected tags: 'bash_20250124', 'browser_toolset_20260801', 'computer_toolset_20260801', 'custom', 'memory_20250818', 'text_editor_20250124', 'text_editor_20250429', 'text_editor_20250728', 'tool_search_tool_bm25', 'tool_search_tool_bm25_20251119', 'tool_search_tool_regex', 'tool_search_tool_regex_20251119', 'web_search_20250305'","type":"invalid_request_error","param":null,"code":null}}
[400]

Gemini error, Responses count

  1. Send the request
curl -s -w '\n[%{http_code}]\n' http://localhost:$PORT/v1/responses/input_tokens -H "Authorization: Bearer $LITELLM_MASTER_KEY" -H 'Content-Type: application/json' -d '{"model":"gemini-typo","input":"Return exactly OK."}'
  1. Observe
{"error":{"message":"models/gemini-typo is not found for API version v1beta, or is not supported for countTokens. Call ModelService.ListModels to see the list of available models and their supported methods.","type":"invalid_request_error","param":null,"code":null}}
[404]

Vertex GLM, /utils/token_counter

  1. Send the request
curl -s -w '\n[%{http_code}]\n' http://localhost:$PORT/utils/token_counter?call_endpoint=true -H "Authorization: Bearer $LITELLM_MASTER_KEY" -H 'Content-Type: application/json' -d '{"model":"vertex-glm-5.2","messages":[{"role":"user","content":"Return exactly OK."}]}'
  1. Observe
{"error":{"message":"LiteLLM does not support counting tokens for Vertex AI model zai-org/glm-5.2-maas.","type":"token_counting_error","param":"model","code":"400"}}
[400]

Vertex GLM with its own custom_tokenizer, count routes

  1. Send the request
curl -s -w '\n[%{http_code}]\n' http://localhost:$PORT/v1/messages/count_tokens -H "Authorization: Bearer $LITELLM_MASTER_KEY" -H 'Content-Type: application/json' -d '{"model":"vertex-glm-5.2-own-tokenizer","messages":[{"role":"user","content":"Return exactly OK."}]}'
  1. Observe
{"input_tokens":11}
[200]
  1. Send the request
curl -s -w '\n[%{http_code}]\n' http://localhost:$PORT/v1/responses/input_tokens -H "Authorization: Bearer $LITELLM_MASTER_KEY" -H 'Content-Type: application/json' -d '{"model":"vertex-glm-5.2-own-tokenizer","input":"Return exactly OK."}'
  1. Observe
{"object":"response.input_tokens","input_tokens":11}
[200]
  1. Send the request
curl -s -w '\n[%{http_code}]\n' http://localhost:$PORT/v1beta/models/vertex-glm-5.2-own-tokenizer:countTokens -H "Authorization: Bearer $LITELLM_MASTER_KEY" -H 'Content-Type: application/json' -d '{"contents":[{"role":"user","parts":[{"text":"Return exactly OK."}]}]}'
  1. Observe
{"totalTokens":11,"promptTokensDetails":[]}
[200]
  1. Send the request
curl -s -w '\n[%{http_code}]\n' http://localhost:$PORT/utils/token_counter?call_endpoint=true -H "Authorization: Bearer $LITELLM_MASTER_KEY" -H 'Content-Type: application/json' -d '{"model":"vertex-glm-5.2-own-tokenizer","contents":[{"role":"user","parts":[{"text":"Return exactly OK."}]}]}'
  1. Observe
{"error":{"message":"LiteLLM does not support counting tokens for Vertex AI model zai-org/glm-5.2-maas.","type":"token_counting_error","param":"model","code":"400"}}
[400]

Requests that should not change

  1. Send the request
curl -s -w '\n[%{http_code}]\n' http://localhost:$PORT/v1/responses/input_tokens -H "Authorization: Bearer $LITELLM_MASTER_KEY" -H 'Content-Type: application/json' -d '{"input":"hi"}'
  1. Observe
{"error":{"message":"Missing required parameter: 'model'.","type":"invalid_request_error","param":"model","code":"missing_required_parameter"}}
[400]
  1. Send the request
curl -s -w '\n[%{http_code}]\n' http://localhost:$PORT/v1/responses/input_tokens -H "Authorization: Bearer $LITELLM_MASTER_KEY" -H 'Content-Type: application/json' -d '{"model":"gpt-6-luna","input":"Return exactly OK."}'
  1. Observe
{"object":"response.input_tokens","input_tokens":10}
[200]
  1. Send the request
curl -s -w '\n[%{http_code}]\n' http://localhost:$PORT/v1/responses/input_tokens -H "Authorization: Bearer $LITELLM_MASTER_KEY" -H 'Content-Type: application/json' -d '{"model":"claude-sonnet-4-5-vertex","input":"Return exactly OK."}'
  1. Observe
{"object":"response.input_tokens","input_tokens":11}
[200]
  1. Send the request
curl -s -w '\n[%{http_code}]\n' http://localhost:$PORT/v1/messages/count_tokens -H "Authorization: Bearer $LITELLM_MASTER_KEY" -H 'Content-Type: application/json' -d '{"model":"claude-sonnet-4-5-vertex","messages":[{"role":"user","content":"Return exactly OK."}]}'
  1. Observe
{"input_tokens":11}
[200]
  1. Send the request
curl -s -w '\n[%{http_code}]\n' http://localhost:$PORT/v1/messages/count_tokens -H "Authorization: Bearer $LITELLM_MASTER_KEY" -H 'Content-Type: application/json' -d '{"model":"deepseek-r1","messages":[{"role":"user","content":"Return exactly OK."}]}'
  1. Observe
{"type":"error","error":{"type":"invalid_request_error","message":"The provided model doesn't support counting tokens."}}
[400]
  1. Send the request
curl -s -w '\n[%{http_code}]\n' http://localhost:$PORT/v1/messages -H "Authorization: Bearer $LITELLM_MASTER_KEY" -H 'Content-Type: application/json' -d '{"model":"vertex-glm-5.2","max_tokens":256,"messages":[{"role":"user","content":"Return exactly OK."}]}'
  1. Observe
{"id":"1856c26f-f7e8-426a-9bf4-e9c0fd5f415c","type":"message","role":"assistant","model":"vertex-glm-5.2","stop_sequence":null,"usage":{"input_tokens":16,"output_tokens":108},"content":[{"type":"thinking","thinking":"1.  **Analyze the Request:** The user wants me to return exactly \"OK\".\n2.  **Constraint Checklist & Confidence Score:**\n    *   Return exactly OK? Yes.\n    *   Confidence Score: 5/5.\n3.  **Formulate Response:** \"OK\" (without quotes, exactly the string requested).\n4.  **Review against constraints:** The response must be *exactly* OK. No other words, no punctuation unless specified (none specified, just the letters OK).","signature":null},{"type":"text","text":"OK"}],"stop_reason":"end_turn","stop_details":null}
[200]

Customer's six shapes, count vs inference

  1. For each of the six shapes, build the body with the customer's request builder, send it to /v1/messages/count_tokens, then send it with "max_tokens": 256 to /v1/messages and compare input_tokens (builder and runner): PORT=$PORT ./run_cases.sh vertex-glm-5.2 claude-sonnet-4-5-vertex
vertex-glm-5.2             baseline                 inf=1102 count=None diff=- FAIL count 400: {"type": "error", "error": {"type": "invalid_request_error", "message": "LiteLLM does not support counting tokens for Vertex AI model zai-org/glm-5.2-maas."}}
vertex-glm-5.2             large_system             inf=2101 count=None diff=- FAIL count 400: {"type": "error", "error": {"type": "invalid_request_error", "message": "LiteLLM does not support counting tokens for Vertex AI model zai-org/glm-5.2-maas."}}
vertex-glm-5.2             large_tool               inf=2223 count=None diff=- FAIL count 400: {"type": "error", "error": {"type": "invalid_request_error", "message": "LiteLLM does not support counting tokens for Vertex AI model zai-org/glm-5.2-maas."}}
vertex-glm-5.2             large_system_and_tool    inf=3223 count=None diff=- FAIL count 400: {"type": "error", "error": {"type": "invalid_request_error", "message": "LiteLLM does not support counting tokens for Vertex AI model zai-org/glm-5.2-maas."}}
vertex-glm-5.2             pdf_base64_1_page        inf=139 count=None diff=- FAIL count 400: {"type": "error", "error": {"type": "invalid_request_error", "message": "LiteLLM does not support counting tokens for Vertex AI model zai-org/glm-5.2-maas."}}
vertex-glm-5.2             pdf_base64_12_pages      inf=400 count=None diff=- FAIL count 400: {"type": "error", "error": {"type": "invalid_request_error", "message": "LiteLLM does not support counting tokens for Vertex AI model zai-org/glm-5.2-maas."}}
claude-sonnet-4-5-vertex   baseline                 inf=1105 count=1105 diff=+0.00 PASS
claude-sonnet-4-5-vertex   large_system             inf=2109 count=2109 diff=+0.00 PASS
claude-sonnet-4-5-vertex   large_tool               inf=2639 count=2639 diff=+0.00 PASS
claude-sonnet-4-5-vertex   large_system_and_tool    inf=3635 count=3635 diff=+0.00 PASS
claude-sonnet-4-5-vertex   pdf_base64_1_page        inf=2688 count=2688 diff=+0.00 PASS
claude-sonnet-4-5-vertex   pdf_base64_12_pages      inf=30738 count=30738 diff=+0.00 PASS

Customer's test_count_tokens.py

  1. Run the customer's own test_count_tokens.py from the ticket, unchanged, with a stand-in for its unshared base_integration_test harness that lists models from /model/info and posts with the master key (stand-in): LITELLM_BASE_URL=http://127.0.0.1:$PORT pytest test_count_tokens.py -k test_count_tokens_matches_inference --models 'vertex-glm-5.2*' --models claude-sonnet-4-5-vertex -s
model | case | status | count_tokens | inference | diff% | error
claude-sonnet-4-5-vertex | baseline | pass | 1103 | 1103 | 0.0 | 
claude-sonnet-4-5-vertex | large_system | pass | 2106 | 2106 | 0.0 | 
claude-sonnet-4-5-vertex | large_tool | pass | 2635 | 2635 | 0.0 | 
claude-sonnet-4-5-vertex | large_system_and_tool | pass | 3632 | 3632 | 0.0 | 
claude-sonnet-4-5-vertex | pdf_base64_1_page | pass | 2687 | 2687 | 0.0 | 
claude-sonnet-4-5-vertex | pdf_base64_12_pages | pass | 30739 | 30739 | 0.0 | 
vertex-glm-5.2 | baseline | fail | None | 1103 | None | 400 count_tokens: LiteLLM does not support counting tokens for Vertex AI model zai-org/glm-5.2-maas.
vertex-glm-5.2 | large_system | fail | None | 2104 | None | 400 count_tokens: LiteLLM does not support counting tokens for Vertex AI model zai-org/glm-5.2-maas.
vertex-glm-5.2 | large_tool | fail | None | 2222 | None | 400 count_tokens: LiteLLM does not support counting tokens for Vertex AI model zai-org/glm-5.2-maas.
vertex-glm-5.2 | large_system_and_tool | fail | None | 3224 | None | 400 count_tokens: LiteLLM does not support counting tokens for Vertex AI model zai-org/glm-5.2-maas.
vertex-glm-5.2 | pdf_base64_1_page | fail | None | 136 | None | 400 count_tokens: LiteLLM does not support counting tokens for Vertex AI model zai-org/glm-5.2-maas.
vertex-glm-5.2 | pdf_base64_12_pages | fail | None | 402 | None | 400 count_tokens: LiteLLM does not support counting tokens for Vertex AI model zai-org/glm-5.2-maas.
vertex-glm-5.2-own-tokenizer | baseline | pass | 1101 | 1103 | 0.18165304268846502 | 
vertex-glm-5.2-own-tokenizer | large_system | pass | 2101 | 2103 | 0.09519276534983341 | 
vertex-glm-5.2-own-tokenizer | large_tool | pass | 2124 | 2224 | 4.708097928436912 | 
vertex-glm-5.2-own-tokenizer | large_system_and_tool | pass | 3125 | 3225 | 3.2 | 
vertex-glm-5.2-own-tokenizer | pdf_base64_1_page | fail | 2544 | 137 | -94.61477987421384 | 
vertex-glm-5.2-own-tokenizer | pdf_base64_12_pages | fail | 29308 | 402 | -98.62836085710386 | 
18 passed, 3 skipped, 9 deselected in 29.11s
Pre-existing bugs seen during QA, follow-ups filed
  • /v1/responses/input_tokens answers 200 for some bodies OpenAI rejects
  • Contents-only /utils/token_counter bodies answer 500 on non-Gemini models

/live-pr-risk (1288a94)

Breaking, backward incompatible, regression risk, dependency graph, not verified

Each leg ran one proxy (2 workers) on the same config with a recording proxy in front of real Vertex AI, Gemini, OpenAI, Bedrock and Hugging Face, and the same 40 calls in the same order. Legs were aa32e4c (base), 1288a94 (head) and 1288a94 merged with main 355dea2. The merged tree matched the head on all 40 calls (status, body keys, error type, header keys and recorded upstream calls)

Breaking

None observed. Every call outside the changed contracts answered the same status, body keys and upstream calls on both legs. That covers chat completions (streaming and not), /v1/messages on Vertex Claude and Vertex Mistral, OpenAI and Vertex Claude counts on all four count routes, Bedrock Messages count, missing and unknown models, and unauthenticated counts

Backward incompatible

The ticket approved both changes. It asks to "Decide between a validated framing/fallback (via the fallback ticket) or an explicit error" and to "confirm it matches OpenAI's {"error":{"message","type","param","code"}}" for /v1/responses/input_tokens

  • Vertex partner models without a count route now answer 400 with no Vertex call. GLM and gpt-oss answered 500 before, and Mistral answered 404 after a Vertex call. This holds on Messages count, Responses input_tokens and both of its aliases, /utils/token_counter?call_endpoint=true, and Google countTokens and its alias
  • Responses count errors keep their status. type: token_counting_error becomes the OpenAI type, param: model becomes the provider's value or null, the stringified status in code becomes the provider's code or null, and the message is unwrapped. Observed for an OpenAI nameless tool, a Vertex Claude tool error, Bedrock DeepSeek R1 and a Gemini 404
  • GLM with custom_tokenizer went from 500 to a local count (200) on all four routes, including prompt-only and 5 KB utils bodies. Contents-only and empty-messages utils bodies went from 500 to 400

Regression risk

A custom_tokenizer that cannot load (a repo the hub answers 401 for) answers 500 on Messages count and 503 no_db_connection on utils. The base answered 500 for the same deployment, so a bad tokenizer setting was already an error. The misleading 503 is the existing utils mapping tracked in LIT-8415

Dependency graph

Dependent Reaches State
/v1/messages/count_tokens partner gate verified live
/v1/responses/input_tokens + 2 aliases gate, error body verified live
/utils/token_counter gate verified live
Google countTokens + alias gate verified live
SDK litellm.acount_tokens gate verified live
VertexAIPartnerModelsTokenCounter publisher table tested
openai_error_type callers (9 routes) extracted helper tested
chat, Messages, Responses inference none verified live

The SDK check called acount_tokens for GLM and Mistral on both legs. Both legs returned the same local count of 11. The base also sent a Mistral count call that Vertex answered 404, and the head sent no call

Integration suites run at d50daf4, the last tip before the two error-body commits: providers 682 passed and sdk 2 passed. The /audit control lane reran every count file at 1288a94

Not verified

  • The real Vertex Meta Llama count route. The QA project has no Meta access, the route is unchanged from main, and a scripted cell covers its wiring
  • Codestral, which takes the same publisher-table miss as Mistral
  • disable_token_counter on a partner model without a count route
  • Spend and key rows, which count routes never write

/audit (4115e57)

Base fails 10 of 11 cells, head passes all 11 twice, 285 controls pass and 3 are skipped as known bugs (matrix)

Contracts, base and head

Rig lit9564, base aa32e4c, head 4115e57, group providers, 4 workers, seed 9564, order seed 46990. Nothing inside the proxy is mocked, and only the upstream is scripted

Contract Base Head
GLM count, 4 routes 500 400, no Vertex call
Mistral count 200 via peer 400, no Vertex call
Llama count (control) meta route meta route
GLM custom_tokenizer, 4 routes 500 local count
custom_tokenizer, contents-only utils 500 400
Vertex Claude 400, Responses count proxy shape OpenAI shape
Anthropic 404, Responses count proxy shape 404, OpenAI shape
OpenAI error, Responses count proxy shape passed through

Node ids: tests/integration/providers/test_vertex_partner_count_tokens_wire.py::test_partner_without_a_count_route_answers_400_without_calling_vertex[glm-messages,glm-responses,glm-google,glm-utils,mistral-messages], ::test_llama_count_still_reaches_the_meta_count_route, ::test_custom_tokenizer_partner_counts_locally_on_every_count_route, ::test_responses_input_tokens_surfaces_the_peer_error, ::test_responses_input_tokens_types_a_peer_error_by_its_status, tests/integration/providers/test_openai_count_tokens_tools_wire.py::test_responses_input_tokens_passes_an_openai_count_error_through[full,bare]

Type

🐛 Bug Fix

Caveats (if any)

Medium

  • OpenAI Responses count errors can name the wrong input index, since system and developer items move into instructions first (pre-existing, follow-up filed)
  • On purpose, count errors change shape as the breaking change note says (Mistral answered 404, the rest 500)
  • Vertex Meta Llama's count route is unverified, for lack of Meta access (unchanged from main)
  • 5xx count errors say internal_server_error, not OpenAI's server_error (follow-up filed)

Low

  • Workload identity count failures keep the OpenAI SDK's Error code: 401 text (follow-up filed)
  • The route copies the global handler's call-id and span steps
  • /utils/token_counter keeps token_counting_error
  • Messages count keeps Gemini's prefixed raw JSON (follow-up filed)
  • The docs still describe a local fallback (follow-up filed)
  • The call-id test sets a header real count errors never carry
  • Rebasing feat(count_tokens)!: configurable token_count_framing and token_count_model, count source in the response #46777 must keep this 400 eligible for its fallback
  • The trace-span close is untested

Final Attestation

  • The tests check the right things, including the edge cases, and regressions in the respective real-world customer use-cases are not possible after this PR
Bugbot summary

[!NOTE]
Medium Risk
Intentional breaking change to Responses count error shape and HTTP status for several Vertex partner models; touches proxy error handling and token-count routing across multiple count endpoints.

Overview
Breaking: /v1/responses/input_tokens provider count failures no longer use type: token_counting_error with JSON stuffed in message; they return OpenAI-style error objects. Vertex partner models that previously 500/404 on count now return 400 with a clear unsupported-model message.

Vertex partner token counting now gates on a shared count_tokens_publisher map (Anthropic Claude and Meta Llama only). Partners without a publisher count route (e.g. GLM, Mistral, gpt-oss) answer 400 naming the model and do not call Vertex, instead of raising “Unknown partner model” (500) or upstream 404. Deployments with model_info.custom_tokenizer still count locally when the request has a messages-style body; contents-only counts keep the 400.

/v1/responses/input_tokens catches ProxyException with type: token_counting_error, unwraps nested provider errors (OpenAI passthrough, Anthropic/Google/Bedrock/plain text), maps other failures to invalid_request_error / internal_server_error via openai_error_type_for_status, and optionally adds litellm_call_id while closing the OTel server span like the global handler.

Reviewed by Cursor Bugbot for commit 2bed82a. Bugbot is set up for automated code reviews on this repo. Configure here.

…nt API and OpenAI-shaped provider errors on /v1/responses/input_tokens
…input_tokens error tests

Vertex has no count-tokens route for Mistral or codestral models, so they now
get the same 400 as other partner models without a count API instead of a 404
that points operators at IAM.
…vertex_partner_and_responses_errors

# Conflicts:
#	litellm/proxy/response_api_endpoints/endpoints.py
…ustom_tokenizer and unwrap prefixed flat provider errors
# Conflicts:
#	litellm/proxy/response_api_endpoints/endpoints.py
@devin-ai-integration

devin-ai-integration Bot commented Oct 17, 2026 •

Copy link
Copy Markdown
Contributor

I'll fix CI failures and address comments from users with write access. I'll skip comments containing "(aside)".

  • Disable automatic comment, CI, and merge conflict monitoring

@mateo-berri

Copy link
Copy Markdown
Contributor Author

@litellm-stampbot

@kerry-berri

kerry-berri commented Oct 17, 2026 •

Copy link
Copy Markdown
Contributor

litellm-stampbot: risk low

Approved at 0494425.

Rules (stampbot/risk_rules.yml):

  • low: no rule flagged it

Cursor Bugbot: Low Risk at 0494425. Test-only changes with no production code in this diff; risk is limited to CI failing until matching fixes are merged. Bugbot run requested, finished in 6 min.
Bugbot Low is low, Medium and High are high. The judge model was not called.

Pushes do not re-run this check. Comment @litellm-stampbot again to re-check the new head.

@kerry-berri

Copy link
Copy Markdown
Contributor

bugbot run

@cursor cursor Bot left a comment •

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Stale Bugbot comment from a previous run.

@kerry-berri kerry-berri added the risk:low Small, isolated, low-risk change label Oct 17, 2026

@kerry-berri kerry-berri left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Low risk by rule and by judgement at 0494425

@codecov

codecov Bot commented Oct 17, 2026

Copy link
Copy Markdown

Codecov Report

✅ All modified and coverable lines are covered by tests.

📢 Thoughts on this report? Let us know!

@mateo-berri

Copy link
Copy Markdown
Contributor Author

@litereview code-review

@codspeed

codspeed Bot commented Oct 17, 2026

Copy link
Copy Markdown
Contributor

Merging this PR will not alter performance

⚠️ 1 benchmark spent significant time in system calls

System calls cannot be consistently instrumented, so they are not included in the measure, which understates the real cost. Please switch to the Walltime instrument to accurately measure system calls.

Measurement and system calls

✅ 32 untouched benchmarks


Comparing litellm_count_tokens_partner_400_and_responses_error_shape (2bed82a) with main (1552b5b)

Open in CodSpeed

@litereview

litereview Bot commented Oct 17, 2026

Copy link
Copy Markdown

✅ code-review

5/5 · Ready for human review

Scope: full · Full PR review.

No correctness findings.

Checks and execution details
  • Passed · Real testing evidence (required): Scope: two scoped files change count-tokens translation. litellm/llms/vertex_ai/common_utils.py adds a pre-dispatch 400 for Vertex partner models that have no count route, plus the custom_tokenizer fallthrough. vertex_ai_partner_models/count_tokens/handler.py drops Mistral from the publisher table.

Automated evidence (run here): I ran tests/integration/run.py providers --workers 2 on test_vertex_partner_count_tokens_wire.py and test_openai_count_tokens_tools_wire.py, with a local Postgres and Redis. Result: 61 passed in 105.76s, no skips. These tests drive the real proxy over TCP with a scripted Vertex peer. They cover four paths:

  • GLM on /v1/messages/count_tokens, /v1/responses/input_tokens, Google countTokens and /utils/token_counter, plus Mistral on Messages. Each asserts the 400 body shape and wire.drain() == (), so no upstream call happens.
  • Llama still reaching publishers/meta/models/count-tokens:rawPredict.
  • A GLM deployment with a custom_tokenizer (served by a local HF hub stub). It counts locally with 200 on all four routes, and a contents-only body still gets the 400.
  • Responses passthrough of OpenAI- and Anthropic-shaped peer errors, including status-derived type on a 404.

The gate is local, so the scripted peer only shows the absence of calls. No fixture provenance is needed for that.

Manual E2E: the PR description has before/after curl transcripts against real Vertex, OpenAI, Gemini and Bedrock on commit 1288a9464e. They show a GLM 500 becoming a 400 and a Mistral count-tokens:rawPredict 404 becoming a 400. The Mistral removal therefore rests on a real upstream observation.

  • Passed · Compatibility requirements (required): A real break exists:

  • /v1/responses/input_tokens provider errors used to answer type: token_counting_error, param: model, code: "&lt;status>". They now answer the provider's OpenAI type/param/code, or a status-derived type with null param/code.

  • Vertex partner models without a count route used to answer 500 or 404 on the count routes. They now answer 400 before any upstream call.

The title carries fix(count_tokens)!:. The description's first line explains the impact and migration: clients should match the OpenAI type, and the status is now 400.

  • Passed · Changed behavior and result consistency (required): Standards read: root AGENTS.md/CONTRIBUTING.md, tests/AGENTS.md, tests/integration/AGENTS.md.

Path traced: count_request_tokens → _get_provider_token_counter → _try_provider_token_count. A result with error=True raises ProxyException(type=token_counting_error, code=400). A None result falls through to select_tokenizer with model_info.custom_tokenizer. responses_input_tokens catches only token_counting_error, so token_counting_disabled and other errors still reach the global handler.

Boundary cases checked by reading the code:

  • A plain-text GLM message with no { passes through as is.
  • An Anthropic envelope has a top-level type, which fails the extra=forbid model, so the code takes the nested message.
  • A Gemini error has no type, so the code falls back to the nested message and a status-derived type.
  • An empty messages list with custom_tokenizer keeps the 400.
  • Claude and Llama deployments keep the Vertex route.

The integration run above covers these. Unit run of the three changed unit files: 344 passed and 7 failed. The 7 failures came from an ungenerated Prisma client (cannot import name 'Json' from 'prisma') in billing tests that this change doesn't touch. After prisma generate, the integration suite passed.


View review · Reviewed 2bed82a57d4e

@mateo-berri

Copy link
Copy Markdown
Contributor Author

@greptileai

@greptile-apps

greptile-apps Bot commented Oct 17, 2026 •

Copy link
Copy Markdown
Contributor

RetriggerView in GreptileConfidence Score: 5/5

[Medium impact] The PR appears safe to merge with the stated breaking changes

Summary

Vertex partner models without a supported count route now return 400. Deployments with a custom_tokenizer can count message requests locally. /v1/responses/input_tokens now unwraps provider errors and returns the four OpenAI error fields

Added tests cover unsupported partners, unchanged Meta routing, custom tokenizers across count routes, and provider error bodies. No actionable new issue was established

Acknowledgments supplied by mateo-berri

  • Vertex partner counts now reject models without a supported count route.
  • Responses count errors now use OpenAI error fields.

Reviews (1) · Last reviewed commit: "Merge #46990's fix commits into the stam..." · Reviewed by Greptile

@mateo-berri

Copy link
Copy Markdown
Contributor Author

bugbot run

@cursor cursor Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

✅ Bugbot reviewed your changes and found no new issues!

Comment @cursor review or bugbot run to trigger another review on this PR

Reviewed by Cursor Bugbot for commit 2bed82a. Configure here.

@mateo-berri
mateo-berri merged commit ef1d395 into main Oct 17, 2026
92 of 93 checks passed
@mateo-berri
mateo-berri deleted the litellm_count_tokens_partner_400_and_responses_error_shape branch October 17, 2026 21:15
yuneng-berri added a commit that referenced this pull request Oct 18, 2026
…46839, #46843, #46583, #47057, #47064, #47163, #46777) (#47209)

* fix(proxy)!: count prompt-only token_counter requests with the provider when call_endpoint is set (#46839)

* fix(proxy): count prompt-only token_counter requests with the provider when call_endpoint is set

* fix(proxy): keep the local count for a prompt-only token_counter request when the provider count fails

* fix(proxy): log a prompt-only token count fallback as a one-line warning

* fix(proxy): send a prompt-only token_counter request to the provider only on Gemini and Vertex AI

* fix(proxy): count a token_counter prompt sent next to an empty messages or contents list

* fix(proxy): count a prompt next to messages on the local token count instead of answering 500

* fix(proxy): answer 400 for a token count prompt next to a conversation unless drop_params is set

With drop_params the conversation is counted without the prompt. On the local count, a prompt sent with system or tools is counted as a user message with them, like the messages form.

* test(proxy): count tools with a prompt in the token counter fallback test

* test(proxy): cover prompt counting on /utils/token_counter in the Gemini count wire tests

* test(proxy): name the token counter fallback test by what it checks

(cherry picked from commit 2dc6aaf)

* fix(count_tokens): apply context_management edits in the Gemini /v1/messages/count_tokens count (#46843)

* fix(count_tokens): apply context_management edits in the Gemini /v1/messages/count_tokens count

/v1/messages runs clear_tool_uses context edits before it sends an Anthropic
body to a Gemini or Vertex AI deployment, but /v1/messages/count_tokens counted
the body unedited, so a request with older tool results cleared counted about
2.8x what inference bills.

The count now runs the same history and context-edit step inference runs,
honors additional_drop_params on the deployment, and skips compact edits so a
count never makes a paid summary call.

* fix(count_tokens): match the Gemini count to inference for compact edits and drop opt-outs

Run compact edits in the count without the summary call so trigger checks and
history slicing match /v1/messages, honor a request-level additional_drop_params,
keep the full body when any deployment in the model group drops context_management,
and answer 400 naming a block Gemini cannot count when an edit trigger fails on it

* fix(count_tokens): count the unedited body when an edit fails and honor deployment ids in the drop check

* fix(count_tokens): log a failed edit in the count at debug, since the send already logs it

* fix(count_tokens): resolve a deployment id before wildcard routes in the drop check, as the router does

* fix(count_tokens): honor the router-wide additional_drop_params opt-out in the drop check

The router merges default_litellm_params between the deployment and the request, so a router-wide context_management opt-out makes /v1/messages send the full history. The count now reads it in the same order. Adds the audit's wire tests for the count's context edits.

* fix(count_tokens): read the opt-out of a deployment the router serves by its litellm model name

* fix(count_tokens): read the opt-out and drop_params from the deployments the router and completion_model send to

* fix(messages): drop an invalid context_management spec under drop_params so the send matches the count

* fix(count_tokens): give Claude Code and Codex counts the drop_params default /v1/messages gives them

The proxy turns on drop_params for Claude Code and Codex user agents on /v1/messages. The count now applies the same default, so an invalid context_management spec drops on both endpoints instead of the count answering 400 while the send answers 200. The wire test also covers default_fallbacks, model_group_alias, and completion_model routes.

* test(count_tokens): cover a coding agent that turns drop_params off and stop two count tests running as Claude Code

(cherry picked from commit f8217d2)

* fix(proxy)!: answer 400 for malformed tools on count_tokens instead of crashing (#46583)

* fix(proxy): answer 400 for malformed tools on count_tokens instead of crashing

A non-list tools value crashed the vector store lookup during auth and the
built-in tool cost lookup in the failure logging path, so the proxy answered
an unhandled 500 and closed the keep-alive connection. count_tokens now
answers a 400 invalid_request_error for a malformed body, drops malformed
tools when drop_params is on, and both lookups skip values of the wrong shape.

* fix(proxy): skip non-list tools in the tool allowlist check

Also validate the count_tokens body without recursion, which the recursion detector rejects.

* test(integration): restore the int tools case on count_tokens

The proxy now answers a non-list tools value with a 400, so the case is deterministic again.

* fix(proxy): reject malformed tools at the LLM route entry and keep vector store checks on malformed ids

* fix(proxy): apply drop_params like core when dropping malformed tools, and reject malformed tool vector store ids

Check tools after request setup so the Claude Code default and the logged call type apply, read the request,
global, and model group drop_params the way core does, drop tool_choice and friends with tools, cover Gemini
generateContent, and answer 400 for a malformed tools[].vector_store_ids with the strict flag off

* fix(proxy): keep the request's call type when logging a gate rejection after request setup

The body-shape fallback relabeled a /v1/messages rejection as acompletion and a list-input /v1/responses
rejection as aembedding, so it now only applies when the logging object carries no known call type

* fix(proxy): share the malformed tools check across tool routes and honor drop_params per entry

* fix(proxy): accept null vector_store_ids, read every named store id in auth, check the responses websocket

* refactor(proxy): leave the responses websocket out of the request-level tool check

* fix(proxy): let a request's additional_drop_params replace the deployment list and keep compact's call type on rejections

* fix(proxy): read router default drop lists and deployment ids in the malformed tools check

* fix(proxy): leave malformed tools to the router when it can pick another deployment

Fallbacks, auto-routers, model strings, comma batches and team model names
let the router pick a deployment after the proxy checks the request, so the
proxy now forwards a malformed tools field there as main does, and only
rejects it when the deployment it checks is the one that serves. Token
counting never reroutes, so count_tokens and input_tokens keep reading the
group they count with. additional_drop_params names are read the way core
reads them, so a list with a non-string entry still names its strings.

* test(integration): cover malformed tools on reroutable models, router defaults and deployment ids

* fix(proxy): resolve malformed tools at the deployment the router picks

* fix(proxy): keep provider-repaired tool schemas, honor fallback_on_unsupported_params, skip cooldown on malformed tools

Empty schemas and JSON-string schemas pass the tools check the way litellm's provider paths already read them. The rejection is a BadRequestError subclass carrying the deployment's provider, so fallback_on_unsupported_params: false keeps the 400, and the router never cools a deployment down for a request litellm rejected before calling it. Adds the audit's pre_call guardrail and cross-provider bridge cells.

* test(integration): expect a 400 for an empty-string tools field on /v1/messages

Real Anthropic rejects tools "" with a 400 on main too, so the case joins the malformed tools test

* fix(router): keep web search routing for tools passed as a tuple

* fix(router): keep a deployment's own tools when drop_params drops a malformed request tools

* test(router): list _merged_tools as covered through the deployment tools merge tests

* fix(router): drop the request's tool settings with its malformed tools when deployment tools replace them

* fix(router): skip a tool whose type is not a string in the web search filter instead of raising TypeError

* fix(prometheus): keep deployment health metrics clean on a malformed tools rejection

* test: type the new malformed tools tests

* test: mark new test locals Final and type kwargs dicts

(cherry picked from commit d76ec3a)

* ci(cost map): classify token_count_model as an object key in the schema generator (#47057)

* ci(cost map): classify token_count_model as an object key in the schema generator

* ci(cost map): require non-blank token_count_model strings and test the region rules

(cherry picked from commit 6e191a5)

* ci(cost map): remove the generated model prices JSON schema (#47064)

* ci(cost map): remove the generated model prices JSON schema

Co-Authored-By: Devin AI <158243242+devin-ai-integration[bot]@users.noreply.github.com>

* test(cost map): keep schema-independent cost map tests after dropping the schema

Co-Authored-By: Devin AI <158243242+devin-ai-integration[bot]@users.noreply.github.com>

* ci(cost map): keep the schema file until main's guard stops requiring it

Co-Authored-By: Devin AI <158243242+devin-ai-integration[bot]@users.noreply.github.com>

* ci(cost map): let bot sync PRs keep touching the schema file until it is deleted

Co-Authored-By: Devin AI <158243242+devin-ai-integration[bot]@users.noreply.github.com>

---------

Co-authored-by: Devin AI <158243242+devin-ai-integration[bot]@users.noreply.github.com>
(cherry picked from commit ae6f7f6)

* fix(count_tokens)!: answer 400 for Vertex partner models without a count API and OpenAI-shaped provider errors on /v1/responses/input_tokens (#47163)

* fix(count_tokens): answer 400 for Vertex partner models without a count API and OpenAI-shaped provider errors on /v1/responses/input_tokens

* fix(count_tokens): answer 400 for Vertex Mistral counts and type the input_tokens error tests

Vertex has no count-tokens route for Mistral or codestral models, so they now
get the same 400 as other partner models without a count API instead of a 404
that points operators at IAM.

* fix(count_tokens): unwrap prefixed provider errors on /v1/responses/input_tokens

* fix(count_tokens): say LiteLLM, not Vertex, cannot count a Vertex partner model

* fix(count_tokens): count a Vertex partner model with its configured custom_tokenizer and unwrap prefixed flat provider errors

* fix(count_tokens): keep the 400 for contents-only Vertex partner counts with a custom_tokenizer

* fix(count_tokens): pass through an OpenAI provider error that omits param or code

* fix(count_tokens): keep the status-based type for Anthropic count errors on the Responses route

* test(count_tokens): cover the Vertex partner count gate and Responses count error shapes on a real proxy

* test(count_tokens): add regression tests for the Vertex partner count gate and Responses count error shapes

(cherry picked from commit ef1d395)

* feat(count_tokens)!: configurable token_count_framing and token_count_model, count source in the response (#46777)

* feat(count_tokens): configurable token_count_framing and token_count_fallback_model, count source in the response

Count endpoints now say where each number came from in litellm_count_source
(provider, fallback_model, local_estimate) and name the fallback model in
litellm_count_fallback_model. When the provider answers 400 or 404 for a model
it cannot count, the proxy counts the same request with token_count_fallback_model.
token_count_framing adds a per-model constant to local estimates. Both settings
ship in the cost map for Bedrock Claude Sonnet/Haiku 5.5, Bedrock Kimi K3, and
Databricks Kimi K3 and DeepSeek V4 Flash, and can be overridden in model_info.

* test(count_tokens): classify the new cost map keys in the schema generator and expect count_source in exact-shape tests

* test(count_tokens): e2e matrix against real inference and integration wire tests for count source, fallback and framing

* fix(count_tokens): keep the provider error when local counting is disabled, name the fallback error, keep settings in cooldown

Moves the cost map lookup off the event loop

* ci(cost map): bound token_count_framing to non-negative and token_count_fallback_model to non-empty

* fix(count_tokens): keep a failed fallback's own status, ship fallbacks only where they count, add system.ai framing

A fallback model that answers 404 returns the requested model's error unchanged, and any other fallback
failure answers with its own status and message. The eu, apac, au and jp Sonnet and Haiku 5.5 entries
no longer ship the Opus 5.5 fallback, which AWS serves only in us-east-1. A configured empty
token_count_fallback_model turns the shipped fallback off. Config framing accepts whole-number floats and
rejects negatives. The Databricks system.ai Kimi K3 and DeepSeek V4 Flash names carry the same framing as
their serving endpoint names, and the e2e matrix runs on Bedrock Haiku 5.5 too.

* test(databricks): list the system.ai Kimi K3 and DeepSeek V4 Flash names with their published DBU rates

* fix(count_tokens): skip a token count fallback model for an hour after it answers 404 on that deployment

A us. or global. Sonnet 5.5 deployment outside us-east-1 paid two extra Bedrock
calls and about 200 ms on every count, since Opus 5.5 cannot count there either.
The Kimi K3 e2e also runs the large system prompt shape now.

* test(count_tokens): use the shared integration port allocator in the fallback wire test

* fix(cost map): keep the Databricks system.ai entries to framing only, so their spend stays as today

* test(count_tokens): cover the fallback 404 skip, inference profile base_model, shipped framing, and deployment-scoped token count settings

Adds integration cells for a fallback model that answers 404, an application inference profile ARN deployment whose base_model carries the shipped fallback, and the shipped Kimi K3 framing with token_count_framing 0 turning it off. Adds unit tests that keep token count settings off the shared backend cost map key and that store a token count setting on PATCH only when the operator changed it

* fix(count_tokens): keep the counter's own 400 and the provider's error when a framed estimate cannot read the body

A 400 the OpenAI or Gemini counter returns before calling the provider is the caller's answer, so it no longer tries the fallback model or a framed estimate. When the framed local estimate cannot read a content block, the client gets the provider's error instead of a 500. Adds /audit round 2's integration tests for the fallback leg's converted body, the Anthropic envelope on fallback failures, and both framing cases.

* fix(count_tokens): answer the provider's error whenever a framed estimate raises

A tool schema the local estimate cannot format, such as a boolean subschema or an array with no items, raised AttributeError or KeyError and answered a 500 on a framed deployment whose provider had already answered 400. Any estimate failure now answers the provider's own error.

* fix(count_tokens): load the custom tokenizer inside the guarded framed estimate

A framed deployment whose custom_tokenizer could not load answered a 500 or 503 where the provider had already answered 400, because the tokenizer was selected outside the estimate's error handling. Selecting it inside answers the provider's error, logs a warning with the estimate's error, and still raises the Rust extension's fork-guard errors.

* fix(count_tokens): look up framing under the deployment's custom_llm_provider

* fix(count_tokens): share one tokenizer download per worker and bound the wait after a provider error

A framed deployment whose custom_tokenizer is not cached locally made every
count wait out the Hugging Face hub's whole retry cycle when the hub could not
be reached, and a burst of those loads held the default thread limiter that
every count's cost map lookup also needs. Counts on a worker now share one
download per minute, a failed download is reused for the rest of that minute,
and after a provider error a count waits at most 5 s before answering the
provider's error. The swallowed-estimate warning logs only the error type.

* fix(count_tokens): keep one tokenizer download per key running and load the local route per request

* test(count_tokens): type the scripted counter and wait on events instead of wall time where possible

* fix(count_tokens): run framed tokenizer loads on their own capped threads and answer a tokenizer panic with the provider error

Framed loads used anyio's default 40 threads, so a hub that drops packets let about 40 hanging loads stall every count on the worker. Loads now run on a per-worker pool of 4, and a count that finds 4 loads running answers the provider's error at once. Any finished load is reused for a minute after it finishes, so a load that fell back to tiktoken is not retried on every count. A pyo3 PanicException from the tokenizer, while loading or counting, now answers the provider's error instead of a plain 500

* feat(proxy): count tokens with token_count_model in its pinned region

token_count_model {model, region} replaces token_count_fallback_model. Bedrock Sonnet and Haiku 5.5 count with Opus 5.5 in us-east-1, or Melbourne for au. profiles, and a failure names the region to enable

* fix(count_tokens): use the renamed count model constant in the e2e test and list token_count_model with the object keys

* fix(proxy): keep the upstream error envelope when adding the region hint

* test(proxy): annotate the token count setting echo test

* ci(cost map): require non-blank token_count_model strings and test the region rules

* fix(count_tokens): answer the token_count_model's error even when framing is set

* fix(count_tokens): keep the provider error for Google contents instead of a framed estimate

* fix(count_tokens): estimate Google contents the route translated to messages

* fix(count_tokens): keep the provider error for Google contents with non-text parts

* test(proxy): drive tokenizer wait and cost map tests by events and a skippable loop clock

* fix(count_tokens): check Google text-only parts without a KeysView comparison basedpyright flags

* feat(proxy): count Bedrock Kimi K3 tokens exactly with its pinned tokenizer

* test(bedrock): keep the Kimi K3 image check in-process

* fix(count_tokens): join the region hint to an upstream message that already ends with a period

Also pins that a blank token_count_model in config falls through to the cost map default

* fix(count_tokens): count Gemini tool-call turns and Responses tools, and stop tokenizer retries from stalling counts

The Google countTokens route estimates contents with functionCall, functionResponse and thoughtSignature parts again, and still answers the provider error for media, thought and unknown parts

The Kimi K3 exact count renders Responses API and Anthropic tools through the chat tool translation the Vertex count already used, now shared from the prompt factory, and falls back to the estimate when the Converse body cannot carry a tool

A failed Kimi K3 tokenizer load is retried in the background without making counts wait, and a load still running after the wait logs a warning

* fix(count_tokens): count Kimi K3 tools the way Bedrock inference sends them

A flat Responses API function or custom tool becomes the chat tool the
Responses route sends to inference, and every other tool goes to the
Converse body as is, so hosted tools Bedrock drops are left out of the
count instead of being counted or turning it into an estimate.

* test(count_tokens): annotate new token counter test locals with Final

* fix(count_tokens): keep shipped count regions inside the deployment's geography

A plain Bedrock Sonnet or Haiku 5.5 deployment in a non-US region no longer sends its count prompt to us-east-1. Global count models and configured token_count_model keep their pinned region. Also expect litellm_count_source in the Vertex Llama count test main added

* fix(count_tokens): resolve count settings off the event loop

(cherry picked from commit 75faaea)

---------

Co-authored-by: Mateo Wang <277851410+mateo-berri@users.noreply.github.com>
Co-authored-by: Devin AI <158243242+devin-ai-integration[bot]@users.noreply.github.com>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

risk:low Small, isolated, low-risk change

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants