Repository navigation
chore(typing): clear 670 basedpyright Any errors by validating provider payloads at the boundary - #45388
Conversation
…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
|
Merging this PR will not alter performance
|
Codecov Report❌ Patch coverage is
📢 Thoughts on this report? Let us know! |
|
@litereview code-review |
|
…in the providers shard
|
@litereview code-review |
|
|
@litereview code-review |
✅ code-reviewScope: 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. Checks and execution details
Manual E2E evidence (PR body). The author ran two proxies with the same 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.
View review · Reviewed |
|
bugbot run |
There was a problem hiding this comment.
✅ 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.
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>
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.
TLDR
Problem this solves:
How it solves it:
Anyforobjectwhere every caller already compliesIntentional 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 itUser 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
POST https://litellm-domain/v1/search/searxng-searchwith{"query": "capital of France"}and get HTTP 200 with{"object": "search", "results": [...]}invalid_request_error, messageInvalid request format: ... 'str' object has no attribute 'get'followed by a Python tracebackAfter: 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
POST https://litellm-domain/v1/search/searxng-searchwith{"query": "capital of France"}and get HTTP 200 with{"object": "search", "results": [...]}internal_server_error, message... 1 validation error ... Input should be a valid dictionary, with no tracebackPre-Submission checklist
Please complete all items before asking a LiteLLM maintainer to review your PR
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 moreDelays 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 undercoverage, and each case heading names the changed file underlitellm/llms/whose changed function the request ran. The other five requests point asearxngsearch 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 demandSeven 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_urlinput), 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 Imagen4red_square.pngis 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 pasteThe 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 endpointhttps://oai.endpoints.kepler.ai.cloud.ovh.netanswers without an account only when no token is sent, and litellm always sends one, so a small local forwarder passesPOST /v1/embeddingson to OVHcloud with theAuthorizationheader removed and returns OVHcloud's status and body unchangedTwo changed paths have no proxy route, so
sdk_calls.pycalls them from each checkout's own virtualenv. The sandbox API is SDK-only, and it runs against a local OpenSandbox server (opensandbox-serveron Docker,opensandbox/execd:v1.1.0). That server answersRunningon create, so litellm's poll never starts by itself, and the script calls the poll once on the live sandbox between create and delete.VertexTextToSpeechAPIis imported by no other source file, so the script calls its sync and async methods againsttexttospeech.googleapis.com. At the tip both ran undercoverageand the changed lines of all four functions ranThe stand-in answers every
GET /searchwith HTTP 200 and a body chosen by the querymalformed-item-429malformed-itemmalformed-fieldtitleis7no-results-keyresultskeyFor 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 removedA2AConfig.transform_responseAmazonQwen2Config.transform_responseandAmazonQwen3Config.transform_responsegenerationexample with its text and the two OpenAI-shaped ones with empty content and their usageBraveSearchConfig.transform_search_responseCometAPIEmbeddingConfig.transform_embedding_responseDataForSEOSearchConfig.transform_search_responseFalAIBriaConfig.transform_image_generation_responseandFalAIImagen4Config.transform_image_generation_responseFastCRWSearchConfig.transform_search_responseFirecrawlSearchConfig.transform_search_responseGooglePSESearchConfig.transform_search_responseLemonadeChatConfig.get_modelsandget_model_infoLinkupSearchConfig.transform_search_responseOllamaConfig.transform_responseformat=jsonReplicateConfig.transform_responseandhandle_prediction_response_streamingsucceededexample becomes a chat completion, the other 3 raiseReplicateErrorin the transform, and polling yields 3 outputs and 1ReplicateErroron"output": nullSambaNovaEmbeddingConfig.transform_embedding_responseSearchAPIConfig.transform_search_responseSerperSearchConfig.transform_search_responseVertexAIImagenImageGenerationConfig.transform_image_generation_responseandVertexAIImagenImageEditConfig.transform_image_edit_responseBefore (fb051f9)
Lint counts
scripts/type_check_gate.pyfor whole-tree basedpyright,scripts/ruff_strict_gate.py,scripts/type_discipline_gate.py), errors counted per ruleTavily search (
tavily/search)post /v1/search/tavily-search '{"query": "What is the capital of France?", "max_results": 3}'200 application/json, 3850 bytes, results=3 first keys=date,last_updated,snippet,title,url snippet lengths=[1315, 1048, 947]Perplexity search (
perplexity/search)post /v1/search/perplexity-search '{"query": "What is the capital of France?", "max_results": 3}'200 application/json, 1191 bytes, results=3 first keys=date,last_updated,snippet,title,url snippet lengths=[213, 180, 198]DuckDuckGo search (
duckduckgo/search)post /v1/search/duckduckgo-search '{"query": "Eiffel Tower", "max_results": 3}'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)post /v1/search/duckduckgo-search '{"query": "Python (programming language)", "max_results": 3}'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)post /v1/search/exa-search '{"query": "What is the capital of France?", "max_results": 3}'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)post /v1/search/exa-search '{"query": "What is the capital of France?", "max_results": 3, "contents": {"highlights": true}}'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)post /v1/messages/count_tokens '{"model": "claude-haiku", "messages": [{"role": "user", "content": "Hello, how many tokens is this sentence?"}]}'200 application/json, 19 bytes, {"input_tokens": 16}Azure AI Anthropic token count (
azure_ai/anthropic/count_tokens)post /v1/messages/count_tokens '{"model": "azure-claude-haiku", "messages": [{"role": "user", "content": "Hello, how many tokens is this sentence?"}]}'200 application/json, 19 bytes, {"input_tokens": 16}OpenAI input tokens (
openai/responses/count_tokens)post /v1/responses/input_tokens '{"model": "gpt-mini", "input": "Hello, how many tokens is this sentence?"}'200 application/json, 52 bytes, {"object": "response.input_tokens", "input_tokens": 15}Anthropic files list (
anthropic/files)get '/v1/files?target_model_names=claude-haiku'200 application/json, 1732 bytes, data=8 first item keys=bytes,created_at,expires_at,filename,id,object,purpose,status,status_details has_more=FalseAnthropic Messages request served by a Fireworks model (
anthropic/pass_through/adapters)post /v1/messages '{"model": "fireworks-oss", "max_tokens": 200, "messages": '"$PONG"'}'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)post /v1/chat/completions '{"model": "fireworks-oss", "messages": '"$PONG"', "max_tokens": 200, "temperature": 0}'200 application/json, 548 bytes, content='pong' finish_reason=stop usage={"completion_tokens": 33, "prompt_tokens": 79, "total_tokens": 112} model=fireworks-ossBedrock invoke chat completion (
bedrock/chat/invoke_transformations)post /v1/chat/completions '{"model": "bedrock-invoke-haiku", "messages": '"$PONG"', "max_tokens": 20}'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-haikuDatabricks chat completion with cache_control (
databricks/chat)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}'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-haikuOpenRouter chat completion (
openrouter/chat)post /v1/chat/completions '{"model": "openrouter-haiku", "messages": '"$PONG"', "max_tokens": 20}'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-haikuOpenRouter streaming chat completion (
openrouter/chat)post /v1/chat/completions '{"model": "openrouter-haiku", "messages": '"$PONG"', "max_tokens": 20, "stream": true}'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)post /v1/chat/completions '{"model": "oci-gemini-flash-lite", "messages": '"$PONG"', "max_tokens": 200, "stream": true}'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)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}'200 application/json, 308 bytes, content='{"answer": "pong"}' finish_reason=stop usage={"completion_tokens": 17, "prompt_tokens": 33, "total_tokens": 50} model=ollama-cloudPerplexity chat completion (
perplexity/chat)EXPERIMENTAL_OPENAI_BASE_LLM_HTTP_HANDLER=true, since Perplexity chat only goes through its own response transformation on that routepost /v1/chat/completions '{"model": "perplexity-sonar", "messages": [{"role": "user", "content": "What is the capital of France? Answer in one word."}], "max_tokens": 20}'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-sonarxAI and Fireworks model discovery (
xai/common_utils.py,fireworks_ai/chat)get /v1/models200 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_byPerplexity embeddings (
perplexity/embedding)post /v1/embeddings '{"model": "perplexity-embed", "input": ["hello world", "second input"]}'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)post /v1/embeddings '{"model": "cohere-embed", "input": ["hello world", "second input"]}'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)post /v1/embeddings '{"model": "cohere-embed", "input": ["hello world", "second input"], "embedding_types": ["float", "int8"]}'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)post /v1/embeddings '{"model": "dashscope-embed", "input": ["hello world", "second input"]}'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)post /v1/embeddings '{"model": "vertex-embed", "input": ["hello world", "second input"]}'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)post /v1/embeddings '{"model": "voyage-lite", "input": ["hello world", "second input"]}'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)post /v1/embeddings '{"model": "voyage-context", "input": ["hello world", "second input"]}'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)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')"'"}]}]}'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)post /v1/embeddings '{"model": "infinity-embed", "input": ["hello world", "second text"]}'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)post /v1/embeddings '{"model": "ovhcloud-embed", "input": ["hello world", "second text"]}'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)post /v1/images/generations '{"model": "gemini-image", "prompt": "A plain red circle on a white background", "n": 1}'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)post /v1/images/generations '{"model": "vertex-gemini-image", "prompt": "A plain red circle on a white background", "n": 1}'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)post /v1/images/generations '{"model": "aiml-flux-schnell", "prompt": "A plain red circle on a white background", "n": 1}'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)post /v1/images/generations '{"model": "fal-gpt-image-2", "prompt": "A plain red circle on a white background", "n": 1, "quality": "low", "size": "1024x768"}'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)post_form /v1/images/edits model=fal-nano-banana-edit "prompt=Make the red square blue" "image=@red_square.png;type=image/png"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)post_form /v1/images/edits model=azure-flux2 "prompt=Make the red square blue" "image=@red_square.png;type=image/png"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)post /v1/audio/speech '{"model": "mistral-tts", "input": "Hello from the gateway.", "voice": "alloy"}'200 audio/mpeg, 11236 bytes, binary audio (mp3 magic)Vertex AI Lyria audio over predict (
vertex_ai/text_to_speech)post /v1/audio/speech '{"model": "vertex-lyria-002", "input": "A calm solo piano melody", "voice": "alloy"}'200 audio/wav, 6291544 bytes, binary audio (wav magic)Vertex AI Lyria audio over interactions (
vertex_ai/text_to_speech)post /v1/audio/speech '{"model": "vertex-lyria-3-clip", "input": "A calm solo piano melody", "voice": "alloy"}'200 audio/mpeg, 712394 bytes, binary audio (mp3 magic)OpenSandbox create, poll and delete (
opensandbox/sandbox).venv/bin/python sdk_calls.py, which callslitellm.sandbox.main.acreate_sandbox(provider="opensandbox", template="python:3.12-alpine", entrypoint=["tail", "-f", "/dev/null"]), then the provider config's_wait_until_runningonce, thenadelete_sandboxContainerHandlewhose id is a UUID and whose exec endpoint is127.0.0.1:<port>/proxy/<port>, the poll returns once the server reportsRunning, and the delete returnsTrueGoogle Cloud Text-to-Speech handler (
vertex_ai/text_to_speech/text_to_speech_handler.py).venv/bin/python sdk_calls.py, which callsVertexTextToSpeechAPI().audio_speech(...)andasync_audio_speech(...)with inputHello from the LiteLLM proxyand voiceen-US-Standard-CHttpxBinaryResponseContentholding 126116 bytes that start withRIFFSearch provider returns well-formed results (
searxng/search)post /v1/search/searxng-search '{"query": "capital of France"}'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)post /v1/search/searxng-search '{"query": "no-results-key"}'200 application/json, 32 bytes, results=0 first keys= snippet lengths=[]Search provider returns a malformed result item (
searxng/search)post /v1/search/searxng-search '{"query": "malformed-item"}'400 application/json, typeinvalid_request_error, messageInvalid request format: litellm.APIConnectionError: 'str' object has no attribute 'get', followed by the Python tracebackpost /v1/search/searxng-search '{"query": "malformed-item-429"}'400 application/json, the same body as step 2 byte for byteSearch provider returns a wrong-typed field (
searxng/search)post /v1/search/searxng-search '{"query": "malformed-field"}'500 application/json, typeinternal_server_error, messagelitellm.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_typeDocumented provider responses
.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 itAfter (4a227be)
Lint counts
scripts/type_check_gate.pyfor whole-tree basedpyright,scripts/ruff_strict_gate.py,scripts/type_discipline_gate.py), errors counted per rulemake checkprintsOK: every basedpyright rule is within its ceiling (111586 errors total, base fb051f9647b6)and ends withcheck: PASSTavily search (
tavily/search)post /v1/search/tavily-search '{"query": "What is the capital of France?", "max_results": 3}'200 application/json, 4356 bytes, results=3 first keys=date,last_updated,snippet,title,url snippet lengths=[1315, 1048, 1453]Perplexity search (
perplexity/search)post /v1/search/perplexity-search '{"query": "What is the capital of France?", "max_results": 3}'200 application/json, the same body as Before byte for byteDuckDuckGo search (
duckduckgo/search)post /v1/search/duckduckgo-search '{"query": "Eiffel Tower", "max_results": 3}'200 application/json, the same body as Before byte for byteDuckDuckGo search with an abstract (
duckduckgo/search)post /v1/search/duckduckgo-search '{"query": "Python (programming language)", "max_results": 3}'200 application/json, the same body as Before byte for byteExa search (
exa_ai/search)post /v1/search/exa-search '{"query": "What is the capital of France?", "max_results": 3}'200 application/json, the same body as Before byte for byteExa search with highlights (
exa_ai/search)post /v1/search/exa-search '{"query": "What is the capital of France?", "max_results": 3, "contents": {"highlights": true}}'200 application/json, the same body as Before byte for byteAnthropic token count (
anthropic/count_tokens)post /v1/messages/count_tokens '{"model": "claude-haiku", "messages": [{"role": "user", "content": "Hello, how many tokens is this sentence?"}]}'200 application/json, the same body as Before byte for byteAzure AI Anthropic token count (
azure_ai/anthropic/count_tokens)post /v1/messages/count_tokens '{"model": "azure-claude-haiku", "messages": [{"role": "user", "content": "Hello, how many tokens is this sentence?"}]}'200 application/json, the same body as Before byte for byteOpenAI input tokens (
openai/responses/count_tokens)post /v1/responses/input_tokens '{"model": "gpt-mini", "input": "Hello, how many tokens is this sentence?"}'200 application/json, the same body as Before byte for byteAnthropic files list (
anthropic/files)get '/v1/files?target_model_names=claude-haiku'200 application/json, the same body as Before byte for byteAnthropic Messages request served by a Fireworks model (
anthropic/pass_through/adapters)post /v1/messages '{"model": "fireworks-oss", "max_tokens": 200, "messages": '"$PONG"'}'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)post /v1/chat/completions '{"model": "fireworks-oss", "messages": '"$PONG"', "max_tokens": 200, "temperature": 0}'200 application/json, 549 bytes, content='pong' finish_reason=stop usage={"completion_tokens": 33, "prompt_tokens": 79, "total_tokens": 112} model=fireworks-ossBedrock invoke chat completion (
bedrock/chat/invoke_transformations)post /v1/chat/completions '{"model": "bedrock-invoke-haiku", "messages": '"$PONG"', "max_tokens": 20}'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-haikuDatabricks chat completion with cache_control (
databricks/chat)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}'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-haikuOpenRouter chat completion (
openrouter/chat)post /v1/chat/completions '{"model": "openrouter-haiku", "messages": '"$PONG"', "max_tokens": 20}'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-haikuOpenRouter streaming chat completion (
openrouter/chat)post /v1/chat/completions '{"model": "openrouter-haiku", "messages": '"$PONG"', "max_tokens": 20, "stream": true}'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)post /v1/chat/completions '{"model": "oci-gemini-flash-lite", "messages": '"$PONG"', "max_tokens": 200, "stream": true}'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)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}'200 application/json, 308 bytes, content='{"answer": "pong"}' finish_reason=stop usage={"completion_tokens": 17, "prompt_tokens": 33, "total_tokens": 50} model=ollama-cloudPerplexity chat completion (
perplexity/chat)EXPERIMENTAL_OPENAI_BASE_LLM_HTTP_HANDLER=true, since Perplexity chat only goes through its own response transformation on that routepost /v1/chat/completions '{"model": "perplexity-sonar", "messages": [{"role": "user", "content": "What is the capital of France? Answer in one word."}], "max_tokens": 20}'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-sonarxAI and Fireworks model discovery (
xai/common_utils.py,fireworks_ai/chat)get /v1/models200 application/json, the same body as Before byte for bytePerplexity embeddings (
perplexity/embedding)post /v1/embeddings '{"model": "perplexity-embed", "input": ["hello world", "second input"]}'200 application/json, the same body as Before byte for byteCohere embeddings (
cohere/embed)post /v1/embeddings '{"model": "cohere-embed", "input": ["hello world", "second input"]}'200 application/json, the same body as Before byte for byteCohere embeddings with two embedding types (
cohere/embed)post /v1/embeddings '{"model": "cohere-embed", "input": ["hello world", "second input"], "embedding_types": ["float", "int8"]}'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)post /v1/embeddings '{"model": "dashscope-embed", "input": ["hello world", "second input"]}'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)post /v1/embeddings '{"model": "vertex-embed", "input": ["hello world", "second input"]}'200 application/json, the same body as Before byte for byteVoyage embeddings (
voyage/embedding/transformation.py)post /v1/embeddings '{"model": "voyage-lite", "input": ["hello world", "second input"]}'200 application/json, the same body as Before byte for byteVoyage contextual embeddings (
voyage/embedding/transformation_contextual.py)post /v1/embeddings '{"model": "voyage-context", "input": ["hello world", "second input"]}'200 application/json, the same body as Before byte for byteVoyage multimodal embeddings (
voyage/embedding/transformation_multimodal.py)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')"'"}]}]}'200 application/json, the same body as Before byte for byteInfinity embeddings (
infinity/embedding)post /v1/embeddings '{"model": "infinity-embed", "input": ["hello world", "second text"]}'200 application/json, the same body as Before byte for byteOVHcloud embeddings (
ovhcloud/embedding)post /v1/embeddings '{"model": "ovhcloud-embed", "input": ["hello world", "second text"]}'200 application/json, the same body as Before byte for byteGemini image generation (
gemini/image_generation)post /v1/images/generations '{"model": "gemini-image", "prompt": "A plain red circle on a white background", "n": 1}'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)post /v1/images/generations '{"model": "vertex-gemini-image", "prompt": "A plain red circle on a white background", "n": 1}'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)post /v1/images/generations '{"model": "aiml-flux-schnell", "prompt": "A plain red circle on a white background", "n": 1}'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)post /v1/images/generations '{"model": "fal-gpt-image-2", "prompt": "A plain red circle on a white background", "n": 1, "quality": "low", "size": "1024x768"}'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)post_form /v1/images/edits model=fal-nano-banana-edit "prompt=Make the red square blue" "image=@red_square.png;type=image/png"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)post_form /v1/images/edits model=azure-flux2 "prompt=Make the red square blue" "image=@red_square.png;type=image/png"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)post /v1/audio/speech '{"model": "mistral-tts", "input": "Hello from the gateway.", "voice": "alloy"}'200 audio/mpeg, 9158 bytes, binary audio (mp3 magic)Vertex AI Lyria audio over predict (
vertex_ai/text_to_speech)post /v1/audio/speech '{"model": "vertex-lyria-002", "input": "A calm solo piano melody", "voice": "alloy"}'200 audio/wav, 6291544 bytes, binary audio (wav magic)Vertex AI Lyria audio over interactions (
vertex_ai/text_to_speech)post /v1/audio/speech '{"model": "vertex-lyria-3-clip", "input": "A calm solo piano melody", "voice": "alloy"}'200 audio/mpeg, 746248 bytes, binary audio (mp3 magic)OpenSandbox create, poll and delete (
opensandbox/sandbox).venv/bin/python sdk_calls.py, which callslitellm.sandbox.main.acreate_sandbox(provider="opensandbox", template="python:3.12-alpine", entrypoint=["tail", "-f", "/dev/null"]), then the provider config's_wait_until_runningonce, thenadelete_sandboxGoogle Cloud Text-to-Speech handler (
vertex_ai/text_to_speech/text_to_speech_handler.py).venv/bin/python sdk_calls.py, which callsVertexTextToSpeechAPI().audio_speech(...)andasync_audio_speech(...)with inputHello from the LiteLLM proxyand voiceen-US-Standard-CSearch provider returns well-formed results (
searxng/search)post /v1/search/searxng-search '{"query": "capital of France"}'200 application/json, the same body as Before byte for byteSearch provider returns no results key (
searxng/search)post /v1/search/searxng-search '{"query": "no-results-key"}'200 application/json, the same body as Before byte for byteSearch provider returns a malformed result item (
searxng/search)post /v1/search/searxng-search '{"query": "malformed-item"}'500 application/json, typeinternal_server_error, messagelitellm.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_typepost /v1/search/searxng-search '{"query": "malformed-item-429"}'500 application/json, the same body as step 2 byte for byteSearch provider returns a wrong-typed field (
searxng/search)post /v1/search/searxng-search '{"query": "malformed-field"}'500 application/json, the same body as Before byte for byteDocumented provider responses
.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 itType
🧹 Refactoring
Changes
The diff touches 126 source files (+901, -463) and 73 test modules plus 18 package
__init__.pyfiles (+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 hiddenThree 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 pydanticTypeAdapteror an existing response model exactly once, and everything after that point is typed. Validation is per item and built withhide_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 annotatedAnyalthough every caller already passes something narrower, the annotation becomesobjector the real type, with each caller checked. And where a value was only ever read through one or two attributes, a smallProtocolor single-keyTypedDictview describes that readThe 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,TypeIsor newcast()was added. Two existing casts in the Databricks chat transformation changed their target fromdict[str, Any]todict[str, object].ANY_CAPSis untouched, since the repo lowers it only in its own PRWith
mainmerged in at fb051f9, the branch's 73 test modules give 2,738 passed and 2 skippedFour of the test directories are new (brave, google_pse, nlp_cloud and opensandbox), so
.github/workflows/test-unit.ymlnow lists them in thellms-providersunit shard. Without those four lines the required lint job fails because no shard would run themCaveats (if any)
Low
ValidationError, notAttributeError,TypeErrororKeyErrorValidationErroron a non-objectmessageExceptionAnytoobject, static onlyProtocols__getattr__Final Attestation
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 broadAnyannotations withobject,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-typeheaders before choosing JSON vs SSE;VantageLoggertypes its pod lock manager separately fromFocusLogger; CI adds unit-test shard entries forbrave,google_pse,nlp_cloud, andopensandbox.Reviewed by Cursor Bugbot for commit 4a227be. Bugbot is set up for automated code reviews on this repo. Configure here.