Skip to content

Go: implement embed, rerank, tts for AstraFlow - #15135

Merged
JinHai-CN merged 1 commit into
infiniflow:mainfrom
Haruko386:main
May 22, 2026
Merged

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

Conversation

@Haruko386

Copy link
Copy Markdown
Member

What problem does this PR solve?

implement embed, rerank, tts for AstraFlow

Verify from CLI

# Astraflow
RAGFlow(user)> tts with 'IndexTeam/IndexTTS-2@test3@astraflow' text 'hello? show yourself' play format 'wav' param '{"voice": "jack_cheng"}'
SUCCESS

RAGFlow(user)> rerank query 'what is rag' document 'rag is retrieval augment generation' 'rag need llm' 'famous rag project includes ragflow' with 'bge-reranker-v2-m3@test3@astraflow' top 3;
+-------+---------------------+
| index | relevance_score     |
+-------+---------------------+
| 0     | 0.9837390184402466  |
| 2     | 0.06322699040174484 |
| 1     | 0.04663187265396118 |
+-------+---------------------+

RAGFlow(user)> embed text 'walkerwhat' 'jumperwho' with 'text-embedding-3-large@test3@astraflow' dimension 16
+-----------+-------+
| dimension | index |
+-----------+-------+
| 3072      | 0     |
| 3072      | 1     |
+-----------+-------+

# Xinference


Type of change

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

@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

The PR extends the Astraflow provider with embedding, reranking, and text-to-speech support. Configuration registers new API endpoints and adds three new model types to the model registry. Implementation replaces stub methods with POST-based flows that validate input, select regions, send requests, unmarshal responses, and return typed results.

Changes

Astraflow Multi-Modality Support

Layer / File(s) Summary
Configuration expansion for endpoints and models
conf/models/astraflow.json
Astraflow endpoint configuration extended with default API base URL and new route suffixes for embedding, rerank, and tts, alongside model registry updates including text-embedding-3-large, bge-reranker-v2-m3, and IndexTeam/IndexTTS-2.
Embed, Rerank, and AudioSpeech implementations
internal/entity/models/astraflow.go
Three previously-stubbed methods replaced with working implementations: Embed validates and sends embedding requests, unmarshals vectors with indices; Rerank validates documents, sends rerank requests with computed top_n, unmarshals scored results; AudioSpeech validates credentials, sends TTS requests with configurable format, reads and returns audio bytes.

Estimated code review effort

🎯 2 (Simple) | ⏱️ ~12 minutes

Possibly related PRs

  • infiniflow/ragflow#15064: Directly related earlier work extending Astraflow Go driver by implementing embed/rerank/TTS stubs and corresponding model registration.
  • infiniflow/ragflow#15107: Parallel work adding Rerank and AudioSpeech implementations in another provider-specific Go model integration with similar response unmarshaling patterns.

Suggested labels

ci

Poem

🐰 Three new talents join the flow,
Embed, rerank, TTS in tow,
Config blooms with routes so bright,
Methods rise from stubby night,
Astraflow's reach grows far and wide!

🚥 Pre-merge checks | ✅ 5
✅ Passed checks (5 passed)
Check name Status Explanation
Title check ✅ Passed The title accurately describes the main change: implementing embed, rerank, and tts functionality for AstraFlow in Go.
Description check ✅ Passed The description includes the required 'What problem does this PR solve?' section and properly selected 'New Feature' and 'Refactoring' change types, with verification examples from CLI testing.
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: 2

🤖 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/astraflow.go`:
- Around line 459-467: The Embed, Rerank, and AudioSpeech flows are
dereferencing nullable pointers and directly indexing a.BaseURL by region which
can panic or yield bad URLs; update Embed, Rerank, AudioSpeech (and affected
blocks around where modelName, apiConfig.ApiKey, rerankConfig are used) to first
validate non-nil pointers (modelName, apiConfig, apiConfig.ApiKey, rerankConfig)
and return clear errors if missing, then compute the region and call
baseURLForRegion(region) (instead of a.BaseURL[region]) to get a safe base URL
before constructing fmt.Sprintf("%s/%s", ...); also replace direct dereferences
of *modelName and *apiConfig.ApiKey with local validated variables so URL and
reqBody construction cannot panic.
- Around line 476-477: The HTTP POST requests created with http.NewRequest
(variables req, url, jsonData) lack per-request deadlines; wrap the parent
context with context.WithTimeout (choose a sensible timeout or a configurable
value), defer cancel(), attach it to the request via req =
req.WithContext(ctxWithTimeout) before calling c.httpClient.Do, and handle the
context timeout error path; apply the same change to the other http.NewRequest
sites mentioned (the occurrences around lines noted: the other request creations
using req, url, and jsonData in the same file).
🪄 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: 8fd77c49-0ce2-4ae7-bb8a-9548d2a35381

📥 Commits

Reviewing files that changed from the base of the PR and between 57ddd79 and 2ca0d1b.

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

Comment on lines +459 to +467
var region = "default"
if apiConfig != nil && apiConfig.Region != nil && *apiConfig.Region != "" {
region = *apiConfig.Region
}

url := fmt.Sprintf("%s/%s", a.BaseURL[region], a.URLSuffix.Embedding)

reqBody := map[string]interface{}{
"model": *modelName,

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 | 🔴 Critical | ⚡ Quick win

Validate required pointers and use baseURLForRegion before request construction.

Embed, Rerank, and AudioSpeech dereference nullable inputs (modelName, apiConfig.ApiKey, rerankConfig) and build URLs from a.BaseURL[region] directly. This can panic on nil input and can produce malformed URLs for unknown regions.

Suggested hardening pattern
 func (a *AstraflowModel) Embed(modelName *string, texts []string, apiConfig *APIConfig, embeddingConfig *EmbeddingConfig) ([]EmbeddingData, error) {
+   if modelName == nil || *modelName == "" {
+     return nil, fmt.Errorf("model name is required")
+   }
+   if apiConfig == nil || apiConfig.ApiKey == nil || *apiConfig.ApiKey == "" {
+     return nil, fmt.Errorf("api key is required")
+   }
    if len(texts) == 0 {
      return []EmbeddingData{}, nil
    }
    region := "default"
    if apiConfig.Region != nil && *apiConfig.Region != "" {
      region = *apiConfig.Region
    }
-   url := fmt.Sprintf("%s/%s", a.BaseURL[region], a.URLSuffix.Embedding)
+   baseURL, err := a.baseURLForRegion(region)
+   if err != nil {
+     return nil, err
+   }
+   url := fmt.Sprintf("%s/%s", baseURL, a.URLSuffix.Embedding)
 func (a *AstraflowModel) Rerank(..., rerankConfig *RerankConfig) (*RerankResponse, error) {
+   if modelName == nil || *modelName == "" {
+     return nil, fmt.Errorf("model name is required")
+   }
+   if apiConfig == nil || apiConfig.ApiKey == nil || *apiConfig.ApiKey == "" {
+     return nil, fmt.Errorf("api key is required")
+   }
+   topN := len(documents)
+   if rerankConfig != nil && rerankConfig.TopN > 0 {
+     topN = rerankConfig.TopN
+   }

Also applies to: 482-483, 530-547, 559-560, 621-631

🤖 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/astraflow.go` around lines 459 - 467, The Embed,
Rerank, and AudioSpeech flows are dereferencing nullable pointers and directly
indexing a.BaseURL by region which can panic or yield bad URLs; update Embed,
Rerank, AudioSpeech (and affected blocks around where modelName,
apiConfig.ApiKey, rerankConfig are used) to first validate non-nil pointers
(modelName, apiConfig, apiConfig.ApiKey, rerankConfig) and return clear errors
if missing, then compute the region and call baseURLForRegion(region) (instead
of a.BaseURL[region]) to get a safe base URL before constructing
fmt.Sprintf("%s/%s", ...); also replace direct dereferences of *modelName and
*apiConfig.ApiKey with local validated variables so URL and reqBody construction
cannot panic.

Comment on lines +476 to +477
req, err := http.NewRequest("POST", url, bytes.NewBuffer(jsonData))
if err != nil {

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

Add deadline contexts to non-stream HTTP calls.

These methods use http.NewRequest(...) without a timeout context. Since this driver’s http.Client has no client-level Timeout, stalled non-stream calls can block indefinitely.

Suggested fix
+ctx, cancel := context.WithTimeout(context.Background(), nonStreamCallTimeout)
+defer cancel()
-req, err := http.NewRequest("POST", url, bytes.NewBuffer(jsonData))
+req, err := http.NewRequestWithContext(ctx, "POST", url, bytes.NewBuffer(jsonData))

Based on learnings: if httpClient.Timeout is intentionally unset, per-request context.WithTimeout is the legitimate overall deadline.

Also applies to: 554-555, 647-648

🤖 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/astraflow.go` around lines 476 - 477, The HTTP POST
requests created with http.NewRequest (variables req, url, jsonData) lack
per-request deadlines; wrap the parent context with context.WithTimeout (choose
a sensible timeout or a configurable value), defer cancel(), attach it to the
request via req = req.WithContext(ctxWithTimeout) before calling
c.httpClient.Do, and handle the context timeout error path; apply the same
change to the other http.NewRequest sites mentioned (the occurrences around
lines noted: the other request creations using req, url, and jsonData in the
same file).

@Haruko386 Haruko386 added the ci Continue Integration label May 22, 2026
@Haruko386
Haruko386 marked this pull request as draft May 22, 2026 01:51
@Haruko386
Haruko386 marked this pull request as ready for review May 22, 2026 01:51
@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 (2ca0d1b).

Additional details and impacted files
@@            Coverage Diff             @@
##             main   #15135      +/-   ##
==========================================
- 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.

@JinHai-CN
JinHai-CN merged commit 3f02ca7 into infiniflow:main May 22, 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 size:L This PR changes 100-499 lines, ignoring generated files.

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants