Repository navigation
refactor(typing): clear 1146 basedpyright Any errors across 365 files - #52768
Conversation
…ing and provider handlers
…t and single-Any modules
…es and proxy endpoints
…ometheus, gigachat and http handler
…and passthrough paths
…nd management paths
…, cache and provider paths
…d route request pass
[High impact] The latest changes appear safe to merge and fully address the previous finding.
|
Codecov Report✅ All modified and coverable lines are covered by tests. 📢 Thoughts on this report? Let us know! |
The Anthropic chat transform now rejects a decoded body that is not a JSON object. Four tests mocked the HTTP client with a bare MagicMock, whose json() is never a real decoded response, so they now return a real Anthropic message.
The wave 14 pass dropped the now-unused FileTypes import, which also removed the litellm.utils.FileTypes attribute SDK users could import. Re-export it as a TypeAlias the same way TextChoices is.
…20261117 # Conflicts: # litellm/litellm_core_utils/llm_response_utils/response_metadata.py # litellm/llms/bedrock/claude_platform/messages_transformation.py # litellm/llms/gemini/files/transformation.py # litellm/llms/vertex_ai/gemini_embeddings/batch_embed_content_handler.py # litellm/proxy/db/budget_window_spend_writer.py # litellm/proxy/mcp_server/operations.py # litellm/proxy/pass_through_endpoints/success_handler.py # litellm/responses/litellm_completion_transformation/transformation.py # litellm/responses/streaming_iterator.py
…20261117 # Conflicts: # litellm/proxy/db/check_migration.py
…20261117 # Conflicts: # litellm/llms/anthropic/chat/handler.py # litellm/llms/openai/responses/transformation.py # litellm/proxy/auth/host/python.py # litellm/proxy/common_utils/reset_budget_job.py # litellm/proxy/guardrails/guardrail_hooks/bedrock_guardrails.py # litellm/repositories/table_repositories.py # litellm/responses/streaming_iterator.py
Co-Authored-By: Devin AI <158243242+devin-ai-integration[bot]@users.noreply.github.com>
…3.10 Co-Authored-By: Devin AI <158243242+devin-ai-integration[bot]@users.noreply.github.com>
|
bugbot run |
Bugbot is paused — your team has an unpaid invoiceBugbot is paused because your team has an unpaid invoice. Pay it from the billing page in the Cursor dashboard and Bugbot resumes automatically. (requestId: 02e70ae9-5462-4e77-8251-f09aee824eb2) |
…20261117 Co-Authored-By: Devin AI <158243242+devin-ai-integration[bot]@users.noreply.github.com>
…20261117 Co-Authored-By: Devin AI <158243242+devin-ai-integration[bot]@users.noreply.github.com>
Co-Authored-By: Devin AI <158243242+devin-ai-integration[bot]@users.noreply.github.com>
|
bugbot run |
There was a problem hiding this comment.
Cursor Bugbot has reviewed your changes using high effort and found 1 potential issue.
❌ Bugbot Autofix is OFF. To automatically fix reported issues with cloud agents, enable autofix in the Cursor dashboard.
Want reviews to match your repository better? Bugbot Learning can learn team-specific rules from PR activity. A team admin can enable Learning in the Cursor dashboard.
Reviewed by Cursor Bugbot for commit c8526e8. Configure here.
| list: A list of completion results. | ||
| """ | ||
| args: Final = locals() | ||
| args: Final = MappingProxyType[str, object](locals()) |
There was a problem hiding this comment.
batch_completion crashes on MappingProxyType subscript
High Severity
batch_completion now builds args with MappingProxyType[str, object](locals()). types.MappingProxyType is not a PEP 585 generic, so that subscript raises TypeError at runtime on supported Python 3.10–3.13 before any completions run.
Reviewed by Cursor Bugbot for commit c8526e8. Configure here.
There was a problem hiding this comment.
Not a bug: types.MappingProxyType has been subscriptable since Python 3.9, and this exact line returns the mapping on 3.10.12 and 3.12.16 when run
Upstream's BerriAI#52768 typing-cleanup refactor collapsed the typing import line in two fork-diverged files, dropping Any while it stayed in live use: google_genai/adapters/transformation.py's _is_terminal_sse_chunk and success_handler.py's _coerce_token_count/extract_generic_usage. Caught by the lint job's ruff F821 sweep.
…#53430) #50768 annotated two cold storage helpers with "SpendLogsPayload" after #52768 had dropped that import, so ruff fails with F821 on main and on every PR. The helpers only read the spend log with .get() and their caller passes a Mapping[str, object], so they take that type instead of the TypedDict.


Handwritten 1-3 sentence description
This clears 1,118 loosely typed spots across 429 files so the type checker can catch real bugs there. Requests, responses, errors and spend tracking behave the same as on main
Details
Link to Devin session: https://app.devin.ai/sessions/3242d590986444e499b3a5b6958207b4
Open in Devin Desktop: https://app.devin.ai/desktop/session/3242d590986444e499b3a5b6958207b4?variant=devin
Requested by: @mateo-berri
TLDR
Problem this solves:
How it solves it:
User Flow
Before: the flow succeeds, and every request and its spend tracking behave as they do today
POST https://litellm-domain/v1/chat/completionswith{"model": "gpt-4o", "messages": [{"role": "user", "content": "hi"}]}200 OKwith achat.completionwhoseidlooks likechatcmpl-...and token counts inusageGET https://litellm-domain/key/info?key=sk-...shows the key'sspendwent up by that request's costAfter: the same flow succeeds the same way, with nothing the user can see changed
POST https://litellm-domain/v1/chat/completionswith{"model": "gpt-4o", "messages": [{"role": "user", "content": "hi"}]}200 OKwith achat.completionwhoseidlooks likechatcmpl-...and token counts inusageGET https://litellm-domain/key/info?key=sk-...shows the key'sspendwent up by that request's costPre-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
Measured on the whole tree at 4e3875d against main at 5669abf with the type gate's own basedpyright run (
litellm/scripts/type_check_gate.py). 7ad9fab after it only edits one test file, 21a528c only merges main, and c8526e8 marks three TypedDict fieldsReadOnly, a typing-only change.make checkpasses at c8526e8Tests. The new core_helpers tests compare each typed wrapper's result and error with the builtin it wraps, for ints, floats, strings, mappings, a
UserStringand an object whose__getattr__answers every name.tests/unit/litellm_core_utils/test_core_helpers.pypasses at c8526e8 (274 tests), and the suites are left to CI. 7ad9fab swapsoperator.call, which needs Python 3.11, for a local helper so the file still collects on Python 3.10Merge with main. 21a528c merges main at 0cfb2c3. Across the merges five files conflicted. The budget reset job and the budget endpoints take main's new typed raw-query code, the Cisco guardrail keeps both import lines and main's
request_datatype, the key endpoints keep both import lines, and the table repositories take main's file withprisma_clienttypedobjectRecursion check. Six narrowing helpers called themselves after the builtin call that raises, so an attribute that answers only every other lookup recursed until
RecursionError. They now raise the builtin's exception type instead, and a new test covers that case. The oldrequire_attributesat e44098a raisesRecursionErrorafter 1,992 lookups on that objectCI. At 7ad9fab the required
smoke passed,cost-map-guard,spend-logs-guardandzizmorwere green, whilelint passedandunit passedwere red only through four failures main had too. Those are fixed on main by #53237, #53287, #53289 and #53295, and 21a528c merges them in. The six helpers this PR had tripped the recursion detector with are fixed in 4e3875dLive A/B (/live-pr-risk). Two real proxies, base at 17fb98f and head at 53655d0, ran the same 50 scenarios in the same order. Each had 2 workers, its own Postgres, one Redis for router state and
coordination_redis, and a mitm recorder in front of the real upstreams. Upstreams were OpenAI, Anthropic, Gemini, Vertex AI, xAI, Cohere, Langfuse, AWS Bedrock chat and guardrails, Azure AI Foundry and a local MCP server (A/B files). Head ran 53655d0's tree before onereturninlitellm/utils.pymoved into anelseblock for ruff.Last updated: c8526e8. QA ran on 53655d0. Changes since QA: that ruff-only move, five merges of main, 4e3875d (the six helpers raise where they used to call themselves, a line no builtin lets them reach) 7ad9fab (one test file) and c8526e8 (three TypedDict fields marked
ReadOnly, which no runtime code reads). Proof remains valid because this PR's own diff against main changed only in the helpers' fall-through lines, which no request reaches, and in tests. Verification: the tip check below and the core_helpers testsEvery request litellm sent upstream matched base after scrubbing ids and timestamps, with the same host, path, status and body the same number of times. The only body differences are values the run made itself, the MP3 the speech step returned and then uploaded for transcription, and the signed JWT in the Vertex AI token exchange. Bedrock and Azure chat, streaming, Responses and embeddings returned the same results, and both Bedrock guardrail modes blocked the same prompts and replies with the same 400
Every differing result traces to per-run values, the upstream or timing. Key suffixes in error text differ per run, Gemini answered two byte-identical requests differently, one team spend read ran before the batch write landed, and call types reached the spend log in a different order. Base has one more Azure chat row because its recorder missed a streaming call, which was run again to record its body. Container create and retrieve share one request id, so they race for one spend row. Base kept retrieve and head kept create here, and two earlier runs today kept the same one on both sides, so that race is on main
Commands
Tip check. Two real proxies, base at 5669abf (the merge base) and head at 4e3875d, each with 2 workers and its own Postgres, ran the User Flow and nine neighbours against OpenAI and Anthropic. Every case answered the same on both sides. The streamed reply had 5 or 6
data:lines on either side across reruns, since the model answeredOkorOk.chat.completion, usage[DONE]/v1/messageson Claudemessage, usagepermission_errorkey_model_access_deniedmax_tokens: -1invalid_request_error/key/updatebudget and tpm/team/new/key/infospend/spend/logsrowsTip check commands and output
Head at 4e3875d
Base at 5669abf
Risk report
Breaking. None observed. No scenario answered differently on head except where the upstream itself answered differently to the same request
Backward incompatible. None known. Errors come from the same builtins main calls, with the same types and messages, and the client SDK keeps main's return types
Regression risk. Changed code this run could not reach live: SageMaker, the S3 cache and vector stores, guardrails other than Bedrock and the content filter, integrations other than Langfuse and OTel, and the long-tail providers. CI's unit suites are their only coverage
Type
🧹 Refactoring
Caveats (if any)
Low
TypeAdapter(object), about 0.7µs per calltest_spend_counter_batch_ledger.pyreports Redis calls out of order about 1 run in 48, on main tooFinal Attestation
Note
Low Risk
Refactor is annotation and validation-wrapping only; live A/B and tip checks reported identical API behavior, with main risk being a missed edge case in new narrowing helpers rather than intentional logic changes.
Overview
This is a codebase-wide static typing cleanup aimed at clearing ~1,100+
basedpyrightAnyviolations across hundreds of files, without changing intended runtime behavior.The main mechanical changes are: replacing loose
Anyannotations withobject,Mapping[str, object], Protocols, and TypedDicts; routing untyped JSON and lazy-loaded attributes throughpydantic.TypeAdapter(object)validation at boundaries (caching, A2A, containers, streaming bridges, etc.); and narrowing dynamic values via shared helpers (require_attributes,subscript,as_object_list,json_contains,float_of, and similar) instead of unchecked dict access. Touches span A2A/bedrock bridges, batch/cache layers, responses↔chat transformation, containers, harness/deepagents, integrations (Slack, ClickHouse, prompts), and proxy enterprise endpoints.litellm/__init__.pyalso tightens a few module globals (audit_log_callbacks,secret_manager_client) and addsglobal_prompt_directory.Custom logger hook signatures now use
object/AsyncGenerator[object, None]instead ofAny/ModelResponseStream, which is typing-only for callers.Reviewed by Cursor Bugbot for commit c8526e8. Bugbot is set up for automated code reviews on this repo. Configure here.