Skip to content

Go: implement TTS and ASR for Cometapi - #15001

Merged
JinHai-CN merged 1 commit into
infiniflow:mainfrom
Haruko386:main
May 19, 2026
Merged

JinHai-CN merged 1 commit into
infiniflow:mainfrom
Haruko386:main

Conversation

@Haruko386

Copy link
Copy Markdown
Member

What problem does this PR solve?

Verified from CLI

RAGFlow(user)> tts with 'tts-1@test@cometapi' text 'hello? show yourself' play format 'wav' param '{"voice": "alloy"}'
SUCCESS

RAGFlow(user)> asr with 'FunAudioLLM/SenseVoiceSmall@test@siliconflow' audio './internal/test.wav' param '{"language": "en"}'
+----------------------------------------------------------------------------------------------------------------------+
| text                                                                                                                 |
+----------------------------------------------------------------------------------------------------------------------+
| The examination and testimony of the experts enabled the commission to conclude that five shots may have been fired. |
+----------------------------------------------------------------------------------------------------------------------+

Type of change

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

@dosubot dosubot Bot added the size:L This PR changes 100-499 lines, ignoring generated files. label May 19, 2026
@Haruko386 Haruko386 added the ci Continue Integration label May 19, 2026
@Haruko386
Haruko386 marked this pull request as draft May 19, 2026 10:02
@Haruko386
Haruko386 marked this pull request as ready for review May 19, 2026 10:02
@coderabbitai

coderabbitai Bot commented May 19, 2026 •

Copy link
Copy Markdown
Contributor

Review Change Stack

📝 Walkthrough

Walkthrough

This PR adds audio capability to CometAPI by registering ASR (whisper-1) and TTS (tts-1) endpoints and models in the configuration, expanding imports for multipart and file operations, and implementing the TranscribeAudio and AudioSpeech methods to handle audio transcription and speech synthesis via HTTP multipart and JSON requests.

Changes

CometAPI Audio Support

Layer / File(s) Summary
Configuration and endpoint setup
conf/models/cometapi.json
CometAPI url_suffix map is extended with tts and asr endpoint paths. Two models are added: whisper-1 (ASR, model_types: ["asr"]) and tts-1 (TTS, model_types: ["tts"], max_tokens: 8192).
Audio transcription (ASR) implementation
internal/entity/models/cometapi.go
Imports are added for multipart encoding, file/path operations, and type conversions. TranscribeAudio is implemented to validate the audio file, construct a multipart/form-data POST request to the region-specific ASR endpoint with the file, model name, and optional ASR config parameters, set Bearer authentication, parse the JSON text field from a successful 200 response, and return an ASRResponse or an error on failure.
Speech synthesis (TTS) implementation
internal/entity/models/cometapi.go
AudioSpeech is implemented to validate audioContent, select the region-specific TTS endpoint, build a JSON request body containing model, input text, optional TTS config parameters, and response_format, send a POST request with Bearer auth, require HTTP 200, read the raw response body as audio bytes, and return TTSResponse{Audio: body} or an error with status and response body on failure.

Estimated code review effort

🎯 3 (Moderate) | ⏱️ ~20 minutes

Possibly related PRs

  • infiniflow/ragflow#14930: Introduces the TranscribeAudio and AudioSpeech method signatures as stubs in CometAPI, which this PR fills with complete implementations.
  • infiniflow/ragflow#14944: Implements the same ASR/TTS pattern for alternative providers (Siliconflow and StepFun), adding similar endpoint configuration and method implementations.

Suggested labels

size:L

🐰 Hop along to audio dreams,
Whispers transcribed, speeches streamed,
CometAPI now speaks and hears,
Bridging voices through the years! 🎤✨

🚥 Pre-merge checks | ✅ 5
✅ Passed checks (5 passed)
Check name Status Explanation
Title check ✅ Passed The title clearly and concisely describes the main change: implementing TTS and ASR functionality for the Cometapi integration in Go.
Description check ✅ Passed The PR description includes the required 'What problem does this PR solve?' section with CLI-verified examples, and the 'Type of change' section with appropriate selections, covering the essential information.
Docstring Coverage ✅ Passed No functions found in the changed files to evaluate docstring coverage. Skipping docstring coverage check.
Linked Issues check ✅ Passed Check skipped because no linked issues were found for this pull request.
Out of Scope Changes check ✅ Passed Check skipped because no linked issues were found for this pull request.

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

Actionable comments posted: 5

🤖 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 `@conf/models/cometapi.json`:
- Around line 118-119: Remove the unused "max_tokens" field from the TTS model
entry "tts-1" in conf/models/cometapi.json because AudioSpeech (function
AudioSpeech in cometapi.go) never reads or uses it; edit the JSON to delete the
"max_tokens" property for the "tts-1" model so the config accurately reflects
the parameters the TTS request builder uses (model, input, custom parameters,
format).

In `@internal/entity/models/cometapi.go`:
- Around line 721-726: The error string returned when the CometAPI upstream
returns a non-200 (the resp.StatusCode != http.StatusOK branch that calls
fmt.Errorf("SiliconFlow ASR error: %s - %s", resp.Status, string(respBody)))
incorrectly names "SiliconFlow"; change that message to reference "CometAPI"
(e.g., "CometAPI ASR error: ...") so the returned error and logs correctly
identify the CometAPI driver/endpoint (update the fmt.Errorf call in that
resp.StatusCode check).
- Around line 632-638: Replace the ad-hoc region/url construction that sets
region := "default" and uses fmt.Sprintf("%s/%s", m.BaseURL[region],
m.URLSuffix.ASR) with the existing helpers: call
endpointURL(cometapiRegion(apiConfig), m.URLSuffix.ASR) so you reuse the
cometapiRegion logic (which picks and validates the region against m.BaseURL)
and endpointURL (which trims slashes and preserves fast-fail behavior); do the
same replacement for the analogous block around m.URLSuffix.ASR at lines
~747-752, referencing m.BaseURL and m.URLSuffix.ASR as the target components to
build the endpoint.
- Around line 627-629: The TranscribeAudio method currently dereferences
modelName and apiConfig.ApiKey directly and can panic; call
validateCometAPIModelName(modelName) and validateCometAPIAPIKey(apiConfig) at
the start of TranscribeAudio (and the other CometAPI methods flagged) to perform
nil checks and return the same validation errors, then use the validated
modelName value and the validated apiConfig.ApiKey value for subsequent
dereferences (replace direct uses of *modelName and *apiConfig.ApiKey with the
validated variables).
- Around line 699-710: TranscribeAudio and AudioSpeech create requests with
http.NewRequest and lack the context deadline; update both to create the request
with context using context.WithTimeout(ctx, nonStreamCallTimeout) and
http.NewRequestWithContext so the overall non-stream timeout is enforced before
calling m.httpClient.Do; locate the request creation in the TranscribeAudio and
AudioSpeech methods (where req, err := http.NewRequest(...) is used), wrap the
provided ctx with nonStreamCallTimeout, use that context in
NewRequestWithContext, and ensure defers/cancel are handled correctly.
🪄 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: b30912fb-2851-4c36-9877-fa8b97b2398a

📥 Commits

Reviewing files that changed from the base of the PR and between 8990d09 and b4f8b53.

⛔ Files ignored due to path filters (2)
  • internal/test.pdf is excluded by !**/*.pdf
  • internal/test.wav is excluded by !**/*.wav
📒 Files selected for processing (2)
  • conf/models/cometapi.json
  • internal/entity/models/cometapi.go

Comment thread conf/models/cometapi.json
Comment on lines +118 to +119
"name": "tts-1",
"max_tokens": 8192,

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.

⚠️ Potential issue | 🟡 Minor | ⚡ Quick win

🧩 Analysis chain

🏁 Script executed:

#!/bin/bash
# Description: Search for max_tokens usage in TTS/audio context

# Search for max_tokens field access in audio/TTS related code
rg -n -C5 'max_tokens' --type=go -g '*audio*' -g '*tts*' -g '*cometapi*'

# Search for TTS model configuration loading
ast-grep --pattern 'model_types.*tts'

# Search for how model fields are accessed for TTS
rg -n -C5 'model_types.*tts|tts.*model_types' --type=go

Repository: infiniflow/ragflow

Length of output: 7938


🏁 Script executed:

# Search for TTS request struct definitions
rg -n -C5 'type.*tts.*[Rr]equest|type.*audio.*[Rr]equest' --type=go

# Search for how cometapi handles TTS model requests
rg -n -C10 'tts|audio' internal/entity/models/cometapi.go

# Check if max_tokens is accessed from model config for TTS
rg -n -C5 'GetMaxTokens|maxTokens|max_tokens.*model' --type=go

# Look for model field access patterns
ast-grep --pattern 'model\["max_tokens"\]|model\.MaxTokens'

Repository: infiniflow/ragflow

Length of output: 34326


Remove unused max_tokens field from TTS model configuration.

The max_tokens field for the tts-1 model is defined in the config but never used in the TTS request construction. The AudioSpeech function (cometapi.go:742-797) builds requests using only the model name, input text, custom parameters, and format—it does not access max_tokens from the model config. Unlike embedding models which explicitly document and use max_tokens for text truncation, TTS models should not include this unused field.

🤖 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 `@conf/models/cometapi.json` around lines 118 - 119, Remove the unused
"max_tokens" field from the TTS model entry "tts-1" in conf/models/cometapi.json
because AudioSpeech (function AudioSpeech in cometapi.go) never reads or uses
it; edit the JSON to delete the "max_tokens" property for the "tts-1" model so
the config accurately reflects the parameters the TTS request builder uses
(model, input, custom parameters, format).

Comment on lines 627 to +629
func (m *CometAPIModel) TranscribeAudio(modelName *string, file *string, apiConfig *APIConfig, asrConfig *ASRConfig) (*ASRResponse, error) {
return nil, fmt.Errorf("%s, no such method", m.Name())
if file == nil || *file == "" {
return nil, fmt.Errorf("file is missing")

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.

⚠️ Potential issue | 🔴 Critical | ⚡ Quick win

Validate modelName and apiConfig before dereferencing them.

Line 662 and Line 705, plus Line 755 and Line 779, dereference *modelName and *apiConfig.ApiKey without any guard. A nil modelName, nil apiConfig, or nil apiConfig.ApiKey will panic the driver instead of returning the same validation errors used by the other CometAPI methods. Please run validateCometAPIAPIKey / validateCometAPIModelName up front in both methods and use the validated values afterwards.

Also applies to: 661-705, 742-745, 754-779

🤖 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/cometapi.go` around lines 627 - 629, The
TranscribeAudio method currently dereferences modelName and apiConfig.ApiKey
directly and can panic; call validateCometAPIModelName(modelName) and
validateCometAPIAPIKey(apiConfig) at the start of TranscribeAudio (and the other
CometAPI methods flagged) to perform nil checks and return the same validation
errors, then use the validated modelName value and the validated
apiConfig.ApiKey value for subsequent dereferences (replace direct uses of
*modelName and *apiConfig.ApiKey with the validated variables).

Comment on lines +632 to +638
region := "default"
if apiConfig != nil && apiConfig.Region != nil && *apiConfig.Region != "" {
region = *apiConfig.Region
}

url := fmt.Sprintf("%s/%s", m.BaseURL[region], m.URLSuffix.ASR)

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.

⚠️ Potential issue | 🟡 Minor | ⚡ Quick win

Reuse cometapiRegion / endpointURL instead of open-coding the endpoint.

These blocks duplicate logic that already exists in this file, and they also drop the fast-fail behavior from baseURLForRegion. If apiConfig.Region points to a region missing from m.BaseURL, fmt.Sprintf("%s/%s", m.BaseURL[region], ...) produces a path-only URL and the transport fails later with an opaque scheme error. Calling endpointURL(cometapiRegion(apiConfig), ...) keeps the error consistent and trims slashes correctly.

Also applies to: 747-752

🤖 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/cometapi.go` around lines 632 - 638, Replace the
ad-hoc region/url construction that sets region := "default" and uses
fmt.Sprintf("%s/%s", m.BaseURL[region], m.URLSuffix.ASR) with the existing
helpers: call endpointURL(cometapiRegion(apiConfig), m.URLSuffix.ASR) so you
reuse the cometapiRegion logic (which picks and validates the region against
m.BaseURL) and endpointURL (which trims slashes and preserves fast-fail
behavior); do the same replacement for the analogous block around
m.URLSuffix.ASR at lines ~747-752, referencing m.BaseURL and m.URLSuffix.ASR as
the target components to build the endpoint.

Comment on lines +699 to +710
// build request
req, err := http.NewRequest("POST", url, &body)
if err != nil {
return nil, fmt.Errorf("failed to create request: %w", err)
}

req.Header.Set("Authorization", fmt.Sprintf("Bearer %s", *apiConfig.ApiKey))
req.Header.Set("Content-Type", writer.FormDataContentType())
req.Header.Set("Accept", "application/json")

// send request
resp, err := m.httpClient.Do(req)

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.

⚠️ Potential issue | 🟠 Major | ⚡ Quick win

🧩 Analysis chain

🏁 Script executed:

wc -l internal/entity/models/cometapi.go

Repository: infiniflow/ragflow

Length of output: 101


🏁 Script executed:

head -100 internal/entity/models/cometapi.go | tail -20

Repository: infiniflow/ragflow

Length of output: 630


🏁 Script executed:

sed -n '1,50p' internal/entity/models/cometapi.go

Repository: infiniflow/ragflow

Length of output: 1442


🏁 Script executed:

# Search for NewCometAPIModel function
rg -n "func NewCometAPIModel" internal/entity/models/cometapi.go -A 20

Repository: infiniflow/ragflow

Length of output: 738


🏁 Script executed:

# Search for httpClient initialization
rg -n "httpClient" internal/entity/models/cometapi.go | head -20

Repository: infiniflow/ragflow

Length of output: 277


🏁 Script executed:

# Check for nonStreamCallTimeout definition
rg -n "nonStreamCallTimeout" internal/entity/models/cometapi.go

Repository: infiniflow/ragflow

Length of output: 398


🏁 Script executed:

sed -n '310,330p' internal/entity/models/cometapi.go

Repository: infiniflow/ragflow

Length of output: 651


🏁 Script executed:

sed -n '490,510p' internal/entity/models/cometapi.go

Repository: infiniflow/ragflow

Length of output: 541


🏁 Script executed:

sed -n '550,570p' internal/entity/models/cometapi.go

Repository: infiniflow/ragflow

Length of output: 668


🏁 Script executed:

sed -n '580,600p' internal/entity/models/cometapi.go

Repository: infiniflow/ragflow

Length of output: 706


🏁 Script executed:

sed -n '690,715p' internal/entity/models/cometapi.go

Repository: infiniflow/ragflow

Length of output: 752


🏁 Script executed:

sed -n '765,790p' internal/entity/models/cometapi.go

Repository: infiniflow/ragflow

Length of output: 784


🏁 Script executed:

# Find nonStreamCallTimeout definition
rg -n "nonStreamCallTimeout\s*=" internal/entity/models/cometapi.go

Repository: infiniflow/ragflow

Length of output: 44


🏁 Script executed:

# Find ASR/TTS method names
rg -n "func.*ASR|func.*TTS|func.*Asr|func.*Tts" internal/entity/models/cometapi.go

Repository: infiniflow/ragflow

Length of output: 712


🏁 Script executed:

rg -n "nonStreamCallTimeout" internal/entity/models/cometapi.go -B 2 -A 2

Repository: infiniflow/ragflow

Length of output: 634


🏁 Script executed:

# Check if it's defined at package level (near top of file)
sed -n '1,100p' internal/entity/models/cometapi.go | grep -n "nonStreamCallTimeout\|timeout\|Timeout"

Repository: infiniflow/ragflow

Length of output: 375


🏁 Script executed:

# Look for const definitions in the file
rg -n "const " internal/entity/models/cometapi.go

Repository: infiniflow/ragflow

Length of output: 44


🏁 Script executed:

# Search for nonStreamCallTimeout across the entire codebase
rg -n "nonStreamCallTimeout" --type go -B 2 -A 2

Repository: infiniflow/ragflow

Length of output: 13092


Use http.NewRequestWithContext with nonStreamCallTimeout for TranscribeAudio and AudioSpeech methods.

TranscribeAudio (lines 699-710) and AudioSpeech (lines 773-781) build plain http.NewRequest requests without context, while ChatWithMessages, Embed, ListModels, and Balance all wrap non-stream calls in context.WithTimeout with nonStreamCallTimeout (120 seconds). Since httpClient.Timeout is intentionally unset in NewCometAPIModel, the context timeout is the required overall deadline for non-streaming requests. Update both methods to use http.NewRequestWithContext to prevent stalled uploads or responses from blocking indefinitely.

🤖 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/cometapi.go` around lines 699 - 710, TranscribeAudio
and AudioSpeech create requests with http.NewRequest and lack the context
deadline; update both to create the request with context using
context.WithTimeout(ctx, nonStreamCallTimeout) and http.NewRequestWithContext so
the overall non-stream timeout is enforced before calling m.httpClient.Do;
locate the request creation in the TranscribeAudio and AudioSpeech methods
(where req, err := http.NewRequest(...) is used), wrap the provided ctx with
nonStreamCallTimeout, use that context in NewRequestWithContext, and ensure
defers/cancel are handled correctly.

Comment on lines +721 to +726
if resp.StatusCode != http.StatusOK {
return nil, fmt.Errorf("SiliconFlow ASR error: %s - %s", resp.Status, string(respBody))
}

// SiliconFlow response
var result struct {

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.

⚠️ Potential issue | 🟡 Minor | ⚡ Quick win

Fix the copied provider name in the ASR error path.

Line 722 returns "SiliconFlow ASR error" from the CometAPI driver. That will mislead debugging and alerting when the CometAPI upstream is the one failing.

🤖 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/cometapi.go` around lines 721 - 726, The error string
returned when the CometAPI upstream returns a non-200 (the resp.StatusCode !=
http.StatusOK branch that calls fmt.Errorf("SiliconFlow ASR error: %s - %s",
resp.Status, string(respBody))) incorrectly names "SiliconFlow"; change that
message to reference "CometAPI" (e.g., "CometAPI ASR error: ...") so the
returned error and logs correctly identify the CometAPI driver/endpoint (update
the fmt.Errorf call in that resp.StatusCode check).

@codecov

codecov Bot commented May 19, 2026

Copy link
Copy Markdown

Codecov Report

✅ All modified and coverable lines are covered by tests.
✅ Project coverage is 93.12%. Comparing base (8990d09) to head (b4f8b53).

Additional details and impacted files
@@           Coverage Diff           @@
##             main   #15001   +/-   ##
=======================================
  Coverage   93.12%   93.12%           
=======================================
  Files          10       10           
  Lines         713      713           
  Branches      116      116           
=======================================
  Hits          664      664           
  Misses         29       29           
  Partials       20       20           

☔ 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 1a95f9b into infiniflow:main May 19, 2026
1 check passed
@coderabbitai coderabbitai Bot mentioned this pull request May 27, 2026
3 tasks done
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.

2 participants