Repository navigation
Go: implement ASR in ZhipuAI driver - #15134
Conversation
📝 WalkthroughWalkthroughAdds an ChangesZhipuAI ASR Transcription and TTS
Sequence Diagram(s)sequenceDiagram
participant ComponentA
participant ComponentB
ComponentA->>ComponentB: observable interaction
Estimated code review effort🎯 4 (Complex) | ⏱️ ~45 minutes Possibly related PRs
Suggested reviewers
🚥 Pre-merge checks | ✅ 4 | ❌ 1❌ Failed checks (1 warning)
✅ Passed checks (4 passed)
✏️ Tip: You can configure your own custom pre-merge checks in the settings. Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out. Comment |
Haruko386
left a comment
There was a problem hiding this comment.
Hi @jakearmstrong59, All tests are passed, just do a small change:
Also I have implement TTS for zhipu-ai, would you mind adding my implement in your PR?
| @@ -268,4 +269,4 @@ | |||
| ] | |||
There was a problem hiding this comment.
Add some model for zhipu-ai ASR, TTS
{
"name": "glm-asr-2512",
"model_types": [
"asr"
]
},
{
"name": "glm-tts",
"model_types": [
"tts"
]
}| "embedding": "embeddings", | ||
| "rerank": "rerank", | ||
| "asr": "audio/transcriptions", | ||
| "files": "files", |
There was a problem hiding this comment.
add TTS:
"tts": "audio/speech"
| } | ||
| } | ||
|
|
||
| func (z *ZhipuAIModel) TranscribeAudioWithSender(modelName *string, file *string, apiConfig *APIConfig, asrConfig *ASRConfig, sender func(*string, *string) error) error { |
There was a problem hiding this comment.
Add TTS
// AudioSpeech convert text to audio
func (z *ZhipuAIModel) AudioSpeech(modelName *string, audioContent *string, apiConfig *APIConfig, ttsConfig *TTSConfig) (*TTSResponse, error) {
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", z.BaseURL[region], z.URLSuffix.TTS)
reqBody := map[string]interface{}{
"model": *modelName,
"input": *audioContent,
"stream": false,
}
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))
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 := z.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
}
func (z *ZhipuAIModel) AudioSpeechWithSender(modelName *string, audioContent *string, apiConfig *APIConfig, ttsConfig *TTSConfig, sender func(*string, *string) error) error {
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
}|
Thanks @Haruko386. I added the ZhipuAI TTS suffix and implemented both Verified locally: GOCACHE=/tmp/ragflow-go-build-cache GOMODCACHE=/tmp/ragflow-go-mod-cache /tmp/go1.26.3/bin/go test -vet=off -run TestZhipuAI -count=1 ./internal/entity/models
python3 -m json.tool conf/models/zhipu-ai.json |
There was a problem hiding this comment.
🧹 Nitpick comments (1)
internal/entity/models/zhipu_ai_test.go (1)
242-253: ⚡ Quick winStrengthen streaming TTS request contract assertions.
This handler only checks
stream=true; method/path/auth/content-type regressions inAudioSpeechWithSenderwould go undetected.Suggested test hardening
func TestZhipuAIAudioSpeechWithSender(t *testing.T) { srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + if r.Method != http.MethodPost { + t.Errorf("method=%s", r.Method) + return + } + if r.URL.Path != "/audio/speech" { + t.Errorf("path=%s", r.URL.Path) + return + } + if got := r.Header.Get("Authorization"); got != "Bearer test-key" { + t.Errorf("Authorization=%q", got) + return + } + if got := r.Header.Get("Content-Type"); !strings.HasPrefix(got, "application/json") { + t.Errorf("Content-Type=%q", got) + return + } + var body map[string]interface{} if err := json.NewDecoder(r.Body).Decode(&body); err != nil { t.Errorf("Decode: %v", err) return }🤖 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/zhipu_ai_test.go` around lines 242 - 253, The test server handler for AudioSpeechWithSender only asserts body["stream"]==true and thus misses regressions in HTTP method, request path, auth header and content-type; update the httptest.NewServer handler used by AudioSpeechWithSender tests to validate the incoming request method (e.g., POST), the request URL path expected by AudioSpeechWithSender, the Authorization header contains the expected API key/token, Content-Type is application/json (or the exact type used), and any required request body fields (besides "stream") such as voice/format parameters; keep the existing stream assertion and respond with the same chunked body to preserve streaming behavior.
🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.
Nitpick comments:
In `@internal/entity/models/zhipu_ai_test.go`:
- Around line 242-253: The test server handler for AudioSpeechWithSender only
asserts body["stream"]==true and thus misses regressions in HTTP method, request
path, auth header and content-type; update the httptest.NewServer handler used
by AudioSpeechWithSender tests to validate the incoming request method (e.g.,
POST), the request URL path expected by AudioSpeechWithSender, the Authorization
header contains the expected API key/token, Content-Type is application/json (or
the exact type used), and any required request body fields (besides "stream")
such as voice/format parameters; keep the existing stream assertion and respond
with the same chunked body to preserve streaming behavior.
ℹ️ Review info
⚙️ Run configuration
Configuration used: Organization UI
Review profile: CHILL
Plan: Pro
Run ID: 59f50a7e-cf78-4617-8b6e-5a9197f381f6
📒 Files selected for processing (3)
conf/models/zhipu-ai.jsoninternal/entity/models/zhipu-ai.gointernal/entity/models/zhipu_ai_test.go
Codecov Report✅ All modified and coverable lines are covered by tests. Additional details and impacted files@@ Coverage Diff @@
## main #15134 +/- ##
==========================================
- Coverage 94.53% 93.12% -1.41%
==========================================
Files 10 10
Lines 713 713
Branches 116 116
==========================================
- Hits 674 664 -10
- Misses 25 29 +4
- Partials 14 20 +6 ☔ View full report in Codecov by Sentry. 🚀 New features to boost your workflow:
|
Haruko386
left a comment
There was a problem hiding this comment.
@jakearmstrong59 LGTM, thank you for your contribution.
What problem does this PR solve?
This PR implements ASR and TTS support for the ZhipuAI Go driver.
The ZhipuAI model config already advertises
glm-asr-2512as an ASR model, but the Go driver returnedzhipu, no such methodfromTranscribeAudio. This adds the documented audio transcription endpoint suffix and sends multipart transcription requests withmodel,stream=false, andfilefields.Per maintainer review, this also adds the ZhipuAI TTS endpoint suffix and implements
AudioSpeech/AudioSpeechWithSenderforglm-tts.Closes #15133
Type of change