Repository navigation
feat(soniox): decode proxy form fields for context, translation and flags - #40605
mateo-berri merged 11 commits into
Conversation
Merging this PR will not alter performance
|
Codecov Report✅ All modified and coverable lines are covered by tests. 📢 Thoughts on this report? Let us know! |
|
@greptileai please review this PR, the automatic review did not start after it was opened. |
|
|
@greptileai both findings are addressed in cf33d3f, please review the updated commit. |
|
@greptileai added a test covering the new Soniox types in 3d9e261, no behavior change, please re-review. |
|
@greptileai the mutable params workflow is replaced in 70f8bce, please re-review. |
|
@greptileai the flagged comment is removed in 80c56c0, please re-review. |
80c56c0 to
63c0924
Compare
63c0924 to
847eaeb
Compare
7cbbc55 to
ef2a39b
Compare
2ad0457 to
9c17c17
Compare
|
Nothing more from you. Code review is done. The last step is a live run against Soniox on our account, being set up now |
…t_proxy_form_params
|
Automatic reviews are disabled for this repository. |
|
@litereview code-review |
✅ code-review5/5 · Ready for human reviewScope: full · Full PR review. No correctness findings. Checks and execution details
The PR description includes inspectable manual E2E evidence. It names the base (
The decisive success evidence is the In the repository, I ran
View review · Reviewed |
Validate structured context before sending it as an object, answer 400 for a bad polling interval or flag unless drop_params is on, nest SDK bracketed extra_body fields, keep the OpenAI language at the head of language_hints, and return the translated text for one-way translation without tags.
|
@litereview code-review |
| _STRUCTURED_CONTEXT: Final = TypeAdapter(SonioxContext) | ||
| _FORM_BOOL: Final = TypeAdapter(bool) | ||
| _LANGUAGE_HINTS: Final = TypeAdapter(tuple[object, ...]) | ||
| _BRACKETED_FORM_FIELD: Final = re.compile(r"(?P<param>context|translation)\[(?P<field>\w+)\]") |
There was a problem hiding this comment.
Low · SDK dict context silently loses general and translation_terms
- A developer calls the proxy with the OpenAI SDK and sets
extra_body={'context': {'terms': ['Kold Brew'], 'general': [{'key': 'domain', 'value': 'Coffee shop'}]}}. - The SDK flattens this into the form keys
context[terms][],context[general][][key]andcontext[general][][value]. get_form_datastrips only a trailing[], socontext[terms][]becomescontext[terms]. Thegeneralkeys keep their[][key]suffix.- The new
_BRACKETED_FORM_FIELDregex (context\[\w+\]) matches onlycontext[terms]. Soniox receivescontext={'terms': [...]}. The twogeneralkeys go out as unknown top-level body fields. - The caller gets no error, but Soniox never sees the
generalcontext.translation_termsfollows the same path.
This is code-derived and confirmed locally against decode_soniox_form_params. I did not observe how Soniox handles the stray top-level keys. The PR caveat says these fields "keep only the last entry", but the code drops them from context entirely. The smallest fix is to nest context[<field>][][<sub>] keys into lists of objects, or return a 400 when bracketed context keys can't be nested.
Evidence
openai SDK _serialize_multipartform output for {'context': {'terms': ['a'], 'general': [{'key': 'k', 'value': 'v'}], 'translation_terms': [{'source': 'a', 'target': 'b'}]}}:
{'context[terms][]': 'a', 'context[general][][key]': 'k', 'context[general][][value]': 'v', 'context[translation_terms][][source]': 'a', 'context[translation_terms][][target]': 'b', ...}
Local run: decode_soniox_form_params({'context[general][][key]':'k','context[general][][value]':'v','context[terms]':['a'], ...}) returned {'context': {'terms': ['a']}, 'context[general][][key]': 'k', 'context[general][][value]': 'v', ...}
litellm/proxy/common_utils/http_parsing_utils.py:497: get_form_data strips only a trailing [] from form keys.
handler.py _prepare forwards every decoded key not in _NOT_FORWARDED_TO_SONIOX into the create body, so the stray keys reach Soniox.
Latest summary by code-review · View this review · Reviewed 008dcd9e6991
There was a problem hiding this comment.
The proxy form parser keeps one value per repeated key, so these entries cannot be rebuilt. A JSON-string context works, listed as a caveat
There was a problem hiding this comment.
Finding still applies
Thanks for the context. Part of the reply is correct: get_form_data overwrites a repeated key unless it ends in []. With two or more general entries, the proxy can't fully rebuild context[general][][key] and context[general][][value].
That point doesn't refute the finding, which is about the silent failure:
- A caller sends
extra_body={'context': {'terms': [...], 'general': [{'key': 'domain', 'value': 'Coffee shop'}]}}through the OpenAI SDK. _BRACKETED_FORM_FIELD(context\[\w+\]) matches onlycontext[terms]. Thegeneralkeys don't match, so the code leaves them out ofcontext._prepareforwards those keys to Soniox as unknown top-level body fields.- The request still succeeds with no error, but Soniox never gets the
generalcontext.
The current code can rebuild even a single entry, and the proxy can always reject unnested bracketed context[...] / translation[...] keys with a 400. Either change would close the finding. The PR caveat acknowledges the limitation, but an acknowledged caveat isn't technical evidence, so the finding stays upheld at Low severity.
Evidence
Local run at head: decode_soniox_form_params({'context[terms]':['a'],'context[general][][key]':'k','context[general][][value]':'v'}) returned {'context': {'terms': ['a']}, 'context[general][][key]': 'k', 'context[general][][value]': 'v'}. No error was raised.
litellm/llms/soniox/audio_transcription/transformation.py:75: _BRACKETED_FORM_FIELD = re.compile(r"(?P<param>context|translation)\[(?P<field>\w+)\]") only fully matches single-level keys. _nest_bracketed_form_fields passes every unmatched key through unchanged.
litellm/proxy/common_utils/http_parsing_utils.py get_form_data: keys ending in [] accumulate into lists. Every other key does parsed_form_data[key] = value, so the last repeat wins. This confirms the reply's premise for multi-entry lists only.
litellm/llms/soniox/audio_transcription/handler.py:273: the create body includes every decoded key not in _NOT_FORWARDED_TO_SONIOX, so the stray context[general][][...] keys reach Soniox as top-level fields.
PR caveat: "SDK extra_body context general and translation_terms never reach Soniox ... send JSON text". This acknowledges the defect and does not fix it.
Reviewed 008dcd9e6991 · View follow-up
There was a problem hiding this comment.
d1478ac rebuilds general and translation_terms entries from the SDK's bracketed columns. Lists past one entry keep the last, noted in Caveats
There was a problem hiding this comment.
Finding withdrawn
Thanks for the fix. The finding said OpenAI SDK extra_body general and translation_terms context never reached Soniox and leaked as unknown top-level fields. That no longer happens at d1478ac69b:
_BRACKETED_FORM_FIELDnow matchescontext[<field>][][<entry_field>]._nested_form_paramand_form_entrieszip the matched columns into lists of objects undercontext._nest_bracketed_form_fieldsremoves the matched bracketed keys, so_preparedoesn't forward them as top-level fields.
One limitation remains. The SDK sends repeated context[general][][key] keys, and get_form_data keeps only the last value for each one, so a list with more than one entry arrives as its last entry. The earlier follow-up said that rebuilding a single entry would close this finding, and the PR documents the multi-entry case as a caveat. The proxy parser's handling of repeated keys causes it, and this PR didn't add that behavior. I don't consider that enough to keep this finding open.
Evidence
Local run at head: decode_soniox_form_params({'context[terms]':['a'],'context[general][][key]':'k','context[general][][value]':'v','context[translation_terms][][source]':'s','context[translation_terms][][target]':'t'}) returned {'context': {'terms': ['a'], 'translation_terms': ({'source': 's', 'target': 't'},), 'general': ({'key': 'k', 'value': 'v'},)}}. The result has no stray top-level keys.
litellm/llms/soniox/audio_transcription/transformation.py:74-76: _BRACKETED_FORM_FIELD = re.compile(r"(?P<param>context|translation)\[(?P<field>\w+)\](?:\[\]\[(?P<entry_field>\w+)\])?")
transformation.py:162-209: _form_entries zips the columns into rows. _nest_bracketed_form_fields keeps a key unnested only when it doesn't match or its param was dropped.
tests/unit/llms/soniox/audio_transcription/test_soniox_audio_transcription_transformation.py:852 test_should_rebuild_openai_sdk_list_of_object_context_fields passed locally: 6 passed for -k "bracket or general or nest".
litellm/proxy/common_utils/http_parsing_utils.py:496-501: get_form_data accumulates values only for keys ending in []. For context[general][][key], the last repeat wins. This is the multi-entry caveat.
GitHub does not allow this App to resolve this thread. A repository maintainer must do it manually.
Reviewed d1478ac69b0a · View follow-up
|
@litereview code-review |
… reject malformed JSON values
|
@litereview code-review |
|
Keeping the source transcript in |
|
@litereview code-review |
|
@litereview code-review |
…he proxy form path
|
@litereview code-review |
| ) | ||
|
|
||
|
|
||
| def soniox_language_hints(language: object, hints: object) -> object: |
There was a problem hiding this comment.
Medium · language is dropped when language_hints is also set
- A caller runs
litellm.transcription(model="soniox/stt-async-v5", language="en", language_hints=["fr"], ...). The proxy form fieldslanguage=enandlanguage_hints=frtake the same path. map_openai_paramsand the handler's_prepareboth call the newsoniox_language_hints(language, hints).- That helper returns
hintsunchanged whenever they are present. The handler then stripslanguagethrough_NOT_FORWARDED_TO_SONIOX. - Soniox receives
language_hints: ["fr"]with noen. At base,map_openai_paramsprepended the value and sent["en", "fr"].
The PR description says the opposite: "language joins the hints, as the base map_openai_params and its tests specify". Its Low caveat says sending both now adds language to the hints. The PR also renamed and inverted the base test test_should_prepend_language_to_existing_hints to test_should_keep_explicit_hints_over_language, which locks in the regression.
Smallest fix: have soniox_language_hints prepend language when it is missing from hints, and restore the base test. If dropping language is intended, correct the description and caveat and treat this as a behavior change.
Evidence
Base map_openai_params (removed in the diff): elif language not in existing_hints: optional_params["language_hints"] = [language] + list(existing_hints).
Head transformation.py:93-97: if hints is not None or not isinstance(language, str) or not language: return hints.
Local reproducer through litellm.transcription with the repo's _MockSyncClient, language="en", language_hints=["fr"] and audio_url. The captured POST body was {'model': 'stt-async-v5', 'language_hints': ['fr'], 'audio_url': 'https://x/a.wav'}.
Test diff: test_should_prepend_language_to_existing_hints asserting ["en", "fr"] became test_should_keep_explicit_hints_over_language asserting ["fr"].
Latest summary by code-review · View this review · Reviewed 2cbb5c745ac4
There was a problem hiding this comment.
Deliberate. Explicit language_hints win over language, as the base did at runtime, so a pinned strict list never widens. Case R covers it
There was a problem hiding this comment.
Finding withdrawn
You're right, and thanks for pointing to Case R. The prepend branch in the base map_openai_params never ran through litellm.transcription:
get_optional_params_transcriptioncallsmap_openai_paramswithoptional_params={}. At that pointexisting_hintsis alwaysNone, so the base code setlanguage_hints=["en"].- Next,
add_provider_specific_params_to_optional_paramscopied the caller'slanguage_hints=["fr"]over that value, because Soniox is not an OpenAI-SDK provider. - Soniox received
["fr"]at base, and it receives["fr"]at head. Runtime behavior did not regress.
The base unit test test_should_prepend_language_to_existing_hints called map_openai_params with prefilled optional_params, which the real caller never passes. Changing that test makes it match runtime behavior. The current PR description also states that "Explicit language_hints win over language, as at the base", so the mismatch with the description no longer applies. I'm withdrawing the finding.
Evidence
litellm/utils.py:3632 sets optional_params = {}. Then :3671 calls provider_config.map_openai_params(..., optional_params=optional_params).
litellm/utils.py:3678 and :5196-5200: for providers that don't use the OpenAI SDK, optional_params[k] = passed_params[k] runs for every non-OpenAI param. That overwrites language_hints.
Base simulation (base map_openai_params patched in, uv run) printed base sees existing_hints = None, then {'language_hints': ['fr'], 'model': 'stt-async-v5'}.
Head printed {'language': 'en', 'language_hints': ['fr'], 'model': 'stt-async-v5'}. language is in _NOT_FORWARDED_TO_SONIOX (handler.py), so Soniox gets ['fr'].
transformation.py:93-97 soniox_language_hints returns explicit hints unchanged. test_should_keep_explicit_hints_over_language asserts ['fr'].
The current PR description says: "Explicit language_hints win over language, as at the base, so pinned strict hints stay as set".
GitHub does not allow this App to resolve this thread. A repository maintainer must do it manually.
Reviewed 2cbb5c745ac4 · View follow-up
|
@litereview code-review |
|
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 2cbb5c7. Configure here.
|
@litellm-stampbot |
litellm-stampbotthe head branch lives on |
mateo-berri
left a comment
There was a problem hiding this comment.
LGTM. Thanks for the contribution!
TLDR
Problem this solves:
context,translation, or flags, since form fields arrive as stringsHow it solves it:
translationJSON and flags get real types, decoded once at the handler entrylanguage_hints=en,esbecomes a list, and OpenAIlanguagefills the hints only when none are setextra_bodydicts sent as bracketed keys likecontext[terms]become objectsdrop_paramsDecisions and their alternatives:
language_hintswin overlanguage, as at the base, so pinned strict hints stay as setonandyeswork toosoniox_max_polling_attemptskeeps the default, as beforeUser Flow
Before: Soniox context and flags reach Soniox as plain strings
Kold Brew, Mayneas context termstranslationas stringsAfter: the fields reach Soniox with real JSON types
Linear ticket
Resolves LIT-7513
Pre-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 moreDelays 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
Both legs call the real Soniox API through a 2-worker proxy with no database, booted from cf1e6b1, the merge base, or 2cbb5c7, the tip. The audio says "cold brew", so
Kold Brewshows only whencontextreaches Soniox as an objectT. The author's audio translation app
The app posts form fields to the proxy in
GATSBY_LITELLM_API_URL. Steps on both legscoffee_shop.mp3stt-async-v5, and formatjsonenand Context: terms toKold Brew, Mayne, and tick Language identification, Speaker diarization (Soniox), and Translate inside SonioxThe app's curl preview
Before (cf1e6b1): Soniox rejects both flags and
translationBefore, the raw response
After (2cbb5c7):
Kold BrewandMayne, with German linesAfter, the raw response
Other clients and cases
soniox-sttissoniox/stt-async-v5, andsoniox-stt-dropaddsdrop_params: truecold brewKold Brewmaybetwo_wayaloneone_wayaloneonabcdrop_paramsdrop_paramslanguageplus hintscold brewKold BrewH. `context` with only `terms`
Before (cf1e6b1)
After (2cbb5c7)
A. Context, one_way translation, and the three flags
Before (cf1e6b1)
After (2cbb5c7)
B. A flag set to `maybe`
Before (cf1e6b1)
After (2cbb5c7)
C. `language_hints=en,es` with `enable_speaker_diarization=1`
Before (cf1e6b1)
After (2cbb5c7)
D. `language_hints` as a JSON array
Before (cf1e6b1)
After (2cbb5c7)
E. Free-form text `context`
Before (cf1e6b1)
After (2cbb5c7)
F. No Soniox fields
Before (cf1e6b1)
After (2cbb5c7)
G. `two_way` translation alone
Before (cf1e6b1)
After (2cbb5c7)
I. `context` as a JSON list, sent as text on both legs
Before (cf1e6b1)
After (2cbb5c7)
J. `one_way` translation alone
Before (cf1e6b1)
After (2cbb5c7)
K. A flag set to `on`
Before (cf1e6b1)
After (2cbb5c7)
L. `soniox_polling_interval=abc`
Before (cf1e6b1)
After (2cbb5c7)
M. A flag set to `maybe` on the `drop_params: true` model group
Before (cf1e6b1)
After (2cbb5c7)
N. Malformed `translation` JSON on the `drop_params: true` model group
Before (cf1e6b1)
After (2cbb5c7)
P. `language_hints=[en, es]`
Before (cf1e6b1)
After (2cbb5c7)
R. `language=de` with `language_hints=en` and `language_hints_strict=true`
Before (cf1e6b1)
After (2cbb5c7)
O1. OpenAI Python SDK, `extra_body` with JSON strings
Before (cf1e6b1)
After (2cbb5c7)
O2. OpenAI Python SDK, `extra_body` with dict values
Before (cf1e6b1)
After (2cbb5c7)
O3. OpenAI Python SDK, `extra_body` with a dict `context`
Before (cf1e6b1)
After (2cbb5c7)
The OpenAI SDK script behind O1 to O3, run as
python sdk_case.py $PORT .Type
🆕 New Feature
Caveats (if any)
Medium
contextkeeps only the lastgeneralandtranslation_termsentrytranslationsent alone returns no translated text, as beforeverbose_json, untimed translated tokens sit inwordsnext to the source wordsLow
contextobject with a typo or a future Soniox key goes as text, as beforesoniox_cleanupstring deletes nothing, as beforeFinal 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
2cbb5c7 passes /live-pr-risk
Note
Medium Risk
Changes request parsing and language-hint precedence for all Soniox transcription calls via proxy/SDK forms; scope is isolated to Soniox but affects forwarded API payloads and error behavior.
Overview
Fixes Soniox audio transcription through the LiteLLM proxy when multipart form fields arrive as strings. Soniox was rejecting
context,translation, booleans, andlanguage_hintsbecause they were forwarded as plain text instead of typed JSON.The handler’s
_preparenow runsdecode_soniox_form_paramsonce (without mutating caller params): booleans from strings (includingon/yes), JSON forcontext/translation, comma- or JSON-listlanguage_hints, and nesting of OpenAI SDK bracket keys likecontext[terms]andcontext[general][][key]. Handler-only fields stay out of the Soniox POST body; OpenAIlanguagemaps tolanguage_hintsonly when hints are absent, and explicit hints overridelanguage(no more prepending).Invalid form values return a 400
SonioxExceptionwith a clear message; withdrop_params, bad fields are dropped (e.g. invalid poll interval falls back to defaults after decode). AddsSonioxContexttyping and broad unit/proxy-form tests.Reviewed by Cursor Bugbot for commit 2cbb5c7. Bugbot is set up for automated code reviews on this repo. Configure here.