Skip to content

Go: implement ASR and TTS for xiaomi - #15765

Merged
JinHai-CN merged 1 commit into
infiniflow:mainfrom
Haruko386:master
Jun 8, 2026
Merged

JinHai-CN merged 1 commit into
infiniflow:mainfrom
Haruko386:master

Conversation

@Haruko386

Copy link
Copy Markdown
Member

What problem does this PR solve?

Verified from CLI

RAGFlow(user)> chat with 'mimo-v2.5@test@xiaomi' message 'who r u'
Answer: Hello! I'm MiMo-v2.5, a large language model developed by Xiaomi's LLM Core Team. You can think of me as a friendly AI assistant ready to help you answer questions, have conversations, or work on creative tasks. My context window can handle up to 1 million tokens, so we can dive into pretty long discussions or documents if you'd like. What can I help you with today?
Time: 3.831830

RAGFlow(user)> stream chat with 'mimo-v2.5@test@xiaomi' message 'who r u'
Answer:  there! I'm MiMo-v2.5, an AI assistant created by the Xiaomi LLM Core Team. I'm here to chat, help out, answer questions, or just have a friendly conversation. Think of me as a helpful buddy with a pretty big memory (1 million tokens worth!). What can I do for you today?😊
Time: 2.421630

RAGFlow(user)> think chat with 'mimo-v2.5@test@xiaomi' message 'who r u'
Thinking: The user is asking a simple question about who I am. According to my system prompt, I should:
- Identify myself as **MiMo-v2.5**
- State that I was developed by the **Xiaomi LLM Core Team**
- Answer in first person and be warm and conversational
Answer: Hey there! 👋

I'm **MiMo**, an AI assistant created by the **Xiaomi LLM Core Team**. Think of me as a friendly chat buddy who's here to help you with all sorts of questions and tasks!

I love having conversations, answering questions, brainstorming ideas, and helping people figure things out. Whether you want to chat, need help with something specific, or just want to explore ideas together — I'm here for it! 😊

What can I help you with today?
Time: 6.651589

RAGFlow(user)> tts with 'mimo-v2.5-tts@test@xiaomi' text 'hello? show yourself' play format 'wav' param '{"voice": "Chloe"}'
SUCCESS

RAGFlow(user)> asr with 'mimo-v2.5-asr@test@xiaomi' audio './internal/test.wav' param '{"language": "zh"}'
+------------------------------------------------------------------------------------------------------------------------+
| text                                                                                                                   |
+------------------------------------------------------------------------------------------------------------------------+
| 1 The examination and testimony of the experts enabled the commission to conclude that five shots may have been fired. |
+------------------------------------------------------------------------------------------------------------------------+

Type of change

  • New Feature (non-breaking change which adds functionality)
  • Refactoring

@dosubot dosubot Bot added size:XL This PR changes 500-999 lines, ignoring generated files. ☯️ refactor Pull request that refactor/refine code 💞 feature Feature request, pull request that fullfill a new feature. labels Jun 8, 2026
@Haruko386 Haruko386 added the ci Continue Integration label Jun 8, 2026
@Haruko386
Haruko386 marked this pull request as draft June 8, 2026 07:57
@Haruko386
Haruko386 marked this pull request as ready for review June 8, 2026 07:57
@coderabbitai

coderabbitai Bot commented Jun 8, 2026 •

Copy link
Copy Markdown
Contributor

Review Change Stack

📝 Walkthrough

Walkthrough

This PR implements a complete Xiaomi model driver supporting chat, speech-to-text (ASR), and text-to-speech (TTS) across both non-stream and SSE streaming modes. Configuration endpoints are updated with /v1 path normalization, and the model catalog is restructured to distinguish modality-specific entries. The driver uses map-based request/response payloads for flexibility and implements thinking support in chat.

Changes

Xiaomi Model Driver: Chat, ASR, and TTS Implementation

Layer / File(s) Summary
Configuration and Model Catalog
conf/models/xiaomi.json
Base URL updated to https://api.xiaomimimo.com/v1; chat endpoint suffix adjusted to chat/completions. Model catalog restructured with separate modality-specific entries including mimo-v2.5-asr, mimo-v2.5-tts, and mimo-v2-tts.
Driver Initialization and Transport
internal/entity/models/xiaomi.go
Constructor rewritten to consistently configure HTTP transport with idle connection limits, timeouts, and compression. Name() and NewInstance() helpers added for model identification and re-instantiation.
Chat with Thinking Support
internal/entity/models/xiaomi.go
Non-stream ChatWithMessages validates config and messages, constructs map-based request body, extracts choices[0].message.content and optional reasoning_content. Streaming ChatStreamlyWithSender handles SSE events with delta.reasoning_content and delta.content until [DONE] marker.
Speech-to-Text (ASR)
internal/entity/models/xiaomi.go
Non-stream and streaming TranscribeAudio methods build requests with base64-encoded audio data URL and asr_options. Response decoding and ASR stream parsing extract and forward transcribed content chunks. MIME type detection and audio decoding helpers included.
Text-to-Speech (TTS)
internal/entity/models/xiaomi.go
Non-stream and streaming AudioSpeech methods construct requests with assistant message payloads and audio configuration options. Responses decode base64-encoded audio data; streaming mode consumes SSE events and forwards audio chunks to sender until completion.
Interface Stubs and Connection Validation
internal/entity/models/xiaomi.go
Unimplemented methods (OCR, Parse, ListModels, Balance, ListTasks, ShowTask) return "no such method" errors. CheckConnection validates API config and tests base URL resolution.

Estimated code review effort

🎯 4 (Complex) | ⏱️ ~50 minutes

Possibly related PRs

  • infiniflow/ragflow#15626: Further evolves the Xiaomi integration with additional chat provider enhancements and endpoint configuration updates building on this driver foundation.

Suggested labels

ci, size:L

Poem

🐰 A Xiaomi driver now takes flight,
with chat and voice both streaming right,
ASR hears, TTS sings loud,
thinking thoughts in SSE cloud,
Configuration paths made neat and bright! 🎵

🚥 Pre-merge checks | ✅ 5
✅ Passed checks (5 passed)
Check name Status Explanation
Title check ✅ Passed The title clearly and concisely summarizes the main change: implementing ASR and TTS functionality for Xiaomi models in Go.
Description check ✅ Passed The description adequately addresses the template with verified CLI examples demonstrating the new feature and identifies change types as New Feature and Refactoring.
Docstring Coverage ✅ Passed No functions found in the changed files to evaluate docstring coverage. Skipping docstring coverage check.
Linked Issues check ✅ Passed Check skipped because no linked issues were found for this pull request.
Out of Scope Changes check ✅ Passed Check skipped because no linked issues were found for this pull request.

✏️ Tip: You can configure your own custom pre-merge checks in the settings.


Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ Share

Comment @coderabbitai help to get the list of available commands and usage tips.

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Actionable comments posted: 3

🤖 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/entity/models/xiaomi.go`:
- Around line 311-313: The loop that reads SSE lines currently calls
common.Info(line) and will log potentially sensitive SSE content; modify the
code around scanner.Scan() to stop unguarded logging by either removing the
common.Info(line) call or wrapping it behind a runtime-configurable debug flag
(e.g., an application DEBUG/LOG_LEVEL check or a function like isDebugEnabled())
so that common.Info(line) only executes when debugging is explicitly enabled;
locate and update the scanner.Scan() loop and the common.Info usage to implement
the guard.
- Around line 710-718: The TTS stream handler readXiaomiTTSStream currently
returns without emitting the same "[DONE]" end-of-stream marker that ASR streams
send; update readXiaomiTTSStream (and the fallback branch that returns
sender(&chunk, nil)) to call sender with a "[DONE]" marker (e.g., create a done
string and call sender(&done, nil)) after all audio chunks are delivered so
callers receive a consistent end signal; ensure the sender invocation for the
final chunk remains unchanged and the done emission happens once after the
stream/body processing completes.
- Around line 99-101: The ChatWithMessages non-streaming path currently respects
chatModelConfig.Stream and can set reqBody["stream"] to true which will break
JSON parsing; change ChatWithMessages to always set reqBody["stream"] = false
(or omit any use of chatModelConfig.Stream) so the request is never sent as
SSE—locate the block that checks chatModelConfig.Stream and replace it with a
hardcoded false assignment or remove the conditional, mirroring how
ChatStreamlyWithSender hardcodes stream: true.
🪄 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: 021f23db-58ee-47f6-98e1-069e3bf32c3f

📥 Commits

Reviewing files that changed from the base of the PR and between e81bca7 and d864925.

📒 Files selected for processing (2)
  • conf/models/xiaomi.json
  • internal/entity/models/xiaomi.go

Comment on lines +99 to +101
if chatModelConfig.Stream != nil {
reqBody["stream"] = *chatModelConfig.Stream
}

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

⚠️ Potential issue | 🟠 Major | ⚡ Quick win

Non-streaming method allows stream override that would break response parsing.

ChatWithMessages is a non-streaming method that parses the response as a single JSON object (lines 163-212). If chatModelConfig.Stream is true, the API returns SSE chunks, causing JSON unmarshal failures.

Consider forcing stream: false regardless of config, consistent with ChatStreamlyWithSender which hardcodes stream: true without allowing override.

Proposed fix
 	if chatModelConfig != nil {
-		if chatModelConfig.Stream != nil {
-			reqBody["stream"] = *chatModelConfig.Stream
-		}
+		// Note: Stream is intentionally not overridden here.
+		// This is a non-streaming method; use ChatStreamlyWithSender for streaming.

 		if chatModelConfig.MaxTokens != 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/xiaomi.go` around lines 99 - 101, The ChatWithMessages
non-streaming path currently respects chatModelConfig.Stream and can set
reqBody["stream"] to true which will break JSON parsing; change ChatWithMessages
to always set reqBody["stream"] = false (or omit any use of
chatModelConfig.Stream) so the request is never sent as SSE—locate the block
that checks chatModelConfig.Stream and replace it with a hardcoded false
assignment or remove the conditional, mirroring how ChatStreamlyWithSender
hardcodes stream: true.

Comment on lines +311 to +313
for scanner.Scan() {
line := scanner.Text()
common.Info(line)

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

⚠️ Potential issue | 🟡 Minor | ⚡ Quick win

Logging every SSE line may expose sensitive content in production.

common.Info(line) logs all SSE data including user messages and model reasoning. Consider removing this debug logging or guarding it with a debug flag.

🤖 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/xiaomi.go` around lines 311 - 313, The loop that reads
SSE lines currently calls common.Info(line) and will log potentially sensitive
SSE content; modify the code around scanner.Scan() to stop unguarded logging by
either removing the common.Info(line) call or wrapping it behind a
runtime-configurable debug flag (e.g., an application DEBUG/LOG_LEVEL check or a
function like isDebugEnabled()) so that common.Info(line) only executes when
debugging is explicitly enabled; locate and update the scanner.Scan() loop and
the common.Info usage to implement the guard.

Comment on lines +710 to 718
if len(audio.Audio) > 0 {
chunk := base64.StdEncoding.EncodeToString(audio.Audio)
return sender(&chunk, nil)
}
return nil
}

return readXiaomiTTSStream(resp.Body, sender)
}

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

⚠️ Potential issue | 🟡 Minor | ⚡ Quick win

Inconsistent [DONE] marker handling between ASR and TTS streams.

ASR streaming (both SSE and fallback) sends a [DONE] marker to signal completion, but TTS streaming does not. This inconsistency could confuse callers expecting uniform end-of-stream signaling.

Consider adding [DONE] emission to TTS for consistency, or document the difference if intentional.

Proposed fix for non-stream fallback
 		if len(audio.Audio) > 0 {
 			chunk := base64.StdEncoding.EncodeToString(audio.Audio)
-			return sender(&chunk, nil)
+			if err := sender(&chunk, nil); err != nil {
+				return err
+			}
 		}
-		return nil
+		done := "[DONE]"
+		return sender(&done, nil)
 	}
📝 Committable suggestion

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

Suggested change
if len(audio.Audio) > 0 {
chunk := base64.StdEncoding.EncodeToString(audio.Audio)
return sender(&chunk, nil)
}
return nil
}
return readXiaomiTTSStream(resp.Body, sender)
}
if len(audio.Audio) > 0 {
chunk := base64.StdEncoding.EncodeToString(audio.Audio)
if err := sender(&chunk, nil); err != nil {
return err
}
}
done := "[DONE]"
return sender(&done, nil)
}
return readXiaomiTTSStream(resp.Body, sender)
}
🤖 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/xiaomi.go` around lines 710 - 718, The TTS stream
handler readXiaomiTTSStream currently returns without emitting the same "[DONE]"
end-of-stream marker that ASR streams send; update readXiaomiTTSStream (and the
fallback branch that returns sender(&chunk, nil)) to call sender with a "[DONE]"
marker (e.g., create a done string and call sender(&done, nil)) after all audio
chunks are delivered so callers receive a consistent end signal; ensure the
sender invocation for the final chunk remains unchanged and the done emission
happens once after the stream/body processing completes.

@codecov

codecov Bot commented Jun 8, 2026

Copy link
Copy Markdown

Codecov Report

✅ All modified and coverable lines are covered by tests.
✅ Project coverage is 93.16%. Comparing base (220ee9d) to head (d864925).
⚠️ Report is 7 commits behind head on main.

Additional details and impacted files
@@           Coverage Diff           @@
##             main   #15765   +/-   ##
=======================================
  Coverage   93.16%   93.16%           
=======================================
  Files          10       10           
  Lines         717      717           
  Branches      118      118           
=======================================
  Hits          668      668           
  Misses         29       29           
  Partials       20       20           

☔ View full report in Codecov by Harness.
📢 Have feedback on the report? Share it here.

🚀 New features to boost your workflow:
  • ❄️ Test Analytics: Detect flaky tests, report on failures, and find test suite problems.
  • 📦 JS Bundle Analysis: Save yourself from yourself by tracking and limiting bundle sizes in JS merges.

@JinHai-CN
JinHai-CN merged commit 8dc7f1d into infiniflow:main Jun 8, 2026
1 check passed
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

ci Continue Integration 💞 feature Feature request, pull request that fullfill a new feature. ☯️ refactor Pull request that refactor/refine code size:XL This PR changes 500-999 lines, ignoring generated files.

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants