Skip to content

fix(proxy): return 4xx instead of 500 for proxy-side request validation errors - #43918

Closed
devin-ai-integration[bot] wants to merge 1 commit into
mainfrom
litellm_item159_status_codes
Closed

devin-ai-integration[bot] wants to merge 1 commit into
mainfrom
litellm_item159_status_codes

Conversation

@devin-ai-integration

Copy link
Copy Markdown
Contributor

TLDR

Problem this solves:

  • Requests missing a required field got a 500 from the proxy
  • Clients could not tell their own mistakes from real server failures
  • Unknown search tools, bad pagination and bad spend-log dates also returned 500
  • An unknown Responses API id returned 400 where OpenAI returns 404

How it solves it:

  • Extends the proxy's required-body-param check to speech, moderations, images, completions, rerank, search and /v1/messages
  • Proxy endpoint handlers keep the status a ProxyException carries instead of falling back to 500
  • Unknown search tool raises a 400, unroutable response id raises a 404
  • Daily activity pagination and /spend/logs dates are validated up front with a 400

Upstream provider errors already came through with the provider's own status. I checked 400, 401 and 404 across chat, streaming, completions, embeddings, speech, transcription, moderations, images, responses, files, batches and /v1/messages against the direct provider call. This PR only changes errors the proxy raises itself

User Flow

Before: a developer whose app forgets a required field gets a 500, so their retry logic treats it as an outage

  1. They send POST https://litellm-domain/v1/audio/speech with model and voice but no input
  2. The proxy answers 500 with Router.aspeech() missing 1 required positional argument: 'input'
  3. Their client retries the same broken request with backoff, and alerting pages on a "server error"

After: the same request comes back as a client error naming the field

  1. They send the same POST https://litellm-domain/v1/audio/speech without input
  2. The proxy answers 400 with {"type":"invalid_request_error","param":"input"}, the same status OpenAI returns
  3. Their client surfaces the validation error instead of retrying, and no provider call is made

Linear ticket

Resolves LIT-9016

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
  • I have received a Greptile Confidence Score of at least 4/5 before requesting a maintainer review (Greptile reviews automatically once the PR is opened; only comment @greptileai to re-request a review after pushing changes)

Screenshots / Proof of Fix

After was captured on 6593f28fcc, which differs from b88110f only in a suppression comment. A live proxy on localhost:4000 with real OpenAI and Anthropic deployments (gpt-5-mini, gpt-4o-mini-tts, gpt-image-1-mini, claude-opus-4-8), master key sk-item159. Each case was also sent straight to the provider for comparison. The full 54-case matrix is summarized at the end

Before (3930c5b)

Speech missing input

  1. curl -X POST localhost:4000/v1/audio/speech -H "Authorization: Bearer sk-item159" -H "Content-Type: application/json" -d '{"model":"gpt-4o-mini-tts","voice":"alloy","response_format":"mp3"}'
  2. 500 {"error":{"message":"Router.aspeech() missing 1 required positional argument: 'input'","type":"None","param":"None","code":"500"}}, while OpenAI directly returns 400

Image generation missing prompt

  1. curl -X POST localhost:4000/v1/images/generations -H "Authorization: Bearer sk-item159" -H "Content-Type: application/json" -d '{"model":"gpt-image-1-mini","n":1,"size":"1024x1024","quality":"low"}'
  2. 500 {"error":{"message":"Router.aimage_generation() missing 1 required positional argument: 'prompt'","type":"internal_server_error","param":null,"code":"500"}}, while OpenAI directly returns 400

Messages missing max_tokens

  1. curl -X POST localhost:4000/v1/messages -H "Authorization: Bearer sk-item159" -H "Content-Type: application/json" -d '{"model":"claude-opus-4-8","messages":[{"role":"user","content":"hi"}]}'
  2. 500 {"type":"error","error":{"type":"api_error","message":"anthropic_messages() missing 1 required positional argument: 'max_tokens'"}}, while Anthropic directly returns 400

Rerank missing query

  1. curl -X POST localhost:4000/v1/rerank -H "Authorization: Bearer sk-item159" -H "Content-Type: application/json" -d '{"model":"gpt-5-mini"}'
  2. 500 {"error":{"message":"arerank() missing 2 required positional arguments: 'query' and 'documents'","type":"internal_server_error","param":null,"code":"500"}}

Responses GET unknown id

  1. curl localhost:4000/v1/responses/resp_0000000000000000000000000000000000000000000000ab -H "Authorization: Bearer sk-item159"
  2. 400 {"error":{"message":"litellm.BadRequestError: You passed in model=None. There are no healthy deployments for this model","type":"invalid_request_error","param":null,"code":"400"}}, while OpenAI directly returns 404

Spend logs bad date

  1. curl "localhost:4000/spend/logs?start_date=notadate&end_date=alsonot" -H "Authorization: Bearer sk-item159"
  2. 500 {"error":{"message":"/spend/logs Errortime data 'notadate' does not match format '%Y-%m-%d'","type":"internal_error","param":"None","code":"500"}}

Upstream 400 passthrough

  1. curl -X POST localhost:4000/v1/chat/completions -H "Authorization: Bearer sk-item159" -H "Content-Type: application/json" -d '{"model":"gpt-5-mini","messages":[{"role":"user","content":"hi"}],"reasoning_effort":"bogus"}'
  2. 400 {"error":{"message":"litellm.BadRequestError: OpenAIException - Unsupported value: 'reasoning_effort' does not support 'bogus' with this model..., matching OpenAI's 400

After (b88110f)

Speech missing input

  1. Same curl as Before
  2. 400 {"error":{"message":"/audio/speech: Missing required parameter: 'input'.","type":"invalid_request_error","param":"input","code":"400"}}

Image generation missing prompt

  1. Same curl as Before
  2. 400 {"error":{"message":"/images/generations: Missing required parameter: 'prompt'.","type":"invalid_request_error","param":"prompt","code":"400"}}

Messages missing max_tokens

  1. Same curl as Before
  2. 400 {"type":"error","error":{"type":"invalid_request_error","message":"/v1/messages: Missing required parameter: 'max_tokens'."}}

Rerank missing query

  1. Same curl as Before
  2. 400 {"error":{"message":"/rerank: Missing required parameter: 'query'.","type":"invalid_request_error","param":"query","code":"400"}}

Responses GET unknown id

  1. Same curl as Before
  2. 404 {"error":{"message":"litellm.NotFoundError: Response 'resp_0000000000000000000000000000000000000000000000ab' not found. It carries no LiteLLM routing information and no model was provided.","type":"invalid_request_error",...,"code":"404"}}

Spend logs bad date

  1. Same curl as Before
  2. 400 {"error":{"message":"/spend/logs: Invalid start_date 'notadate', expected YYYY-MM-DD","type":"invalid_request_error","param":"start_date","code":"400"}}

Upstream 400 passthrough

  1. Same curl as Before
  2. 400, unchanged, still matching OpenAI

Across the whole matrix, 14 rows changed status and all of them moved from 500 (or the wrong 4xx) to the 4xx the provider returns. These were speech, moderations, image generation and edits, completions, rerank, search, /v1/messages missing messages or max_tokens, daily activity page=0, /spend/logs bad date, and responses GET/DELETE for an unknown id. No other row changed

Type

🐛 Bug Fix
✅ Test

Caveats (if any)

Medium

  • Multipart requests missing the file still get FastAPI's 422, OpenAI uses 400
    • Changing the global validation handler is a wider behavior change, left out on purpose
  • A malformed response id like invalid-response-id-xyz now gets 404, OpenAI returns 400

Low

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

Link to Devin session: https://app.devin.ai/sessions/c431842b4f6d4ccd9daef79826e6e2c7
Open in Devin Desktop: https://app.devin.ai/desktop/session/c431842b4f6d4ccd9daef79826e6e2c7?variant=devin
Requested by: @yucheng-berri

…on errors

Co-authored-by: shivam <shivam@berri.ai>
Co-authored-by: AtsutoNakayama <atsuto010707@gmail.com>
Co-Authored-By: Devin AI <158243242+devin-ai-integration[bot]@users.noreply.github.com>
@devin-ai-integration

Copy link
Copy Markdown
Contributor Author

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

  • Disable automatic comment, CI, and merge conflict monitoring

@greptile-apps

greptile-apps Bot commented Sep 30, 2026 •

Copy link
Copy Markdown
Contributor

RetriggerConfidence Score: 3/5

[Medium risk] Improves HTTP status codes for request validation errors.

The PR should not merge until image edits retain their supported optional-field behavior and proxy-specific error wording is removed from the shared Router.

Findings

  1. P1 Optional image edits rejected ▶
  2. P1 Proxy error added to Router ▶

Summary

The PR adds proxy-side required-field validation and maps several locally generated validation and resource errors to 4xx responses.

  • It also validates daily-activity pagination and spend-log dates, and adds compatibility and unit tests.
  • The image-edit validation conflicts with supported optional fields; response-ID error wording was added to the shared Router.

Reviews (1) · Last reviewed commit: "fix(proxy): return 4xx instead of 500 fo..."

"aspeech": ("input",),
"amoderation": ("input",),
"aimage_generation": ("prompt",),
"aimage_edit": ("image", "prompt"),

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.

P1 Optional image edits rejected The image-edit endpoint allows some Bedrock Stability requests without an image and sets an omitted prompt to None. Requiring both fields here makes those requests return 400 before the model can handle them.

Comment thread litellm/router.py
Comment on lines +7117 to +7123
raise litellm.NotFoundError(
message=(
f"Response '{response_id}' not found. "
"It carries no LiteLLM routing information and no model was provided."
),
model="",
llm_provider="",

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.

P1 Proxy error added to Router This adds a proxy-facing response-ID error message to the shared SDK Router. The repository requires proxy error messages to stay out of router.py because they also affect SDK users.

Rule Used: Don’t add stuff to router.py that is error messages for proxy. This impacts SDK users. (source)

Note: If this suggestion doesn't match your team's coding style, reply to this and let me know. I'll remember it for next time!

@codspeed

codspeed Bot commented Sep 30, 2026

Copy link
Copy Markdown
Contributor

Merging this PR will not alter performance

✅ 31 untouched benchmarks


Comparing litellm_item159_status_codes (b88110f) with main (657bb77)

Open in CodSpeed

@codecov

codecov Bot commented Sep 30, 2026 •

Copy link
Copy Markdown

Codecov Report

❌ Patch coverage is 68.75000% with 5 lines in your changes missing coverage. Please review.

Files with missing lines Patch % Lines
litellm/router.py 0.00% 4 Missing ⚠️
litellm/router_utils/search_api_router.py 50.00% 1 Missing ⚠️

📢 Thoughts on this report? Let us know!

This branch had an error being deployed

1 failed deployment
e2e-changed — b88110f9 Deployed Sep 30, 2026 by devin-ai-integration[bot] via oauth #2076
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.

1 participant