Skip to content

Go: implement ASR in ZhipuAI driver - #15134

Merged
JinHai-CN merged 2 commits into
infiniflow:mainfrom
whitepicker:fix/zhipu-ai-asr
May 22, 2026
Merged

JinHai-CN merged 2 commits into
infiniflow:mainfrom
whitepicker:fix/zhipu-ai-asr

Conversation

@whitepicker

@whitepicker whitepicker commented May 22, 2026 •

Copy link
Copy Markdown
Contributor

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-2512 as an ASR model, but the Go driver returned zhipu, no such method from TranscribeAudio. This adds the documented audio transcription endpoint suffix and sends multipart transcription requests with model, stream=false, and file fields.

Per maintainer review, this also adds the ZhipuAI TTS endpoint suffix and implements AudioSpeech / AudioSpeechWithSender for glm-tts.

Closes #15133

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 22, 2026
@coderabbitai

coderabbitai Bot commented May 22, 2026 •

Copy link
Copy Markdown
Contributor

Review Change Stack

📝 Walkthrough

Walkthrough

Adds an asr URL suffix to ZhipuAI config, implements ZhipuAIModel.TranscribeAudio (multipart ASR upload and response parsing), implements AudioSpeech and streaming AudioSpeechWithSender (TTS), and adds unit tests covering happy paths, validation, configuration, and HTTP errors.

Changes

ZhipuAI ASR Transcription and TTS

Layer / File(s) Summary
ASR endpoint configuration
conf/models/zhipu-ai.json
Added asr URL suffix mapping to audio/transcriptions and adjusted final newline/brace placement.
ASR multipart implementation
internal/entity/models/zhipu-ai.go
Added imports for multipart/file handling; implemented TranscribeAudio to validate inputs, select region base URL, build multipart/form-data (model, stream, optional ASR params, file), POST to /audio/transcriptions, and parse the JSON text field. Added writeZhipuASRParams and writeZhipuASRField helpers to serialize params.
TTS implementation and streaming
internal/entity/models/zhipu-ai.go
Added buildTTSRequest helper to validate inputs, compute TTS URL and JSON body including optional params/response_format; implemented AudioSpeech to POST JSON and return audio bytes; implemented AudioSpeechWithSender to stream response chunks via the provided sender callback.
ASR/TTS unit tests
internal/entity/models/zhipu_ai_test.go
Added test helpers and tests: ASR happy path, ASR validation cases, missing ASR suffix, ASR HTTP error; TTS happy path, TTS streaming test, TTS validation cases, missing TTS suffix, and TTS HTTP error tests.

Sequence Diagram(s)

sequenceDiagram
  participant ComponentA
  participant ComponentB
  ComponentA->>ComponentB: observable interaction
Loading

Estimated code review effort

🎯 4 (Complex) | ⏱️ ~45 minutes

Possibly related PRs

  • infiniflow/ragflow#15107: Implements similar ASR/TTS functionality and multipart/streaming request handling for another provider.

Suggested reviewers

  • Haruko386

🐰 I hopped in code and found a sound,
Multipart fields all neatly bound.
From bytes to text, from text to song,
Zhipu’s audio flows along.
🥕🎶

🚥 Pre-merge checks | ✅ 4 | ❌ 1

❌ Failed checks (1 warning)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 0.00% which is insufficient. The required threshold is 80.00%. Write docstrings for the functions missing them to satisfy the coverage threshold.
✅ Passed checks (4 passed)
Check name Status Explanation
Title check ✅ Passed The PR title 'Go: implement ASR in ZhipuAI driver' directly summarizes the main change: implementing ASR functionality for the ZhipuAI Go driver. This is the primary objective stated in the PR description.
Linked Issues check ✅ Passed The PR fully addresses the requirements from issue #15133: adds the missing 'asr' URL suffix to conf/models/zhipu-ai.json, implements multipart POST requests with model/stream/file fields in TranscribeAudio, and returns transcribed text. Additionally implements TTS support per maintainer review.
Out of Scope Changes check ✅ Passed All changes are in-scope. The conf file adds the asr suffix, zhipu-ai.go implements ASR/TTS methods, and zhipu_ai_test.go adds comprehensive test coverage—all directly aligned with issue #15133 requirements and maintainer-requested TTS functionality.
Description check ✅ Passed The PR description includes a clear problem statement explaining the ASR/TTS implementation for ZhipuAI driver and the 'no such method' issue it addresses, and specifies both Bug Fix and New Feature types.

✏️ 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 left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

Hi @jakearmstrong59, 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?

Comment thread conf/models/zhipu-ai.json
@@ -268,4 +269,4 @@
]

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

Add some model for zhipu-ai ASR, TTS

{
      "name": "glm-asr-2512",
      "model_types": [
        "asr"
      ]
    },
    {
      "name": "glm-tts",
      "model_types": [
        "tts"
      ]
    }

Comment thread conf/models/zhipu-ai.json
"embedding": "embeddings",
"rerank": "rerank",
"asr": "audio/transcriptions",
"files": "files",

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

add TTS:
"tts": "audio/speech"

}
}

func (z *ZhipuAIModel) TranscribeAudioWithSender(modelName *string, file *string, apiConfig *APIConfig, asrConfig *ASRConfig, sender func(*string, *string) error) error {

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

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
}

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

Copy link
Copy Markdown
Contributor Author

Thanks @Haruko386. I added the ZhipuAI TTS suffix and implemented both AudioSpeech and AudioSpeechWithSender for glm-tts, with tests for request shape, protected fields, streaming, validation, missing suffix, and HTTP errors.

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

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

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

242-253: ⚡ Quick win

Strengthen streaming TTS request contract assertions.

This handler only checks stream=true; method/path/auth/content-type regressions in AudioSpeechWithSender would 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

📥 Commits

Reviewing files that changed from the base of the PR and between e0cc6fe and 513736f.

📒 Files selected for processing (3)
  • conf/models/zhipu-ai.json
  • internal/entity/models/zhipu-ai.go
  • internal/entity/models/zhipu_ai_test.go

@codecov

codecov Bot commented May 22, 2026 •

Copy link
Copy Markdown

Codecov Report

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

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.
📢 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.

@Haruko386 Haruko386 left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

@jakearmstrong59 LGTM, thank you for your contribution.

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

Labels

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

Projects

None yet

Development

Successfully merging this pull request may close these issues.

[Bug]: ZhipuAI Go driver advertises ASR model but returns no such method

3 participants