Skip to content

Go: implement TTS, ASR for Siliconflow and TTs for StepFun - #14944

Merged
JinHai-CN merged 2 commits into
infiniflow:mainfrom
Haruko386:main
May 15, 2026
Merged

JinHai-CN merged 2 commits into
infiniflow:mainfrom
Haruko386:main

Conversation

@Haruko386

Copy link
Copy Markdown
Member

What problem does this PR solve?

This PRimplement TTS, ASR for Siliconflow and TTs for StepFun

The following functionalities are now supported:

SiliConFlow:

  • Text To Speech
  • Audio To Text
  • Stream Audio To Text

StrepFun:

  • Audio To Text
  • Stream Audio To Text

Verified examples from the CLI:

# SiliconFlow

RAGFlow(user)> tts with 'FunAudioLLM/CosyVoice2-0.5B@test@Siliconflow' text 'hello? show yourself' play format 'wav' param '{"voice": "fnlp/MOSS-TTSD-v0.5:alex"}'
SUCCESS

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

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

Type of change

  • Bug Fix (non-breaking change which fixes an issue)
  • New Feature (non-breaking change which adds functionality)

@dosubot dosubot Bot added the size:L This PR changes 100-499 lines, ignoring generated files. label May 15, 2026
@coderabbitai

coderabbitai Bot commented May 15, 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: 8bab8e41-6bee-4757-a9d6-6c1f35381cbc

📥 Commits

Reviewing files that changed from the base of the PR and between 1b540d7 and 3ed4e49.

📒 Files selected for processing (3)
  • internal/cli/user_command.go
  • internal/entity/models/siliconflow.go
  • internal/entity/models/stepfun.go
🚧 Files skipped from review as they are similar to previous changes (2)
  • internal/cli/user_command.go
  • internal/entity/models/stepfun.go

📝 Walkthrough

Walkthrough

Implements SiliconFlow audio methods: adds multipart/imports support, a multipart TranscribeAudio (ASR) implementation, JSON-based AudioSpeech (TTS), and a streaming AudioSpeechWithSender that forwards response chunks to a sender.

Changes

SiliconFlow audio implementation

Layer / File(s) Summary
Imports for multipart and filesystem
internal/entity/models/siliconflow.go
Adds multipart/form-data, os, and path/filepath imports required for building multipart uploads and file handling.
TranscribeAudio (multipart file upload)
internal/entity/models/siliconflow.go
Implements ASR file upload: validates file path, streams file into file form field, writes model and serialized asrConfig.Params form fields, posts with authorization, checks HTTP 200, unmarshals JSON response to extract text, and returns ASRResponse.
AudioSpeech (non-streaming TTS)
internal/entity/models/siliconflow.go
Implements non-streaming TTS: validates audioContent, builds region-specific TTS URL, POSTs JSON including model and input plus optional params/format and stream:false, checks HTTP 200, and returns TTSResponse containing audio bytes.
AudioSpeechWithSender (streaming TTS)
internal/entity/models/siliconflow.go
Implements streaming TTS: validates API key and input, posts stream:true JSON, reads response body incrementally, forwards each chunk (as string) to the provided sender callback, and returns any read/send errors.

Estimated code review effort

🎯 4 (Complex) | ⏱️ ~45 minutes

Possibly related PRs

Suggested labels

size:XXL

Poem

🐰 I stitched sound from bytes and streams,

nibbling chunks in moonlit beams.
Files uploaded, JSON calls reply—
Voices born where words would lie.
Hop, decode, and forward on, hooray!

🚥 Pre-merge checks | ✅ 5
✅ Passed checks (5 passed)
Check name Status Explanation
Title check ✅ Passed The title clearly and concisely summarizes the main changes: implementing TTS and ASR for Siliconflow and TTS for StepFun, matching the core functionality additions in the changeset.
Description check ✅ Passed The description covers the required sections: problem statement, type of change, supported functionalities, and verified CLI examples demonstrating the implementations working correctly.
Docstring Coverage ✅ Passed Docstring coverage is 100.00% which is sufficient. The required threshold is 80.00%.
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.

@Haruko386 Haruko386 added the ci Continue Integration label May 15, 2026
@Haruko386
Haruko386 marked this pull request as draft May 15, 2026 02:06
@Haruko386
Haruko386 marked this pull request as ready for review May 15, 2026 02:06

@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: 9

🤖 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/stepfun.json`:
- Line 94: The model entry in conf/models/stepfun.json has a trailing space in
the name field ("name": "step-tts-2 "), causing lookups to fail; edit the JSON
entry for the model (the "name" property for the step-tts-2 entry) and remove
the trailing whitespace so the value is exactly "step-tts-2" (update any other
occurrences in the file if present) to ensure requests use the canonical model
id when calling StepFun's /audio/speech endpoint.

In `@internal/cli/user_command.go`:
- Around line 2202-2204: The direct type assertion
rawResult.Data["text"].(string) can panic; update the code in user_command.go to
safely check the map entry and type before assigning to result.Data: retrieve
rawResult.Data["text"], test presence and that it's a string (e.g., v, ok :=
rawResult.Data["text"].(string)), and only append {"text": v} when ok; otherwise
set a safe default (empty string) or skip the field and optionally log a warning
so result.Data is never populated via an unchecked assertion.

In `@internal/development.md`:
- Line 367: Replace the incorrect heading "### 6.24 Audio to Speech" with a
correct ASR label such as "### 6.24 Speech to Text" (or "### 6.24 Audio to
Text") so the section title accurately reflects the Automatic Speech Recognition
example; update the heading text exactly where "### 6.24 Audio to Speech"
appears.

In `@internal/entity/models/siliconflow.go`:
- Around line 853-910: The AudioSpeech method has misleading comment and unsafe
nil dereferences; update the doc comment to indicate this is TTS (text→speech),
rename the parameter asrConfig to ttsConfig to match AudioSpeechWithSender and
TTSConfig, and add nil guards: validate modelName is non-nil/non-empty, ensure
apiConfig is non-nil before accessing apiConfig.Region and apiConfig.ApiKey and
ensure apiConfig.ApiKey is non-nil/non-empty; also mirror error returns used in
TranscribeAudio for these checks so the method (SiliconflowModel.AudioSpeech)
returns descriptive errors instead of panicking.
- Around line 733-847: The TranscribeAudio function dereferences apiConfig,
modelName, and apiConfig.ApiKey without nil checks and contains dead code (local
res not used); add initial guards: if apiConfig == nil return an error, if
modelName == nil or *modelName == "" return an error, and if apiConfig.ApiKey ==
nil or *apiConfig.ApiKey == "" return an error; update uses of apiConfig.Region
to only read when apiConfig != nil (use the validated apiConfig), and remove the
unused local variable res (or return &res instead of recreating a new
ASRResponse) so you don't have dead code; refer to TranscribeAudio, apiConfig,
modelName, apiConfig.ApiKey, and the local res variable when making these
changes.
- Around line 912-987: AudioSpeechWithSender currently dereferences modelName
without a nil/empty guard and streams raw binary by converting bytes to string
(data corruption risk); add an early check that modelName is non-nil and not
empty (e.g., return error if modelName == nil || *modelName == "") before using
it, and when reading resp.Body replace the string conversion of buf[:n] with
base64 encoding of the bytes (encode buf[:n] to base64 string and pass that to
sender) so streamed audio preserves binary integrity; keep the existing sender
signature but ensure callers know they receive base64 chunks.

In `@internal/entity/models/stepfun.go`:
- Around line 596-636: The SSE parsing loop in the StepFun stream uses
strings.HasPrefix(line, "data: ") which will drop valid lines like "data:{...}"
— change the prefix check to "data:" and then use strings.TrimSpace on the
substring (e.g., dataStr := strings.TrimSpace(line[len("data:"):])) to match the
ChatStreamlyWithSender behavior; keep the existing JSON unmarshal into the
anonymous event struct (Type, Audio) and for the error case (when event.Type ==
"speech.audio.error") return an error that includes the raw event payload (or
the unmarshaled event content) instead of the generic message so callers get
useful debugging information, and leave the audio decode/send logic using
sender(...) intact.
- Around line 481-537: AudioSpeech has several correctness gaps: null-derefs
(apiConfig, apiConfig.ApiKey, modelName), missing per-request timeout/context,
wrong region URL lookup, and misnamed param; fix by validating apiConfig and
apiConfig.ApiKey (return error if nil/empty) and modelName (return error if
nil/empty) before use, rename parameter asrConfig to ttsConfig to match other
helpers, build the URL via baseURLForRegion(region) instead of
s.BaseURL[region], create the request with
context.WithTimeout(context.Background(), nonStreamCallTimeout) and use
http.NewRequestWithContext, and only set the Authorization header after
confirming ApiKey; keep existing body marshaling and response handling but
ensure you reference AudioSpeech, apiConfig.ApiKey, modelName, ttsConfig,
baseURLForRegion, nonStreamCallTimeout and s.httpClient in your changes.
- Around line 540-595: AudioSpeechWithSender currently dereferences modelName
without a nil check, indexes s.BaseURL[region] directly (which can produce an
empty/relative URL), and leaves a leftover TODO; fix by adding a nil/empty check
for modelName at the start of AudioSpeechWithSender and returning an explicit
error if missing, replace the direct s.BaseURL[region] usage with the helper
baseURLForRegion (same pattern used by ChatStreamlyWithSender) to fail fast with
a clear message when the region is unconfigured, and remove the "// TODO Test
it" comment (or convert it into a tracked issue reference) before merging.
🪄 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: b6d4c58c-2a9f-49fe-8819-ccf0b1073e0e

📥 Commits

Reviewing files that changed from the base of the PR and between d887b57 and 1b540d7.

📒 Files selected for processing (6)
  • conf/models/siliconflow.json
  • conf/models/stepfun.json
  • internal/cli/user_command.go
  • internal/development.md
  • internal/entity/models/siliconflow.go
  • internal/entity/models/stepfun.go

Comment thread conf/models/stepfun.json
]
},
{
"name": "step-tts-2 ",

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

Trailing whitespace in model name "step-tts-2 ".

The name value has a stray trailing space, so any lookup or API request keyed on the canonical id step-tts-2 will miss this entry, and any request that does use this exact name will pass step-tts-2 (with the space) to StepFun's /audio/speech endpoint, which will almost certainly fail with an unknown-model error.

🔧 Proposed fix
-      "name": "step-tts-2 ",
+      "name": "step-tts-2",
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
"name": "step-tts-2 ",
"name": "step-tts-2",
🤖 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/stepfun.json` at line 94, The model entry in
conf/models/stepfun.json has a trailing space in the name field ("name":
"step-tts-2 "), causing lookups to fail; edit the JSON entry for the model (the
"name" property for the step-tts-2 entry) and remove the trailing whitespace so
the value is exactly "step-tts-2" (update any other occurrences in the file if
present) to ensure requests use the canonical model id when calling StepFun's
/audio/speech endpoint.

Comment on lines +2202 to +2204
result.Data = []map[string]interface{}{
{"text": rawResult.Data["text"].(string)},
}

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

Add defensive type checking to prevent runtime panic.

The direct type assertion rawResult.Data["text"].(string) on line 2203 will panic if the "text" key doesn't exist or contains a non-string value. API responses can be unpredictable, especially during error conditions.

🛡️ Proposed fix with safe type assertion
 var result CommonResponse
 result.Code = rawResult.Code
+	text, ok := rawResult.Data["text"].(string)
+	if !ok {
+		return nil, fmt.Errorf("ASR document failed: invalid or missing text in response")
+	}
 result.Data = []map[string]interface{}{
-		{"text": rawResult.Data["text"].(string)},
+		{"text": text},
 }
 result.Duration = resp.Duration
🤖 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/cli/user_command.go` around lines 2202 - 2204, The direct type
assertion rawResult.Data["text"].(string) can panic; update the code in
user_command.go to safely check the map entry and type before assigning to
result.Data: retrieve rawResult.Data["text"], test presence and that it's a
string (e.g., v, ok := rawResult.Data["text"].(string)), and only append
{"text": v} when ok; otherwise set a safe default (empty string) or skip the
field and optionally log a warning so result.Data is never populated via an
unchecked assertion.

Comment thread internal/development.md
SUCCESS
```

### 6.24 Audio to Speech

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

Correct the section heading.

The heading "Audio to Speech" is incorrect for an ASR (Automatic Speech Recognition) example. ASR converts audio/speech to text, not speech. The heading should be "Speech to Text" or "Audio to Text" to accurately reflect the ASR functionality demonstrated in the example.

📝 Proposed fix
-### 6.24 Audio to Speech
+### 6.24 Speech to Text
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
### 6.24 Audio to Speech
### 6.24 Speech to Text
🤖 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/development.md` at line 367, Replace the incorrect heading "### 6.24
Audio to Speech" with a correct ASR label such as "### 6.24 Speech to Text" (or
"### 6.24 Audio to Text") so the section title accurately reflects the Automatic
Speech Recognition example; update the heading text exactly where "### 6.24
Audio to Speech" appears.

Comment on lines 733 to 847
func (o *SiliconflowModel) TranscribeAudio(modelName *string, file *string, apiConfig *APIConfig, asrConfig *ASRConfig) (*ASRResponse, error) {
return nil, fmt.Errorf("%s, no such method", o.Name())
if file == nil || *file == "" {
return nil, fmt.Errorf("file is missing")
}

region := "default"
if apiConfig.Region != nil && *apiConfig.Region != "" {
region = *apiConfig.Region
}

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

// multipart body
var body bytes.Buffer
writer := multipart.NewWriter(&body)

// open audio file
audioFile, err := os.Open(*file)
if err != nil {
return nil, fmt.Errorf("failed to open audio file: %w", err)
}
defer audioFile.Close()

// create multipart file field
part, err := writer.CreateFormFile(
"file",
filepath.Base(*file),
)
if err != nil {
return nil, fmt.Errorf("failed to create multipart file: %w", err)
}

// copy file content
if _, err = io.Copy(part, audioFile); err != nil {
return nil, fmt.Errorf("failed to copy audio data: %w", err)
}

// model field
if err := writer.WriteField("model", *modelName); err != nil {
return nil, fmt.Errorf("failed to write model field: %w", err)
}

// extra params
if asrConfig != nil && asrConfig.Params != nil {
for key, value := range asrConfig.Params {

var val string

switch v := value.(type) {
case string:
val = v
case bool:
val = strconv.FormatBool(v)
case int:
val = strconv.Itoa(v)
case int64:
val = strconv.FormatInt(v, 10)
case float32:
val = strconv.FormatFloat(float64(v), 'f', -1, 32)
case float64:
val = strconv.FormatFloat(v, 'f', -1, 64)
default:
val = fmt.Sprintf("%v", v)
}

if err = writer.WriteField(key, val); err != nil {
return nil, fmt.Errorf("failed to write field %s: %w", key, err)
}
}
}

if err = writer.Close(); err != nil {
return nil, fmt.Errorf("failed to close multipart writer: %w", err)
}

// 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 := o.httpClient.Do(req)
if err != nil {
return nil, fmt.Errorf("failed to send request: %w", err)
}
defer resp.Body.Close()

respBody, err := io.ReadAll(resp.Body)
if err != nil {
return nil, fmt.Errorf("failed to read response body: %w", err)
}

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

// SiliconFlow response
var result struct {
Text string `json:"text"`
}

if err = json.Unmarshal(respBody, &result); err != nil {
return nil, fmt.Errorf("failed to unmarshal response: %w, body=%s", err, string(respBody))
}

var res ASRResponse
res.Text = result.Text

return &ASRResponse{Text: result.Text}, nil
}

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

Guard nil pointers and drop dead code in TranscribeAudio.

Several mandatory inputs are dereferenced without nil checks; any of these will panic at runtime instead of returning a clean error:

  • Line 739: apiConfig.Region is read without first checking apiConfig == nil. Every other method in this file (e.g. ChatWithMessages, AudioSpeechWithSender) guards apiConfig before touching its fields.
  • Line 771: *modelName is dereferenced without a nil/empty check; modelName is a *string.
  • Line 814: *apiConfig.ApiKey is dereferenced without checking apiConfig.ApiKey != nil.

Also, lines 843–844 build a res ASRResponse, populate res.Text, and then return a freshly constructed &ASRResponse{Text: result.Text} instead — the local res is dead code.

🛡️ Proposed fix
 func (o *SiliconflowModel) TranscribeAudio(modelName *string, file *string, apiConfig *APIConfig, asrConfig *ASRConfig) (*ASRResponse, error) {
+	if apiConfig == nil || apiConfig.ApiKey == nil || *apiConfig.ApiKey == "" {
+		return nil, fmt.Errorf("api key is nil or empty")
+	}
+	if modelName == nil || *modelName == "" {
+		return nil, fmt.Errorf("model name is required")
+	}
 	if file == nil || *file == "" {
 		return nil, fmt.Errorf("file is missing")
 	}
@@
-	var res ASRResponse
-	res.Text = result.Text
-
 	return &ASRResponse{Text: result.Text}, nil
 }
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
func (o *SiliconflowModel) TranscribeAudio(modelName *string, file *string, apiConfig *APIConfig, asrConfig *ASRConfig) (*ASRResponse, error) {
return nil, fmt.Errorf("%s, no such method", o.Name())
if file == nil || *file == "" {
return nil, fmt.Errorf("file is missing")
}
region := "default"
if apiConfig.Region != nil && *apiConfig.Region != "" {
region = *apiConfig.Region
}
url := fmt.Sprintf("%s/%s", o.BaseURL[region], o.URLSuffix.ASR)
// multipart body
var body bytes.Buffer
writer := multipart.NewWriter(&body)
// open audio file
audioFile, err := os.Open(*file)
if err != nil {
return nil, fmt.Errorf("failed to open audio file: %w", err)
}
defer audioFile.Close()
// create multipart file field
part, err := writer.CreateFormFile(
"file",
filepath.Base(*file),
)
if err != nil {
return nil, fmt.Errorf("failed to create multipart file: %w", err)
}
// copy file content
if _, err = io.Copy(part, audioFile); err != nil {
return nil, fmt.Errorf("failed to copy audio data: %w", err)
}
// model field
if err := writer.WriteField("model", *modelName); err != nil {
return nil, fmt.Errorf("failed to write model field: %w", err)
}
// extra params
if asrConfig != nil && asrConfig.Params != nil {
for key, value := range asrConfig.Params {
var val string
switch v := value.(type) {
case string:
val = v
case bool:
val = strconv.FormatBool(v)
case int:
val = strconv.Itoa(v)
case int64:
val = strconv.FormatInt(v, 10)
case float32:
val = strconv.FormatFloat(float64(v), 'f', -1, 32)
case float64:
val = strconv.FormatFloat(v, 'f', -1, 64)
default:
val = fmt.Sprintf("%v", v)
}
if err = writer.WriteField(key, val); err != nil {
return nil, fmt.Errorf("failed to write field %s: %w", key, err)
}
}
}
if err = writer.Close(); err != nil {
return nil, fmt.Errorf("failed to close multipart writer: %w", err)
}
// 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 := o.httpClient.Do(req)
if err != nil {
return nil, fmt.Errorf("failed to send request: %w", err)
}
defer resp.Body.Close()
respBody, err := io.ReadAll(resp.Body)
if err != nil {
return nil, fmt.Errorf("failed to read response body: %w", err)
}
if resp.StatusCode != http.StatusOK {
return nil, fmt.Errorf("SiliconFlow ASR error: %s - %s", resp.Status, string(respBody))
}
// SiliconFlow response
var result struct {
Text string `json:"text"`
}
if err = json.Unmarshal(respBody, &result); err != nil {
return nil, fmt.Errorf("failed to unmarshal response: %w, body=%s", err, string(respBody))
}
var res ASRResponse
res.Text = result.Text
return &ASRResponse{Text: result.Text}, nil
}
func (o *SiliconflowModel) TranscribeAudio(modelName *string, file *string, apiConfig *APIConfig, asrConfig *ASRConfig) (*ASRResponse, error) {
if apiConfig == nil || apiConfig.ApiKey == nil || *apiConfig.ApiKey == "" {
return nil, fmt.Errorf("api key is nil or empty")
}
if modelName == nil || *modelName == "" {
return nil, fmt.Errorf("model name is required")
}
if file == nil || *file == "" {
return nil, fmt.Errorf("file is missing")
}
region := "default"
if apiConfig.Region != nil && *apiConfig.Region != "" {
region = *apiConfig.Region
}
url := fmt.Sprintf("%s/%s", o.BaseURL[region], o.URLSuffix.ASR)
// multipart body
var body bytes.Buffer
writer := multipart.NewWriter(&body)
// open audio file
audioFile, err := os.Open(*file)
if err != nil {
return nil, fmt.Errorf("failed to open audio file: %w", err)
}
defer audioFile.Close()
// create multipart file field
part, err := writer.CreateFormFile(
"file",
filepath.Base(*file),
)
if err != nil {
return nil, fmt.Errorf("failed to create multipart file: %w", err)
}
// copy file content
if _, err = io.Copy(part, audioFile); err != nil {
return nil, fmt.Errorf("failed to copy audio data: %w", err)
}
// model field
if err := writer.WriteField("model", *modelName); err != nil {
return nil, fmt.Errorf("failed to write model field: %w", err)
}
// extra params
if asrConfig != nil && asrConfig.Params != nil {
for key, value := range asrConfig.Params {
var val string
switch v := value.(type) {
case string:
val = v
case bool:
val = strconv.FormatBool(v)
case int:
val = strconv.Itoa(v)
case int64:
val = strconv.FormatInt(v, 10)
case float32:
val = strconv.FormatFloat(float64(v), 'f', -1, 32)
case float64:
val = strconv.FormatFloat(v, 'f', -1, 64)
default:
val = fmt.Sprintf("%v", v)
}
if err = writer.WriteField(key, val); err != nil {
return nil, fmt.Errorf("failed to write field %s: %w", key, err)
}
}
}
if err = writer.Close(); err != nil {
return nil, fmt.Errorf("failed to close multipart writer: %w", err)
}
// 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 := o.httpClient.Do(req)
if err != nil {
return nil, fmt.Errorf("failed to send request: %w", err)
}
defer resp.Body.Close()
respBody, err := io.ReadAll(resp.Body)
if err != nil {
return nil, fmt.Errorf("failed to read response body: %w", err)
}
if resp.StatusCode != http.StatusOK {
return nil, fmt.Errorf("SiliconFlow ASR error: %s - %s", resp.Status, string(respBody))
}
// SiliconFlow response
var result struct {
Text string `json:"text"`
}
if err = json.Unmarshal(respBody, &result); err != nil {
return nil, fmt.Errorf("failed to unmarshal response: %w, body=%s", err, string(respBody))
}
return &ASRResponse{Text: result.Text}, nil
}
🤖 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/siliconflow.go` around lines 733 - 847, The
TranscribeAudio function dereferences apiConfig, modelName, and apiConfig.ApiKey
without nil checks and contains dead code (local res not used); add initial
guards: if apiConfig == nil return an error, if modelName == nil or *modelName
== "" return an error, and if apiConfig.ApiKey == nil or *apiConfig.ApiKey == ""
return an error; update uses of apiConfig.Region to only read when apiConfig !=
nil (use the validated apiConfig), and remove the unused local variable res (or
return &res instead of recreating a new ASRResponse) so you don't have dead
code; refer to TranscribeAudio, apiConfig, modelName, apiConfig.ApiKey, and the
local res variable when making these changes.

Comment on lines 853 to 910
// AudioSpeech convert audio to text
func (o *SiliconflowModel) AudioSpeech(modelName *string, audioContent *string, apiConfig *APIConfig, asrConfig *TTSConfig) (*TTSResponse, error) {
return nil, fmt.Errorf("%s, no such method", o.Name())
if audioContent == nil || *audioContent == "" {
return nil, fmt.Errorf("audio content is empty")
}

var region = "default"
if apiConfig != nil && apiConfig.Region != nil && *apiConfig.Region != "" {
region = *apiConfig.Region
}

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

reqBody := map[string]interface{}{
"model": *modelName,
"input": *audioContent,
"stream": false,
}

if asrConfig != nil && asrConfig.Params != nil {
for key, value := range asrConfig.Params {
reqBody[key] = value
}
}
if asrConfig != nil && asrConfig.Format != "" {
reqBody["response_format"] = asrConfig.Format
}

jsonData, err := json.Marshal(reqBody)
if err != nil {
return nil, fmt.Errorf("failed to marshal request: %w", err)
}

req, err := http.NewRequest("POST", url, bytes.NewBuffer(jsonData))
if err != nil {
return nil, fmt.Errorf("failed to create request: %w", err)
}

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

resp, err := o.httpClient.Do(req)
if err != nil {
return nil, fmt.Errorf("failed to send request: %w", err)
}
defer resp.Body.Close()

body, err := io.ReadAll(resp.Body)
if err != nil {
return nil, fmt.Errorf("failed to read response body: %w", err)
}

if resp.StatusCode != http.StatusOK {
return nil, fmt.Errorf("%s - %s", resp.Status, string(body))
}

return &TTSResponse{Audio: body}, nil
}

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

Fix misleading doc/param naming and add missing nil guards in AudioSpeech.

  • Line 853 comment says “convert audio to text”, but this is TTS (text → speech). The comment is inverted and will mislead future readers.
  • Line 854: the parameter is typed *TTSConfig but named asrConfig. Rename to ttsConfig for consistency with AudioSpeechWithSender and to avoid confusion at call sites.
  • Missing guards mirror the issues in TranscribeAudio:
    • apiConfig is not checked for nil before line 860 (apiConfig.Region) or line 892 (*apiConfig.ApiKey).
    • modelName is dereferenced on line 867 without a nil/empty check.
    • apiConfig.ApiKey is dereferenced on line 892 without a nil check.

Any of these will panic on bad input instead of returning an error like the other methods in this file.

🛡️ Proposed fix
-// AudioSpeech convert audio to text
-func (o *SiliconflowModel) AudioSpeech(modelName *string, audioContent *string, apiConfig *APIConfig, asrConfig *TTSConfig) (*TTSResponse, error) {
+// AudioSpeech converts text to speech audio.
+func (o *SiliconflowModel) AudioSpeech(modelName *string, audioContent *string, apiConfig *APIConfig, ttsConfig *TTSConfig) (*TTSResponse, error) {
+	if apiConfig == nil || apiConfig.ApiKey == nil || *apiConfig.ApiKey == "" {
+		return nil, fmt.Errorf("api key is nil or empty")
+	}
+	if modelName == nil || *modelName == "" {
+		return nil, fmt.Errorf("model name is required")
+	}
 	if audioContent == nil || *audioContent == "" {
 		return nil, fmt.Errorf("audio content is empty")
 	}
@@
-	if asrConfig != nil && asrConfig.Params != nil {
-		for key, value := range asrConfig.Params {
+	if ttsConfig != nil && ttsConfig.Params != nil {
+		for key, value := range ttsConfig.Params {
 			reqBody[key] = value
 		}
 	}
-	if asrConfig != nil && asrConfig.Format != "" {
-		reqBody["response_format"] = asrConfig.Format
+	if ttsConfig != nil && ttsConfig.Format != "" {
+		reqBody["response_format"] = ttsConfig.Format
 	}
🤖 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/siliconflow.go` around lines 853 - 910, The
AudioSpeech method has misleading comment and unsafe nil dereferences; update
the doc comment to indicate this is TTS (text→speech), rename the parameter
asrConfig to ttsConfig to match AudioSpeechWithSender and TTSConfig, and add nil
guards: validate modelName is non-nil/non-empty, ensure apiConfig is non-nil
before accessing apiConfig.Region and apiConfig.ApiKey and ensure
apiConfig.ApiKey is non-nil/non-empty; also mirror error returns used in
TranscribeAudio for these checks so the method (SiliconflowModel.AudioSpeech)
returns descriptive errors instead of panicking.

Comment on lines 912 to 987
func (z *SiliconflowModel) AudioSpeechWithSender(modelName *string, audioContent *string, apiConfig *APIConfig, ttsConfig *TTSConfig, sender func(*string, *string) error) error {
return fmt.Errorf("%s, no such method", z.Name())
if apiConfig == nil || apiConfig.ApiKey == nil || *apiConfig.ApiKey == "" {
return fmt.Errorf("SiliconFlow API key is missing")
}

if audioContent == nil || *audioContent == "" {
return fmt.Errorf("audio content is empty")
}

var region = "default"
if apiConfig.Region != nil && *apiConfig.Region != "" {
region = *apiConfig.Region
}

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

reqBody := map[string]interface{}{
"model": *modelName,
"input": *audioContent,
"stream": true,
}

if ttsConfig != nil && ttsConfig.Params != nil {
for key, value := range ttsConfig.Params {
reqBody[key] = value
}
}
if ttsConfig != nil && ttsConfig.Format != "" {
reqBody["response_format"] = ttsConfig.Format
}

jsonData, err := json.Marshal(reqBody)
if err != nil {
return fmt.Errorf("failed to marshal request: %w", err)
}

req, err := http.NewRequest("POST", url, bytes.NewBuffer(jsonData))
if err != nil {
return fmt.Errorf("failed to create request: %w", err)
}

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

resp, err := z.httpClient.Do(req)
if err != nil {
return fmt.Errorf("failed to send request: %w", err)
}
defer resp.Body.Close()

if resp.StatusCode != http.StatusOK {
body, _ := io.ReadAll(resp.Body)
return fmt.Errorf("SiliconFlow stream TTS API error: %d, body: %s", resp.StatusCode, string(body))
}

buf := make([]byte, 32*1024)

for {
n, err := resp.Body.Read(buf)
if n > 0 {
chunk := string(buf[:n])
if errSend := sender(&chunk, nil); errSend != nil {
return errSend
}
}

if err != nil {
if err == io.EOF {
break
}
return fmt.Errorf("error reading SiliconFlow binary audio stream: %w", err)
}
}

return nil
}

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 | 🏗️ Heavy lift

🧩 Analysis chain

🏁 Script executed:

#!/bin/bash
# Find call sites that invoke AudioSpeechWithSender and inspect what they do with the chunk.
rg -nP --type=go -C5 '\bAudioSpeechWithSender\s*\('
# Also check how TTSUserCommand / HTTP handlers forward streamed audio chunks.
rg -nP --type=go -C5 '\bTTSUserCommand\b|tts.*stream|TTS.*Stream'

Repository: infiniflow/ragflow

Length of output: 34548


🏁 Script executed:

# First, let's look at the SiliconflowModel.AudioSpeechWithSender implementation more carefully
# to confirm the modelName dereference issue
sed -n '912,987p' internal/entity/models/siliconflow.go

Repository: infiniflow/ragflow

Length of output: 2054


🏁 Script executed:

# Now let's look at the TTSUserCommand implementation to understand how the sender is used downstream
sed -n '1931,2000p' internal/cli/user_command.go

Repository: infiniflow/ragflow

Length of output: 2381


🏁 Script executed:

# Check the StepFun implementation for comparison on how it handles TTS streaming
sed -n '540,600p' internal/entity/models/stepfun.go

Repository: infiniflow/ragflow

Length of output: 1865


🏁 Script executed:

# Get the full TTSUserCommand implementation
sed -n '1931,2100p' internal/cli/user_command.go

Repository: infiniflow/ragflow

Length of output: 4977


🏁 Script executed:

# Look at model_service.go around line 1478 where AudioSpeechWithSender is called
# to see how the sender callback is constructed
sed -n '1450,1520p' internal/service/model_service.go

Repository: infiniflow/ragflow

Length of output: 2160


🏁 Script executed:

# Check if there's any base64 encoding or binary handling in the HTTP response path
rg -A 20 'TTSUserCommand.*ResponseWriter|tts.*stream|WriteHeader.*200' internal/cli/ --type=go

Repository: infiniflow/ragflow

Length of output: 44


🏁 Script executed:

# Let's find where the sender callback is created in model_service.go for the HTTP endpoint
sed -n '1400,1480p' internal/service/model_service.go

Repository: infiniflow/ragflow

Length of output: 2644


🏁 Script executed:

# Search for the HTTP handler that calls AudioSpeechWithSender
rg -B 10 -A 30 'func.*AudioSpeech.*handler|func.*tts.*speech|/audio/speech' internal/ --type=go | head -100

Repository: infiniflow/ragflow

Length of output: 5224


🏁 Script executed:

# Check how the sender callback is constructed and what it does with the string
rg -B 5 -A 15 'sender\s*:=.*func' internal/service/ --type=go

Repository: infiniflow/ragflow

Length of output: 44


🏁 Script executed:

# Find the HTTP handler for /audio/speech (AudioSpeech endpoint)
rg -B 5 -A 40 'func.*AudioSpeech.*[Hh]andler|providerHandler.*AudioSpeech' internal/handler/ --type=go

Repository: infiniflow/ragflow

Length of output: 44


🏁 Script executed:

# Check if the sender callback streams to HTTP ResponseWriter or accumulates to base64
rg -B 10 -A 30 'AudioSpeechStream|sender.*func|WriteHeader.*text/event-stream' internal/handler/ --type=go

Repository: infiniflow/ragflow

Length of output: 11608


🏁 Script executed:

# Look for how binary chunks are being handled - base64 encoding of the string
rg 'base64.*Encode|EncodeToString.*chunk|sender.*base64' internal/ --type=go -B 2 -A 2

Repository: infiniflow/ragflow

Length of output: 3511


Add nil guard for modelName and encode binary audio as base64 for streaming.

  • Line 929 dereferences *modelName without nil/empty check. Add guard before the region logic:

    +	if modelName == nil || *modelName == "" {
    +		return fmt.Errorf("model name is required")
    +	}
     	var region = "default"
  • Lines 970–976: Converting binary audio bytes to string via string(buf[:n]) and passing through the sender(*string, *string) callback creates a data corruption risk. The handler sends these strings via SSEvent (text/event-stream), losing binary integrity. The non-streaming path correctly uses base64 encoding. Either encode chunks as base64 before passing to sender, or introduce a binary-aware sender variant that the streaming handler can use for TTS responses.

🤖 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/siliconflow.go` around lines 912 - 987,
AudioSpeechWithSender currently dereferences modelName without a nil/empty guard
and streams raw binary by converting bytes to string (data corruption risk); add
an early check that modelName is non-nil and not empty (e.g., return error if
modelName == nil || *modelName == "") before using it, and when reading
resp.Body replace the string conversion of buf[:n] with base64 encoding of the
bytes (encode buf[:n] to base64 string and pass that to sender) so streamed
audio preserves binary integrity; keep the existing sender signature but ensure
callers know they receive base64 chunks.

Comment on lines +481 to 537
func (s *StepFunModel) AudioSpeech(modelName *string, audioContent *string, apiConfig *APIConfig, asrConfig *TTSConfig) (*TTSResponse, error) {
// TODO Test it
if audioContent == nil || *audioContent == "" {
return nil, fmt.Errorf("audio content is empty")
}

var region = "default"
if apiConfig != nil && apiConfig.Region != nil && *apiConfig.Region != "" {
region = *apiConfig.Region
}

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

reqBody := map[string]interface{}{
"model": *modelName,
"input": *audioContent,
}

if asrConfig != nil && asrConfig.Params != nil {
for key, value := range asrConfig.Params {
reqBody[key] = value
}
}
if asrConfig != nil && asrConfig.Format != "" {
reqBody["response_format"] = asrConfig.Format
}

jsonData, err := json.Marshal(reqBody)
if err != nil {
return nil, fmt.Errorf("failed to marshal request: %w", err)
}

req, err := http.NewRequest("POST", url, bytes.NewBuffer(jsonData))
if err != nil {
return nil, fmt.Errorf("failed to create request: %w", err)
}

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

resp, err := s.httpClient.Do(req)
if err != nil {
return nil, fmt.Errorf("failed to send request: %w", err)
}
defer resp.Body.Close()

body, err := io.ReadAll(resp.Body)
if err != nil {
return nil, fmt.Errorf("failed to read response body: %w", err)
}

if resp.StatusCode != http.StatusOK {
return nil, fmt.Errorf("%s - %s", resp.Status, string(body))
}

return &TTSResponse{Audio: body}, nil
}

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

AudioSpeech has multiple correctness gaps: NPE risk, missing request timeout, and wrong helper/naming.

Several issues in this non-streaming TTS path:

  1. Nil-deref on apiConfig and apiConfig.ApiKey (line 519): Unlike ChatWithMessages (lines 103-105) and ListModels (lines 385-387), there is no guard. If a caller passes a nil apiConfig or nil/empty ApiKey, this panics or sends Bearer with an empty token. The conditional at line 488 even tolerates apiConfig == nil, which makes the later unconditional deref worse.
  2. Nil-deref on modelName (line 495): *modelName is dereferenced without a nil check; the public signature takes *string.
  3. Missing per-request timeout context: The driver intentionally leaves httpClient.Timeout unset (see the explanatory comment at lines 51-54) and the convention in this file is that non-streaming callers wrap each request with context.WithTimeout(context.Background(), nonStreamCallTimeout) (see ChatWithMessages line 159 and ListModels line 400). This call instead uses http.NewRequest with no deadline at all, so a slow/hung TTS request can block indefinitely on ResponseHeaderTimeout alone (60s) and then on body read forever.
  4. Bypasses baseURLForRegion at line 492: directly indexing s.BaseURL[region] silently yields an empty string for a misconfigured region and produces a relative URL that the transport then rejects with a confusing error. Other methods route through baseURLForRegion for fail-fast behavior.
  5. Parameter name & doc comment: the parameter is named asrConfig *TTSConfig and the doc comment says "convert audio to text" — both wrong; this is TTS (text → speech). Renaming the param to ttsConfig matches AudioSpeechWithSender and avoids reader confusion.
🔧 Proposed fix
-// AudioSpeech convert audio to text
-func (s *StepFunModel) AudioSpeech(modelName *string, audioContent *string, apiConfig *APIConfig, asrConfig *TTSConfig) (*TTSResponse, error) {
-	// TODO Test it
-	if audioContent == nil || *audioContent == "" {
-		return nil, fmt.Errorf("audio content is empty")
-	}
-
-	var region = "default"
-	if apiConfig != nil && apiConfig.Region != nil && *apiConfig.Region != "" {
-		region = *apiConfig.Region
-	}
-
-	url := fmt.Sprintf("%s/%s", s.BaseURL[region], s.URLSuffix.TTS)
-
-	reqBody := map[string]interface{}{
-		"model": *modelName,
-		"input": *audioContent,
-	}
-
-	if asrConfig != nil && asrConfig.Params != nil {
-		for key, value := range asrConfig.Params {
-			reqBody[key] = value
-		}
-	}
-	if asrConfig != nil && asrConfig.Format != "" {
-		reqBody["response_format"] = asrConfig.Format
-	}
+// AudioSpeech performs non-streaming text-to-speech via StepFun's /audio/speech endpoint.
+func (s *StepFunModel) AudioSpeech(modelName *string, audioContent *string, apiConfig *APIConfig, ttsConfig *TTSConfig) (*TTSResponse, error) {
+	if apiConfig == nil || apiConfig.ApiKey == nil || *apiConfig.ApiKey == "" {
+		return nil, fmt.Errorf("api key is required")
+	}
+	if modelName == nil || *modelName == "" {
+		return nil, fmt.Errorf("model name is required")
+	}
+	if audioContent == nil || *audioContent == "" {
+		return nil, fmt.Errorf("audio content is empty")
+	}
+
+	region := "default"
+	if apiConfig.Region != nil && *apiConfig.Region != "" {
+		region = *apiConfig.Region
+	}
+
+	baseURL, err := s.baseURLForRegion(region)
+	if err != nil {
+		return nil, err
+	}
+	url := fmt.Sprintf("%s/%s", baseURL, s.URLSuffix.TTS)
+
+	reqBody := map[string]interface{}{
+		"model": *modelName,
+		"input": *audioContent,
+	}
+	if ttsConfig != nil && ttsConfig.Params != nil {
+		for key, value := range ttsConfig.Params {
+			reqBody[key] = value
+		}
+	}
+	if ttsConfig != nil && ttsConfig.Format != "" {
+		reqBody["response_format"] = ttsConfig.Format
+	}

 	jsonData, err := json.Marshal(reqBody)
 	if err != nil {
 		return nil, fmt.Errorf("failed to marshal request: %w", err)
 	}
-
-	req, err := http.NewRequest("POST", url, bytes.NewBuffer(jsonData))
+
+	ctx, cancel := context.WithTimeout(context.Background(), nonStreamCallTimeout)
+	defer cancel()
+
+	req, err := http.NewRequestWithContext(ctx, "POST", url, bytes.NewBuffer(jsonData))
 	if err != nil {
 		return nil, fmt.Errorf("failed to create request: %w", err)
 	}

Based on learnings: the documented design in this file (lines 51-54) and the prior learning on httpClient.Timeout vs context.WithTimeout agree — because httpClient.Timeout is intentionally unset, non-streaming methods must supply a per-request context.WithTimeout.

📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
func (s *StepFunModel) AudioSpeech(modelName *string, audioContent *string, apiConfig *APIConfig, asrConfig *TTSConfig) (*TTSResponse, error) {
// TODO Test it
if audioContent == nil || *audioContent == "" {
return nil, fmt.Errorf("audio content is empty")
}
var region = "default"
if apiConfig != nil && apiConfig.Region != nil && *apiConfig.Region != "" {
region = *apiConfig.Region
}
url := fmt.Sprintf("%s/%s", s.BaseURL[region], s.URLSuffix.TTS)
reqBody := map[string]interface{}{
"model": *modelName,
"input": *audioContent,
}
if asrConfig != nil && asrConfig.Params != nil {
for key, value := range asrConfig.Params {
reqBody[key] = value
}
}
if asrConfig != nil && asrConfig.Format != "" {
reqBody["response_format"] = asrConfig.Format
}
jsonData, err := json.Marshal(reqBody)
if err != nil {
return nil, fmt.Errorf("failed to marshal request: %w", err)
}
req, err := http.NewRequest("POST", url, bytes.NewBuffer(jsonData))
if err != nil {
return nil, fmt.Errorf("failed to create request: %w", err)
}
req.Header.Set("Content-Type", "application/json")
req.Header.Set("Authorization", fmt.Sprintf("Bearer %s", *apiConfig.ApiKey))
resp, err := s.httpClient.Do(req)
if err != nil {
return nil, fmt.Errorf("failed to send request: %w", err)
}
defer resp.Body.Close()
body, err := io.ReadAll(resp.Body)
if err != nil {
return nil, fmt.Errorf("failed to read response body: %w", err)
}
if resp.StatusCode != http.StatusOK {
return nil, fmt.Errorf("%s - %s", resp.Status, string(body))
}
return &TTSResponse{Audio: body}, nil
}
// AudioSpeech performs non-streaming text-to-speech via StepFun's /audio/speech endpoint.
func (s *StepFunModel) AudioSpeech(modelName *string, audioContent *string, apiConfig *APIConfig, ttsConfig *TTSConfig) (*TTSResponse, error) {
if apiConfig == nil || apiConfig.ApiKey == nil || *apiConfig.ApiKey == "" {
return nil, fmt.Errorf("api key is required")
}
if modelName == nil || *modelName == "" {
return nil, fmt.Errorf("model name is required")
}
if audioContent == nil || *audioContent == "" {
return nil, fmt.Errorf("audio content is empty")
}
region := "default"
if apiConfig.Region != nil && *apiConfig.Region != "" {
region = *apiConfig.Region
}
baseURL, err := s.baseURLForRegion(region)
if err != nil {
return nil, err
}
url := fmt.Sprintf("%s/%s", baseURL, s.URLSuffix.TTS)
reqBody := map[string]interface{}{
"model": *modelName,
"input": *audioContent,
}
if ttsConfig != nil && ttsConfig.Params != nil {
for key, value := range ttsConfig.Params {
reqBody[key] = value
}
}
if ttsConfig != nil && ttsConfig.Format != "" {
reqBody["response_format"] = ttsConfig.Format
}
jsonData, err := json.Marshal(reqBody)
if err != nil {
return nil, fmt.Errorf("failed to marshal request: %w", err)
}
ctx, cancel := context.WithTimeout(context.Background(), nonStreamCallTimeout)
defer cancel()
req, err := http.NewRequestWithContext(ctx, "POST", url, bytes.NewBuffer(jsonData))
if err != nil {
return nil, fmt.Errorf("failed to create request: %w", err)
}
req.Header.Set("Content-Type", "application/json")
req.Header.Set("Authorization", fmt.Sprintf("Bearer %s", *apiConfig.ApiKey))
resp, err := s.httpClient.Do(req)
if err != nil {
return nil, fmt.Errorf("failed to send request: %w", err)
}
defer resp.Body.Close()
body, err := io.ReadAll(resp.Body)
if err != nil {
return nil, fmt.Errorf("failed to read response body: %w", err)
}
if resp.StatusCode != http.StatusOK {
return nil, fmt.Errorf("%s - %s", resp.Status, string(body))
}
return &TTSResponse{Audio: body}, nil
}
🤖 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/stepfun.go` around lines 481 - 537, AudioSpeech has
several correctness gaps: null-derefs (apiConfig, apiConfig.ApiKey, modelName),
missing per-request timeout/context, wrong region URL lookup, and misnamed
param; fix by validating apiConfig and apiConfig.ApiKey (return error if
nil/empty) and modelName (return error if nil/empty) before use, rename
parameter asrConfig to ttsConfig to match other helpers, build the URL via
baseURLForRegion(region) instead of s.BaseURL[region], create the request with
context.WithTimeout(context.Background(), nonStreamCallTimeout) and use
http.NewRequestWithContext, and only set the Authorization header after
confirming ApiKey; keep existing body marshaling and response handling but
ensure you reference AudioSpeech, apiConfig.ApiKey, modelName, ttsConfig,
baseURLForRegion, nonStreamCallTimeout and s.httpClient in your changes.

Comment on lines +540 to +595
func (s *StepFunModel) AudioSpeechWithSender(modelName *string, audioContent *string, apiConfig *APIConfig, ttsConfig *TTSConfig, sender func(*string, *string) error) error {
// TODO Test it
if apiConfig == nil || apiConfig.ApiKey == nil || *apiConfig.ApiKey == "" {
return fmt.Errorf("StepFun API key is missing")
}

if audioContent == nil || *audioContent == "" {
return fmt.Errorf("audio content is empty")
}

var region = "default"
if apiConfig.Region != nil && *apiConfig.Region != "" {
region = *apiConfig.Region
}

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

reqBody := map[string]interface{}{
"model": *modelName,
"input": *audioContent,
"stream_format": "sse",
}

if ttsConfig != nil && ttsConfig.Params != nil {
for key, value := range ttsConfig.Params {
reqBody[key] = value
}
}
if ttsConfig != nil && ttsConfig.Format != "" {
reqBody["response_format"] = ttsConfig.Format
}

jsonData, err := json.Marshal(reqBody)
if err != nil {
return fmt.Errorf("failed to marshal request: %w", err)
}

req, err := http.NewRequest("POST", url, bytes.NewBuffer(jsonData))
if err != nil {
return fmt.Errorf("failed to create request: %w", err)
}

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

resp, err := s.httpClient.Do(req)
if err != nil {
return fmt.Errorf("failed to send request: %w", err)
}
defer resp.Body.Close()

if resp.StatusCode != http.StatusOK {
body, _ := io.ReadAll(resp.Body)
return fmt.Errorf("StepFun stream TTS API error: %d - %s", resp.StatusCode, string(body))
}

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

AudioSpeechWithSender: missing modelName nil check, bypasses baseURLForRegion, and should drop the TODO before merge.

Three smaller issues mirroring the non-streaming path:

  1. *modelName deref at line 558 is unchecked; the signature accepts *string.
  2. Direct s.BaseURL[region] indexing at line 555 silently yields "" for an unconfigured region and produces a relative URL the transport rejects with an opaque error. Use baseURLForRegion as ChatStreamlyWithSender does (line 238) for fail-fast behavior with a clear message.
  3. // TODO Test it at line 541 — please remove once tested, or open a tracking issue so this isn't shipped with an unresolved TODO on a public method.

For the request itself, the streaming http.NewRequest(...) without context is acceptable here per the design comment at lines 51-54 (long-lived SSE), so no timeout change is needed.

🔧 Proposed fix
 func (s *StepFunModel) AudioSpeechWithSender(modelName *string, audioContent *string, apiConfig *APIConfig, ttsConfig *TTSConfig, sender func(*string, *string) error) error {
-	// TODO Test it
 	if apiConfig == nil || apiConfig.ApiKey == nil || *apiConfig.ApiKey == "" {
 		return fmt.Errorf("StepFun API key is missing")
 	}
-
+	if modelName == nil || *modelName == "" {
+		return fmt.Errorf("model name is required")
+	}
 	if audioContent == nil || *audioContent == "" {
 		return fmt.Errorf("audio content is empty")
 	}
@@
-	var region = "default"
+	region := "default"
 	if apiConfig.Region != nil && *apiConfig.Region != "" {
 		region = *apiConfig.Region
 	}
-
-	url := fmt.Sprintf("%s/%s", s.BaseURL[region], s.URLSuffix.TTS)
+
+	baseURL, err := s.baseURLForRegion(region)
+	if err != nil {
+		return err
+	}
+	url := fmt.Sprintf("%s/%s", baseURL, s.URLSuffix.TTS)

Happy to open a tracking issue for end-to-end test coverage of AudioSpeech/AudioSpeechWithSender against StepFun's /audio/speech endpoint — let me know.

🤖 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/stepfun.go` around lines 540 - 595,
AudioSpeechWithSender currently dereferences modelName without a nil check,
indexes s.BaseURL[region] directly (which can produce an empty/relative URL),
and leaves a leftover TODO; fix by adding a nil/empty check for modelName at the
start of AudioSpeechWithSender and returning an explicit error if missing,
replace the direct s.BaseURL[region] usage with the helper baseURLForRegion
(same pattern used by ChatStreamlyWithSender) to fail fast with a clear message
when the region is unconfigured, and remove the "// TODO Test it" comment (or
convert it into a tracked issue reference) before merging.

Comment on lines +596 to +636
scanner := bufio.NewScanner(resp.Body)
scanner.Buffer(make([]byte, 64*1024), 8*1024*1024)

for scanner.Scan() {
line := scanner.Text()

if !strings.HasPrefix(line, "data: ") {
continue
}

dataStr := strings.TrimSpace(line[6:])
// [DONE]
if dataStr == "" || dataStr == "[DONE]" {
continue
}

// Parse
var event struct {
Type string `json:"type"`
Audio string `json:"audio"`
}

if err := json.Unmarshal([]byte(dataStr), &event); err != nil {
continue
}

if event.Type == "speech.audio.error" {
return fmt.Errorf("StepFun stream encountered an error during generation")
}

// Extract the Base64 string containing the audio and decode it
if event.Type == "speech.audio.delta" && event.Audio != "" {
audioBytes, err := base64.StdEncoding.DecodeString(event.Audio)
if err == nil && len(audioBytes) > 0 {
chunk := string(audioBytes)
if errSend := sender(&chunk, nil); errSend != nil {
return errSend
}
}
}
}

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

SSE prefix "data: " with trailing space will silently drop chunks; align with the existing ChatStreamlyWithSender parser.

strings.HasPrefix(line, "data: ") requires a literal space after the colon, but the SSE spec treats that space as optional and servers (including OpenAI-compatible ones) commonly emit data:{...} without it. If StepFun ever returns a line without the space — or returns the [DONE] sentinel as data:[DONE] — every audio delta will fall through the continue and the caller will receive zero audio with no error. ChatStreamlyWithSender at line 316 already uses the correct, prefix-only form ("data:") and strips the optional space via TrimSpace.

Additionally, event.Type == "speech.audio.error" returns a generic message — surfacing the raw event payload would make production debugging far easier.

🔧 Proposed fix
-		if !strings.HasPrefix(line, "data: ") {
+		if !strings.HasPrefix(line, "data:") {
 			continue
 		}

-		dataStr := strings.TrimSpace(line[6:])
+		dataStr := strings.TrimSpace(line[5:])
 		// [DONE]
 		if dataStr == "" || dataStr == "[DONE]" {
 			continue
 		}
@@
-		if event.Type == "speech.audio.error" {
-			return fmt.Errorf("StepFun stream encountered an error during generation")
+		if event.Type == "speech.audio.error" {
+			return fmt.Errorf("StepFun stream error: %s", dataStr)
 		}
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
scanner := bufio.NewScanner(resp.Body)
scanner.Buffer(make([]byte, 64*1024), 8*1024*1024)
for scanner.Scan() {
line := scanner.Text()
if !strings.HasPrefix(line, "data: ") {
continue
}
dataStr := strings.TrimSpace(line[6:])
// [DONE]
if dataStr == "" || dataStr == "[DONE]" {
continue
}
// Parse
var event struct {
Type string `json:"type"`
Audio string `json:"audio"`
}
if err := json.Unmarshal([]byte(dataStr), &event); err != nil {
continue
}
if event.Type == "speech.audio.error" {
return fmt.Errorf("StepFun stream encountered an error during generation")
}
// Extract the Base64 string containing the audio and decode it
if event.Type == "speech.audio.delta" && event.Audio != "" {
audioBytes, err := base64.StdEncoding.DecodeString(event.Audio)
if err == nil && len(audioBytes) > 0 {
chunk := string(audioBytes)
if errSend := sender(&chunk, nil); errSend != nil {
return errSend
}
}
}
}
scanner := bufio.NewScanner(resp.Body)
scanner.Buffer(make([]byte, 64*1024), 8*1024*1024)
for scanner.Scan() {
line := scanner.Text()
if !strings.HasPrefix(line, "data:") {
continue
}
dataStr := strings.TrimSpace(line[5:])
// [DONE]
if dataStr == "" || dataStr == "[DONE]" {
continue
}
// Parse
var event struct {
Type string `json:"type"`
Audio string `json:"audio"`
}
if err := json.Unmarshal([]byte(dataStr), &event); err != nil {
continue
}
if event.Type == "speech.audio.error" {
return fmt.Errorf("StepFun stream error: %s", dataStr)
}
// Extract the Base64 string containing the audio and decode it
if event.Type == "speech.audio.delta" && event.Audio != "" {
audioBytes, err := base64.StdEncoding.DecodeString(event.Audio)
if err == nil && len(audioBytes) > 0 {
chunk := string(audioBytes)
if errSend := sender(&chunk, nil); errSend != nil {
return errSend
}
}
}
}
🤖 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/stepfun.go` around lines 596 - 636, The SSE parsing
loop in the StepFun stream uses strings.HasPrefix(line, "data: ") which will
drop valid lines like "data:{...}" — change the prefix check to "data:" and then
use strings.TrimSpace on the substring (e.g., dataStr :=
strings.TrimSpace(line[len("data:"):])) to match the ChatStreamlyWithSender
behavior; keep the existing JSON unmarshal into the anonymous event struct
(Type, Audio) and for the error case (when event.Type == "speech.audio.error")
return an error that includes the raw event payload (or the unmarshaled event
content) instead of the generic message so callers get useful debugging
information, and leave the audio decode/send logic using sender(...) intact.

@codecov

codecov Bot commented May 15, 2026 •

Copy link
Copy Markdown

Codecov Report

✅ All modified and coverable lines are covered by tests.
✅ Project coverage is 94.16%. Comparing base (c9622d0) to head (3ed4e49).
⚠️ Report is 2 commits behind head on main.

Additional details and impacted files
@@           Coverage Diff           @@
##             main   #14944   +/-   ##
=======================================
  Coverage   94.16%   94.16%           
=======================================
  Files          10       10           
  Lines         703      703           
  Branches      112      112           
=======================================
  Hits          662      662           
  Misses         25       25           
  Partials       16       16           

☔ 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 c286317 into infiniflow:main May 15, 2026
1 check passed
@coderabbitai coderabbitai Bot mentioned this pull request May 19, 2026
2 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