Skip to content

Go: implement ASR in OpenRouter driver - #15067

Merged
JinHai-CN merged 3 commits into
infiniflow:mainfrom
whitepicker:feat/15066-novita-balance
May 22, 2026
Merged

JinHai-CN merged 3 commits into
infiniflow:mainfrom
whitepicker:feat/15066-novita-balance

Conversation

@whitepicker

@whitepicker whitepicker commented May 20, 2026 •

Copy link
Copy Markdown
Contributor

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 returned openrouter, no such method from TranscribeAudio. 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: implement OpenRouterModel.TranscribeAudio.
    • Validate API key, model name, file path, and ASR URL suffix.
    • Read the audio file, base64-encode it, and send the documented input_audio JSON object.
    • Infer input_audio.format from the file extension, with asrConfig.Params["format"] as an explicit override.
    • Forward additional ASR params such as language, temperature, and provider.
    • Parse the response text into ASRResponse.Text.
    • Preserve upstream status and body on non-200 responses.
  • conf/models/openrouter.json: add the audio/transcriptions ASR 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.
  • Also fixes a stale OpenRouter fmt.Errorf format string found while running the package tests.

Type of change

  • New Feature (non-breaking change which adds functionality)

Test plan

  • /tmp/go1.26.3/bin/gofmt -l internal/entity/models/openrouter.go internal/entity/models/openrouter_test.go
  • python3 -m json.tool conf/models/openrouter.json
  • GOCACHE=/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/models

Notes for reviewers

  • A normal go test -run TestOpenRouter -count=1 ./internal/entity/models currently trips unrelated pre-existing vet failures in other provider files. With vet disabled, the focused OpenRouter tests pass.
  • A full go test -vet=off -count=1 ./internal/entity/models currently fails in the existing Novita balance test path on current main; that is unrelated to this OpenRouter ASR change.

@dosubot dosubot Bot added the size:M This PR changes 30-99 lines, ignoring generated files. label May 20, 2026
@coderabbitai

coderabbitai Bot commented May 20, 2026 •

Copy link
Copy Markdown
Contributor

Review Change Stack

No actionable comments were generated in the recent review. 🎉

ℹ️ Recent review info
⚙️ Run configuration

Configuration used: Organization UI

Review profile: CHILL

Plan: Pro

Run ID: 9da257fc-a570-43d5-9985-8ad6b472fd39

📥 Commits

Reviewing files that changed from the base of the PR and between e7a46d5 and 84a72e6.

📒 Files selected for processing (2)
  • internal/entity/models/openrouter.go
  • internal/entity/models/openrouter_test.go

📝 Walkthrough

Walkthrough

This PR adds OpenRouter ASR transcription support by configuring the ASR endpoint and model in JSON, implementing TranscribeAudio with file I/O, base64 encoding, and format inference, and adding unit tests covering happy path, validation, and error handling.

Changes

OpenRouter ASR Implementation

Layer / File(s) Summary
ASR endpoint and model configuration
conf/models/openrouter.json
Adds audio/transcriptions ASR URL suffix and registers openai/whisper-large-v3 as an ASR model with token limits.
TranscribeAudio implementation
internal/entity/models/openrouter.go
Implements TranscribeAudio with API/key/model/file validation, base64 encoding of audio, automatic format inference from config or filename extension, merging ASR params (excluding format, model, input_audio), HTTP POST to OpenRouter ASR endpoint, 200-check, response { "text": ... } parsing, and a minor ListModels error formatting tweak. Adds imports and helpers.
Test infrastructure and TranscribeAudio coverage
internal/entity/models/openrouter_test.go
Adds httptest-based helpers, temp audio file writer, and tests for configured-format handling, inferred-format from filename, happy-path request/response shape, input validation errors, missing ASR suffix error, and upstream HTTP error propagation.

Estimated code review effort

🎯 4 (Complex) | ⏱️ ~45 minutes

Possibly related PRs

Suggested labels

💞 feature, size:L

Suggested reviewers

  • Haruko386

Poem

🐰 I nibble bytes and hum a tune so spry,
I base64-hop audio up to the sky,
Formats inferred from filenames I keep,
OpenRouter listens while I softly leap,
Transcribed whispers delivered—nice and sly.

🚥 Pre-merge checks | ✅ 4 | ❌ 1

❌ Failed checks (1 warning)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 0.00% which is insufficient. The required threshold is 80.00%. Write docstrings for the functions missing them to satisfy the coverage threshold.
✅ Passed checks (4 passed)
Check name Status Explanation
Title check ✅ Passed The title clearly and concisely describes the main change: implementing ASR (Automatic Speech Recognition) in the OpenRouter driver for the Go codebase.
Description check ✅ Passed The description includes all required template sections (problem statement, type of change) with comprehensive details about what is being fixed, the specific changes made, test plan, and notes for reviewers.
Linked Issues check ✅ Passed The PR fully implements the requirements from issue #15066: implements TranscribeAudio with proper validation and error handling [#15066], adds audio/transcriptions ASR suffix and model entry to openrouter.json [#15066], includes base64 encoding and format inference [#15066], forwards ASR params and parses responses [#15066], and provides httptest coverage [#15066].
Out of Scope Changes check ✅ Passed All changes are directly scoped to implementing OpenRouter ASR support: openrouter.json configuration, TranscribeAudio implementation, test coverage, and an unrelated fmt.Errorf fix discovered during testing are all aligned with issue #15066 objectives.

✏️ 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.

❤️ Share

Comment @coderabbitai help to get the list of available commands and usage tips.

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

🧹 Nitpick comments (1)
internal/entity/models/novita_test.go (1)

703-706: ⚡ Quick win

Strengthen 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

📥 Commits

Reviewing files that changed from the base of the PR and between dc01e0e and 9cba072.

📒 Files selected for processing (3)
  • conf/models/novita.json
  • internal/entity/models/novita.go
  • internal/entity/models/novita_test.go

@Haruko386 Haruko386 left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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.

@whitepicker
whitepicker force-pushed the feat/15066-novita-balance branch from 9cba072 to e7a46d5 Compare May 21, 2026 19:41

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

Actionable comments posted: 1

🧹 Nitpick comments (3)
internal/entity/models/openrouter.go (2)

541-552: 💤 Low value

Format type-assertion silently ignores non-string values.

If a caller passes Params["format"] as a non-string (e.g., from JSON decoded to float64/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.Params merge can clobber model and input_audio.

The loop only skips "format", so a caller that passes "model" or "input_audio" in Params will silently overwrite the values you just set on lines 580–585. Either expand the skip list, or perform the params merge before setting model/input_audio so 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 value

Optional: add a test case for the missing ASR URL suffix branch.

TranscribeAudio returns "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 empty URLSuffix.ASR would 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

📥 Commits

Reviewing files that changed from the base of the PR and between 9cba072 and e7a46d5.

📒 Files selected for processing (3)
  • conf/models/openrouter.json
  • internal/entity/models/openrouter.go
  • internal/entity/models/openrouter_test.go

@whitepicker whitepicker changed the title Go: implement Balance in Novita driver Go: implement ASR in OpenRouter driver May 21, 2026
@whitepicker
whitepicker requested a review from Haruko386 May 21, 2026 19:52
@dosubot dosubot Bot added size:L This PR changes 100-499 lines, ignoring generated files. and removed size:M This PR changes 30-99 lines, ignoring generated files. labels May 21, 2026
@whitepicker

whitepicker commented May 22, 2026 •

Copy link
Copy Markdown
Contributor Author

@Haruko386 @JinHai-CN
I changed PR to solve totally different issue.
Can you review my PR again please? Thanks.

@Haruko386 Haruko386 left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

@jakearmstrong59 LGTM
Thank you for your contribution

@Haruko386 Haruko386 added the ci Continue Integration label May 22, 2026
@codecov

codecov Bot commented May 22, 2026

Copy link
Copy Markdown

Codecov Report

✅ All modified and coverable lines are covered by tests.
✅ Project coverage is 93.12%. Comparing base (57ddd79) to head (207627f).
⚠️ Report is 4 commits behind head on main.

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.
📢 Have feedback on the report? Share it here.

🚀 New features to boost your workflow:
  • ❄️ Test Analytics: Detect flaky tests, report on failures, and find test suite problems.
  • 📦 JS Bundle Analysis: Save yourself from yourself by tracking and limiting bundle sizes in JS merges.

@JinHai-CN
JinHai-CN merged commit b1ef5d3 into infiniflow:main May 22, 2026
1 check passed
@whitepicker
whitepicker deleted the feat/15066-novita-balance branch May 22, 2026 10:55
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

ci Continue Integration size:L This PR changes 100-499 lines, ignoring generated files.

Projects

None yet

Development

Successfully merging this pull request may close these issues.

[Feature Request]: Implement ASR in the OpenRouter Go driver

3 participants