Repository navigation
Go: implement TTS, ASR for Siliconflow and TTs for StepFun - #14944
Conversation
|
No actionable comments were generated in the recent review. 🎉 ℹ️ Recent review info⚙️ Run configurationConfiguration used: Organization UI Review profile: CHILL Plan: Pro Run ID: 📒 Files selected for processing (3)
🚧 Files skipped from review as they are similar to previous changes (2)
📝 WalkthroughWalkthroughImplements 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. ChangesSiliconFlow audio implementation
Estimated code review effort🎯 4 (Complex) | ⏱️ ~45 minutes Possibly related PRs
Suggested labels
Poem
🚥 Pre-merge checks | ✅ 5✅ Passed checks (5 passed)
✏️ Tip: You can configure your own custom pre-merge checks in the settings. Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out. Comment |
There was a problem hiding this comment.
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
📒 Files selected for processing (6)
conf/models/siliconflow.jsonconf/models/stepfun.jsoninternal/cli/user_command.gointernal/development.mdinternal/entity/models/siliconflow.gointernal/entity/models/stepfun.go
| ] | ||
| }, | ||
| { | ||
| "name": "step-tts-2 ", |
There was a problem hiding this comment.
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.
| "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.
| result.Data = []map[string]interface{}{ | ||
| {"text": rawResult.Data["text"].(string)}, | ||
| } |
There was a problem hiding this comment.
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.
| SUCCESS | ||
| ``` | ||
|
|
||
| ### 6.24 Audio to Speech |
There was a problem hiding this comment.
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.
| ### 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.
| 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 | ||
| } |
There was a problem hiding this comment.
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.Regionis read without first checkingapiConfig == nil. Every other method in this file (e.g.ChatWithMessages,AudioSpeechWithSender) guardsapiConfigbefore touching its fields. - Line 771:
*modelNameis dereferenced without a nil/empty check;modelNameis a*string. - Line 814:
*apiConfig.ApiKeyis dereferenced without checkingapiConfig.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.
| 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.
| // 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 | ||
| } |
There was a problem hiding this comment.
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
*TTSConfigbut namedasrConfig. Rename tottsConfigfor consistency withAudioSpeechWithSenderand to avoid confusion at call sites. - Missing guards mirror the issues in
TranscribeAudio:apiConfigis not checked fornilbefore line 860 (apiConfig.Region) or line 892 (*apiConfig.ApiKey).modelNameis dereferenced on line 867 without a nil/empty check.apiConfig.ApiKeyis 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.
| 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 | ||
| } |
There was a problem hiding this comment.
🧩 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.goRepository: 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.goRepository: 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.goRepository: infiniflow/ragflow
Length of output: 1865
🏁 Script executed:
# Get the full TTSUserCommand implementation
sed -n '1931,2100p' internal/cli/user_command.goRepository: 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.goRepository: 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=goRepository: 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.goRepository: 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 -100Repository: 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=goRepository: 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=goRepository: 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=goRepository: 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 2Repository: infiniflow/ragflow
Length of output: 3511
Add nil guard for modelName and encode binary audio as base64 for streaming.
-
Line 929 dereferences
*modelNamewithout 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 thesender(*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.
| 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 | ||
| } |
There was a problem hiding this comment.
AudioSpeech has multiple correctness gaps: NPE risk, missing request timeout, and wrong helper/naming.
Several issues in this non-streaming TTS path:
- Nil-deref on
apiConfigandapiConfig.ApiKey(line 519): UnlikeChatWithMessages(lines 103-105) andListModels(lines 385-387), there is no guard. If a caller passes a nilapiConfigor nil/emptyApiKey, this panics or sendsBearerwith an empty token. The conditional at line 488 even toleratesapiConfig == nil, which makes the later unconditional deref worse. - Nil-deref on
modelName(line 495):*modelNameis dereferenced without a nil check; the public signature takes*string. - Missing per-request timeout context: The driver intentionally leaves
httpClient.Timeoutunset (see the explanatory comment at lines 51-54) and the convention in this file is that non-streaming callers wrap each request withcontext.WithTimeout(context.Background(), nonStreamCallTimeout)(seeChatWithMessagesline 159 andListModelsline 400). This call instead useshttp.NewRequestwith no deadline at all, so a slow/hung TTS request can block indefinitely onResponseHeaderTimeoutalone (60s) and then on body read forever. - Bypasses
baseURLForRegionat line 492: directly indexings.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 throughbaseURLForRegionfor fail-fast behavior. - Parameter name & doc comment: the parameter is named
asrConfig *TTSConfigand the doc comment says "convert audio to text" — both wrong; this is TTS (text → speech). Renaming the param tottsConfigmatchesAudioSpeechWithSenderand 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.
| 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.
| 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)) | ||
| } | ||
|
|
There was a problem hiding this comment.
AudioSpeechWithSender: missing modelName nil check, bypasses baseURLForRegion, and should drop the TODO before merge.
Three smaller issues mirroring the non-streaming path:
*modelNamederef at line 558 is unchecked; the signature accepts*string.- 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. UsebaseURLForRegionasChatStreamlyWithSenderdoes (line 238) for fail-fast behavior with a clear message. // TODO Test itat 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.
| 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 | ||
| } | ||
| } | ||
| } | ||
| } |
There was a problem hiding this comment.
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.
| 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 Report✅ All modified and coverable lines are covered by tests. 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. 🚀 New features to boost your workflow:
|
What problem does this PR solve?
This PRimplement TTS, ASR for Siliconflow and TTs for StepFun
The following functionalities are now supported:
SiliConFlow:
StrepFun:
Verified examples from the CLI:
Type of change