Repository navigation
feat(gradium): add text-to-speech support for /v1/audio/speech (lts/1.108.x) - #53463
mateo-berri merged 15 commits into
Conversation
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).
|
|
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 Report❌ Patch coverage is
📢 Thoughts on this report? Let us know! |
[Medium impact] The reviewed changes appear safe to merge
|
|
bugbot run |
There was a problem hiding this comment.
✅ 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.
Handwritten 1-3 sentence description
Gradium text-to-speech now works on the 1.108 LTS line. A proxy admin can add a
gradium/defaultmodel, and/v1/audio/speechreturns Gradium audio billed per input character, spaces included, the way Gradium counts creditsLTS twin of main #46427. Main merges first, this PR must not merge before it
Original
TLDR
Problem this solves:
How it solves it:
gradium/provider forlitellm.speechand/v1/audio/speechjson_configfrom the caller, at top level or inextra_body, and nothing elsegradium/default,gradium/gradium-tts-betaandgradium/gradium-tts-202602at the same per-character rateUser Flow
Before: a developer whose proxy admin adds a Gradium voice model gets an error instead of audio
gradium/defaultmodel with anapi_baseand anapi_key, then restarts the proxy{"model": "gradium/default", "input": "Bonjour !", "voice": "alloy"}After: the same request comes back as playable Gradium audio, billed per character
gradium/defaultmodel and restarts the proxyaudio/wavbytes and anx-litellm-response-costheadergradium/defaultCommit mapping
3342c8200a6ca4c9978e428c1d0562a334842e0cd583ba29f05d957c9286bb7d9e3c22ed533ae328767d832ba5f4bc9ce4520a87862254e05f55b0e7d65672346675724c763c2f09c16f1336dde492bd9b5d71d07560eb54da8386448b35fd9df1d1bc70a9be7a2f57c4465138fc3b8d91f88fb6886fdb01c57080cb45dbb833572b00c0acc5fb8a92bcc2d1359118074a3bbfbc1a065bce4336ae36deab59b8a1b0ba1a13f6dd6d0d817f45c1963acfe1f0309a9f57ff58e9d473dc396a0c6236a2f782cd072c9b8597deeba31089f84229a03f38368b7bd5f1cd7d0d5979b8b2ac6d59944805ba287f7a2f5a9f2ed19ee0d5b42bfb0d4a33eb59030c973caeba8470c73a977fecc293d759bd6d9d097c44023498218b73adapted364272ae12131d42acadeb44c98f0696384782178b9289f39f1c073fdfdbaf304b32ebd36536e8e3adaptedd7243e687d5807ab37d6753ef70cc2e96f173e92a29f0cc4ef482f99c4be6f4364fb467d70497290adaptedb70cc7478143cfb16435c68f9463389edd9895a9348f6f89cebc1f920e6f137c2c924657db79d5ac7e10af7fb4baa4233adf2044f503880339a140de51063b726c6ba6c628c01a4fc3ed24e4014dbb95adapted2c3ac63d8eccdf78f4a8b890da1149056aa2af4d18bfcd28270e50cdd03eb37774182c711274f64304d1963696dda76dc44b73264d3b35ed7a3f40a83d98be6ee61b244fed6e16a91841c8d50f1b97daadapted4553dda866518b694b7684521f89e8cccef1beba(streaming) and7a205320ef03d76ece9d4a8a458e6ba91f4877b6(it closes a streamed reply, which 1.108 never has) are main only, see the pair block.af94850f9b9f72262fe923db7156e8121c0a70e4andac92521e12eea6cb37200fa193a1b12eddfc14d8are a partial pick of #48998, also in the pair blockDifferences from main
streamargument, so the Gradium config leaves streaming out, main's streaming test is dropped and the 502 test drops itsstreamcases. Astream: truerequest gets the buffered clipaf94850f9bbrings 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 changesac92521e12is LTS only. The speech cost hook takesbilled_charactersfrom its call site, because passing 1.108's genericHttpxBinaryResponseContentadded a basedpyright finding. Speech cost is unchanged for every providerScreenshots / 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
--reloadbecause uvicorn 0.51 then serves one worker.LITELLM_LOCAL_MODEL_COST_MAP=Truemakes each leg read its own cost mapConfig, proxy command and env var names
qa_config.yamlislitellm/proxy/dev_config.yamlplus this model and these settingsEach leg's
.envsetsGRADIUM_API_KEY,LITELLM_MASTER_KEY,DATABASE_URL,REDIS_HOST,REDIS_PORTandLITELLM_LOCAL_MODEL_COST_MAP=TrueThe request bodies.
speech_stream.jsonisspeech.jsonplus"stream": truespeech_json_config.jsonisspeech.jsonplus"json_config": {"padding_bonus": -1.0}, andspeech_extra_body_string.jsonisspeech.jsonplus"extra_body": "oops"Before 7ab941f, after 18bfcd2
speech.jsonaudio/wavspeech_stream.jsonaudio/wavspeech_ulaw.jsonaudio/basicspeech_json_config.jsonaudio/wavspeech_extra_body_string.jsonaudio/wavspeech_blank_voice.jsonThe base proxy drops
gradium/defaultat boot withLLM Provider NOT provided, so every request answersThere are no healthy deployments for this model, and the two new bodies were not sent thereSpeech request after
curl -X POST http://127.0.0.1:26927/v1/audio/speech --data-binary @speech.jsonanswersHTTP 200, 460844 byteswithcontent-type: audio/wavandx-litellm-response-cost: 0.004549999999999999, which is 65 characters at $0.00007file speech.outreportsRIFF (little-endian) data, WAVE audio, Microsoft PCM, 16 bit, mono 48000 HzGET /spend/logs?request_id=fd453679-813c-413f-bc49-d82e6ac17da1returns the row withcall_typeaspeech,custom_llm_providergradiumandspend0.004549999999999999Other cases after
Speech request with stream true
speech_stream.jsonanswersHTTP 200, 476204 bytes,audio/wav, the same cost, as one buffered clipμ-law request
speech_ulaw.jsonanswersHTTP 200, 36160 byteswithcontent-type: audio/basicand the same cost. That is 4.5 seconds of 8 kHz audiojson_config
speech_json_config.jsonanswersHTTP 200, 422444 bytes,audio/wav, the same cost{'json_config': {'padding_bonus': -1.0}, 'output_format': 'wav', 'text': '...', 'voice_id': 'YTpq7expH9539ERJ', 'only_audio': True}Non-object extra_body
speech_extra_body_string.jsonanswersHTTP 200, 437804 bytes,audio/wav, the same cost, and the body sent to Gradium has no extra fieldBlank voice
speech_blank_voice.jsonanswersHTTP 400withGradium voice_id is required. Pass voice when calling litellm.speech()Full transcripts
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
audio/pcm, billedaudio/pcm, billedaudio/pcm, billedaudio/wavaudio/wavaudio/oggaudio/oggThe proxy retried each 502 twice, three stub calls per request, as on main
Stubs, cells and output
stub.py <port> json|htmlcells.py <leg> <proxy port>andformats.py <leg> <proxy port>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_bodyanswered 500, and main fixed that in 7e10af7. Run a270dc7b576e on the 04d1963 pick SURVIVED with one low finding, itsstreamtest cases did nothing on 1.108, so they were droppedinput_cost_per_characteroverride does not change speech cost. Rejected, the same probe gives the same cost on main 758d7d6. This is the strongest dissentaudio/pcmwhen the upstream content type is notaudio/*. Rejected, a direct call to Gradium answersaudio/wavfor wav andaudio/oggfor opus, so the fallback never runs for them, and the code matches mainlitellm.speechraisesGradiumExceptionon an upstream error. Rejected,speech()maps no provider's errors on main or 1.108, onlyaspeech()doescompletion_costcall drops whitespace from the count. Rejected, that is the shared fallback and the live call bills every characterapi_basedoubles the path. Rejected, the code matches mainresponse_formatvalues answer 400. Rejected, OpenAI's formats are lower case and the code matches mainextra_bodyis now ignored, where litellm usually answers 400 or drops underdrop_params. Rejected as a defect, it is main's intended behavior and only SDK callers can send oneextra_bodytest passes a version that also drops a top-leveljson_config. Rejected as a blocker, the code is right and the test matches mainType
🆕 New Feature
Caveats (if any)
Medium
input_cost_per_characterfor speech,tts-1too. Main honors it since fix(cost): bill speech at a deployment's custom per-character price #53265, which is not on this lineLow
json_configvalue such aspadding_bonus: 100answers 200 with empty audio and bills the text, like a direct Gradium callstream: truerequest gets one buffered cliplitellm.speechraises a rawGradiumExceptionon an upstream error, as every speech provider does on main and 1.108Pre-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 moreFinal Attestation
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 solitellm.speech()and proxy/v1/audio/speechcan call Gradium’s REST TTS endpoint (/api/speech/tts) with requiredapi_baseandapi_key.The new
GradiumTextToSpeechConfigmaps OpenAI-style voices andresponse_formatvalues to Gradium’s voice IDs and PCM/μ-law/A-law formats, forwardsjson_configfrom the caller orextra_body, rejects missing voices (400), and returns 502 when Gradium responds 200 with non-audio. Responses attachbilled_charactersin hidden params for pricing.Spend tracking now uses a shared
_speech_billed_charactershelper so TTS cost can follow provider-reported character counts (including whitespace) instead of only re-counting the prompt.Registry updates wire
gradiuminto model lists, cost maps, endpoint capability metadata, proxy “Add model” credentials, and thellms-providersunit-test shard, with a largetests/unit/llms/gradiumsuite.Reviewed by Cursor Bugbot for commit 3d98be6. Bugbot is set up for automated code reviews on this repo. Configure here.