Skip to content

fix(health): send max_output_tokens on the responses health probe - #52436

Open
narmstrong-berri wants to merge 1 commit into
mainfrom
nate_fix_responses_health_max_output_tokens
Open

narmstrong-berri wants to merge 1 commit into
mainfrom
nate_fix_responses_health_max_output_tokens

Conversation

@narmstrong-berri

@narmstrong-berri narmstrong-berri commented Nov 18, 2026 •

Copy link
Copy Markdown
Contributor

Handwritten 1-3 sentence description

Add max_output_tokens to responses health checks

Details

TLDR

Problem this solves:

  • The /health probe for a Responses deployment is unbounded
  • Its max_tokens cap is dropped before reaching the provider

How it solves it:

  • Map max_tokens to max_output_tokens for the Responses probe
  • An explicit max_output_tokens on the deployment still wins

User Flow

Before: an admin health checking a Responses API deployment pays for an uncapped answer on every probe

  1. The admin configures a deployment with model_info.mode: responses
  2. They call GET https://litellm-domain/health
  3. The provider receives POST /v1/responses with only model and input, so the reply length is unbounded

After: the same probe is capped

  1. The admin configures the same deployment
  2. They call GET https://litellm-domain/health
  3. The provider receives POST /v1/responses with max_output_tokens set from the health check token cap

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

Live proxy proof

No OpenAI credentials exist in this environment, so two openai/ deployments point their api_base at a local stub that serves the OpenAI /v1/responses route and records each request body. Both set model_info.mode: responses and model_info.health_check_max_tokens: 37, which is the cap _resolve_health_check_max_tokens reads, and responses-probe-null also sets max_output_tokens: null in its litellm_params. The client calls GET /health?model=<name> with the master key for each one

Before is 532df6ef85655e56d82e334e1ab071c5c7fc29e9 (parent of the fix commit) and after is 4d963742b4df41c3ba55ea29d81839be847c00a2 (branch tip of nate_fix_responses_health_max_output_tokens). The same proxy command, config, Redis, and stub were used for both

Proxy command, run from the repo root of each checkout (run_proxy.sh)

#!/bin/bash
# usage: run_proxy.sh <label>
cd <checkout>
export PYTHONPATH=<checkout> LITELLM_MASTER_KEY=<random sk- key> GROQ_API_KEY=stub-not-a-real-key AZURE_AI_API_KEY=stub-not-a-real-key OPENAI_API_KEY=stub-not-a-real-key
exec python litellm/proxy/proxy_cli.py --config config.yaml --port 4201 --num_workers 2 --detailed_debug --reload --use_v2_migration_resolver

A dedicated Redis on 6402 (redis-server --port 6402 --save '' --appendonly no) backs router_settings and general_settings.coordination_redis. The two workers were confirmed in each run by two Started server process lines, and no checkout printed that the workers flag is ignored with reload. The master key is a random sk- value exported as LITELLM_MASTER_KEY (the proxy refuses the well known sk-1234). The provider keys are placeholder strings since the deployments point at the local stub

Proxy config (one config shared by the three proofs)
model_list:
  - model_name: groq-stub
    litellm_params:
      model: groq/llama-3.3-70b-versatile
      api_base: http://127.0.0.1:4251/openai/v1
      api_key: os.environ/GROQ_API_KEY
  - model_name: foundry-embed
    litellm_params:
      model: azure_ai/embed-v-4-0
      api_base: http://127.0.0.1:4251/models
      api_key: os.environ/AZURE_AI_API_KEY
    model_info:
      mode: embedding
  - model_name: responses-probe
    litellm_params:
      model: openai/probe-model
      api_base: http://127.0.0.1:4251/v1
      api_key: os.environ/OPENAI_API_KEY
    model_info:
      mode: responses
      health_check_max_tokens: 37
  - model_name: responses-probe-null
    litellm_params:
      model: openai/probe-model-null
      api_base: http://127.0.0.1:4251/v1
      api_key: os.environ/OPENAI_API_KEY
      max_output_tokens: null
    model_info:
      mode: responses
      health_check_max_tokens: 37

general_settings:
  master_key: os.environ/LITELLM_MASTER_KEY
  coordination_redis:
    host: 127.0.0.1
    port: 6402

router_settings:
  redis_host: 127.0.0.1
  redis_port: 6402
Stub (stub.py, run as python stub.py 4251, prints every request it receives)
"""Local provider stub. Usage: python stub.py <port>. Records every request body to stdout."""
import json
import sys
from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer


def groq_chat(body):
    # Groq-shaped chat completion with service_tier omitted
    return {
        "id": "chatcmpl-stub-1",
        "object": "chat.completion",
        "created": 1763438400,
        "model": body.get("model"),
        "choices": [{"index": 0, "message": {"role": "assistant", "content": "hello from the groq stub"}, "finish_reason": "stop"}],
        "usage": {"prompt_tokens": 9, "completion_tokens": 5, "total_tokens": 14},
        "x_groq": {"id": "req_stub"},
    }


def foundry_text(body):
    inputs = body["input"] if isinstance(body["input"], list) else [body["input"]]
    return {
        "object": "list",
        "data": [{"object": "embedding", "embedding": [0.1 + i, 0.2 + i], "index": i} for i in range(len(inputs))],
        "model": body.get("model", "embed-v-4-0"),
        "usage": {"prompt_tokens": len(inputs), "total_tokens": len(inputs)},
    }


def foundry_image(body):
    inputs = body["input"]
    return {
        "data": [{"object": "embedding", "embedding": [0.9, 0.9], "index": i} for i in range(len(inputs))],
        "model": body.get("model", "embed-v-4-0"),
        "usage": {"prompt_tokens": len(inputs), "total_tokens": len(inputs)},
    }


def responses(body):
    return {
        "id": "resp_stub_1",
        "object": "response",
        "created_at": 1763438400,
        "status": "completed",
        "model": body.get("model"),
        "output": [{"type": "message", "id": "msg_stub_1", "status": "completed", "role": "assistant",
                    "content": [{"type": "output_text", "text": "ok", "annotations": []}]}],
        "usage": {"input_tokens": 5, "output_tokens": 1, "total_tokens": 6},
    }


ROUTES = {
    "/openai/v1/chat/completions": groq_chat,
    "/models/embeddings": foundry_text,
    "/models/images/embeddings": foundry_image,
    "/v1/responses": responses,
}


class H(BaseHTTPRequestHandler):
    def do_POST(self):
        path = self.path.split("?")[0]
        raw = self.rfile.read(int(self.headers.get("content-length", 0)))
        body = json.loads(raw or b"{}")
        print(json.dumps({"path": self.path, "body": body}), flush=True)
        fn = ROUTES.get(path)
        out = json.dumps(fn(body) if fn else {"error": {"message": f"no route {path}"}}).encode()
        self.send_response(200 if fn else 404)
        self.send_header("content-type", "application/json")
        self.send_header("content-length", str(len(out)))
        self.end_headers()
        self.wfile.write(out)

    def log_message(self, *a):
        pass


ThreadingHTTPServer(("127.0.0.1", int(sys.argv[1])), H).serve_forever()
Client script (client.sh, run with LITELLM_MASTER_KEY exported)
#!/bin/bash
# usage: client.sh groq|foundry|health
P=http://localhost:4201
AUTH="Authorization: Bearer $LITELLM_MASTER_KEY"
PNG="data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAYAAAAfFcSJAAAADUlEQVR42mP8z8BQDwAEhQGAhKmMIQAAAABJRU5ErkJggg=="
case $1 in
groq)
  curl -s -w '\nHTTP %{http_code}\n' $P/v1/chat/completions -H "$AUTH" -H 'content-type: application/json' \
    -d '{"model":"groq-stub","messages":[{"role":"user","content":"say hello"}]}' ;;
foundry)
  curl -s -w '\nHTTP %{http_code}\n' $P/v1/embeddings -H "$AUTH" -H 'content-type: application/json' \
    -d "{\"model\":\"foundry-embed\",\"input\":[\"text one\",\"$PNG\",\"text two\"]}" | python3 -c 'import sys,json; raw=sys.stdin.read(); body,_,code=raw.rpartition("\nHTTP "); d=json.loads(body); print("HTTP",code.strip()); print(json.dumps({"indexes":[x["index"] for x in d.get("data",[])],"embeddings":[x["embedding"] for x in d.get("data",[])]}) if "data" in d else body)'
  curl -s -w '\nHTTP %{http_code}\n' $P/v1/embeddings -H "$AUTH" -H 'content-type: application/json' \
    -d '{"model":"foundry-embed","input":"hello"}' | python3 -c 'import sys,json; raw=sys.stdin.read(); body,_,code=raw.rpartition("\nHTTP "); d=json.loads(body); print("HTTP",code.strip()); print(json.dumps({"indexes":[x["index"] for x in d.get("data",[])],"embeddings":[x["embedding"] for x in d.get("data",[])]}) if "data" in d else body)' ;;
health)
  for m in responses-probe responses-probe-null; do
    curl -s -w '\nHTTP %{http_code}\n' "$P/health?model=$m" -H "$AUTH"; done ;;
esac

Before

Both probes report healthy, but the bodies the stub received carry no max_output_tokens, so the provider is free to generate an unbounded reply on every health check

$ ./client.sh health
{"healthy_endpoints":[{"api_base":"`` http://127.0.0.1:4251/v1","model":"openai/probe-model","model_id":"a8c776a6d7998ba175c76c2260b767d251cd99ce9a6bd956923ac0ee891b5f29"}],"unhealthy_endpoints":[],"healthy_count":1,"unhealthy_count":0} ``
HTTP 200
{"healthy_endpoints":[{"api_base":"```` http://127.0.0.1:4251/v1","model":"openai/probe-model-null","model_id":"106ead618619485a1d193e43947c20a294b62b11fd1a069299d3fa9cf6cf1d7a"}],"unhealthy_endpoints":[],"healthy_count":1,"unhealthy_count":0} ````
HTTP 200
stub received (before)
{"path": "/v1/responses", "body": {"model": "probe-model", "input": "test from litellm"}}
{"path": "/v1/responses", "body": {"model": "probe-model-null", "input": "test from litellm"}}

After

The same calls send max_output_tokens: 37 for both deployments, including the one that sets max_output_tokens: null, and no max_tokens key

$ ./client.sh health
{"healthy_endpoints":[{"api_base":"````` http://127.0.0.1:4251/v1","model":"openai/probe-model","model_id":"a8c776a6d7998ba175c76c2260b767d251cd99ce9a6bd956923ac0ee891b5f29"}],"unhealthy_endpoints":[],"healthy_count":1,"unhealthy_count":0} `````
HTTP 200
{"healthy_endpoints":[{"api_base":"`````` http://127.0.0.1:4251/v1","model":"openai/probe-model-null","model_id":"106ead618619485a1d193e43947c20a294b62b11fd1a069299d3fa9cf6cf1d7a"}],"unhealthy_endpoints":[],"healthy_count":1,"unhealthy_count":0} ``````
HTTP 200
stub received (after)
{"path": "/v1/responses", "body": {"model": "probe-model", "input": "test from litellm", "max_output_tokens": 37}}
{"path": "/v1/responses", "body": {"model": "probe-model-null", "input": "test from litellm", "max_output_tokens": 37}}
Worker PIDs (after)
== git HEAD: 4d963742b4df41c3ba55ea29d81839be847c00a2
== worker PIDs:
INFO:     Started server process [12854]
INFO:     Started server process [12853]

Unit tests

Scope is the responses entry of the health check mode handlers in litellm/litellm_core_utils/health_check_helpers.py. responses is in _MAX_TOKEN_SUPPORT_MODES (litellm/proxy/health_check.py), so the probe params carry max_tokens, but litellm.aresponses has no such parameter and the cap never reached the provider. A small helper _responses_probe_params now removes max_tokens and sets it as max_output_tokens unless the deployment already sets a non-null one, so max_output_tokens: null still gets the cap. No other mode handler changes. Below-minimum values are still raised to the provider's floor by the existing Responses transformation (16 for OpenAI).

The bug was found by the Dec 1 integration contract tests (draft PR #50853). The test skipped with BUG for it is tests/integration/routing/test_dec1_healthchk_probe_requests.py::test_a_responses_probe_posts_the_default_prompt_to_the_responses_api.

The new regression test test_a_responses_probe_is_bounded_by_the_health_check_max_tokens runs ahealth_check in responses mode with max_tokens: 37 against a mocked /v1/responses endpoint and checks the body sent carries max_output_tokens: 37 and no max_tokens. A second cell sets max_output_tokens: None on the deployment. Both cells failed before the fix with KeyError: 'max_output_tokens' and pass at the tip.

PYTHONPATH=. python -m pytest tests/unit/litellm_core_utils/test_health_check_helpers.py::test_a_responses_probe_is_bounded_by_the_health_check_max_tokens -q
# before the fix: 1 failed (KeyError: 'max_output_tokens')
# at the tip: 1 passed

PYTHONPATH=. python -m pytest tests/unit/litellm_core_utils/test_health_check_helpers.py -q
# at the tip: 106 passed

ruff format --check litellm/litellm_core_utils/health_check_helpers.py   # already formatted
ruff check litellm/litellm_core_utils/health_check_helpers.py   # all checks passed
ruff check --config .github/linters/ruff-tests.toml tests/unit/litellm_core_utils/test_health_check_helpers.py   # all checks passed

Type

Bug Fix

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

Generated by Claude Code

@veria-ai

veria-ai Bot commented Nov 18, 2026 •

Copy link
Copy Markdown
Contributor

PR overview

No security issues were found in this pull request.

Reviews

Copy link
Copy Markdown
Contributor Author

[AI] @greptileai review


Generated by Claude Code

@devin-ai-integration devin-ai-integration 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.

Devin Review found 1 potential issue.

Devin Review

Comment on lines +102 to +105
params: Final = {k: v for k, v in model_params.items() if k != "max_tokens"}
if max_tokens is not None:
params.setdefault("max_output_tokens", max_tokens)
return params

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.

🟡 Mutable Responses probe parameter construction

When max_tokens exists, params.setdefault mutates the probe dictionary. The mandatory no-mutation rule applies to this new helper.

Suggested change
params: Final = {k: v for k, v in model_params.items() if k != "max_tokens"}
if max_tokens is not None:
params.setdefault("max_output_tokens", max_tokens)
return params
return {
**({"max_output_tokens": max_tokens} if max_tokens is not None else {}),
**{k: v for k, v in model_params.items() if k != "max_tokens"},
}

Devin Review


Was this helpful? React with 👍 or 👎 to provide feedback.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

[AI] Fixed. _responses_probe_params no longer mutates anything. It builds the params without max_tokens in one comprehension and returns a new mapping with max_output_tokens added, at 4d96374.


Generated by Claude Code

@greptile-apps

greptile-apps Bot commented Nov 18, 2026 •

Copy link
Copy Markdown
Contributor

Confidence Score: 5/5 · The PR appears safe to merge.RetriggerView in GreptileConfidence Score: 5/5

[Medium impact] The PR appears safe to merge.

Summary

Responses health probes now send the health check's max_tokens value as max_output_tokens.

  • Responses health checks send a token cap the provider can use.

Reviews (2) · Last reviewed commit: "fix(health): send max_output_tokens on t..." · Reviewed by Greptile

@codspeed

codspeed Bot commented Nov 18, 2026 •

Copy link
Copy Markdown
Contributor

Merging this PR will not alter performance

1 warning

⚠️ 2 benchmarks are dominated by system calls

System calls cannot be simulated consistently and are left out of the measure. The reported value understates the real cost. Switch to the Walltime instrument to measure them.

Learn more about system calls

See affected benchmarks

✅ 45 untouched benchmarks


Comparing nate_fix_responses_health_max_output_tokens (4d96374) with main (bb29e9a)1

Open in CodSpeed

Footnotes

  1. No successful run was found on main (304b76a) during the generation of this report, so bb29e9a was used instead as the comparison base. There might be some changes unrelated to this pull request in this report. ↩

@codecov

codecov Bot commented Nov 18, 2026 •

Copy link
Copy Markdown

Codecov Report

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

Files with missing lines Patch % Lines
litellm/litellm_core_utils/health_check_helpers.py 16.66% 5 Missing ⚠️

📢 Thoughts on this report? Let us know!

@narmstrong-berri
narmstrong-berri force-pushed the nate_fix_responses_health_max_output_tokens branch 3 times, most recently from 5f170fe to 4d96374 Compare November 18, 2026 21:12
@narmstrong-berri narmstrong-berri self-assigned this Nov 19, 2026
@narmstrong-berri
narmstrong-berri enabled auto-merge (squash) November 19, 2026 00:57
@narmstrong-berri
narmstrong-berri force-pushed the nate_fix_responses_health_max_output_tokens branch from 4d96374 to 603adbc Compare November 19, 2026 00:58
@aidanasingh

aidanasingh commented Nov 26, 2026 •

Copy link
Copy Markdown
Contributor

Reproduced the unbounded probe on main and this fixes it. health_check_reasoning_effort is also ignored for mode: responses, since _HEALTH_CHECK_MODES_SUPPORTING_REASONING_EFFORT leaves it out.

This branch has not been deployed

No deployments
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