Skip to content

fix(groq): default service_tier when the reply omits it - #52431

Merged
narmstrong-berri merged 1 commit into
mainfrom
nate_fix_groq_missing_service_tier
Nov 18, 2026
Merged

narmstrong-berri merged 1 commit into
mainfrom
nate_fix_groq_missing_service_tier

Conversation

@narmstrong-berri

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

Copy link
Copy Markdown
Contributor

Handwritten 1-3 sentence description

[insert handwritten description here]

Details

TLDR

Problem this solves:

  • Groq replies without service_tier fail with AttributeError
  • Chat returns 400, /v1/messages returns 500, Responses bridge fails

How it solves it:

  • Read service_tier with a None default
  • A missing tier then maps to auto, as already intended

User Flow

Before: a developer calling a Groq model gets an error whenever Groq leaves service_tier out of its reply

  1. They send POST https://litellm-domain/v1/chat/completions with "model": "groq/llama-3.3-70b-versatile"
  2. Groq answers 200 with a normal completion that has no service_tier field
  3. The proxy returns 400 with 'ModelResponse' object has no attribute 'service_tier', and the same call on POST https://litellm-domain/v1/messages returns 500

After: the same request returns the completion

  1. They send the same POST https://litellm-domain/v1/chat/completions
  2. Groq answers 200 with no service_tier field
  3. The proxy returns 200 with the completion and "service_tier": "auto", and POST https://litellm-domain/v1/messages returns 200 too

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 Groq credentials exist in this environment, so the groq/llama-3.3-70b-versatile deployment points its api_base at a local stub that speaks Groq's OpenAI compatible /openai/v1/chat/completions wire format and answers with a normal Groq style completion that leaves out service_tier. A client then sends one chat completion through the live proxy

Before is 532df6ef85655e56d82e334e1ab071c5c7fc29e9 (parent of the fix commit) and after is 9afe0fe69706c9b5f02c56fb7479ce673c7b4004 (branch tip of nate_fix_groq_missing_service_tier). 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

The client gets an error even though the stub answered 200 with content. The router retried twice, so the stub saw three identical requests

$ ./client.sh groq
{"error":{"message":"Invalid request format: litellm.APIConnectionError: APIConnectionError: GroqException - 'ModelResponse' object has no attribute 'service_tier'\n\nLiteLLM: model group 'groq-stub' failed with the error above. No fallback was attempted. LiteLLM Retried: 2 times, LiteLLM Max Retries: 2","type":"invalid_request_error","param":null,"code":"400"}}
HTTP 400
Stub received (before)
{"path": "/openai/v1/chat/completions", "body": {"model": "llama-3.3-70b-versatile", "messages": [{"role": "user", "content": "say hello"}], "stream": false}}
{"path": "/openai/v1/chat/completions", "body": {"model": "llama-3.3-70b-versatile", "messages": [{"role": "user", "content": "say hello"}], "stream": false}}
{"path": "/openai/v1/chat/completions", "body": {"model": "llama-3.3-70b-versatile", "messages": [{"role": "user", "content": "say hello"}], "stream": false}}
Proxy traceback (before)
  File "<checkout>/litellm/llms/custom_httpx/llm_http_handler.py", line 900, in async_completion
    initial_response: Final = provider_config.transform_response(
                              ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "<checkout>/litellm/llms/groq/chat/transformation.py", line 329, in transform_response
    original_service_tier: Final = _ATTRIBUTE_VALUE.validate_python(getattr(model_response, "service_tier"))
                                                                    ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "/tmp/claude-0/-home-user/31fe6aa2-8276-5c39-b04a-027313f5e2af/scratchpad/cv/lib/python3.12/site-packages/pydantic/main.py", line 1110, in __getattr__
    raise AttributeError(f'{type(self).__name__!r} object has no attribute {item!r}')
AttributeError: 'ModelResponse' object has no attribute 'service_tier'

After

The same request returns 200 with the stub's content and service_tier reported as auto

$ ./client.sh groq
{"id":"chatcmpl-stub-1","created":1763438400,"model":"groq-stub","object":"chat.completion","choices":[{"finish_reason":"stop","index":0,"message":{"content":"hello from the groq stub","role":"assistant"}}],"usage":{"completion_tokens":5,"prompt_tokens":9,"total_tokens":14},"x_groq":{"id":"req_stub"},"service_tier":"auto"}
HTTP 200
Worker PIDs and stub received (after)
== git HEAD: 9afe0fe69706c9b5f02c56fb7479ce673c7b4004
== worker PIDs:
INFO:     Started server process [11935]
INFO:     Started server process [11936]
{"path": "/openai/v1/chat/completions", "body": {"model": "llama-3.3-70b-versatile", "messages": [{"role": "user", "content": "say hello"}], "stream": false}}

Unit tests

Scope is one line in GroqChatConfig.transform_response (litellm/llms/groq/chat/transformation.py), where getattr(model_response, "service_tier") now passes None as the default. _map_groq_service_tier already maps None to auto, so a reply that carries a tier behaves exactly as before and only the reply without one changes, from an exception to auto. Every Groq chat path (chat completions, the /v1/messages bridge and the Responses bridge) goes through this method, so one unit test through litellm.completion covers the shared defect.

The bug was found by the Dec 1 integration contract tests (draft PR #50853). The tests skipped with BUG for it are tests/integration/providers/test_dec1_otherprov2_groq_wire.py::test_groq_service_tier_is_reported_in_the_openai_vocabulary[None-auto] and the other Groq cells that skip with _SERVICE_TIER_BUG or _GROQ_SERVICE_TIER_BUG in test_dec1_otherprov2_groq_wire.py, test_dec1_openai_compatible_chat_wire.py, test_dec1_openai_messages_bridge_wire.py, test_dec1_respapi2_carriers_wire.py and test_dec1_respapi2_chaining_owned_proxy.py.

The new regression test test_reply_without_service_tier_is_reported_as_auto mocks a Groq reply with no service_tier and checks the response comes back with service_tier == "auto" and its content intact. It failed before the fix with APIConnectionError: GroqException - 'ModelResponse' object has no attribute 'service_tier' and passes at the tip.

PYTHONPATH=. python -m pytest tests/unit/llms/groq/chat/test_groq_chat_transformation.py::test_reply_without_service_tier_is_reported_as_auto -q
# before the fix: 1 failed
# at the tip: 1 passed

PYTHONPATH=. python -m pytest tests/unit/llms/groq/chat/test_groq_chat_transformation.py -q
# at the tip: 41 passed

ruff format --check litellm/llms/groq/chat/transformation.py   # already formatted
ruff check --config .github/linters/ruff-tests.toml tests/unit/llms/groq/chat/test_groq_chat_transformation.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: No Issues Found

Devin Review analyzed this PR and found no bugs or issues to report.

Devin Review

@greptile-apps

greptile-apps Bot commented Nov 18, 2026 •

Copy link
Copy Markdown
Contributor

RetriggerView in GreptileConfidence Score: 4/5

[Medium impact] The change affects Groq chat responses that omit a service tier.

The live QA requirement must be satisfied before merging.

Findings

  1. P2 Live QA proof is missing ▶

Summary

Fixes Groq replies that omit service_tier by using the existing auto fallback instead of raising an error.

  • Groq replies without a tier now return with auto.

Reviews (1) · Last reviewed commit: "fix(groq): default service_tier when the..." · 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_groq_missing_service_tier (9afe0fe) with main (6a09e4e)1

Open in CodSpeed

Footnotes

  1. No successful run was found on main (532df6e) during the generation of this report, so 6a09e4e 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

✅ All modified and coverable lines are covered by tests.

📢 Thoughts on this report? Let us know!

@narmstrong-berri
narmstrong-berri force-pushed the nate_fix_groq_missing_service_tier branch from f7f11a6 to 9afe0fe Compare November 18, 2026 05:17
@narmstrong-berri
narmstrong-berri enabled auto-merge (squash) November 18, 2026 20:58
@narmstrong-berri narmstrong-berri self-assigned this Nov 18, 2026

@ryan-crabbe-berri ryan-crabbe-berri 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.

lgtm

@narmstrong-berri
narmstrong-berri merged commit 7e21590 into main Nov 18, 2026
156 of 158 checks passed
@narmstrong-berri
narmstrong-berri deleted the nate_fix_groq_missing_service_tier branch November 18, 2026 21:17
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