Skip to content

feat(gradium): add text-to-speech support for /v1/audio/speech (lts/1.108.x) - #53463

Merged
mateo-berri merged 15 commits into
BerriAI:lts/1.108.xfrom
martenj4:litellm_backport_46427_lts_1_108_x
Nov 22, 2026
Merged

mateo-berri merged 15 commits into
BerriAI:lts/1.108.xfrom
martenj4:litellm_backport_46427_lts_1_108_x

Conversation

@martenj4

@martenj4 martenj4 commented Nov 21, 2026 •

Copy link
Copy Markdown
Contributor

Handwritten 1-3 sentence description

Gradium text-to-speech now works on the 1.108 LTS line. A proxy admin can add a gradium/default model, and /v1/audio/speech returns Gradium audio billed per input character, spaces included, the way Gradium counts credits

LTS twin of main #46427. Main merges first, this PR must not merge before it

Original

TLDR

Problem this solves:

  • Gradium text-to-speech has no LiteLLM route on 1.108

How it solves it:

  • Adds the gradium/ provider for litellm.speech and /v1/audio/speech
  • Maps OpenAI voices and formats onto Gradium's REST TTS endpoint, plus Gradium's own PCM, μ-law and A-law formats
  • Answers 400 when the voice is missing
  • Answers 502 when Gradium's 200 reply is not audio
  • Forwards Gradium's json_config from the caller, at top level or in extra_body, and nothing else
  • Prices gradium/default, gradium/gradium-tts-beta and gradium/gradium-tts-202602 at the same per-character rate
  • Bills every input character, spaces included, through a provider-reported count

User Flow

Before: a developer whose proxy admin adds a Gradium voice model gets an error instead of audio

  1. The proxy admin adds a gradium/default model with an api_base and an api_key, then restarts the proxy
  2. The developer sends POST https://litellm-domain/v1/audio/speech with {"model": "gradium/default", "input": "Bonjour !", "voice": "alloy"}
  3. The proxy answers with an error, and no audio comes back

After: the same request comes back as playable Gradium audio, billed per character

  1. The proxy admin adds the same gradium/default model and restarts the proxy
  2. The developer sends the same POST https://litellm-domain/v1/audio/speech
  3. The proxy answers 200 with audio/wav bytes and an x-litellm-response-cost header
  4. GET https://litellm-domain/spend/logs?request_id= shows that cost against gradium/default

Commit mapping

Main commit LTS commit
3342c8200a6ca4c9978e428c1d0562a334842e0c d583ba29f05d957c9286bb7d9e3c22ed533ae328
767d832ba5f4bc9ce4520a87862254e05f55b0e7 d65672346675724c763c2f09c16f1336dde492bd
9b5d71d07560eb54da8386448b35fd9df1d1bc70 a9be7a2f57c4465138fc3b8d91f88fb6886fdb01
c57080cb45dbb833572b00c0acc5fb8a92bcc2d1 359118074a3bbfbc1a065bce4336ae36deab59b8
a1b0ba1a13f6dd6d0d817f45c1963acfe1f0309a 9f57ff58e9d473dc396a0c6236a2f782cd072c9b
8597deeba31089f84229a03f38368b7bd5f1cd7d 0d5979b8b2ac6d59944805ba287f7a2f5a9f2ed1
9ee0d5b42bfb0d4a33eb59030c973caeba8470c7 3a977fecc293d759bd6d9d097c44023498218b73 adapted
364272ae12131d42acadeb44c98f069638478217 8b9289f39f1c073fdfdbaf304b32ebd36536e8e3 adapted
d7243e687d5807ab37d6753ef70cc2e96f173e92 a29f0cc4ef482f99c4be6f4364fb467d70497290 adapted
b70cc7478143cfb16435c68f9463389edd9895a9 348f6f89cebc1f920e6f137c2c924657db79d5ac
7e10af7fb4baa4233adf2044f503880339a140de 51063b726c6ba6c628c01a4fc3ed24e4014dbb95 adapted
2c3ac63d8eccdf78f4a8b890da1149056aa2af4d 18bfcd28270e50cdd03eb37774182c711274f643
04d1963696dda76dc44b73264d3b35ed7a3f40a8 3d98be6ee61b244fed6e16a91841c8d50f1b97da adapted

4553dda866518b694b7684521f89e8cccef1beba (streaming) and 7a205320ef03d76ece9d4a8a458e6ba91f4877b6 (it closes a streamed reply, which 1.108 never has) are main only, see the pair block. af94850f9b9f72262fe923db7156e8121c0a70e4 and ac92521e12eea6cb37200fa193a1b12eddfc14d8 are a partial pick of #48998, also in the pair block

Differences from main

  • No streaming. 1.108's speech handler has no stream argument, so the Gradium config leaves streaming out, main's streaming test is dropped and the 502 test drops its stream cases. A stream: true request gets the buffered clip
  • af94850f9b brings only feat(dashscope): add image edits and text-to-speech #48998's cost hook for a provider-reported character count, so no other provider's speech cost changes
  • ac92521e12 is LTS only. The speech cost hook takes billed_characters from its call site, because passing 1.108's generic HttpxBinaryResponseContent added a basedpyright finding. Speech cost is unchanged for every provider
  • The endpoint support entry uses 1.108's 12-key shape
  • Everything else in the provider, its tests, the cost row and the Add Model fields is identical to main

Screenshots / Proof of Fix

Both legs ran on this laptop against the real Gradium EU API with the same config, each proxy with 2 uvicorn workers, its own fresh Postgres database, and one shared dedicated Redis. I dropped --reload because uvicorn 0.51 then serves one worker. LITELLM_LOCAL_MODEL_COST_MAP=True makes each leg read its own cost map

Config, proxy command and env var names

qa_config.yaml is litellm/proxy/dev_config.yaml plus this model and these settings

model_list:
  - model_name: gradium/default
    litellm_params:
      model: gradium/default
      api_base: https://eu.api.gradium.ai
      api_key: os.environ/GRADIUM_API_KEY
general_settings:
  master_key: os.environ/LITELLM_MASTER_KEY
  coordination_redis:
    host: os.environ/REDIS_HOST
    port: os.environ/REDIS_PORT
router_settings:
  redis_host: os.environ/REDIS_HOST
  redis_port: os.environ/REDIS_PORT

Each leg's .env sets GRADIUM_API_KEY, LITELLM_MASTER_KEY, DATABASE_URL, REDIS_HOST, REDIS_PORT and LITELLM_LOCAL_MODEL_COST_MAP=True

.venv/bin/python litellm/proxy/proxy_cli.py --config qa_config.yaml --port <port> --num_workers 2 --detailed_debug --use_v2_migration_resolver --timeout_worker_healthcheck 60

The request bodies. speech_stream.json is speech.json plus "stream": true

speech.json             {"model": "gradium/default", "input": "Bonjour ! Votre rendez-vous est confirmé pour demain à 10 heures.", "voice": "alloy", "response_format": "wav"}
speech_ulaw.json        {"model": "gradium/default", "input": "Bonjour ! Votre rendez-vous est confirmé pour demain à 10 heures.", "voice": "coral", "response_format": "ulaw_8000"}
speech_blank_voice.json {"model": "gradium/default", "input": "Bonjour ! Votre rendez-vous est confirmé pour demain à 10 heures.", "voice": " ", "response_format": "wav"}

speech_json_config.json is speech.json plus "json_config": {"padding_bonus": -1.0}, and speech_extra_body_string.json is speech.json plus "extra_body": "oops"

Before 7ab941f, after 18bfcd2

Case Before After
speech.json 400, no audio 200 audio/wav
speech_stream.json 400, no audio 200 audio/wav
speech_ulaw.json 400, no audio 200 audio/basic
speech_json_config.json not sent 200 audio/wav
speech_extra_body_string.json not sent 200 audio/wav
speech_blank_voice.json 400, no audio 400, voice required

The base proxy drops gradium/default at boot with LLM Provider NOT provided, so every request answers There are no healthy deployments for this model, and the two new bodies were not sent there

Speech request after

  1. curl -X POST http://127.0.0.1:26927/v1/audio/speech --data-binary @speech.json answers HTTP 200, 460844 bytes with content-type: audio/wav and x-litellm-response-cost: 0.004549999999999999, which is 65 characters at $0.00007
  2. file speech.out reports RIFF (little-endian) data, WAVE audio, Microsoft PCM, 16 bit, mono 48000 Hz
  3. GET /spend/logs?request_id=fd453679-813c-413f-bc49-d82e6ac17da1 returns the row with call_type aspeech, custom_llm_provider gradium and spend 0.004549999999999999
Other cases after

Speech request with stream true

  1. The same curl with speech_stream.json answers HTTP 200, 476204 bytes, audio/wav, the same cost, as one buffered clip

μ-law request

  1. The same curl with speech_ulaw.json answers HTTP 200, 36160 bytes with content-type: audio/basic and the same cost. That is 4.5 seconds of 8 kHz audio

json_config

  1. The same curl with speech_json_config.json answers HTTP 200, 422444 bytes, audio/wav, the same cost
  2. The proxy debug log shows the body sent to Gradium as {'json_config': {'padding_bonus': -1.0}, 'output_format': 'wav', 'text': '...', 'voice_id': 'YTpq7expH9539ERJ', 'only_audio': True}

Non-object extra_body

  1. The same curl with speech_extra_body_string.json answers HTTP 200, 437804 bytes, audio/wav, the same cost, and the body sent to Gradium has no extra field

Blank voice

  1. The same curl with speech_blank_voice.json answers HTTP 400 with Gradium voice_id is required. Pass voice when calling litellm.speech()
Full transcripts
== leg base, proxy http://127.0.0.1:30985, commit 7ab941f451153a6e62f70ba3b0cc9d8437464c07
-- case speech
$ cat speech.json
{"model": "gradium/default", "input": "Bonjour ! Votre rendez-vous est confirmé pour demain à 10 heures.", "voice": "alloy", "response_format": "wav"}
$ curl -sS -o speech.out -D speech.headers -w 'HTTP %{http_code}, %{size_download} bytes, %{time_total}s\n' -X POST http://127.0.0.1:30985/v1/audio/speech -H "Authorization: Bearer $LITELLM_MASTER_KEY" -H 'Content-Type: application/json' --data-binary @speech.json
HTTP 400, 269 bytes, 0.080514s

$ grep -i -E '^(content-type|x-litellm-response-cost|x-litellm-call-id|x-litellm-model-api-base):' speech.headers
x-litellm-call-id: a4e3d687-f1fa-46ce-85c8-f1b3934fe9df
content-type: application/json

$ file speech.out
speech.out: JSON data

$ head -c 400 speech.out
{"error":{"message":"litellm.BadRequestError: You passed in model=gradium/default. There are no healthy deployments for this model\n\nLiteLLM: model group 'gradium/default' failed with the error above. No fallback was attempted.","type":null,"param":null,"code":"400"}}
-- case speech_stream
$ cat speech_stream.json
{"model": "gradium/default", "input": "Bonjour ! Votre rendez-vous est confirmé pour demain à 10 heures.", "voice": "alloy", "response_format": "wav", "stream": true}
$ curl -sS -o speech_stream.out -D speech_stream.headers -w 'HTTP %{http_code}, %{size_download} bytes, %{time_total}s\n' -X POST http://127.0.0.1:30985/v1/audio/speech -H "Authorization: Bearer $LITELLM_MASTER_KEY" -H 'Content-Type: application/json' --data-binary @speech_stream.json
HTTP 400, 269 bytes, 0.019781s

$ grep -i -E '^(content-type|x-litellm-response-cost|x-litellm-call-id|x-litellm-model-api-base):' speech_stream.headers
x-litellm-call-id: 5ba11cc7-1142-4813-8b61-e2214baf8027
content-type: application/json

$ file speech_stream.out
speech_stream.out: JSON data

$ head -c 400 speech_stream.out
{"error":{"message":"litellm.BadRequestError: You passed in model=gradium/default. There are no healthy deployments for this model\n\nLiteLLM: model group 'gradium/default' failed with the error above. No fallback was attempted.","type":null,"param":null,"code":"400"}}
-- case speech_ulaw
$ cat speech_ulaw.json
{"model": "gradium/default", "input": "Bonjour ! Votre rendez-vous est confirmé pour demain à 10 heures.", "voice": "coral", "response_format": "ulaw_8000"}
$ curl -sS -o speech_ulaw.out -D speech_ulaw.headers -w 'HTTP %{http_code}, %{size_download} bytes, %{time_total}s\n' -X POST http://127.0.0.1:30985/v1/audio/speech -H "Authorization: Bearer $LITELLM_MASTER_KEY" -H 'Content-Type: application/json' --data-binary @speech_ulaw.json
HTTP 400, 269 bytes, 0.073636s

$ grep -i -E '^(content-type|x-litellm-response-cost|x-litellm-call-id|x-litellm-model-api-base):' speech_ulaw.headers
x-litellm-call-id: 086e1797-0978-45bc-b98d-11fe7afe7307
content-type: application/json

$ file speech_ulaw.out
speech_ulaw.out: JSON data

$ head -c 400 speech_ulaw.out
{"error":{"message":"litellm.BadRequestError: You passed in model=gradium/default. There are no healthy deployments for this model\n\nLiteLLM: model group 'gradium/default' failed with the error above. No fallback was attempted.","type":null,"param":null,"code":"400"}}
-- case speech_blank_voice
$ cat speech_blank_voice.json
{"model": "gradium/default", "input": "Bonjour ! Votre rendez-vous est confirmé pour demain à 10 heures.", "voice": " ", "response_format": "wav"}
$ curl -sS -o speech_blank_voice.out -D speech_blank_voice.headers -w 'HTTP %{http_code}, %{size_download} bytes, %{time_total}s\n' -X POST http://127.0.0.1:30985/v1/audio/speech -H "Authorization: Bearer $LITELLM_MASTER_KEY" -H 'Content-Type: application/json' --data-binary @speech_blank_voice.json
HTTP 400, 269 bytes, 0.018514s

$ grep -i -E '^(content-type|x-litellm-response-cost|x-litellm-call-id|x-litellm-model-api-base):' speech_blank_voice.headers
x-litellm-call-id: 1e5cf45a-4e0f-4b13-aa28-81494f31cac6
content-type: application/json

$ file speech_blank_voice.out
speech_blank_voice.out: JSON data

$ head -c 400 speech_blank_voice.out
{"error":{"message":"litellm.BadRequestError: You passed in model=gradium/default. There are no healthy deployments for this model\n\nLiteLLM: model group 'gradium/default' failed with the error above. No fallback was attempted.","type":null,"param":null,"code":"400"}}
== leg head, proxy http://127.0.0.1:26927, commit 18bfcd28270e50cdd03eb37774182c711274f643
-- case speech
$ cat speech.json
{"model": "gradium/default", "input": "Bonjour ! Votre rendez-vous est confirmé pour demain à 10 heures.", "voice": "alloy", "response_format": "wav"}
$ curl -sS -o speech.out -D speech.headers -w 'HTTP %{http_code}, %{size_download} bytes, %{time_total}s\n' -X POST http://127.0.0.1:26927/v1/audio/speech -H "Authorization: Bearer $LITELLM_MASTER_KEY" -H 'Content-Type: application/json' --data-binary @speech.json
HTTP 200, 460844 bytes, 4.718399s

$ grep -i -E '^(content-type|x-litellm-response-cost|x-litellm-call-id|x-litellm-model-api-base):' speech.headers
x-litellm-call-id: fd453679-813c-413f-bc49-d82e6ac17da1
x-litellm-model-api-base: https://eu.api.gradium.ai
x-litellm-response-cost: 0.004549999999999999
content-type: audio/wav

$ file speech.out
speech.out: RIFF (little-endian) data, WAVE audio, Microsoft PCM, 16 bit, mono 48000 Hz

-- case speech_stream
$ cat speech_stream.json
{"model": "gradium/default", "input": "Bonjour ! Votre rendez-vous est confirmé pour demain à 10 heures.", "voice": "alloy", "response_format": "wav", "stream": true}
$ curl -sS -o speech_stream.out -D speech_stream.headers -w 'HTTP %{http_code}, %{size_download} bytes, %{time_total}s\n' -X POST http://127.0.0.1:26927/v1/audio/speech -H "Authorization: Bearer $LITELLM_MASTER_KEY" -H 'Content-Type: application/json' --data-binary @speech_stream.json
HTTP 200, 476204 bytes, 2.555778s

$ grep -i -E '^(content-type|x-litellm-response-cost|x-litellm-call-id|x-litellm-model-api-base):' speech_stream.headers
x-litellm-call-id: 11def864-3679-4cc9-b151-aaca25b6d3d7
x-litellm-model-api-base: https://eu.api.gradium.ai
x-litellm-response-cost: 0.004549999999999999
content-type: audio/wav

$ file speech_stream.out
speech_stream.out: RIFF (little-endian) data, WAVE audio, Microsoft PCM, 16 bit, mono 48000 Hz

-- case speech_ulaw
$ cat speech_ulaw.json
{"model": "gradium/default", "input": "Bonjour ! Votre rendez-vous est confirmé pour demain à 10 heures.", "voice": "coral", "response_format": "ulaw_8000"}
$ curl -sS -o speech_ulaw.out -D speech_ulaw.headers -w 'HTTP %{http_code}, %{size_download} bytes, %{time_total}s\n' -X POST http://127.0.0.1:26927/v1/audio/speech -H "Authorization: Bearer $LITELLM_MASTER_KEY" -H 'Content-Type: application/json' --data-binary @speech_ulaw.json
HTTP 200, 36160 bytes, 3.576980s

$ grep -i -E '^(content-type|x-litellm-response-cost|x-litellm-call-id|x-litellm-model-api-base):' speech_ulaw.headers
x-litellm-call-id: 776edf21-b217-4bd3-8f31-1baeaf63cc62
x-litellm-model-api-base: https://eu.api.gradium.ai
x-litellm-response-cost: 0.004549999999999999
content-type: audio/basic

$ file speech_ulaw.out
speech_ulaw.out: data

-- case speech_blank_voice
$ cat speech_blank_voice.json
{"model": "gradium/default", "input": "Bonjour ! Votre rendez-vous est confirmé pour demain à 10 heures.", "voice": " ", "response_format": "wav"}
$ curl -sS -o speech_blank_voice.out -D speech_blank_voice.headers -w 'HTTP %{http_code}, %{size_download} bytes, %{time_total}s\n' -X POST http://127.0.0.1:26927/v1/audio/speech -H "Authorization: Bearer $LITELLM_MASTER_KEY" -H 'Content-Type: application/json' --data-binary @speech_blank_voice.json
HTTP 400, 260 bytes, 0.816706s

$ grep -i -E '^(content-type|x-litellm-response-cost|x-litellm-call-id|x-litellm-model-api-base):' speech_blank_voice.headers
x-litellm-call-id: 1c75c886-8c89-4c44-9c3e-d5f3cdbafb6f
content-type: application/json

$ file speech_blank_voice.out
speech_blank_voice.out: JSON data

$ head -c 400 speech_blank_voice.out
{"error":{"message":"litellm.BadRequestError: Gradium voice_id is required. Pass `voice` when calling `litellm.speech()`.\n\nLiteLLM: model group 'gradium/default' failed with the error above. No fallback was attempted.","type":null,"param":null,"code":"400"}}
-- case speech_json_config
$ cat speech_json_config.json
{"model": "gradium/default", "input": "Bonjour ! Votre rendez-vous est confirmé pour demain à 10 heures.", "voice": "alloy", "response_format": "wav", "json_config": {"padding_bonus": -1.0}}
$ curl -sS -o speech_json_config.out -D speech_json_config.headers -w 'HTTP %{http_code}, %{size_download} bytes, %{time_total}s\n' -X POST http://127.0.0.1:26927/v1/audio/speech -H "Authorization: Bearer $LITELLM_MASTER_KEY" -H 'Content-Type: application/json' --data-binary @speech_json_config.json
HTTP 200, 422444 bytes, 2.665181s

$ grep -i -E '^(content-type|x-litellm-response-cost|x-litellm-call-id|x-litellm-model-api-base):' speech_json_config.headers
x-litellm-call-id: b3e4ab8c-8c5b-4e65-8797-781f3e4d8abd
x-litellm-model-api-base: https://eu.api.gradium.ai
x-litellm-response-cost: 0.004549999999999999
content-type: audio/wav

$ file speech_json_config.out
speech_json_config.out: RIFF (little-endian) data, WAVE audio, Microsoft PCM, 16 bit, mono 48000 Hz

-- case speech_extra_body_string
$ cat speech_extra_body_string.json
{"model": "gradium/default", "input": "Bonjour ! Votre rendez-vous est confirmé pour demain à 10 heures.", "voice": "alloy", "response_format": "wav", "extra_body": "oops"}
$ curl -sS -o speech_extra_body_string.out -D speech_extra_body_string.headers -w 'HTTP %{http_code}, %{size_download} bytes, %{time_total}s\n' -X POST http://127.0.0.1:26927/v1/audio/speech -H "Authorization: Bearer $LITELLM_MASTER_KEY" -H 'Content-Type: application/json' --data-binary @speech_extra_body_string.json
HTTP 200, 437804 bytes, 2.444940s

$ grep -i -E '^(content-type|x-litellm-response-cost|x-litellm-call-id|x-litellm-model-api-base):' speech_extra_body_string.headers
x-litellm-call-id: d4deb8a4-4297-4eaa-990a-3a5b73521947
x-litellm-model-api-base: https://eu.api.gradium.ai
x-litellm-response-cost: 0.004549999999999999
content-type: audio/wav

$ file speech_extra_body_string.out
speech_extra_body_string.out: RIFF (little-endian) data, WAVE audio, Microsoft PCM, 16 bit, mono 48000 Hz

-- case spend log for the headline request
$ curl -sS 'http://127.0.0.1:26927/spend/logs?request_id=fd453679-813c-413f-bc49-d82e6ac17da1' -H "Authorization: Bearer $LITELLM_MASTER_KEY" | python3 -c 'import json,sys; [print(json.dumps({k: r.get(k) for k in ("request_id", "call_type", "model", "custom_llm_provider", "spend", "model_group")})) for r in json.load(sys.stdin)]'
{"request_id": "fd453679-813c-413f-bc49-d82e6ac17da1", "call_type": "aspeech", "model": "gradium/default", "custom_llm_provider": "gradium", "spend": 0.004549999999999999, "model_group": "gradium/default"}

502 for a 200 that is not audio, before 18bfcd2, after 3d98be6

Same setup, plus two deployments pointed at a local stub answering 200 with JSON or HTML

Case Before After
Stub JSON, pcm 200 audio/pcm, billed 502, $0
Stub HTML, pcm 200 audio/pcm, billed 502, $0
Stub JSON, wav 200 audio/pcm, billed 502, $0
Gradium wav 200 audio/wav 200 audio/wav
Gradium opus 200 audio/ogg 200 audio/ogg
Gradium pcm, ulaw, alaw 200 audio 200 audio

The proxy retried each 502 twice, three stub calls per request, as on main

Stubs, cells and output
  - model_name: gradium-stub-json
    litellm_params:
      model: gradium/default
      api_base: http://127.0.0.1:<json stub port>
      api_key: gsk_not_a_real_key
  - model_name: gradium-stub-html
    litellm_params:
      model: gradium/default
      api_base: http://127.0.0.1:<html stub port>
      api_key: gsk_not_a_real_key

stub.py <port> json|html

import sys
from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer

PORT, KIND = int(sys.argv[1]), sys.argv[2]
BODIES = {
    "json": ("application/json", b'{"text": "Bonjour", "type": "text"}'),
    "html": ("text/html; charset=utf-8", b"<html><body>" + b"maintenance " * 400 + b"</body></html>"),
}


class Handler(BaseHTTPRequestHandler):
    protocol_version = "HTTP/1.1"

    def do_POST(self):
        self.rfile.read(int(self.headers.get("content-length", 0)))
        content_type, body = BODIES[KIND]
        self.send_response(200)
        self.send_header("content-type", content_type)
        self.send_header("content-length", str(len(body)))
        self.end_headers()
        self.wfile.write(body)


ThreadingHTTPServer(("127.0.0.1", PORT), Handler).serve_forever()

cells.py <leg> <proxy port> and formats.py <leg> <proxy port>

import sys, time, pathlib, httpx

LEG, PORT = sys.argv[1], sys.argv[2]
q = pathlib.Path(__file__).parent
H = {"Authorization": "Bearer " + (q / "master.key").read_text().strip()}
c = httpx.Client(base_url=f"http://127.0.0.1:{PORT}", timeout=120)
cases = (
    ("gradium-stub-json", "pcm"),
    ("gradium-stub-html", "pcm"),
    ("gradium-stub-json", "wav"),
    ("gradium/default", "wav"),
)
ids = []
for model, fmt in cases:
    r = c.post("/v1/audio/speech", headers=H, json={"model": model, "input": "Bonjour", "voice": "alloy", "response_format": fmt})
    call_id = r.headers.get("x-litellm-call-id")
    ids.append((model, fmt, call_id, r.status_code))
    body = r.content[:120].decode("utf-8", "replace").replace("\n", " ")
    print(f"[{LEG}] {model} {fmt}: {r.status_code} {r.headers.get('content-type')} bytes={len(r.content)} cost={r.headers.get('x-litellm-response-cost')} body={body!r}")
time.sleep(12)
for model, fmt, call_id, code in ids:
    if not call_id:
        print(f"[{LEG}] {model} {fmt}: no call id")
        continue
    logs = c.get("/spend/logs", headers=H, params={"request_id": call_id}).json()
    rows = logs if isinstance(logs, list) else logs.get("data", [])
    print(f"[{LEG}] spend log {model} {fmt}: rows={len(rows)} " + " ".join(f"status={x.get('status')} spend={x.get('spend')}" for x in rows))
import sys, pathlib, httpx

LEG, PORT = sys.argv[1], sys.argv[2]
q = pathlib.Path(__file__).parent
H = {"Authorization": "Bearer " + (q / "master.key").read_text().strip()}
c = httpx.Client(base_url=f"http://127.0.0.1:{PORT}", timeout=120)
for fmt in ("opus", "pcm", "ulaw_8000", "alaw_8000", "wav", "flac", "aac"):
    r = c.post("/v1/audio/speech", headers=H, json={"model": "gradium/default", "input": "Bonjour", "voice": "alloy", "response_format": fmt})
    head = r.content[:8]
    detail = r.text[:160] if r.status_code != 200 else head.hex()
    print(f"[{LEG}] real {fmt}: {r.status_code} {r.headers.get('content-type')} bytes={len(r.content)} {detail}")
[before] gradium-stub-json pcm: 200 audio/pcm bytes=35 cost=0.00049 body='{"text": "Bonjour", "type": "text"}'
[before] gradium-stub-html pcm: 200 audio/pcm bytes=4826 cost=0.00049 body='<html><body>maintenance maintenance maintenance maintenance maintenance maintenance maintenance maintenance maintenance '
[before] gradium-stub-json wav: 200 audio/pcm bytes=35 cost=0.00049 body='{"text": "Bonjour", "type": "text"}'
[before] gradium/default wav: 200 audio/wav bytes=176684 cost=0.00049 body='RIFF����WAVEfmt \x10\x00\x00\x00\x01\x00\x01\x00��\x00\x00\x00w\x01\x00\x02\x00\x10\x00data����\x00\x00\x04\x00\x1f\x00P\x00�\x00�\x00�\x00\x14\x01;\x01A\x013\x01H\x01q\x01o\x01F\x01?\x01c\x01�\x01�\x01�\x01`\x01$\x01�\x00�\x00p\x00A\x00.\x00\x07\x00��S�B�m�y�=�\x12�Z�����'
[before] spend log gradium-stub-json pcm: rows=1 status=success spend=0.00049
[before] spend log gradium-stub-html pcm: rows=1 status=success spend=0.00049
[before] spend log gradium-stub-json wav: rows=1 status=success spend=0.00049
[before] spend log gradium/default wav: rows=1 status=success spend=0.00049
[before] real opus: 200 audio/ogg bytes=11384 4f67675300020000
[before] real pcm: 200 audio/pcm bytes=86400 fcff1f008900ee00
[before] real ulaw_8000: 200 audio/basic bytes=14400 fde7dedadbdedbd7
[before] real alaw_8000: 200 audio/x-alaw-basic bytes=14400 d5d8c1c0dc5351d5
[before] real wav: 200 audio/wav bytes=176684 52494646ffffffff
[before] real flac: 200 audio/wav bytes=176684 52494646ffffffff
[before] real aac: 200 audio/wav bytes=176684 52494646ffffffff

[after] gradium-stub-json pcm: 502 application/json bytes=265 cost=None body='{"error":{"message":"litellm.BadGatewayError: GradiumException - Gradium answered 200 with application/json instead of a'
[after] gradium-stub-html pcm: 502 application/json bytes=258 cost=None body='{"error":{"message":"litellm.BadGatewayError: GradiumException - Gradium answered 200 with text/html instead of audio\\n\\'
[after] gradium-stub-json wav: 502 application/json bytes=265 cost=None body='{"error":{"message":"litellm.BadGatewayError: GradiumException - Gradium answered 200 with application/json instead of a'
[after] gradium/default wav: 200 audio/wav bytes=176684 cost=0.00049 body='RIFF����WAVEfmt \x10\x00\x00\x00\x01\x00\x01\x00��\x00\x00\x00w\x01\x00\x02\x00\x10\x00data����\x00\x00\x05\x00\x1f\x00H\x00v\x00�\x00�\x00�\x00�\x00�\x00�\x00�\x00\x06\x01\x06\x01�\x00�\x00\x07\x01"\x01+\x01=\x019\x01\r\x01�\x00�\x00�\x00�\x00�\x00�\x00�\x00b\x00H\x00U\x00w\x00z\x00_\x00x\x00�\x00�\x00'
[after] spend log gradium-stub-json pcm: rows=1 status=failure spend=0.0
[after] spend log gradium-stub-html pcm: rows=1 status=failure spend=0.0
[after] spend log gradium-stub-json wav: rows=1 status=failure spend=0.0
[after] spend log gradium/default wav: rows=1 status=success spend=0.00049
[after] real opus: 200 audio/ogg bytes=10570 4f67675300020000
[after] real pcm: 200 audio/pcm bytes=86400 feff1e008100e000
[after] real ulaw_8000: 200 audio/basic bytes=14400 feece8e8fb68696e
[after] real alaw_8000: 200 audio/x-alaw-basic bytes=14400 d5d8c1c2dbd7dcc6
[after] real wav: 200 audio/wav bytes=176684 52494646ffffffff
[after] real flac: 200 audio/wav bytes=176684 52494646ffffffff
[after] real aac: 200 audio/wav bytes=176684 52494646ffffffff
Gauntlet-mini runs and rejected findings

Gauntlet-mini ran six times with 5/5 lenses each. Runs 9b021a1d3e6e, 188efa6d7c1f, d7d81b19f322 and a77f329af63d SURVIVED with 0 confirmed findings. Run 17697f850549 was PARTIAL, a non-object extra_body answered 500, and main fixed that in 7e10af7. Run a270dc7b576e on the 04d1963 pick SURVIVED with one low finding, its stream test cases did nothing on 1.108, so they were dropped

  • A deployment input_cost_per_character override does not change speech cost. Rejected, the same probe gives the same cost on main 758d7d6. This is the strongest dissent
  • wav and opus fall back to audio/pcm when the upstream content type is not audio/*. Rejected, a direct call to Gradium answers audio/wav for wav and audio/ogg for opus, so the fallback never runs for them, and the code matches main
  • Sync litellm.speech raises GradiumException on an upstream error. Rejected, speech() maps no provider's errors on main or 1.108, only aspeech() does
  • A standalone completion_cost call drops whitespace from the count. Rejected, that is the shared fallback and the live call bills every character
  • A full endpoint URL as api_base doubles the path. Rejected, the code matches main
  • Upper-case response_format values answer 400. Rejected, OpenAI's formats are lower case and the code matches main
  • A non-object extra_body is now ignored, where litellm usually answers 400 or drops under drop_params. Rejected as a defect, it is main's intended behavior and only SDK callers can send one
  • The non-object extra_body test passes a version that also drops a top-level json_config. Rejected as a blocker, the code is right and the test matches main

Type

🆕 New Feature

Caveats (if any)

Medium

Low

  • An out-of-range json_config value such as padding_bonus: 100 answers 200 with empty audio and bills the text, like a direct Gradium call
  • A Gradium model name the cost map does not list yet bills $0 until it gets a row
  • No streaming on 1.108, a stream: true request gets one buffered clip
  • Sync litellm.speech raises a raw GradiumException on an upstream error, as every speech provider does on main and 1.108
  • The provider docs link 404s until litellm-docs ui - fix create key flow / cleanup non admin flow #3198 merges

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

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

Note

Medium Risk
Introduces a new external TTS integration and adjusts speech cost calculation via provider-reported character counts, which affects billing accuracy for speech calls.

Overview
Adds Gradium as an audio_speech-only provider so litellm.speech() and proxy /v1/audio/speech can call Gradium’s REST TTS endpoint (/api/speech/tts) with required api_base and api_key.

The new GradiumTextToSpeechConfig maps OpenAI-style voices and response_format values to Gradium’s voice IDs and PCM/μ-law/A-law formats, forwards json_config from the caller or extra_body, rejects missing voices (400), and returns 502 when Gradium responds 200 with non-audio. Responses attach billed_characters in hidden params for pricing.

Spend tracking now uses a shared _speech_billed_characters helper so TTS cost can follow provider-reported character counts (including whitespace) instead of only re-counting the prompt.

Registry updates wire gradium into model lists, cost maps, endpoint capability metadata, proxy “Add model” credentials, and the llms-providers unit-test shard, with a large tests/unit/llms/gradium suite.

Reviewed by Cursor Bugbot for commit 3d98be6. Bugbot is set up for automated code reviews on this repo. Configure here.

zoveki and others added 14 commits November 20, 2026 10:58
Partial backport of BerriAI#48998 to lts/1.108.x: only the _speech_billed_characters hook in litellm/cost_calculator.py, so a text-to-speech config can report the characters its provider bills through hidden_params["billed_characters"]. Without a reported count, speech cost still counts characters the way it did before.
Cherry-picked hunk from bbc68e2 (main).
Gradium (https://gradium.ai) is a voice AI provider whose TTS had no
LiteLLM route. Adds it as a first-class TTS provider behind the existing
BaseTextToSpeechConfig seam, so `litellm.speech(model="gradium/default")`
and the proxy's /v1/audio/speech both work.

The provider targets Gradium's REST TTS endpoint
(POST /api/post/speech/tts) rather than its Python SDK, so the call
flows through base_llm_http_handler and keeps retries, logging and cost
tracking that an SDK-internal HTTP client would bypass.

Notes on the mapping:
- `only_audio: true` is always sent. Without it Gradium answers a
  line-delimited JSON message stream instead of audio bytes, which
  /v1/audio/speech callers cannot read.
- The six canonical OpenAI voice names map to Gradium library voice IDs;
  anything else is forwarded verbatim, so raw Gradium voice IDs work.
- Gradium has no mp3/aac/flac encoder, so those response_formats raise
  UnsupportedParamsError instead of silently returning mislabeled audio.
  `litellm.drop_params` falls back to the default format.
- Pre-stream failures come back as HTTP 500 with a plain-text body, so
  the response transform raises rather than handing the caller an opaque
  binary payload.
- Cost is per character of input text (1 credit/char), priced from the
  published add-on credit rate.

Backport of BerriAI#46427 to lts/1.108.x.
Cherry-picked from 3342c82 (kabooboo:feat/gradium-text-to-speech).
- register the provider in provider_endpoints_support.json and claim
  tests/unit/llms/gradium in the llms-providers shard, so the provider
  documentation and CI/shard coverage gates see it
- rework the transformation to build its params and request body
  functionally rather than by mutation, so it clears the type-discipline
  rules; the suppressions that remain are the signatures
  BaseTextToSpeechConfig fixes and the dicts its return types require
- get_complete_url now tolerates an api_base that already ends in /api.
  Gradium documents its regional bases that way
  (https://eu.api.gradium.ai/api), and pasting one produced
  /api/api/post/speech/tts.

Backport of BerriAI#46427 to lts/1.108.x.
Cherry-picked from 767d832 (kabooboo:feat/gradium-text-to-speech).
…ruff

- ruff format with the pinned 0.15.3 (the suppression comments were long
  enough to push their lines over the limit and get them wrapped)
- cover get_supported_openai_params, get_error_class, the explicit
  api_base/api_key path, and both missing-voice paths, taking the
  provider to 100% patch coverage

The missing-voice tests record where each guard actually fires:
map_openai_params raises ValueError first (same as elevenlabs), so
speech()'s own BadRequestError is reachable only when the provider
config manager returns None.

Backport of BerriAI#46427 to lts/1.108.x.
Cherry-picked from 9b5d71d (kabooboo:feat/gradium-text-to-speech).
The cost test wrote litellm.model_cost directly, which the test-quality
gate flags (TQ005): it is a process-wide global, and the leak is exactly
what the save/restore conftest exists to undo. The existing
local_model_cost_map fixture does the same setup with teardown, so the
suite no longer depends on LITELLM_LOCAL_MODEL_COST_MAP being exported.

Backport of BerriAI#46427 to lts/1.108.x.
Cherry-picked from c57080c (kabooboo:feat/gradium-text-to-speech).
- add a provider_create_fields.json entry so gradium appears in the
  proxy UI's Add Model dropdown; test_public_endpoints asserts every
  LlmProviders member is listed there
- parameterize the dict/list annotations copied from
  BaseTextToSpeechConfig and type gradium_models, which basedpyright
  counted as new Unknown-type errors against the merge-base ceiling
- suppress the untyped-argument errors on the shared TTS handler call;
  every provider branch of speech() carries the same ones
- keep extra_body support, matching elevenlabs and minimax, and cover it
  with a test

Backport of BerriAI#46427 to lts/1.108.x.
Cherry-picked from a1b0ba1 (kabooboo:feat/gradium-text-to-speech).
The API key and base are set by whoever creates the model, like any other
deployment credential. Drop the GRADIUM_API_KEY / GRADIUM_API_BASE
environment fallbacks, the litellm.api_key fallback (which could send an
unrelated provider's global key to Gradium) and the hardcoded default
base URL; a missing value now raises a clear error.

Backport of BerriAI#46427 to lts/1.108.x.
Cherry-picked from 8597dee (kabooboo:feat/gradium-text-to-speech).
provider_endpoints_support.json and its backup are now generated from
the cost map, so Gradium's hand-written entry was stale and missing
from the backup.

Backport of BerriAI#46427 to lts/1.108.x.
Adapted to the line: lts/1.108.x writes provider_endpoints_support.json by hand (no generator), so the Gradium entry in it and in the backup keeps the line's 12-key endpoint shape (a2a and interactions false) instead of main's generated 20-key shape.
Cherry-picked from 9ee0d5b (kabooboo:feat/gradium-text-to-speech).
…every character

Gradium counts every input character, spaces included, so the response reports billed_characters and the shared cost path no longer under-bills by the stripped whitespace

A deployment's drop_params now drops an unsupported response_format, speed or instructions. Without it those params answer 400, the litellm convention for a param the provider cannot honor

The Pro Voice Clone row is removed because Gradium has no such model name. The XS add-on rate is $7 per 100k credits, and the Add Model form now asks for the API base

Backport of BerriAI#46427 to lts/1.108.x.
Adapted to the line: GradiumTextToSpeechConfig sets no supports_streaming and the speech() branch passes no stream argument, since lts/1.108.x has no streaming text-to-speech handler (BerriAI#46222 is not on the line). Gradium speech on the line is buffered.
Cherry-picked from 364272a (kabooboo:feat/gradium-text-to-speech).
…r 400 on a missing voice

Calls Gradium's documented /api/speech/tts path, passes ulaw_8000, alaw_8000 and the pcm_* rates through with audio content types, maps ash, ballad, coral, sage, verse, marin and cedar, prices gradium/gradium-tts-beta, and types the tests

Backport of BerriAI#46427 to lts/1.108.x.
Adapted to the line: GradiumTextToSpeechConfig keeps no supports_streaming and the streaming test is left out, since lts/1.108.x has no streaming text-to-speech handler. Gradium speech on the line is buffered.
Cherry-picked from d7243e6 (kabooboo:feat/gradium-text-to-speech).
lts/1.108.x types HttpxBinaryResponseContent as a generic, so handing the narrowed response to _speech_billed_characters added a basedpyright reportUnknownArgumentType finding. The call site now reads billed_characters from hidden_params and passes the value, which keeps the gate at its base count. Speech cost is the same for every provider
…g, accept speed 1.0

Missing api_key now answers 401 and a missing api_base answers 500 without a traceback

Backport of BerriAI#46427 to lts/1.108.x.
Cherry-picked from b70cc74 (kabooboo:feat/gradium-text-to-speech).
…n_config

A non-object extra_body no longer answers 500, and a null json_config in
extra_body no longer erases the top-level value. The cost map drops the advice
to override input_cost_per_character, which speech cost ignores today, and adds
gradium/gradium-tts-202602, Gradium's previous model, at the same rate. The
async speech test now checks the request body sent on the buffered path.

Backport of BerriAI#46427 to lts/1.108.x.
Adapted to the line: lts/1.108.x has no Gradium streaming test, so the request body and x-api-key checks moved into the buffered aspeech test.
Cherry-picked from 7e10af7 (kabooboo:feat/gradium-text-to-speech).
A read-only mapping such as MappingProxyType passed as extra_body is now
read like a dict, as it was before the non-object check. The non-object
test also sends a top-level json_config so it fails if that check drops
every caller field

Backport of BerriAI#46427 to lts/1.108.x.
Cherry-picked from 2c3ac63 (kabooboo:feat/gradium-text-to-speech).
@CLAassistant

CLAassistant commented Nov 21, 2026 •

Copy link
Copy Markdown

CLA assistant check
Thank you for your submission! We really appreciate it. Like many open source projects, we ask that you all sign our Contributor License Agreement before we can accept your contribution.
2 out of 3 committers have signed the CLA.

✅ kabooboo
✅ mateo-berri
❌ zoveki
You have signed the CLA already but the status is still pending? Let us recheck it.

@veria-ai

veria-ai Bot commented Nov 21, 2026 •

Copy link
Copy Markdown
Contributor

PR overview

No security issues were found in this pull request.

Reviews

Only a missing content type or application/octet-stream, which Gradium
sends for pcm, ulaw and alaw, is relabeled as audio. Any other 200, such
as JSON or HTML, now raises a 502 instead of reaching the caller labeled
audio/pcm and being billed. Tests also pin case-insensitive voice names,
trimmed voices and extra_body's json_config winning over the top level

On 1.108 the rejection test drops its stream cases, since speech takes
no stream argument on this line

(cherry picked from commit 04d1963)
@codecov

codecov Bot commented Nov 21, 2026 •

Copy link
Copy Markdown

Codecov Report

❌ Patch coverage is 96.19048% with 4 lines in your changes missing coverage. Please review.

Files with missing lines Patch % Lines
litellm/main.py 75.00% 2 Missing ⚠️
litellm/utils.py 33.33% 2 Missing ⚠️

📢 Thoughts on this report? Let us know!

@mateo-berri

Copy link
Copy Markdown
Contributor

@greptileai

@greptile-apps

greptile-apps Bot commented Nov 21, 2026 •

Copy link
Copy Markdown
Contributor

RetriggerView in GreptileConfidence Score: 5/5

[Medium impact] The reviewed changes appear safe to merge

Summary

Adds Gradium speech support to the 1.108 LTS line

  • Gradium models now return audio from LiteLLM speech requests.
  • Gradium speech costs count every input character.

Acknowledgments by martenj4 were excluded from findings. These cover buffered replies instead of streaming, shared speech pricing overrides and standalone character-count fallback, plan and cloned-voice price differences, unlisted models costing zero, raw sync exceptions, the pending documentation link, empty audio from invalid json_config, full-endpoint URL handling, lowercase formats, MIME fallback, and intentionally ignored non-object extra_body. The previously noted weak extra_body test now checks that top-level json_config survives

Diagram

%%{init: {'theme': 'neutral'}}%%
flowchart LR
    A["Speech request"] --> B["Resolve Gradium provider"]
    B --> C["Map voice, format, and json_config"]
    C --> D["Gradium REST endpoint"]
    D --> E{"Audio reply?"}
    E -->|No| F["Return 502"]
    E -->|Yes| G["Return buffered audio"]
    G --> H["Bill input characters, including spaces"]
Loading

Reviews (1) · Last reviewed commit: "fix(gradium): answer 502 for a 200 respo..." · Reviewed by Greptile

@mateo-berri

Copy link
Copy Markdown
Contributor

bugbot run

@cursor cursor 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.

✅ 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 3d98be6. Configure here.

@mateo-berri mateo-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

@mateo-berri
mateo-berri merged commit 67c4ede into BerriAI:lts/1.108.x Nov 22, 2026
60 of 61 checks passed
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.

5 participants