Repository navigation
feat: add chat-level TTS and ASR endpoints for Go API server - #17036
Conversation
- Add POST /api/v1/chat/audio/speech using the tenant's default TTS model, returning a streaming audio/mpeg response. - Add POST /api/v1/chat/audio/transcription using the tenant's default ASR model, supporting multipart file upload and optional SSE streaming. This ports the Python /chat/audio/* endpoints to Go.
📝 WalkthroughWalkthroughAdds authenticated chat endpoints for streaming text-to-speech and audio transcription. Speech uses tenant-default TTS models, while transcription supports validated uploads, tenant-default ASR models, SSE partial results, completion/error events, and JSON responses. ChangesChat audio API
Estimated code review effort: 4 (Complex) | ~45 minutes Sequence Diagram(s)sequenceDiagram
participant Client
participant ChatAudioSpeech
participant TTSModel
Client->>ChatAudioSpeech: Send JSON text
ChatAudioSpeech->>TTSModel: Synthesize each segment
TTSModel-->>ChatAudioSpeech: Return MP3 bytes
ChatAudioSpeech-->>Client: Stream audio/mpeg
sequenceDiagram
participant Client
participant ChatAudioTranscription
participant ASRDriver
Client->>ChatAudioTranscription: Upload audio file
ChatAudioTranscription->>ASRDriver: Transcribe temporary file
ASRDriver-->>ChatAudioTranscription: Return chunks or text
ChatAudioTranscription-->>Client: Send SSE events or JSON
Poem
🚥 Pre-merge checks | ✅ 5✅ Passed checks (5 passed)
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: 5
🧹 Nitpick comments (2)
internal/handler/chat_audio.go (2)
42-47: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick winReplace Python migration-history comments with current Go behavior.
Describe the delimiters, streaming headers, and accepted extensions directly; references to what the Python endpoint did will become stale.
As per coding guidelines, “keep package and documentation comments aligned with the current runtime path rather than migration history” and “do not add compatibility wording to comments or documentation.”
Also applies to: 72-72, 102-103
🤖 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/handler/chat_audio.go` around lines 42 - 47, The comments around ttsSegmentSplitRegex and ChatAudioSpeech currently describe Python migration history; replace them with documentation of the current Go behavior. State the delimiters used for text splitting, the streaming audio/mpeg response headers, and the accepted audio extensions directly, including the related comments at the other referenced locations, without mentioning Python or compatibility history.Source: Coding guidelines
37-40: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick winKeep the handler-only request type private.
Rename
ChatAudioSpeechRequesttochatAudioSpeechRequest; it is not part of an external Go contract.As per coding guidelines, “Reduce public surface area by making helpers private or internal when possible.”
🤖 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/handler/chat_audio.go` around lines 37 - 40, Rename the handler-only request type ChatAudioSpeechRequest to the unexported chatAudioSpeechRequest, and update all references within the audio speech handler flow to use the new name without changing its fields or behavior.Source: Coding guidelines
🤖 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 `@internal/handler/chat_audio.go`:
- Around line 172-196: The transcription response flow around sender and
TranscribeAudioWithSender must always emit exactly one completion event on
success. Track whether sender already received the "[DONE]" marker, then emit
the existing done event after a successful transcription only when it was not
sent; preserve the current error event behavior for failures.
- Around line 130-153: In internal/handler/chat_audio.go lines 130-153, update
the chat-audio upload handler before FormFile to wrap the request body with
http.MaxBytesReader using the configured audio-size limit, and return an
argument error when the multipart payload exceeds that limit. In
internal/handler/chat_audio.go lines 55-59, bound the JSON request body before
decoding and validate the decoded text length or segment count before invoking
the TTS flow; preserve existing validation and responses for acceptable
requests.
- Around line 85-94: Update the AudioSpeech streaming flow so response headers
are committed only when the first non-empty audio chunk is available. Replace
the synthesis-error continue path with stream termination, and likewise
terminate on later failures instead of omitting segments; preserve normal
streaming for valid resp.Audio chunks.
- Around line 165-170: Update the SSE response setup in the streamMode branch of
the chat audio handler to set the X-Accel-Buffering response header to no before
writing the status, preserving the existing streaming headers and behavior.
- Around line 87-89: Update the warning in the chat TTS synthesis error path to
remove the user-provided segment text from zap fields. In the surrounding
handler, log only non-sensitive metadata such as the segment index and length
alongside the synthesis error, preserving the existing failure context.
---
Nitpick comments:
In `@internal/handler/chat_audio.go`:
- Around line 42-47: The comments around ttsSegmentSplitRegex and
ChatAudioSpeech currently describe Python migration history; replace them with
documentation of the current Go behavior. State the delimiters used for text
splitting, the streaming audio/mpeg response headers, and the accepted audio
extensions directly, including the related comments at the other referenced
locations, without mentioning Python or compatibility history.
- Around line 37-40: Rename the handler-only request type ChatAudioSpeechRequest
to the unexported chatAudioSpeechRequest, and update all references within the
audio speech handler flow to use the new name without changing its fields or
behavior.
🪄 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: 6cac0ddd-82ae-434a-83d8-ad51eaf0fea9
📒 Files selected for processing (2)
internal/handler/chat_audio.gointernal/router/router.go
| resp, err := driver.AudioSpeech(&modelName, &seg, apiConfig, &modelModule.TTSConfig{Format: "mp3"}) | ||
| if err != nil { | ||
| common.Warn("chat TTS synthesis failed", | ||
| zap.String("segment", truncateString(seg, 64)), | ||
| zap.Error(err)) | ||
| continue | ||
| } | ||
| if resp == nil || len(resp.Audio) == 0 { | ||
| continue | ||
| } |
There was a problem hiding this comment.
🎯 Functional Correctness | 🟠 Major | ⚡ Quick win
Do not silently omit failed speech segments.
Continuing after synthesis errors returns HTTP 200 with incomplete audio. Delay committing headers until the first valid chunk, and terminate the stream on subsequent failures rather than skipping 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/handler/chat_audio.go` around lines 85 - 94, Update the AudioSpeech
streaming flow so response headers are committed only when the first non-empty
audio chunk is available. Replace the synthesis-error continue path with stream
termination, and likewise terminate on later failures instead of omitting
segments; preserve normal streaming for valid resp.Audio chunks.
wangq8
left a comment
There was a problem hiding this comment.
Review: Add chat-level TTS & ASR Go endpoints
Overall a clean, well-structured PR. The new chat_audio.go handler reuses the existing model resolution and driver infrastructure properly. Below are findings organized by severity.
🐛 Bugs
1. SSE stream missing [DONE] event on success (internal/handler/chat_audio.go:172-196)
In the streaming transcription path, if TranscribeAudioWithSender succeeds without ever sending "[DONE]" through the sender callback, the SSE stream never emits a completion event. The client has no way to know transcription is finished and may hang.
Fix: After TranscribeAudioWithSender returns nil (success), send an explicit {"event":"done","text":"[DONE]"} event unless one was already sent by the driver.
2. truncateString can produce invalid UTF-8 (internal/handler/chat_audio.go:221-225)
s[:n] is byte-wise slicing. A string of 22 Chinese characters = 66 bytes; str[:64] splits the last character in half, producing invalid UTF-8. This is used for zap logging and could break JSON encoding of log output.
Fix: Use []rune(s) for character-aware truncation, or use utf8.ValidString / strings.ToValidUTF8 before logging.
🔒 Security
3. Request body not bounded in either endpoint (internal/handler/chat_audio.go:62-64, 119)
ChatAudioSpeech: Nohttp.MaxBytesReaderon the JSON body beforeShouldBindJSON. A large payload could exhaust memory.ChatAudioTranscription: Nohttp.MaxBytesReaderbeforeFormFile. A malicious upload could fill disk/tmp.
Fix: Add http.MaxBytesReader wrapping, matching the existing pattern in agent_upload.go:88 and mcp_server.go:80.
4. User text logged in TTS warning (internal/handler/chat_audio.go:87-89)
zap.String("segment", truncateString(seg, 64)) logs user-provided text. Even truncated, this may contain PII. The existing chat_session.go SSE handler does not log user message content.
Fix: Log only the segment index/length alongside the error, not the text content.
⚠️ Reliability
5. Response headers committed before data is available (internal/handler/chat_audio.go:76-80)
WriteHeader(http.StatusOK) runs before the synthesis loop. If all segments are empty or all synthesis calls fail, the client gets a 200 OK with zero bytes — indistinguishable from silence.
Fix (optional): Defer WriteHeader until the first successful audio chunk, or at minimum track success and log a warning when zero audio was produced.
6. X-Accel-Buffering: no missing in SSE transcription (internal/handler/chat_audio.go:165-170)
The speech endpoint sets this header but the SSE transcription path does not. Behind nginx, this will cause buffering of SSE events.
Fix: Add c.Header("X-Accel-Buffering", "no") in the streamMode branch, matching chat_session.go:198 and search.go:408.
🧹 Style & Maintainability
7. ChatAudioSpeechRequest should be unexported (internal/handler/chat_audio.go:37-39)
It is only used within this handler file; rename to chatAudioSpeechRequest.
8. Comments reference Python migration history (internal/handler/chat_audio.go:42-47, 72, 102-103)
Phrases like "mirrors Pythons ..." and "matching Pythons ..." describe what was done in the old code rather than documenting current Go behavior. Describe the delimiters, headers, and extensions directly.
9. allowedAudioExtsList() builds a sorted list on every call (internal/handler/chat_audio.go:207-213)
This is called on every transcription request. The set is static — use sync.Once or a var initializer to compute it once.
ℹ️ Notes
- The PR correctly uses
disableWriteDeadlineForSSEfor the streaming path — consistent with existing handlers. - Temp file cleanup via
defer os.Removeis correct. - Extension whitelist is a good security practice. Consider if
.wma(a proprietary/codec-limited format) is intentional, or if it should be removed.
CodeRabbit already flagged items 7 and 8. Items 1-6 and 9 are additional findings from this review.
- Send explicit [DONE] SSE event when the ASR driver does not - Cap TTS JSON body (1 MiB) and transcription upload (64 MiB) - Stop logging user-provided TTS text in synthesis warnings - Defer TTS header commit until first audio chunk; error on zero audio - Add X-Accel-Buffering to SSE transcription branch - Unexport speech request type; precompute allowed extension list - Rewrite Python-migration comments to describe current behavior
There was a problem hiding this comment.
Actionable comments posted: 1
🤖 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 `@internal/handler/chat_audio.go`:
- Around line 159-164: In the multipart handling flow, keep http.MaxBytesReader
using chatAudioUploadMaxBytes as the total request-body limit, but change the
ParseMultipartForm argument to a separate smaller memory threshold constant.
Define or reuse an appropriate multipart memory-budget symbol near
chatAudioUploadMaxBytes, and pass it only to ParseMultipartForm.
🪄 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: 966657d2-c8a0-432c-8690-2e6435f7fc5c
📒 Files selected for processing (1)
internal/handler/chat_audio.go
| c.Request.Body = http.MaxBytesReader(c.Writer, c.Request.Body, chatAudioUploadMaxBytes) | ||
| if cl := c.Request.ContentLength; cl > chatAudioUploadMaxBytes { | ||
| common.ResponseWithCodeData(c, common.CodeArgumentError, nil, "request body too large.") | ||
| return | ||
| } | ||
| if err := c.Request.ParseMultipartForm(chatAudioUploadMaxBytes); err != nil { |
There was a problem hiding this comment.
🩺 Stability & Availability | 🟠 Major | ⚡ Quick win
🧩 Analysis chain
🏁 Script executed:
#!/bin/bash
set -euo pipefail
ast-grep outline internal/handler/chat_audio.go \
--match ChatAudioTranscription --view expanded
rg -n -C4 'chatAudioUploadMaxBytes|ParseMultipartForm' \
internal/handler/chat_audio.go
fd -a '^build\.sh$' .Repository: infiniflow/ragflow
Length of output: 1379
🏁 Script executed:
#!/bin/bash
set -euo pipefail
# Read the relevant handler context.
sed -n '145,185p' internal/handler/chat_audio.go
# Check the standard library documentation for ParseMultipartForm and MaxBytesReader.
go doc net/http.Request.ParseMultipartForm || true
echo '---'
go doc net/http.MaxBytesReader || true
# Search for any existing smaller multipart-memory thresholds in the repo.
rg -n "ParseMultipartForm\(|MultipartForm|multipart.*memory|MaxBytesReader" internal . -g '!**/node_modules/**'Repository: infiniflow/ragflow
Length of output: 11904
🏁 Script executed:
#!/bin/bash
set -euo pipefail
# Inspect how the multipart form is consumed after parsing.
sed -n '164,240p' internal/handler/chat_audio.goRepository: infiniflow/ragflow
Length of output: 2745
Separate the multipart memory budget from the 64 MiB body limit. ParseMultipartForm(chatAudioUploadMaxBytes) can keep up to 64 MiB of file parts in memory per request, which is avoidable heap pressure for concurrent uploads. Keep MaxBytesReader as the total-body cap, but lower the multipart threshold.
🤖 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/handler/chat_audio.go` around lines 159 - 164, In the multipart
handling flow, keep http.MaxBytesReader using chatAudioUploadMaxBytes as the
total request-body limit, but change the ParseMultipartForm argument to a
separate smaller memory threshold constant. Define or reuse an appropriate
multipart memory-budget symbol near chatAudioUploadMaxBytes, and pass it only to
ParseMultipartForm.
wangq8
left a comment
There was a problem hiding this comment.
Re-review: PR #17036 — Chat-level TTS & ASR Go endpoints
Previous reviews (CodeRabbit x2 + wangq8) raised 10 distinct findings. I reviewed the merged code to check which were resolved.
✅ Issues fixed since first round
| # | Finding | Status |
|---|---|---|
| 1 | SSE stream missing [DONE] on success |
✅ Fixed — doneSent flag + fallback emission |
| 2 | truncateString produced invalid UTF-8 on CJK |
✅ Fixed — function removed, user text no longer logged |
| 3 | Request body not bounded (both endpoints) | ✅ Fixed — http.MaxBytesReader on both endpoints |
| 4 | User PII logged in TTS warning | ✅ Fixed — now logs only segmentIndex/segmentLen |
| 5 | Response headers committed before data available | ✅ Fixed — headerWritten flag defers until first chunk |
| 6 | X-Accel-Buffering: no missing in SSE path |
✅ Fixed — set in streamMode branch |
| 7 | Comments referencing Python migration history | ✅ Fixed — clean Go-behavior comments |
| 8 | ChatAudioSpeechRequest should be unexported |
✅ Fixed — renamed to chatAudioSpeechRequest |
| 9 | chatAudioAllowedExtsList built on every call |
✅ Fixed — computed once via var initializer |
| 10 | ParseMultipartForm memory threshold |
🟢 Consistent — uses same pattern as agent_upload.go (same limit for MaxBytesReader + ParseMultipartForm). Not a concern. |
All 10 findings from prior reviews have been addressed. No regressions introduced.
🔍 Additional observations
Structure — clean. Follows existing handler patterns (GetUser → setup → model resolution → response). Error codes match common.* conventions.
Security — solid.
- Body size capped before any parsing.
- Extension whitelist enforced (9 formats).
- Temp file cleanup via
defer os.Remove. - Multipart form cleanup in deferred
RemoveAll(). - No user content logged in warnings.
Robustness — good.
disableWriteDeadlineForSSEcalled on streaming path (consistent withchat_session.go,search.go).- SSE
[DONE]fallback ensures clients always see a completion signal. headerWrittenguard prevents writing headers when all synthesis fails (returns proper error instead).
Only suggestion — no tests. Neither TestChatAudioSpeech nor TestChatAudioTranscription exists. Given the two distinct response modes (binary stream + SSE + JSON), adding integration tests would protect against regressions in model driver changes. Out of scope for this comment, but worth a follow-up.
Verdict
Solid work from @euvre. The code is production-ready, follows existing conventions, and all previous review findings were properly addressed before merge. 🚀
Summary
This PR ports the Python
/chat/audio/*endpoints to the Go API server, adding chat-level TTS and ASR (transcription) support.POST /api/v1/chat/audio/speech: Converts text to speech using the tenant's default TTS model and returns a streamingaudio/mpegresponse.POST /api/v1/chat/audio/transcription: Transcribes an uploaded audio file using the tenant's default ASR model. Supports both a single JSON response and SSE streaming viastream=true.The implementation reuses
ModelProviderService.GetTenantDefaultModelByTypeto resolve the tenant's default models and delegates synthesis/transcription to the existing model drivers.