Skip to content

chore(typing): clear 670 basedpyright Any errors by validating provider payloads at the boundary - #45388

Merged
mateo-berri merged 9 commits into
mainfrom
litellm_decrease_anys_opus55_1008
Oct 13, 2026
Merged

mateo-berri merged 9 commits into
mainfrom
litellm_decrease_anys_opus55_1008

Conversation

@mateo-berri

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

Copy link
Copy Markdown
Contributor

TLDR

Problem this solves:

  • Backend Any counts sit just under the fixed basedpyright caps
  • Decoded provider JSON flows untyped through transformations and proxy handlers

How it solves it:

  • Validates upstream payloads once at the boundary with pydantic
  • Swaps Any for object where every caller already complies
  • reportAny 5,966 to 5,390, reportExplicitAny 1,422 to 1,337
  • No rule grew, no new suppressions or casts
  • Adds 384 tests across 73 test modules, removes none

Intentional product change: when a search provider answers with a malformed result item, POST /v1/search/{search_tool_name} now returns HTTP 500 instead of HTTP 400 "Invalid request format", because the fault is the provider's and not the caller's. A client that keyed on the 400 for this case loses it

User Flow

Before: a developer searching through the gateway is told their request is invalid when it is the search provider that sent a broken answer

  1. They send POST https://litellm-domain/v1/search/searxng-search with {"query": "capital of France"} and get HTTP 200 with {"object": "search", "results": [...]}
  2. The search provider behind that tool starts returning a results list where one entry is a bare string instead of an object
  3. They resend the same request and get HTTP 400, type invalid_request_error, message Invalid request format: ... 'str' object has no attribute 'get' followed by a Python traceback

After: the same broken provider answer comes back as a server-side error, so the developer is not sent looking for a mistake in their request

  1. They send POST https://litellm-domain/v1/search/searxng-search with {"query": "capital of France"} and get HTTP 200 with {"object": "search", "results": [...]}
  2. The search provider behind that tool starts returning a results list where one entry is a bare string instead of an object
  3. They resend the same request and get HTTP 500, type internal_server_error, message ... 1 validation error ... Input should be a valid dictionary, with no traceback

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

Each side runs from its own checkout and Python 3.13 virtualenv with the same config.yaml, 2 workers and no database. One proxy serves the merge base source and the other serves this branch's tip, each on its own random port, and the 44 requests below go to both. 39 of them call 24 real providers, one or more for each changed provider path that can be reached. At the tip the proxy workers ran under coverage, and each case heading names the changed file under litellm/llms/ whose changed function the request ran. The other five requests point a searxng search tool at a small local HTTP server that plays a SearXNG instance, because a real provider cannot be made to return a malformed result on demand

Seven more requests went to both sides with the same result on each and are left out, along with their config entries. Four are refused by the provider before any response is parsed (Bedrock imported Qwen, fal Bria and Imagen4, a Voyage image_url input), two are controls on unchanged paths, and one goes to a public A2A agent, which the A2A specification examples further down cover. The published examples further down also cover Bedrock imported Qwen, fal Bria and Imagen4

model_list:
  - {model_name: claude-haiku, litellm_params: {model: anthropic/claude-haiku-4-5-20251001, api_key: os.environ/ANTHROPIC_API_KEY}}
  - {model_name: gpt-mini, litellm_params: {model: openai/gpt-5-mini, api_key: os.environ/OPENAI_API_KEY}}
  - {model_name: fireworks-oss, litellm_params: {model: fireworks_ai/accounts/fireworks/models/gpt-oss-120b, api_key: os.environ/FIREWORKS_AI_API_KEY}}
  - {model_name: "fireworks_ai/*", litellm_params: {model: "fireworks_ai/*", api_key: os.environ/FIREWORKS_AI_API_KEY, api_base: "https://api.fireworks.ai/v1"}}
  - {model_name: "xai/*", litellm_params: {model: "xai/*", api_key: os.environ/XAI_API_KEY}}
  - {model_name: azure-claude-haiku, litellm_params: {model: azure_ai/claude-haiku-4-5, api_base: os.environ/AZURE_FOUNDRY_API_BASE, api_key: os.environ/AZURE_FOUNDRY_API_KEY}}
  - {model_name: azure-flux2, litellm_params: {model: azure_ai/FLUX.2-pro, api_base: os.environ/AZURE_FOUNDRY_API_BASE, api_key: os.environ/AZURE_FOUNDRY_API_KEY}}
  - {model_name: bedrock-invoke-haiku, litellm_params: {model: bedrock/invoke/us.anthropic.claude-haiku-5-5, aws_access_key_id: os.environ/AWS_ACCESS_KEY_ID, aws_secret_access_key: os.environ/AWS_SECRET_ACCESS_KEY, aws_region_name: us-east-1}}
  - {model_name: databricks-claude-haiku, litellm_params: {model: databricks/databricks-claude-haiku-5-5, api_key: os.environ/DATABRICKS_API_KEY, api_base: os.environ/DATABRICKS_API_BASE}}
  - {model_name: openrouter-haiku, litellm_params: {model: openrouter/anthropic/claude-haiku-5.5, api_key: os.environ/OPENROUTER_API_KEY}}
  - {model_name: oci-gemini-flash-lite, litellm_params: {model: oci/google.gemini-2.5-flash-lite, oci_region: os.environ/OCI_REGION, oci_user: os.environ/OCI_USER, oci_fingerprint: os.environ/OCI_FINGERPRINT, oci_tenancy: os.environ/OCI_TENANCY, oci_key_file: os.environ/OCI_KEY_FILE, oci_compartment_id: os.environ/OCI_COMPARTMENT_ID}}
  - {model_name: ollama-cloud, litellm_params: {model: "ollama/gemma4:31b", api_base: "https://ollama.com", api_key: os.environ/OLLAMA_API_KEY}}
  - {model_name: perplexity-sonar, litellm_params: {model: perplexity/sonar, api_key: os.environ/PERPLEXITY_API_KEY}}
  - {model_name: perplexity-embed, litellm_params: {model: perplexity/pplx-embed-v1-0.6b, api_key: os.environ/PERPLEXITY_API_KEY}}
  - {model_name: cohere-embed, litellm_params: {model: cohere/embed-v5.0-fast, api_key: os.environ/COHERE_API_KEY}}
  - {model_name: dashscope-embed, litellm_params: {model: dashscope/text-embedding-v4, api_key: os.environ/DASHSCOPE_API_KEY, api_base: os.environ/DASHSCOPE_API_BASE}}
  - {model_name: vertex-embed, litellm_params: {model: vertex_ai/text-embedding-005, vertex_project: os.environ/VERTEXAI_PROJECT, vertex_location: us-central1, vertex_credentials: os.environ/GOOGLE_APPLICATION_CREDENTIALS}}
  - {model_name: voyage-lite, litellm_params: {model: voyage/voyage-4-lite, api_key: os.environ/VOYAGE_API_KEY}}
  - {model_name: voyage-context, litellm_params: {model: voyage/voyage-context-4, api_key: os.environ/VOYAGE_API_KEY}}
  - {model_name: voyage-multimodal, litellm_params: {model: voyage/voyage-multimodal-3.5, api_key: os.environ/VOYAGE_API_KEY}}
  - {model_name: infinity-embed, litellm_params: {model: infinity/sentence-transformers/all-MiniLM-L6-v2, api_base: "http://127.0.0.1:7997", api_key: none}}
  - {model_name: ovhcloud-embed, litellm_params: {model: ovhcloud/bge-multilingual-gemma2, api_base: "http://127.0.0.1:<forwarder port>/v1", api_key: anonymous}}
  - {model_name: gemini-image, litellm_params: {model: gemini/gemini-2.5-flash-image, api_key: os.environ/GEMINI_API_KEY}}
  - {model_name: vertex-gemini-image, litellm_params: {model: vertex_ai/gemini-3.1-flash-lite-image, vertex_project: os.environ/VERTEXAI_PROJECT, vertex_location: global, vertex_credentials: os.environ/GOOGLE_APPLICATION_CREDENTIALS}}
  - {model_name: aiml-flux-schnell, litellm_params: {model: aiml/flux/schnell, api_key: os.environ/AIML_API_KEY}}
  - {model_name: fal-gpt-image-2, litellm_params: {model: fal_ai/openai/gpt-image-2, api_key: os.environ/FAL_AI_API_KEY}}
  - {model_name: fal-nano-banana-edit, litellm_params: {model: fal_ai/fal-ai/nano-banana/edit, api_key: os.environ/FAL_AI_API_KEY}}
  - {model_name: mistral-tts, litellm_params: {model: mistral/voxtral-mini-tts-latest, api_key: os.environ/MISTRAL_API_KEY}}
  - {model_name: vertex-lyria-002, litellm_params: {model: vertex_ai/lyria-002, vertex_project: os.environ/VERTEXAI_PROJECT, vertex_location: us-central1, vertex_credentials: os.environ/GOOGLE_APPLICATION_CREDENTIALS}}
  - {model_name: vertex-lyria-3-clip, litellm_params: {model: vertex_ai/lyria-3-clip-preview, vertex_project: os.environ/VERTEXAI_PROJECT, vertex_location: global, vertex_credentials: os.environ/GOOGLE_APPLICATION_CREDENTIALS}}

search_tools:
  - {search_tool_name: tavily-search, litellm_params: {search_provider: tavily, api_key: os.environ/TAVILY_API_KEY}}
  - {search_tool_name: perplexity-search, litellm_params: {search_provider: perplexity, api_key: os.environ/PERPLEXITY_API_KEY}}
  - {search_tool_name: duckduckgo-search, litellm_params: {search_provider: duckduckgo}}
  - {search_tool_name: exa-search, litellm_params: {search_provider: exa_ai, api_key: os.environ/EXA_API_KEY}}
  - {search_tool_name: searxng-search, litellm_params: {search_provider: searxng, api_base: "http://127.0.0.1:<stand-in port>"}}

litellm_settings:
  check_provider_endpoint: true
post() { curl -sS -X POST "$PROXY$1" -H "Authorization: Bearer $LITELLM_MASTER_KEY" -H "Content-Type: application/json" -d "$2" -w '\n%{http_code} %{content_type}\n'; }
get() { curl -sS "$PROXY$1" -H "Authorization: Bearer $LITELLM_MASTER_KEY" -w '\n%{http_code} %{content_type}\n'; }
post_form() { local p=$1 a=(); shift; for f in "$@"; do a+=(-F "$f"); done; curl -sS -X POST "$PROXY$p" -H "Authorization: Bearer $LITELLM_MASTER_KEY" "${a[@]}" -w '\n%{http_code} %{content_type}\n'; }
PONG='[{"role": "user", "content": "Reply with the single word: pong"}]'

red_square.png is a 256 by 256 solid red PNG. Results below give the status line, the body size and the shape of the body, since embeddings, images and audio are too large to paste

The Infinity and OVHcloud requests ran in a second start of the same two checkouts with only those two models in the config. Infinity is its own open-source server run locally (infinity_emb v2 --model-id sentence-transformers/all-MiniLM-L6-v2 --port 7997). OVHcloud's public endpoint https://oai.endpoints.kepler.ai.cloud.ovh.net answers without an account only when no token is sent, and litellm always sends one, so a small local forwarder passes POST /v1/embeddings on to OVHcloud with the Authorization header removed and returns OVHcloud's status and body unchanged

Two changed paths have no proxy route, so sdk_calls.py calls them from each checkout's own virtualenv. The sandbox API is SDK-only, and it runs against a local OpenSandbox server (opensandbox-server on Docker, opensandbox/execd:v1.1.0). That server answers Running on create, so litellm's poll never starts by itself, and the script calls the poll once on the live sandbox between create and delete. VertexTextToSpeechAPI is imported by no other source file, so the script calls its sync and async methods against texttospeech.googleapis.com. At the tip both ran under coverage and the changed lines of all four functions ran

The stand-in answers every GET /search with HTTP 200 and a body chosen by the query

query contains stand-in body
malformed-item-429 429 good results, then a bare string
malformed-item one good result, then a bare string
malformed-field one result whose title is 7
no-results-key JSON with no results key
anything else two well-formed results

For 17 changed provider paths that no credential or account on hand can reach, the response examples printed in each provider's own documentation were saved as they are printed (retrieved 2026-10-13) and replayed through the changed function at both commits. Where a page shortens its JSON with ... or a comment, the example was also run with only that elision removed

provider changed function documented examples result at both commits
a2a A2AConfig.transform_response 7 from section 9 of the A2A 0.3.0 specification, 2 of them elided all 7 become a chat completion
bedrock imported Qwen AmazonQwen2Config.transform_response and AmazonQwen3Config.transform_response 3 from the imported model invoke guide, each through both functions all 6 become a chat completion, the generation example with its text and the two OpenAI-shaped ones with empty content and their usage
brave BraveSearchConfig.transform_search_response 4 from the web search docs, 1 elided, and 1 from Brave's skills repo 1, 1, 0, 0 and 0 results
cometapi CometAPIEmbeddingConfig.transform_embedding_response 1 from the embeddings reference 1 embedding, usage 2 prompt tokens
dataforseo DataForSEOSearchConfig.transform_search_response 1 from the live advanced SERP reference 1 result
fal_ai Bria and Imagen4 FalAIBriaConfig.transform_image_generation_response and FalAIImagen4Config.transform_image_generation_response 1 each from the model page's example response. fal no longer serves either page, so both are the archived copies (Bria 3.2, Imagen 4) 1 image each
fastcrw FastCRWSearchConfig.transform_search_response 1 from the REST API docs and 4 from the search docs, 1 elided 1, 1, 1, 0 and 0 results
firecrawl FirecrawlSearchConfig.transform_search_response 2 from the search reference and 3 from the search feature page, 1 elided 2, 2, 2, 1 and 3 results
google_pse GooglePSESearchConfig.transform_search_response Google prints no Custom Search response, so this is the 1 elided partial-response demo on its performance page 2 results
lemonade LemonadeChatConfig.get_models and get_model_info 2 from the OpenAI-compatible API docs 3 model names, 1 model info
linkup LinkupSearchConfig.transform_search_response 1 from the search reference 1 result
ollama OllamaConfig.transform_response 9 from "Generate a completion" in the API docs, 1 elided, each run with and without format=json all 18 become a chat completion
replicate ReplicateConfig.transform_response and handle_prediction_response_streaming 1 from the HTTP reference and 3 from the create a prediction guide, each through both functions the succeeded example becomes a chat completion, the other 3 raise ReplicateError in the transform, and polling yields 3 outputs and 1 ReplicateError on "output": null
sambanova SambaNovaEmbeddingConfig.transform_embedding_response 1 from the embeddings reference and 2 elided from the embeddings guide 2, 1 and 2 embeddings with their usage
searchapi SearchAPIConfig.transform_search_response 1 elided from the Google search docs 1 result
serper SerperSearchConfig.transform_search_response 3 from the sample responses on the homepage, since the API docs sit behind a login 10 results each
vertex_ai Imagen VertexAIImagenImageGenerationConfig.transform_image_generation_response and VertexAIImagenImageEditConfig.transform_image_edit_response 2 from the generate images guide and 1 from the insert objects guide 2 images each

Before (fb051f9)

Lint counts

  1. The three lint gates' own runners (scripts/type_check_gate.py for whole-tree basedpyright, scripts/ruff_strict_gate.py, scripts/type_discipline_gate.py), errors counted per rule
  2. reportAny 5,966, reportExplicitAny 1,422, all basedpyright rules 112,296, ruff-strict 17,446, type-discipline 52,336

Tavily search (tavily/search)

  1. post /v1/search/tavily-search '{"query": "What is the capital of France?", "max_results": 3}'
  2. 200 application/json, 3850 bytes, results=3 first keys=date,last_updated,snippet,title,url snippet lengths=[1315, 1048, 947]

Perplexity search (perplexity/search)

  1. post /v1/search/perplexity-search '{"query": "What is the capital of France?", "max_results": 3}'
  2. 200 application/json, 1191 bytes, results=3 first keys=date,last_updated,snippet,title,url snippet lengths=[213, 180, 198]

DuckDuckGo search (duckduckgo/search)

  1. post /v1/search/duckduckgo-search '{"query": "Eiffel Tower", "max_results": 3}'
  2. 200 application/json, 778 bytes, results=3 first keys=date,last_updated,snippet,title,url snippet lengths=[67, 102, 75]

DuckDuckGo search with an abstract (duckduckgo/search)

  1. post /v1/search/duckduckgo-search '{"query": "Python (programming language)", "max_results": 3}'
  2. 200 application/json, 1501 bytes, results=3 first keys=date,last_updated,snippet,title,url snippet lengths=[939, 38, 79]

Exa search (exa_ai/search)

  1. post /v1/search/exa-search '{"query": "What is the capital of France?", "max_results": 3}'
  2. 200 application/json, 157061 bytes, results=3 first keys=date,last_updated,snippet,title,url snippet lengths=[1000, 150989, 1000]

Exa search with highlights (exa_ai/search)

  1. post /v1/search/exa-search '{"query": "What is the capital of France?", "max_results": 3, "contents": {"highlights": true}}'
  2. 200 application/json, 4355 bytes, results=3 first keys=date,last_updated,snippet,title,url snippet lengths=[467, 2279, 998]

Anthropic token count (anthropic/count_tokens)

  1. post /v1/messages/count_tokens '{"model": "claude-haiku", "messages": [{"role": "user", "content": "Hello, how many tokens is this sentence?"}]}'
  2. 200 application/json, 19 bytes, {"input_tokens": 16}

Azure AI Anthropic token count (azure_ai/anthropic/count_tokens)

  1. post /v1/messages/count_tokens '{"model": "azure-claude-haiku", "messages": [{"role": "user", "content": "Hello, how many tokens is this sentence?"}]}'
  2. 200 application/json, 19 bytes, {"input_tokens": 16}

OpenAI input tokens (openai/responses/count_tokens)

  1. post /v1/responses/input_tokens '{"model": "gpt-mini", "input": "Hello, how many tokens is this sentence?"}'
  2. 200 application/json, 52 bytes, {"object": "response.input_tokens", "input_tokens": 15}

Anthropic files list (anthropic/files)

  1. get '/v1/files?target_model_names=claude-haiku'
  2. 200 application/json, 1732 bytes, data=8 first item keys=bytes,created_at,expires_at,filename,id,object,purpose,status,status_details has_more=False

Anthropic Messages request served by a Fireworks model (anthropic/pass_through/adapters)

  1. post /v1/messages '{"model": "fireworks-oss", "max_tokens": 200, "messages": '"$PONG"'}'
  2. 200 application/json, 448 bytes, content types=['thinking', 'text'] text='pong' stop_reason=end_turn usage={"cache_read_input_tokens": 78, "input_tokens": 1, "output_tokens": 36}

Fireworks chat completion (fireworks_ai/chat)

  1. post /v1/chat/completions '{"model": "fireworks-oss", "messages": '"$PONG"', "max_tokens": 200, "temperature": 0}'
  2. 200 application/json, 548 bytes, content='pong' finish_reason=stop usage={"completion_tokens": 33, "prompt_tokens": 79, "total_tokens": 112} model=fireworks-oss

Bedrock invoke chat completion (bedrock/chat/invoke_transformations)

  1. post /v1/chat/completions '{"model": "bedrock-invoke-haiku", "messages": '"$PONG"', "max_tokens": 20}'
  2. 200 application/json, 722 bytes, content='pong' finish_reason=stop usage={"cache_creation_input_tokens": 0, "cache_read_input_tokens": 0, "completion_tokens": 4, "prompt_tokens": 18, "total_tokens": 22} model=bedrock-invoke-haiku

Databricks chat completion with cache_control (databricks/chat)

  1. post /v1/chat/completions '{"model": "databricks-claude-haiku", "messages": [{"role": "user", "content": "Reply with the single word: pong", "cache_control": {"type": "ephemeral"}}], "max_tokens": 20}'
  2. 200 application/json, 469 bytes, content='pong' finish_reason=stop usage={"cache_creation_input_tokens": 0, "cache_read_input_tokens": 0, "completion_tokens": 4, "prompt_tokens": 18, "total_tokens": 22} model=databricks-claude-haiku

OpenRouter chat completion (openrouter/chat)

  1. post /v1/chat/completions '{"model": "openrouter-haiku", "messages": '"$PONG"', "max_tokens": 20}'
  2. 200 application/json, 847 bytes, content='pong' finish_reason=stop usage={"completion_tokens": 4, "cost": 3.8e-06, "prompt_tokens": 18, "total_tokens": 22} model=openrouter-haiku

OpenRouter streaming chat completion (openrouter/chat)

  1. post /v1/chat/completions '{"model": "openrouter-haiku", "messages": '"$PONG"', "max_tokens": 20, "stream": true}'
  2. 200 text/event-stream; charset=utf-8, 607 bytes, sse events=4 json chunks=3 done=True content='pong' finish_reasons=['stop']

OCI streaming chat completion (oci/chat)

  1. post /v1/chat/completions '{"model": "oci-gemini-flash-lite", "messages": '"$PONG"', "max_tokens": 200, "stream": true}'
  2. 200 text/event-stream; charset=utf-8, 785 bytes, sse events=5 json chunks=4 done=True content='pong' finish_reasons=['stop']

Ollama JSON mode chat completion (ollama/completion)

  1. post /v1/chat/completions '{"model": "ollama-cloud", "messages": [{"role": "user", "content": "Return a JSON object with one key named answer whose value is the string pong."}], "response_format": {"type": "json_object"}, "max_tokens": 200}'
  2. 200 application/json, 308 bytes, content='{"answer": "pong"}' finish_reason=stop usage={"completion_tokens": 17, "prompt_tokens": 33, "total_tokens": 50} model=ollama-cloud

Perplexity chat completion (perplexity/chat)

  1. Restart the proxy with EXPERIMENTAL_OPENAI_BASE_LLM_HTTP_HANDLER=true, since Perplexity chat only goes through its own response transformation on that route
  2. post /v1/chat/completions '{"model": "perplexity-sonar", "messages": [{"role": "user", "content": "What is the capital of France? Answer in one word."}], "max_tokens": 20}'
  3. 200 application/json, 5777 bytes, content='Paris' finish_reason=stop usage={"citation_tokens": 163, "completion_tokens": 1, "prompt_tokens": 12, "total_tokens": 13} model=perplexity-sonar

xAI and Fireworks model discovery (xai/common_utils.py, fireworks_ai/chat)

  1. get /v1/models
  2. 200 application/json, 15605 bytes, data=95 ids by prefix={"xai/": 14, "fireworks_ai/": 50} first item keys=created,id,max_input_tokens,max_output_tokens,mode,object,owned_by

Perplexity embeddings (perplexity/embedding)

  1. post /v1/embeddings '{"model": "perplexity-embed", "input": ["hello world", "second input"]}'
  2. 200 application/json, 41302 bytes, data=2 first embedding list[float] len 1024 usage={"completion_tokens": 0, "prompt_tokens": 4, "total_tokens": 4}

Cohere embeddings (cohere/embed)

  1. post /v1/embeddings '{"model": "cohere-embed", "input": ["hello world", "second input"]}'
  2. 200 application/json, 51834 bytes, data=2 first embedding list[float] len 2048 usage={"completion_tokens": 0, "prompt_tokens": 4, "total_tokens": 4}

Cohere embeddings with two embedding types (cohere/embed)

  1. post /v1/embeddings '{"model": "cohere-embed", "input": ["hello world", "second input"], "embedding_types": ["float", "int8"]}'
  2. 200 application/json, 65573 bytes, data=4 first embedding list[float] len 2048 usage={"completion_tokens": 0, "prompt_tokens": 4, "total_tokens": 4}

DashScope embeddings (dashscope/embed)

  1. post /v1/embeddings '{"model": "dashscope-embed", "input": ["hello world", "second input"]}'
  2. 200 application/json, 43714 bytes, data=2 first embedding list[float] len 1024 usage={"completion_tokens": 0, "prompt_tokens": 6, "total_tokens": 6}

Vertex AI embeddings (vertex_ai/vertex_embeddings)

  1. post /v1/embeddings '{"model": "vertex-embed", "input": ["hello world", "second input"]}'
  2. 200 application/json, 32736 bytes, data=2 first embedding list[float] len 768 usage={"completion_tokens": 0, "prompt_tokens": 4, "total_tokens": 4}

Voyage embeddings (voyage/embedding/transformation.py)

  1. post /v1/embeddings '{"model": "voyage-lite", "input": ["hello world", "second input"]}'
  2. 200 application/json, 25692 bytes, data=2 first embedding list[float] len 1024 usage={"completion_tokens": 0, "prompt_tokens": 4, "total_tokens": 4}

Voyage contextual embeddings (voyage/embedding/transformation_contextual.py)

  1. post /v1/embeddings '{"model": "voyage-context", "input": ["hello world", "second input"]}'
  2. 200 application/json, 25822 bytes, data=2 groups, first group inner data=1 first embedding list[float] len 1024 usage={"completion_tokens": 0, "prompt_tokens": 4, "total_tokens": 4}

Voyage multimodal embeddings (voyage/embedding/transformation_multimodal.py)

  1. post /v1/embeddings '{"model": "voyage-multimodal", "input": [{"content": [{"type": "text", "text": "A red square on a white background"}, {"type": "image_base64", "image_base64": "data:image/png;base64,'"$(base64 < red_square.png | tr -d '\n')"'"}]}]}'
  2. 200 application/json, 12918 bytes, data=1 first embedding list[float] len 1024 usage={"completion_tokens": 0, "prompt_tokens": 124, "total_tokens": 124}

Infinity embeddings (infinity/embedding)

  1. post /v1/embeddings '{"model": "infinity-embed", "input": ["hello world", "second text"]}'
  2. 200 application/json, 16390 bytes, data=2 first embedding list[float] len 384 usage={"completion_tokens": 0, "prompt_tokens": 22, "total_tokens": 22}

OVHcloud embeddings (ovhcloud/embedding)

  1. post /v1/embeddings '{"model": "ovhcloud-embed", "input": ["hello world", "second text"]}'
  2. 200 application/json, 90524 bytes, data=2 first embedding list[float] len 3584 usage={"completion_tokens": 0, "prompt_tokens": 8, "total_tokens": 8}

Gemini image generation (gemini/image_generation)

  1. post /v1/images/generations '{"model": "gemini-image", "prompt": "A plain red circle on a white background", "n": 1}'
  2. 200 application/json, 1166654 bytes, images=1 first b64_json len 1166288 usage={"input_tokens": 8, "output_tokens": 1295, "total_tokens": 1303}

Vertex AI Gemini image generation (vertex_ai/image_generation/vertex_gemini_transformation.py)

  1. post /v1/images/generations '{"model": "vertex-gemini-image", "prompt": "A plain red circle on a white background", "n": 1}'
  2. 200 application/json, 885808 bytes, images=1 first b64_json len 43364 provider_specific_fields lengths={"thought_signature": 842120} usage={"input_tokens": 8, "output_tokens": 1120, "total_tokens": 1128}

AI/ML API image generation (aiml/image_generation)

  1. post /v1/images/generations '{"model": "aiml-flux-schnell", "prompt": "A plain red circle on a white background", "n": 1}'
  2. 200 application/json, 368 bytes, images=1 first url host s3.aimlapi.com usage={"input_tokens": 0, "output_tokens": 0, "total_tokens": 0}

fal image generation (fal_ai/image_generation/transformation.py)

  1. post /v1/images/generations '{"model": "fal-gpt-image-2", "prompt": "A plain red circle on a white background", "n": 1, "quality": "low", "size": "1024x768"}'
  2. 200 application/json, 395 bytes, images=1 first url host v3b.fal.media provider_specific_fields lengths={"content_type": 9} usage={"input_tokens": 0, "output_tokens": 0, "total_tokens": 0}

fal image edit (fal_ai/image_edit)

  1. post_form /v1/images/edits model=fal-nano-banana-edit "prompt=Make the red square blue" "image=@red_square.png;type=image/png"
  2. 200 application/json, 395 bytes, images=1 first url host v3b.fal.media provider_specific_fields lengths={"content_type": 9} usage={"input_tokens": 0, "output_tokens": 0, "total_tokens": 0}

Azure AI FLUX.2 image edit (azure_ai/image_edit)

  1. post_form /v1/images/edits model=azure-flux2 "prompt=Make the red square blue" "image=@red_square.png;type=image/png"
  2. 200 application/json, 38430 bytes, images=1 first b64_json len 38132 usage={"input_tokens": 0, "output_tokens": 0, "total_tokens": 0}

Mistral speech (mistral/audio_speech)

  1. post /v1/audio/speech '{"model": "mistral-tts", "input": "Hello from the gateway.", "voice": "alloy"}'
  2. 200 audio/mpeg, 11236 bytes, binary audio (mp3 magic)

Vertex AI Lyria audio over predict (vertex_ai/text_to_speech)

  1. post /v1/audio/speech '{"model": "vertex-lyria-002", "input": "A calm solo piano melody", "voice": "alloy"}'
  2. 200 audio/wav, 6291544 bytes, binary audio (wav magic)

Vertex AI Lyria audio over interactions (vertex_ai/text_to_speech)

  1. post /v1/audio/speech '{"model": "vertex-lyria-3-clip", "input": "A calm solo piano melody", "voice": "alloy"}'
  2. 200 audio/mpeg, 712394 bytes, binary audio (mp3 magic)

OpenSandbox create, poll and delete (opensandbox/sandbox)

  1. .venv/bin/python sdk_calls.py, which calls litellm.sandbox.main.acreate_sandbox(provider="opensandbox", template="python:3.12-alpine", entrypoint=["tail", "-f", "/dev/null"]), then the provider config's _wait_until_running once, then adelete_sandbox
  2. A ContainerHandle whose id is a UUID and whose exec endpoint is 127.0.0.1:<port>/proxy/<port>, the poll returns once the server reports Running, and the delete returns True

Google Cloud Text-to-Speech handler (vertex_ai/text_to_speech/text_to_speech_handler.py)

  1. .venv/bin/python sdk_calls.py, which calls VertexTextToSpeechAPI().audio_speech(...) and async_audio_speech(...) with input Hello from the LiteLLM proxy and voice en-US-Standard-C
  2. Each returns HttpxBinaryResponseContent holding 126116 bytes that start with RIFF

Search provider returns well-formed results (searxng/search)

  1. post /v1/search/searxng-search '{"query": "capital of France"}'
  2. 200 application/json, 304 bytes, results=2 first keys=date,last_updated,snippet,title,url snippet lengths=[31, 38]

Search provider returns no results key (searxng/search)

  1. post /v1/search/searxng-search '{"query": "no-results-key"}'
  2. 200 application/json, 32 bytes, results=0 first keys= snippet lengths=[]

Search provider returns a malformed result item (searxng/search)

  1. post /v1/search/searxng-search '{"query": "malformed-item"}'
  2. 400 application/json, type invalid_request_error, message Invalid request format: litellm.APIConnectionError: 'str' object has no attribute 'get', followed by the Python traceback
  3. post /v1/search/searxng-search '{"query": "malformed-item-429"}'
  4. 400 application/json, the same body as step 2 byte for byte

Search provider returns a wrong-typed field (searxng/search)

  1. post /v1/search/searxng-search '{"query": "malformed-field"}'
  2. 500 application/json, type internal_server_error, message litellm.APIConnectionError: 1 validation error for SearchResult title Input should be a valid string [type=string_type, input_value=7, input_type=int] For further information visit https://errors.pydantic.dev/2.13/v/string_type

Documented provider responses

  1. .venv/bin/python -I run.py, which feeds every saved example to the function in the table above the way that provider's unit test calls it
  2. 83 results. 68 transform, 11 are the elided originals that are not valid JSON as printed and never reach litellm, and 4 are the Replicate errors in the table

After (4a227be)

Lint counts

  1. The three lint gates' own runners (scripts/type_check_gate.py for whole-tree basedpyright, scripts/ruff_strict_gate.py, scripts/type_discipline_gate.py), errors counted per rule
  2. reportAny 5,390 (-576), reportExplicitAny 1,337 (-85), all basedpyright rules 111,586 (-710), ruff-strict 17,422 (-24), type-discipline 52,328 (-8)
  3. No rule's count went up in any of the three tools
  4. make check prints OK: every basedpyright rule is within its ceiling (111586 errors total, base fb051f9647b6) and ends with check: PASS

Tavily search (tavily/search)

  1. post /v1/search/tavily-search '{"query": "What is the capital of France?", "max_results": 3}'
  2. 200 application/json, 4356 bytes, results=3 first keys=date,last_updated,snippet,title,url snippet lengths=[1315, 1048, 1453]

Perplexity search (perplexity/search)

  1. post /v1/search/perplexity-search '{"query": "What is the capital of France?", "max_results": 3}'
  2. 200 application/json, the same body as Before byte for byte

DuckDuckGo search (duckduckgo/search)

  1. post /v1/search/duckduckgo-search '{"query": "Eiffel Tower", "max_results": 3}'
  2. 200 application/json, the same body as Before byte for byte

DuckDuckGo search with an abstract (duckduckgo/search)

  1. post /v1/search/duckduckgo-search '{"query": "Python (programming language)", "max_results": 3}'
  2. 200 application/json, the same body as Before byte for byte

Exa search (exa_ai/search)

  1. post /v1/search/exa-search '{"query": "What is the capital of France?", "max_results": 3}'
  2. 200 application/json, the same body as Before byte for byte

Exa search with highlights (exa_ai/search)

  1. post /v1/search/exa-search '{"query": "What is the capital of France?", "max_results": 3, "contents": {"highlights": true}}'
  2. 200 application/json, the same body as Before byte for byte

Anthropic token count (anthropic/count_tokens)

  1. post /v1/messages/count_tokens '{"model": "claude-haiku", "messages": [{"role": "user", "content": "Hello, how many tokens is this sentence?"}]}'
  2. 200 application/json, the same body as Before byte for byte

Azure AI Anthropic token count (azure_ai/anthropic/count_tokens)

  1. post /v1/messages/count_tokens '{"model": "azure-claude-haiku", "messages": [{"role": "user", "content": "Hello, how many tokens is this sentence?"}]}'
  2. 200 application/json, the same body as Before byte for byte

OpenAI input tokens (openai/responses/count_tokens)

  1. post /v1/responses/input_tokens '{"model": "gpt-mini", "input": "Hello, how many tokens is this sentence?"}'
  2. 200 application/json, the same body as Before byte for byte

Anthropic files list (anthropic/files)

  1. get '/v1/files?target_model_names=claude-haiku'
  2. 200 application/json, the same body as Before byte for byte

Anthropic Messages request served by a Fireworks model (anthropic/pass_through/adapters)

  1. post /v1/messages '{"model": "fireworks-oss", "max_tokens": 200, "messages": '"$PONG"'}'
  2. 200 application/json, 427 bytes, content types=['thinking', 'text'] text='pong' stop_reason=end_turn usage={"cache_read_input_tokens": 78, "input_tokens": 1, "output_tokens": 31}

Fireworks chat completion (fireworks_ai/chat)

  1. post /v1/chat/completions '{"model": "fireworks-oss", "messages": '"$PONG"', "max_tokens": 200, "temperature": 0}'
  2. 200 application/json, 549 bytes, content='pong' finish_reason=stop usage={"completion_tokens": 33, "prompt_tokens": 79, "total_tokens": 112} model=fireworks-oss

Bedrock invoke chat completion (bedrock/chat/invoke_transformations)

  1. post /v1/chat/completions '{"model": "bedrock-invoke-haiku", "messages": '"$PONG"', "max_tokens": 20}'
  2. 200 application/json, 722 bytes, content='pong' finish_reason=stop usage={"cache_creation_input_tokens": 0, "cache_read_input_tokens": 0, "completion_tokens": 4, "prompt_tokens": 18, "total_tokens": 22} model=bedrock-invoke-haiku

Databricks chat completion with cache_control (databricks/chat)

  1. post /v1/chat/completions '{"model": "databricks-claude-haiku", "messages": [{"role": "user", "content": "Reply with the single word: pong", "cache_control": {"type": "ephemeral"}}], "max_tokens": 20}'
  2. 200 application/json, 469 bytes, content='pong' finish_reason=stop usage={"cache_creation_input_tokens": 0, "cache_read_input_tokens": 0, "completion_tokens": 4, "prompt_tokens": 18, "total_tokens": 22} model=databricks-claude-haiku

OpenRouter chat completion (openrouter/chat)

  1. post /v1/chat/completions '{"model": "openrouter-haiku", "messages": '"$PONG"', "max_tokens": 20}'
  2. 200 application/json, 847 bytes, content='pong' finish_reason=stop usage={"completion_tokens": 4, "cost": 3.8e-06, "prompt_tokens": 18, "total_tokens": 22} model=openrouter-haiku

OpenRouter streaming chat completion (openrouter/chat)

  1. post /v1/chat/completions '{"model": "openrouter-haiku", "messages": '"$PONG"', "max_tokens": 20, "stream": true}'
  2. 200 text/event-stream; charset=utf-8, 607 bytes, sse events=4 json chunks=3 done=True content='pong' finish_reasons=['stop']

OCI streaming chat completion (oci/chat)

  1. post /v1/chat/completions '{"model": "oci-gemini-flash-lite", "messages": '"$PONG"', "max_tokens": 200, "stream": true}'
  2. 200 text/event-stream; charset=utf-8, 785 bytes, sse events=5 json chunks=4 done=True content='pong' finish_reasons=['stop']

Ollama JSON mode chat completion (ollama/completion)

  1. post /v1/chat/completions '{"model": "ollama-cloud", "messages": [{"role": "user", "content": "Return a JSON object with one key named answer whose value is the string pong."}], "response_format": {"type": "json_object"}, "max_tokens": 200}'
  2. 200 application/json, 308 bytes, content='{"answer": "pong"}' finish_reason=stop usage={"completion_tokens": 17, "prompt_tokens": 33, "total_tokens": 50} model=ollama-cloud

Perplexity chat completion (perplexity/chat)

  1. Restart the proxy with EXPERIMENTAL_OPENAI_BASE_LLM_HTTP_HANDLER=true, since Perplexity chat only goes through its own response transformation on that route
  2. post /v1/chat/completions '{"model": "perplexity-sonar", "messages": [{"role": "user", "content": "What is the capital of France? Answer in one word."}], "max_tokens": 20}'
  3. 200 application/json, 5777 bytes, content='Paris' finish_reason=stop usage={"citation_tokens": 163, "completion_tokens": 1, "prompt_tokens": 12, "total_tokens": 13} model=perplexity-sonar

xAI and Fireworks model discovery (xai/common_utils.py, fireworks_ai/chat)

  1. get /v1/models
  2. 200 application/json, the same body as Before byte for byte

Perplexity embeddings (perplexity/embedding)

  1. post /v1/embeddings '{"model": "perplexity-embed", "input": ["hello world", "second input"]}'
  2. 200 application/json, the same body as Before byte for byte

Cohere embeddings (cohere/embed)

  1. post /v1/embeddings '{"model": "cohere-embed", "input": ["hello world", "second input"]}'
  2. 200 application/json, the same body as Before byte for byte

Cohere embeddings with two embedding types (cohere/embed)

  1. post /v1/embeddings '{"model": "cohere-embed", "input": ["hello world", "second input"], "embedding_types": ["float", "int8"]}'
  2. 200 application/json, 65577 bytes, data=4 first embedding list[float] len 2048 usage={"completion_tokens": 0, "prompt_tokens": 4, "total_tokens": 4}

DashScope embeddings (dashscope/embed)

  1. post /v1/embeddings '{"model": "dashscope-embed", "input": ["hello world", "second input"]}'
  2. 200 application/json, 43714 bytes, data=2 first embedding list[float] len 1024 usage={"completion_tokens": 0, "prompt_tokens": 6, "total_tokens": 6}

Vertex AI embeddings (vertex_ai/vertex_embeddings)

  1. post /v1/embeddings '{"model": "vertex-embed", "input": ["hello world", "second input"]}'
  2. 200 application/json, the same body as Before byte for byte

Voyage embeddings (voyage/embedding/transformation.py)

  1. post /v1/embeddings '{"model": "voyage-lite", "input": ["hello world", "second input"]}'
  2. 200 application/json, the same body as Before byte for byte

Voyage contextual embeddings (voyage/embedding/transformation_contextual.py)

  1. post /v1/embeddings '{"model": "voyage-context", "input": ["hello world", "second input"]}'
  2. 200 application/json, the same body as Before byte for byte

Voyage multimodal embeddings (voyage/embedding/transformation_multimodal.py)

  1. post /v1/embeddings '{"model": "voyage-multimodal", "input": [{"content": [{"type": "text", "text": "A red square on a white background"}, {"type": "image_base64", "image_base64": "data:image/png;base64,'"$(base64 < red_square.png | tr -d '\n')"'"}]}]}'
  2. 200 application/json, the same body as Before byte for byte

Infinity embeddings (infinity/embedding)

  1. post /v1/embeddings '{"model": "infinity-embed", "input": ["hello world", "second text"]}'
  2. 200 application/json, the same body as Before byte for byte

OVHcloud embeddings (ovhcloud/embedding)

  1. post /v1/embeddings '{"model": "ovhcloud-embed", "input": ["hello world", "second text"]}'
  2. 200 application/json, the same body as Before byte for byte

Gemini image generation (gemini/image_generation)

  1. post /v1/images/generations '{"model": "gemini-image", "prompt": "A plain red circle on a white background", "n": 1}'
  2. 200 application/json, 992123 bytes, images=1 first b64_json len 991756 usage={"input_tokens": 8, "output_tokens": 1302, "total_tokens": 1310}

Vertex AI Gemini image generation (vertex_ai/image_generation/vertex_gemini_transformation.py)

  1. post /v1/images/generations '{"model": "vertex-gemini-image", "prompt": "A plain red circle on a white background", "n": 1}'
  2. 200 application/json, 857444 bytes, images=1 first b64_json len 44200 provider_specific_fields lengths={"thought_signature": 812920} usage={"input_tokens": 8, "output_tokens": 1120, "total_tokens": 1128}

AI/ML API image generation (aiml/image_generation)

  1. post /v1/images/generations '{"model": "aiml-flux-schnell", "prompt": "A plain red circle on a white background", "n": 1}'
  2. 200 application/json, 368 bytes, images=1 first url host s3.aimlapi.com usage={"input_tokens": 0, "output_tokens": 0, "total_tokens": 0}

fal image generation (fal_ai/image_generation/transformation.py)

  1. post /v1/images/generations '{"model": "fal-gpt-image-2", "prompt": "A plain red circle on a white background", "n": 1, "quality": "low", "size": "1024x768"}'
  2. 200 application/json, 395 bytes, images=1 first url host v3b.fal.media provider_specific_fields lengths={"content_type": 9} usage={"input_tokens": 0, "output_tokens": 0, "total_tokens": 0}

fal image edit (fal_ai/image_edit)

  1. post_form /v1/images/edits model=fal-nano-banana-edit "prompt=Make the red square blue" "image=@red_square.png;type=image/png"
  2. 200 application/json, 395 bytes, images=1 first url host v3b.fal.media provider_specific_fields lengths={"content_type": 9} usage={"input_tokens": 0, "output_tokens": 0, "total_tokens": 0}

Azure AI FLUX.2 image edit (azure_ai/image_edit)

  1. post_form /v1/images/edits model=azure-flux2 "prompt=Make the red square blue" "image=@red_square.png;type=image/png"
  2. 200 application/json, 37042 bytes, images=1 first b64_json len 36744 usage={"input_tokens": 0, "output_tokens": 0, "total_tokens": 0}

Mistral speech (mistral/audio_speech)

  1. post /v1/audio/speech '{"model": "mistral-tts", "input": "Hello from the gateway.", "voice": "alloy"}'
  2. 200 audio/mpeg, 9158 bytes, binary audio (mp3 magic)

Vertex AI Lyria audio over predict (vertex_ai/text_to_speech)

  1. post /v1/audio/speech '{"model": "vertex-lyria-002", "input": "A calm solo piano melody", "voice": "alloy"}'
  2. 200 audio/wav, 6291544 bytes, binary audio (wav magic)

Vertex AI Lyria audio over interactions (vertex_ai/text_to_speech)

  1. post /v1/audio/speech '{"model": "vertex-lyria-3-clip", "input": "A calm solo piano melody", "voice": "alloy"}'
  2. 200 audio/mpeg, 746248 bytes, binary audio (mp3 magic)

OpenSandbox create, poll and delete (opensandbox/sandbox)

  1. .venv/bin/python sdk_calls.py, which calls litellm.sandbox.main.acreate_sandbox(provider="opensandbox", template="python:3.12-alpine", entrypoint=["tail", "-f", "/dev/null"]), then the provider config's _wait_until_running once, then adelete_sandbox
  2. The same result as Before

Google Cloud Text-to-Speech handler (vertex_ai/text_to_speech/text_to_speech_handler.py)

  1. .venv/bin/python sdk_calls.py, which calls VertexTextToSpeechAPI().audio_speech(...) and async_audio_speech(...) with input Hello from the LiteLLM proxy and voice en-US-Standard-C
  2. The same result as Before, 126116 bytes both times

Search provider returns well-formed results (searxng/search)

  1. post /v1/search/searxng-search '{"query": "capital of France"}'
  2. 200 application/json, the same body as Before byte for byte

Search provider returns no results key (searxng/search)

  1. post /v1/search/searxng-search '{"query": "no-results-key"}'
  2. 200 application/json, the same body as Before byte for byte

Search provider returns a malformed result item (searxng/search)

  1. post /v1/search/searxng-search '{"query": "malformed-item"}'
  2. 500 application/json, type internal_server_error, message litellm.APIConnectionError: 1 validation error for dict[str,any] Input should be a valid dictionary [type=dict_type] For further information visit https://errors.pydantic.dev/2.13/v/dict_type
  3. post /v1/search/searxng-search '{"query": "malformed-item-429"}'
  4. 500 application/json, the same body as step 2 byte for byte

Search provider returns a wrong-typed field (searxng/search)

  1. post /v1/search/searxng-search '{"query": "malformed-field"}'
  2. 500 application/json, the same body as Before byte for byte

Documented provider responses

  1. .venv/bin/python -I run.py, which feeds every saved example to the function in the table above the way that provider's unit test calls it
  2. The same 83 results as Before byte for byte

Type

🧹 Refactoring

Changes

The diff touches 126 source files (+901, -463) and 73 test modules plus 18 package __init__.py files (+8,353, -21). Nothing here adds a feature: the work replaces untyped values with typed ones at the place they enter the code, so the errors disappear downstream instead of being hidden

Three patterns do almost all of it. Where a provider's decoded JSON used to flow onward as Any, it now goes through a module-level pydantic TypeAdapter or an existing response model exactly once, and everything after that point is typed. Validation is per item and built with hide_input_in_errors=True, so neither the payload nor an item index leaks into error text that the exception mapper later matches on. Where a parameter or return was annotated Any although every caller already passes something narrower, the annotation becomes object or the real type, with each caller checked. And where a value was only ever read through one or two attributes, a small Protocol or single-key TypedDict view describes that read

The largest drops are in the search transformations (linkup, brave, searchapi, searxng, perplexity, duckduckgo, exa, serper, dataforseo, google_pse, tavily: each at or near zero now), vertex_ai (52), bedrock (31), the proxy's Google, video, vector store, Anthropic and evals endpoints (about 70 together), guardrail hooks (21), the proxy client (19), and image generation for aiml, gemini and fal_ai. Request-side paths, per-chunk streaming paths, shared base classes and public signatures were left alone on purpose, which is why touched files such as the Fireworks chat transformation still carry a few Any errors

No # type: ignore, # noqa, pyright: ignore, TypeGuard, TypeIs or new cast() was added. Two existing casts in the Databricks chat transformation changed their target from dict[str, Any] to dict[str, object]. ANY_CAPS is untouched, since the repo lowers it only in its own PR

With main merged in at fb051f9, the branch's 73 test modules give 2,738 passed and 2 skipped

Four of the test directories are new (brave, google_pse, nlp_cloud and opensandbox), so .github/workflows/test-unit.yml now lists them in the llms-providers unit shard. Without those four lines the required lint job fails because no shard would run them

Caveats (if any)

Low

  • Malformed search result item: HTTP 500 instead of HTTP 400
    • Same swap for fastcrw, firecrawl, fal_ai and a2a responses
    • Only the SearXNG path was proven live
  • Malformed provider payloads raise ValidationError, not AttributeError, TypeError or KeyError
    • Vertex image generation, TTS and embeddings; Anthropic files list
    • opensandbox, xai, replicate, Google secret manager
  • Some changed response paths were not proven through a real provider call from the proxy
    • Published examples only: Bedrock imported Qwen, Vertex Imagen, fal Bria and Imagen4
    • OVHcloud went through a local forwarder that removes the token
    • OpenSandbox and the Google Cloud speech handler were called from a script, not the proxy
    • OpenSandbox's poll was called directly, and running code in the sandbox was not tried
    • Unit tests only: the Vertex fine-tuning pass-through
  • Anthropic pass-through logging raises ValidationError on a non-object message
    • Every handler there already catches Exception
  • 47 annotations loosened from Any to object, static only
  • A few helper return annotations narrowed, runtime unchanged
  • Two response checks now use runtime-checkable Protocols
    • On Python 3.12+ these ignore attributes served by __getattr__
  • Residual Any errors remain in touched files, none hidden
  • Client-derived request paths deliberately untouched, so their Any errors stay

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

Note

Medium Risk
Wide touch across provider response parsing with one intentional API error-code change for malformed upstream search payloads; most paths are typing-only but regressions could appear if validation is stricter than previous ad-hoc dict access.

Overview
This PR tightens static typing by validating provider JSON at transformation boundaries with Pydantic TypeAdapters and replacing broad Any annotations with object, JsonValue, or narrower types across dozens of LLM integrations (search, embeddings, images, TTS, token counting, Bedrock/A2A, etc.).

Behavioral change: when a search (or similar) provider returns malformed result items, gateway search routes now surface HTTP 500 (internal_server_error) with Pydantic validation messages instead of HTTP 400 framed as an invalid client request. Well-formed provider traffic is unchanged in the author’s proxy comparisons.

Other fixes: Bedrock AgentCore A2A streaming joins multiple content-type headers before choosing JSON vs SSE; VantageLogger types its pod lock manager separately from FocusLogger; CI adds unit-test shard entries for brave, google_pse, nlp_cloud, and opensandbox.

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

…4 basedpyright Any errors

Replaces untyped reads of decoded JSON in 48 provider, guardrail and proxy
modules with one pydantic validation at the point the payload enters the
module, so every value read afterwards carries a real type.

reportAny 6111 -> 5663 and reportExplicitAny 1416 -> 1400. No basedpyright,
ruff-strict or type-discipline rule is higher repo-wide or in any single
file, and no cast, ignore or suppression marker was added.
…atisfies with object

Each annotation here is a parameter or return type whose value is only
stored, compared, logged or forwarded, so object describes it exactly and
no function body changes. A site was kept only if no basedpyright,
ruff-strict or type-discipline rule rose in any file that references it.

reportExplicitAny 1400 -> 1353 and reportAny 5663 -> 5655.
…roviders, proxy and integrations

Second pass of the Any reduction. Decoded upstream JSON is validated once at
the provider boundary and read through typed views afterwards, annotations
that every caller already satisfies move from Any to a concrete type, and the
nine search transformations validate each result item on its own so error
text no longer carries the item index.

No cast, no type: ignore, no suppression marker and no budget file edit
…_opus55_1008

# Conflicts:
#	tests/unit/llms/duckduckgo/search/test_duckduckgo_search_transformation.py
#	tests/unit/llms/exa_ai/search/test_transformation.py
#	tests/unit/llms/perplexity/search/test_perplexity_search_transformation.py
#	tests/unit/llms/vertex_ai/text_to_speech/test_transformation.py
#	tests/unit/secret_managers/test_google_secret_manager.py
@greptile-apps

greptile-apps Bot commented Oct 8, 2026 •

Copy link
Copy Markdown
Contributor

RetriggerConfidence Score: 5/5

[Medium risk] Type annotations updated across 219 files for static analysis.

The PR appears safe to merge, with no actionable regression found

What we checked:

  • Caller restrictions stay intact: LensAccessParams contains exactly all_teams, team, and key_hash. The feedback queries still receive all three values

Summary

This PR replaces untyped provider payloads with Pydantic-checked values and narrows annotations across provider transforms, proxy helpers, integrations, and the CLI

  • Adds tests for normal responses, missing fields, malformed payloads, and preserved provider data
  • No actionable regression or confirmed repository-rule violation was found
  • mateo-berri explicitly acknowledges the intentional malformed-search change from HTTP 400 to HTTP 500, changed exception types for malformed provider payloads, and the Python 3.12+ limitation for members supplied through __getattr__. These were not reported as outstanding issues
  • This review checked code and tests; it did not run tests or make live provider requests

Reviews (1) · Last reviewed commit: "Merge remote-tracking branch 'origin/mai..." · Reviewed by Greptile

@codspeed

codspeed Bot commented Oct 8, 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

✅ 31 untouched benchmarks


Comparing litellm_decrease_anys_opus55_1008 (4a227be) with main (fb051f9)

Open in CodSpeed

@codecov

codecov Bot commented Oct 8, 2026 •

Copy link
Copy Markdown

Codecov Report

❌ Patch coverage is 99.41860% with 3 lines in your changes missing coverage. Please review.

Files with missing lines Patch % Lines
litellm/proxy/mcp_tools.py 0.00% 2 Missing ⚠️
litellm/harness/handlers/deepagents_handler.py 0.00% 1 Missing ⚠️

📢 Thoughts on this report? Let us know!

@mateo-berri

Copy link
Copy Markdown
Contributor Author

@litereview code-review

@litereview

litereview Bot commented Oct 13, 2026 •

Copy link
Copy Markdown

⚠️ code-review

Scope: full · Full PR review.

Review incomplete.

BLOCKED · Test evidence: BLOCKED · 3/5

No correctness findings.

The merge is blocked by the required real-testing gate. This PR changes response translation for more than 40 provider transformations under litellm/llms/**, including search, embeddings usage, image generation, TTS, Bedrock Qwen, Replicate, OpenRouter, xAI and Fireworks. The automated coverage consists of unit tests built on hand-written payloads, with no recorded provenance. The live before/after run in the PR description is narrative only. It ran on df7f73f68b, while the reviewed head is 4837f86f, and it covers only 9 provider paths.

Couldn’t complete

  • The required real-testing-evidence check is not_run. Tests for the changed provider response translations use hand-written fixtures with no provenance. The manual live run covers only 9 providers, on commit df7f73f68b instead of the reviewed head 4837f86f, and its output cannot be inspected.
  • Real testing evidence: In scope. The diff changes response translation in many litellm/llms/**/transformation.py files, plus handlers such as replicate/chat/handler.py, vertex_ai/text_to_speech/text_to_speech_handler.py and vertex_ai/vertex_embeddings/embedding_handler.py. The changes affect parsing, usage construction and error types for malformed payloads.

What exists:

  • The PR adds about 74 test modules, for example tests/unit/llms/brave/search/test_brave_search_transformation.py. They call transform_*_response with payloads written inline in the test (httpx.Response(200, json=payload)). Nothing documents a capture source, includes a recorded artifact, or provides a generation script. Under the rule, this counts as unit-level evidence with hand-written fixtures.
  • The PR description includes a manual before/after proxy run against real Tavily, Perplexity (search and embeddings), DuckDuckGo, Anthropic count_tokens, OpenAI input_tokens, Fireworks, Gemini image and Mistral TTS. That run identifies commit df7f73f68b, not the reviewed head 4837f86f. It is a prose summary with no logs or artifacts to inspect. It does not cover Bedrock Qwen2/3, Cohere, Voyage, Infinity, OVHcloud, SambaNova, CometAPI, Vertex image/TTS/embeddings, Replicate, OpenRouter, xAI, AIML, fal_ai, Brave, Exa, Linkup, Firecrawl, fastcrw, Serper, SearchAPI, DataForSEO or Google PSE.

Needed to pass: either replay or integration tests whose fixtures are shown to come from real provider responses for the changed provider paths, or inspectable E2E output from the reviewed head (4837f86f) that covers those providers.

Checks and execution details
  • Not run · Real testing evidence (required): In scope. The diff changes response translation in many litellm/llms/**/transformation.py files, plus handlers such as replicate/chat/handler.py, vertex_ai/text_to_speech/text_to_speech_handler.py and vertex_ai/vertex_embeddings/embedding_handler.py. The changes affect parsing, usage construction and error types for malformed payloads.

What exists:

  • The PR adds about 74 test modules, for example tests/unit/llms/brave/search/test_brave_search_transformation.py. They call transform_*_response with payloads written inline in the test (httpx.Response(200, json=payload)). Nothing documents a capture source, includes a recorded artifact, or provides a generation script. Under the rule, this counts as unit-level evidence with hand-written fixtures.
  • The PR description includes a manual before/after proxy run against real Tavily, Perplexity (search and embeddings), DuckDuckGo, Anthropic count_tokens, OpenAI input_tokens, Fireworks, Gemini image and Mistral TTS. That run identifies commit df7f73f68b, not the reviewed head 4837f86f. It is a prose summary with no logs or artifacts to inspect. It does not cover Bedrock Qwen2/3, Cohere, Voyage, Infinity, OVHcloud, SambaNova, CometAPI, Vertex image/TTS/embeddings, Replicate, OpenRouter, xAI, AIML, fal_ai, Brave, Exa, Linkup, Firecrawl, fastcrw, Serper, SearchAPI, DataForSEO or Google PSE.

Needed to pass: either replay or integration tests whose fixtures are shown to come from real provider responses for the changed provider paths, or inspectable E2E output from the reviewed head (4837f86f) that covers those providers.

  • Passed · Changed test modules (optional): Ran uv run pytest &lt;91 changed test files> -n 8 on the head checkout after uv sync --frozen --group dev --all-extras. Result: 2736 passed, 4 skipped.
  • Passed · Neighbouring suites for touched shared paths (optional): Ran tests/unit/proxy/pass_through_endpoints/{test_llm_pass_through_endpoints,test_pass_through_endpoints}.py, tests/unit/proxy/test_common_request_processing.py, tests/unit/proxy/response_polling, tests/unit/llms/anthropic, tests/unit/llms/vertex_ai/image_generation and tests/unit/llms/gemini. Result: 4726 passed. These suites cover the new _UPSTREAM_RESPONSE runtime-checkable Protocol on the passthrough route and the _StreamsBody check in background streaming.
  • Passed · One-shot pydantic Iterable adapters (optional): TypeAdapter(Iterable[...]) returns a ValidatorIterator that can be consumed only once. I checked every call site in the diff (search providers, Cohere _EMBEDDINGS_BY_TYPE, Fireworks, Lemonade, xAI, Gemini, Replicate, Anthropic files). Each consumes the iterator once, and none calls len() on it or indexes it.
  • Passed · Usage/SearchResult construction equivalence (optional): Ran a reproducer to confirm that Usage.model_validate({...}) still goes through the custom Usage.__init__. Its output matches Usage(...): None becomes 0 and numeric strings are coerced. SearchResult.model_validate keeps the same fields.
  • Passed · Breaking-change marker (optional): The PR states one intentional change: a malformed provider search item now returns HTTP 500 instead of 400. That case is an upstream fault, and no supported API, configuration, default or persisted data changes, so I am not requiring a ! marker.

View review · Reviewed 4837f86f8a9e

@mateo-berri

Copy link
Copy Markdown
Contributor Author

@litereview code-review

@litereview

litereview Bot commented Oct 13, 2026 •

Copy link
Copy Markdown

⚠️ code-review

Scope: full · Full PR review.

Review incomplete.

BLOCKED · Test evidence: BLOCKED · Merge readiness: 3/5

No correctness findings.

Some changed provider response paths have no real-response evidence:

  • Bedrock imported Qwen2 and Qwen3
  • Vertex Imagen image generation and edit
  • fal Bria and Imagen4
  • Infinity and OVHcloud embeddings
  • OpenSandbox
  • Vertex Cloud text to speech

The PR description says these paths have only unit tests. Those tests use hand-written fixtures, so they don't meet the real testing evidence rule for translation changes under litellm/llms/**.

The intended search change works as described. When a provider sends a malformed result item, POST /v1/search/{search_tool_name} now returns 500 instead of 400. The PR description explains this, and the change only affects responses that already failed, so it doesn't need a ! marker.

Couldn’t complete

  • The required real-testing-evidence check is not_run. These changed translation paths need real E2E evidence, or integration tests with fixtures that show where the values came from:

  • bedrock/chat/invoke_transformations/amazon_qwen2_transformation.py and amazon_qwen3_transformation.py

  • vertex_ai/image_generation/vertex_imagen_transformation.py and vertex_ai/image_edit/vertex_imagen_transformation.py

  • fal_ai/image_generation/bria_transformation.py and imagen4_transformation.py

  • infinity/embedding/transformation.py and ovhcloud/embedding/transformation.py

  • opensandbox/sandbox/transformation.py

  • The Vertex Cloud text-to-speech handler

The evidence could be a real provider response captured through the proxy, or a recorded fixture with a documented capture source.

  • Real testing evidence for LLM translation changes: In scope. The PR changes response translation in about 70 files under litellm/llms/**, including search, embeddings, image, TTS, chat and usage parsing.

Evidence that qualifies. The PR includes manual E2E evidence:

  • Before and after proxies ran at fb051f9647 and 4a227be3fb.
  • 37 real requests reached 22 providers.
  • The PR shows status, body shape and the exact curl commands for each request.
  • A SearXNG stand-in served malformed results.
  • Published provider examples were replayed for 14 providers, with a source URL for each. This counts as documented fixture provenance.

What is missing. The PR's Caveats section says these paths have unit tests only: Bedrock imported Qwen2 and Qwen3, Vertex Imagen, fal Bria and Imagen4, Infinity and OVHcloud embeddings, OpenSandbox, Vertex Cloud TTS, and the Vertex fine-tuning pass-through. For the files listed in limitations, I inspected the tests (for example tests/unit/llms/bedrock/chat/invoke_transformations/test_amazon_qwen3_transformation.py and tests/unit/llms/infinity/embedding/test_infinity_embedding_transformation.py). They use hand-written payloads with no documented source. The Qwen tests cover strict generation text and Usage.model_validate, but those are hand-written payloads too.

Unit tests with unsourced fixtures don't satisfy this rule. I didn't count the Vertex fine-tuning pass-through as a gap because it only wraps response.json() in an untyped validation.

  • Real testing evidence: In scope. The PR changes response translation in about 70 files under litellm/llms/**, including search, embeddings, image, TTS, chat and usage parsing.

Evidence that qualifies. The PR includes manual E2E evidence:

  • Before and after proxies ran at fb051f9647 and 4a227be3fb.
  • 37 real requests reached 22 providers.
  • The PR shows status, body shape and the exact curl commands for each request.
  • A SearXNG stand-in served malformed results.
  • Published provider examples were replayed for 14 providers, with a source URL for each. This counts as documented fixture provenance.

What is missing. The PR's Caveats section says these paths have unit tests only: Bedrock imported Qwen2 and Qwen3, Vertex Imagen, fal Bria and Imagen4, Infinity and OVHcloud embeddings, OpenSandbox, Vertex Cloud TTS, and the Vertex fine-tuning pass-through. For the files listed in limitations, I inspected the tests (for example tests/unit/llms/bedrock/chat/invoke_transformations/test_amazon_qwen3_transformation.py and tests/unit/llms/infinity/embedding/test_infinity_embedding_transformation.py). They use hand-written payloads with no documented source. The Qwen tests cover strict generation text and Usage.model_validate, but those are hand-written payloads too.

Unit tests with unsourced fixtures don't satisfy this rule. I didn't count the Vertex fine-tuning pass-through as a gap because it only wraps response.json() in an untyped validation.

Checks and execution details
  • Not run · Real testing evidence for LLM translation changes (required): In scope. The PR changes response translation in about 70 files under litellm/llms/**, including search, embeddings, image, TTS, chat and usage parsing.

Evidence that qualifies. The PR includes manual E2E evidence:

  • Before and after proxies ran at fb051f9647 and 4a227be3fb.
  • 37 real requests reached 22 providers.
  • The PR shows status, body shape and the exact curl commands for each request.
  • A SearXNG stand-in served malformed results.
  • Published provider examples were replayed for 14 providers, with a source URL for each. This counts as documented fixture provenance.

What is missing. The PR's Caveats section says these paths have unit tests only: Bedrock imported Qwen2 and Qwen3, Vertex Imagen, fal Bria and Imagen4, Infinity and OVHcloud embeddings, OpenSandbox, Vertex Cloud TTS, and the Vertex fine-tuning pass-through. For the files listed in limitations, I inspected the tests (for example tests/unit/llms/bedrock/chat/invoke_transformations/test_amazon_qwen3_transformation.py and tests/unit/llms/infinity/embedding/test_infinity_embedding_transformation.py). They use hand-written payloads with no documented source. The Qwen tests cover strict generation text and Usage.model_validate, but those are hand-written payloads too.

Unit tests with unsourced fixtures don't satisfy this rule. I didn't count the Vertex fine-tuning pass-through as a gap because it only wraps response.json() in an untyped validation.

  • Passed · Changed test modules (optional): I installed dependencies with uv sync --frozen --group ci --group proxy-dev --extra google --extra proxy --extra semantic-router --extra caching --extra extra_proxy --extra proxy-runtime --extra utils, then ran prisma generate.

Then I ran every changed test module under tests/ with pytest -n 8. Result: 2736 passed, 4 skipped, 0 failed, in 63s.

  • Passed · Behavior spot checks (optional): I compared Usage.model_validate({...}) with Usage(...) for normal counts and for None counts. Both produce the same model_dump().

_UPSTREAM_RESPONSE.validate_python(httpx.Response(...)) returns the same object it receives, so the passthrough path is unchanged.

Pydantic Iterable[...] adapters return single-pass iterators. Every changed consumer iterates them only once.

  • Passed · Breaking change review (optional): Two error behaviors change:

  • A malformed search result item now returns 500 instead of 400. The old 400 came from an AttributeError being treated as a bad request (common_request_processing.py:3877).

  • Some malformed provider payloads now raise ValidationError instead of AttributeError, TypeError or KeyError.

Both only affect requests that already failed, and the PR description explains them. Successful response shapes, public signatures and config don't change, so the title doesn't need a ! marker.

  • Passed · Standards (AGENTS.md) (optional): The change follows the AGENTS.md rule to validate untyped data with Pydantic TypeAdapter. It adds no new cast, # type: ignore, or suppressions, and it doesn't touch ANY_CAPS.

One judgment call, not a violation: these shared adapters are redefined in many modules, which is possible Duplicated Code.

  • _JSON_OBJECT
  • _JSON_VALUES
  • _INT

View review · Reviewed 4a227be3fbcc

@mateo-berri

Copy link
Copy Markdown
Contributor Author

@litereview code-review

@litereview

litereview Bot commented Oct 13, 2026 •

Copy link
Copy Markdown

✅ code-review

Scope: full · Full PR review.

READY · Test evidence: VERIFIED · Merge readiness: 4/5

No correctness findings.

This PR intentionally changes the response when a search provider returns a malformed result item. POST /v1/search/{search_tool_name} now returns HTTP 500 instead of HTTP 400 for that case. The provider sent the bad data, not the caller, so the error class is now correct. The PR description documents this caveat and its impact. Because the change narrows an error case and does not break a supported contract, it does not need a ! marker in the title.

Checks and execution details
  • Passed · Real testing evidence (required): In scope. About 70 files under litellm/llms/** change how provider responses are parsed. The main change validates search, embedding, image, TTS, chat-completion and model-list payloads with pydantic TypeAdapters, which changes the error type and HTTP status when a payload is malformed.

Manual E2E evidence (PR body). The author ran two proxies with the same config.yaml: one at the merge base fb051f9647 and one at the head 4a227be3fb. The same 44 curl requests went to both. Of those, 39 called 24 real providers, and the head-side workers ran under coverage to show that each changed function executed. Each case lists the endpoint, payload, status and body shape for both sides. Five SearXNG cases used a local stand-in server to produce malformed results. For 17 paths that the author's credentials cannot reach, including Bedrock imported Qwen, Vertex Imagen, fal Bria/Imagen4, brave, cometapi and replicate, the author replayed each provider's published example response through the changed function at both commits. The PR cites the source URLs and gives a retrieval date. That gives the replayed fixtures a traceable origin. Only the Vertex fine-tuning pass-through has unit tests alone, and its change is an identity TypeAdapter(object) with no behavior change.

Automated tests. I ran all 73 test modules this PR adds or modifies against the head checkout:

uv sync --frozen --group dev --group proxy-dev --extra proxy --extra google
.venv/bin/python -m pytest -n 8 <73 PR test modules>

Result: 2736 passed, 4 skipped. This matches the PR's claim of 2,738 passed and 2 skipped within the skip variance.

  • Passed · PR test modules execute against head (optional): Ran 73 modules covering the changed providers, proxy handlers, the CLI and the Google secret manager: 2736 passed, 4 skipped, 105 warnings in 39.65s.
  • Passed · Pass-through upstream protocol validation accepts real httpx responses (optional): I called _UPSTREAM_RESPONSE.validate_python(httpx.Response(...)), which returned the same httpx.Response. A plain dict was rejected with is_instance_of. The runtime-checkable Protocol swap in base_passthrough_process_llm_request therefore keeps the non-streaming path working.
  • Passed · Usage constructor to model_validate equivalence (Bedrock Qwen2/Qwen3) (optional): I compared Usage(prompt_tokens=3, completion_tokens=4, total_tokens=7) with Usage.model_validate({...}). The two model_dump() results were equal. A None count becomes 0 on both paths, so the token-usage translation is unchanged.
  • Passed · Standards / spec review (optional): No linked issue or spec exists, so I treated the PR description as the spec. The diff matches its stated scope: boundary validation with hide_input_in_errors=True, swaps from Any to object, and no new cast or ignore comments. The four new test directories are registered in .github/workflows/test-unit.yml. Possible smell, a judgement call only: the module-level _JSON_OBJECT and _JSON_VALUES adapters are copied into about 40 modules (Duplicated Code). Sharing one module would cut that repetition, but this is not a blocker.

View review · Reviewed 4a227be3fbcc

@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 4a227be. Configure here.

@mateo-berri
mateo-berri enabled auto-merge (squash) October 13, 2026 19:50
@mateo-berri
mateo-berri merged commit 0ebec12 into main Oct 13, 2026
118 of 119 checks passed
@mateo-berri
mateo-berri deleted the litellm_decrease_anys_opus55_1008 branch October 13, 2026 22:35
BeWayllar added a commit to BeWayllar/litellm that referenced this pull request Oct 14, 2026
Resolve the conflict in litellm/llms/openrouter/chat/transformation.py
with upstream BerriAI#45388: keep the validated response mapping and the
isinstance guard on the cost, and read the top-level provider key
directly from the validated body instead of through a cast.

Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
devYRPauli added a commit to devYRPauli/litellm that referenced this pull request Oct 14, 2026
Upstream BerriAI#45388 changes the return type of
encode_character_id_in_response to object. The PR adds the video id
helpers just above that function. The merge keeps the helpers and
takes the new return type.

This branch had an error being deployed

1 failed deployment
e2e-changed — 4a227be3 Deployed Oct 13, 2026 by mateo-berri via oauth #4767
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants