Repository navigation
Go: implement ASR in OpenRouter driver - #15067
Conversation
|
No actionable comments were generated in the recent review. 🎉 ℹ️ Recent review info⚙️ Run configurationConfiguration used: Organization UI Review profile: CHILL Plan: Pro Run ID: 📒 Files selected for processing (2)
📝 WalkthroughWalkthroughThis PR adds OpenRouter ASR transcription support by configuring the ASR endpoint and model in JSON, implementing ChangesOpenRouter ASR Implementation
Estimated code review effort🎯 4 (Complex) | ⏱️ ~45 minutes Possibly related PRs
Suggested labels
Suggested reviewers
Poem
🚥 Pre-merge checks | ✅ 4 | ❌ 1❌ Failed checks (1 warning)
✅ Passed checks (4 passed)
✏️ Tip: You can configure your own custom pre-merge checks in the settings. Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out. Comment |
There was a problem hiding this comment.
🧹 Nitpick comments (1)
internal/entity/models/novita_test.go (1)
703-706: ⚡ Quick winStrengthen the HTTP-error assertion to verify status line and response body are preserved.
This test currently only asserts a generic prefix, so it can pass even if status/body surfacing regresses.
Suggested assertion tightening
- if err == nil || !strings.Contains(err.Error(), "Novita balance API error") { + if err == nil || + !strings.Contains(err.Error(), "Novita balance API error") || + !strings.Contains(err.Error(), "401 Unauthorized") || + !strings.Contains(err.Error(), `{"reason":"unauthorized"}`) { t.Errorf("err=%v", err) }🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the rest with a brief reason, keep changes minimal, and validate. In `@internal/entity/models/novita_test.go` around lines 703 - 706, The test in novita_test.go uses newNovitaForTest(...).Balance(&APIConfig{ApiKey: &apiKey}) but only checks for a generic "Novita balance API error" substring; update the assertion to verify the error message preserves both the HTTP status line and response body: call Balance as before and assert err is non-nil, then assert strings.Contains(err.Error(), "<expected status text>") (e.g., "500 Internal Server Error" or the exact status line your test server returns) and also assert strings.Contains(err.Error(), "<expected response body substring>") (the body text your test handler returns), referencing newNovitaForTest and Balance to locate the test and tighten the checks.
🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.
Nitpick comments:
In `@internal/entity/models/novita_test.go`:
- Around line 703-706: The test in novita_test.go uses
newNovitaForTest(...).Balance(&APIConfig{ApiKey: &apiKey}) but only checks for a
generic "Novita balance API error" substring; update the assertion to verify the
error message preserves both the HTTP status line and response body: call
Balance as before and assert err is non-nil, then assert
strings.Contains(err.Error(), "<expected status text>") (e.g., "500 Internal
Server Error" or the exact status line your test server returns) and also assert
strings.Contains(err.Error(), "<expected response body substring>") (the body
text your test handler returns), referencing newNovitaForTest and Balance to
locate the test and tighten the checks.
ℹ️ Review info
⚙️ Run configuration
Configuration used: Organization UI
Review profile: CHILL
Plan: Pro
Run ID: d4596ea3-e1b6-4995-b986-de016fa663c0
📒 Files selected for processing (3)
conf/models/novita.jsoninternal/entity/models/novita.gointernal/entity/models/novita_test.go
Haruko386
left a comment
There was a problem hiding this comment.
Hi @jakearmstrong59, thank you for your contribution. Unfortunately, the code you provided in the PR is incorrect, and I have already implemented this interface (just haven't committed it yet). I suggest you work on a different interface and submit a PR for that instead.
9cba072 to
e7a46d5
Compare
There was a problem hiding this comment.
Actionable comments posted: 1
🧹 Nitpick comments (3)
internal/entity/models/openrouter.go (2)
541-552: 💤 Low valueFormat type-assertion silently ignores non-string values.
If a caller passes
Params["format"]as a non-string (e.g., from JSON decoded tofloat64/bool), the assertion fails silently and the code falls back to file-extension inference, which can be surprising. A small reflect/fmt.Sprint-based coercion or an explicit error/log would aid debugging, but this is purely an ergonomics concern.🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the rest with a brief reason, keep changes minimal, and validate. In `@internal/entity/models/openrouter.go` around lines 541 - 552, The function openRouterAudioFormat silently ignores non-string Params["format"]; update openRouterAudioFormat to coerce non-string values (e.g., via fmt.Sprint or reflect to stringify) when asrConfig != nil && asrConfig.Params != nil so that numeric/bool values are accepted, then trim any leading '.' and validate non-empty before returning; keep the existing fallback to file extension ("wav") if the resulting string is empty or invalid and ensure you reference asrConfig.Params["format"] and the openRouterAudioFormat function when implementing the change.
587-594: ⚡ Quick win
asrConfig.Paramsmerge can clobbermodelandinput_audio.The loop only skips
"format", so a caller that passes"model"or"input_audio"inParamswill silently overwrite the values you just set on lines 580–585. Either expand the skip list, or perform the params merge before settingmodel/input_audioso the structured fields always win.♻️ Proposed guard
- if asrConfig != nil && asrConfig.Params != nil { - for key, value := range asrConfig.Params { - if key == "format" { - continue - } - reqBody[key] = value - } - } + if asrConfig != nil && asrConfig.Params != nil { + for key, value := range asrConfig.Params { + switch key { + case "format", "model", "input_audio": + continue + } + reqBody[key] = value + } + }🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the rest with a brief reason, keep changes minimal, and validate. In `@internal/entity/models/openrouter.go` around lines 587 - 594, The merge of asrConfig.Params into reqBody currently only skips "format", so caller-supplied keys like "model" or "input_audio" can overwrite the values you set earlier; update the merge to protect those structured fields by either (A) expanding the skip list to include "model" and "input_audio" (along with "format") when iterating asrConfig.Params into reqBody, or (B) move the params-merge block to run before you assign the structured fields so your subsequent assignments to reqBody["model"] and reqBody["input_audio"] always override any Params values; reference the asrConfig.Params loop and reqBody assignments to locate the change.internal/entity/models/openrouter_test.go (1)
149-174: 💤 Low valueOptional: add a test case for the missing ASR URL suffix branch.
TranscribeAudioreturns"OpenRouter ASR url suffix is missing"(openrouter.go line 565-567), but the validation table doesn't cover that branch. A one-line addition that constructs a model with an emptyURLSuffix.ASRwould lock that contract in, matching the "missing-balance-suffix safety" coverage pattern used elsewhere in this project.🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the rest with a brief reason, keep changes minimal, and validate. In `@internal/entity/models/openrouter_test.go` around lines 149 - 174, Add a test case to TestOpenRouterTranscribeAudioValidatesInputs that covers the ASR URL suffix missing branch: call newOpenRouterForTest(...).TranscribeAudio with valid modelName and ApiKey but supply an APIConfig whose URLSuffix.ASR is an empty string (e.g., APIConfig{ApiKey: &apiKey, URLSuffix: &URLSuffix{ASR: ""}}) and assert the error message contains "OpenRouter ASR url suffix is missing"; this will exercise the TranscribeAudio validation path in openrouter.go that checks URLSuffix.ASR.
🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.
Inline comments:
In `@internal/entity/models/openrouter_test.go`:
- Around line 86-89: Replace the t.Fatalf calls in the HTTP handler inside
newOpenRouterServer with t.Errorf(...) followed by an immediate return:
specifically change the checks that assert inputAudio :=
body["input_audio"].(map[string]interface{}) and the other similar cast (around
the second occurrence) so that on type assertion failure you call
t.Errorf("...") and then return from the handler rather than t.Fatalf(...); this
matches the rest of newOpenRouterServer and prevents the handler goroutine from
calling runtime.Goexit() while the test goroutine continues.
---
Nitpick comments:
In `@internal/entity/models/openrouter_test.go`:
- Around line 149-174: Add a test case to
TestOpenRouterTranscribeAudioValidatesInputs that covers the ASR URL suffix
missing branch: call newOpenRouterForTest(...).TranscribeAudio with valid
modelName and ApiKey but supply an APIConfig whose URLSuffix.ASR is an empty
string (e.g., APIConfig{ApiKey: &apiKey, URLSuffix: &URLSuffix{ASR: ""}}) and
assert the error message contains "OpenRouter ASR url suffix is missing"; this
will exercise the TranscribeAudio validation path in openrouter.go that checks
URLSuffix.ASR.
In `@internal/entity/models/openrouter.go`:
- Around line 541-552: The function openRouterAudioFormat silently ignores
non-string Params["format"]; update openRouterAudioFormat to coerce non-string
values (e.g., via fmt.Sprint or reflect to stringify) when asrConfig != nil &&
asrConfig.Params != nil so that numeric/bool values are accepted, then trim any
leading '.' and validate non-empty before returning; keep the existing fallback
to file extension ("wav") if the resulting string is empty or invalid and ensure
you reference asrConfig.Params["format"] and the openRouterAudioFormat function
when implementing the change.
- Around line 587-594: The merge of asrConfig.Params into reqBody currently only
skips "format", so caller-supplied keys like "model" or "input_audio" can
overwrite the values you set earlier; update the merge to protect those
structured fields by either (A) expanding the skip list to include "model" and
"input_audio" (along with "format") when iterating asrConfig.Params into
reqBody, or (B) move the params-merge block to run before you assign the
structured fields so your subsequent assignments to reqBody["model"] and
reqBody["input_audio"] always override any Params values; reference the
asrConfig.Params loop and reqBody assignments to locate the change.
🪄 Autofix (Beta)
Fix all unresolved CodeRabbit comments on this PR:
- Push a commit to this branch (recommended)
- Create a new PR with the fixes
ℹ️ Review info
⚙️ Run configuration
Configuration used: Organization UI
Review profile: CHILL
Plan: Pro
Run ID: 37137d8e-faa8-4827-b9b0-7eaeae252efd
📒 Files selected for processing (3)
conf/models/openrouter.jsoninternal/entity/models/openrouter.gointernal/entity/models/openrouter_test.go
|
@Haruko386 @JinHai-CN |
Haruko386
left a comment
There was a problem hiding this comment.
@jakearmstrong59 LGTM
Thank you for your contribution
Codecov Report✅ All modified and coverable lines are covered by tests. Additional details and impacted files@@ Coverage Diff @@
## main #15067 +/- ##
==========================================
- Coverage 94.53% 93.12% -1.41%
==========================================
Files 10 10
Lines 713 713
Branches 116 116
==========================================
- Hits 674 664 -10
- Misses 25 29 +4
- Partials 14 20 +6 ☔ View full report in Codecov by Sentry. 🚀 New features to boost your workflow:
|
What problem does this PR solve?
Fixes #15066
OpenRouter now exposes an official speech-to-text endpoint at
POST /api/v1/audio/transcriptions, but the Go model driver still returnedopenrouter, no such methodfromTranscribeAudio. This left OpenRouter ASR models unavailable through the Go API server even though the provider already has OpenRouter audio support for TTS.Related provider-tracking context: #14736
Changes
internal/entity/models/openrouter.go: implementOpenRouterModel.TranscribeAudio.input_audioJSON object.input_audio.formatfrom the file extension, withasrConfig.Params["format"]as an explicit override.language,temperature, andprovider.textintoASRResponse.Text.conf/models/openrouter.json: add theaudio/transcriptionsASR suffix and an OpenRouter transcription model entry.internal/entity/models/openrouter_test.go: add focused httptest coverage for happy path, format inference, input validation, and HTTP error surfacing.fmt.Errorfformat string found while running the package tests.Type of change
Test plan
/tmp/go1.26.3/bin/gofmt -l internal/entity/models/openrouter.go internal/entity/models/openrouter_test.gopython3 -m json.tool conf/models/openrouter.jsonGOCACHE=/tmp/ragflow-go-build-cache GOMODCACHE=/tmp/ragflow-go-mod-cache /tmp/go1.26.3/bin/go test -vet=off -run TestOpenRouter -count=1 ./internal/entity/modelsNotes for reviewers
go test -run TestOpenRouter -count=1 ./internal/entity/modelscurrently trips unrelated pre-existing vet failures in other provider files. With vet disabled, the focused OpenRouter tests pass.go test -vet=off -count=1 ./internal/entity/modelscurrently fails in the existing Novita balance test path on currentmain; that is unrelated to this OpenRouter ASR change.