Skip to content

Go: implement embed for Tencent Hunyuan - #15207

Merged
JinHai-CN merged 2 commits into
infiniflow:mainfrom
Haruko386:main
May 25, 2026
Merged

JinHai-CN merged 2 commits into
infiniflow:mainfrom
Haruko386:main

Conversation

@Haruko386

Copy link
Copy Markdown
Member

What problem does this PR solve?

Implement embed for Tencent Hunyuan

Verified from CLI

RAGFlow(user)> embed text 'what is rag' 'who are you' with 'hunyuan-embedding@test1@hunyuan' dimension 16;
+-----------+-------+
| dimension | index |
+-----------+-------+
| 1024      | 0     |
| 1024      | 1     |
+-----------+-------+

Type of change

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

@dosubot dosubot Bot added size:M This PR changes 30-99 lines, ignoring generated files. ☯️ refactor Pull request that refactor/refine code 💞 feature Feature request, pull request that fullfill a new feature. labels May 25, 2026
@Haruko386 Haruko386 added ci Continue Integration 💞 feature Feature request, pull request that fullfill a new feature. ☯️ refactor Pull request that refactor/refine code and removed 💞 feature Feature request, pull request that fullfill a new feature. ☯️ refactor Pull request that refactor/refine code size:M This PR changes 30-99 lines, ignoring generated files. labels May 25, 2026
@Haruko386
Haruko386 marked this pull request as draft May 25, 2026 07:00
@Haruko386 Haruko386 added the size:M This PR changes 30-99 lines, ignoring generated files. label May 25, 2026
@Haruko386
Haruko386 marked this pull request as ready for review May 25, 2026 07:00
@coderabbitai

coderabbitai Bot commented May 25, 2026 •

Copy link
Copy Markdown
Contributor

Review Change Stack

📝 Walkthrough

Walkthrough

This PR implements Tencent Hunyuan embedding support by adding embedding model configuration with URL suffix keys and implementing the Embed method with full HTTP request/response handling. Four model configuration files update their display names for naming consistency across MinerU and PaddleOCR variants.

Changes

Hunyuan Embedding Implementation

Layer / File(s) Summary
Hunyuan embedding configuration and contracts
conf/models/hunyuan.json, internal/entity/models/hunyuan.go
Hunyuan configuration adds models and embedding URL suffix keys and a new hunyuan-embedding model entry with max tokens 16384 and embedding model type. Package documentation describes the TokenHub migration.
Hunyuan Embed method implementation
internal/entity/models/hunyuan.go
The Embed method derives region from apiConfig, builds the embedding URL, constructs a JSON request body with model name and input texts, sends a POST request with bearer authentication, and parses the response into EmbeddingData entries. Returns error on non-200 status or missing data.

Model Configuration Name Updates

Layer / File(s) Summary
Model display name normalization
conf/models/mineru.json, conf/models/mineru_local.json, conf/models/paddleocr.json, conf/models/paddleocr_local.json
MinerU config name updated to MinerU.Net; MinerU_local to MinerU. PaddleOCR config name updated to PaddleOCR.Net; PaddleOCR_Local to PaddleOCR.

Possibly Related PRs

  • infiniflow/ragflow#15092: Introduces the Tencent Hunyuan driver factory and base configuration that this PR extends with embedding support.

Estimated Code Review Effort

🎯 2 (Simple) | ⏱️ ~12 minutes

Poem

🐰 Embedding dreams take flight at last,
Hunyuan flows from East so vast,
Models named with clarity bright,
Suffixes added, names made right—
TokenHub guides the journey's flight! 🌟

🚥 Pre-merge checks | ✅ 5
✅ Passed checks (5 passed)
Check name Status Explanation
Title check ✅ Passed The title clearly and directly describes the main implementation work: adding embed functionality for Tencent Hunyuan in Go.
Description check ✅ Passed The description includes the required 'What problem does this PR solve?' section with implementation details and CLI verification, plus the 'Type of change' checklist with appropriate selections.
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

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

499-505: 💤 Low value

Pre-allocate slice to avoid repeated allocations.

The result slice can be pre-allocated since the length is known from parsedResponse.Data.

♻️ Suggested improvement
-	var embeddings []EmbeddingData
+	embeddings := make([]EmbeddingData, 0, len(parsedResponse.Data))
 	for _, dataElem := range parsedResponse.Data {
🤖 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/hunyuan.go` around lines 499 - 505, The loop builds
embeddings by repeatedly appending to embeddings causing allocations; instead
pre-allocate embeddings with make([]EmbeddingData, 0, len(parsedResponse.Data))
or directly make([]EmbeddingData, len(parsedResponse.Data)) and fill by index.
Modify the code around the slice declaration and population (the embeddings
variable and the for _, dataElem := range parsedResponse.Data loop) to use a
capacity-sized make or index assignment (e.g., embeddings[i] =
EmbeddingData{...}) to avoid repeated allocations.
🤖 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/hunyuan.go`:
- Around line 461-472: The POST request is created without a context timeout so
it can hang; update the request creation in this method to use a context with
timeout (matching the same timeout used by ChatWithMessages and ListModels) by
calling context.WithTimeout, pass the derived ctx into
http.NewRequestWithContext, and ensure you call defer cancel() right after
creating the context; adjust error handling to use the new ctx-based request and
keep the existing headers and httpClient.Do(req) call unchanged (refer to
ChatWithMessages and ListModels for the exact timeout value and pattern).
- Around line 449-467: Replace the direct indexed lookup and unchecked
dereferences by reusing baseURLForRegion() to obtain and validate the base URL
(instead of a.BaseURL[region]), check that modelName is non-nil and non-empty
before using it, and validate apiConfig and apiConfig.ApiKey (non-nil and
non-empty) before dereferencing; return descriptive errors on validation failure
(similar to ChatWithMessages), then build the URL with the validated base and
URLSuffix.Embedding and proceed to marshal and create the request only after
these checks succeed.

---

Nitpick comments:
In `@internal/entity/models/hunyuan.go`:
- Around line 499-505: The loop builds embeddings by repeatedly appending to
embeddings causing allocations; instead pre-allocate embeddings with
make([]EmbeddingData, 0, len(parsedResponse.Data)) or directly
make([]EmbeddingData, len(parsedResponse.Data)) and fill by index. Modify the
code around the slice declaration and population (the embeddings variable and
the for _, dataElem := range parsedResponse.Data loop) to use a capacity-sized
make or index assignment (e.g., embeddings[i] = EmbeddingData{...}) to avoid
repeated allocations.
🪄 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: bd6b11c0-dd67-4267-ae00-d316d1c8af0f

📥 Commits

Reviewing files that changed from the base of the PR and between 5069561 and b21c275.

📒 Files selected for processing (6)
  • conf/models/hunyuan.json
  • conf/models/mineru.json
  • conf/models/mineru_local.json
  • conf/models/paddleocr.json
  • conf/models/paddleocr_local.json
  • internal/entity/models/hunyuan.go

Comment on lines +449 to +467
url := fmt.Sprintf("%s/%s", a.BaseURL[region], a.URLSuffix.Embedding)

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

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))

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

Missing validation for region, modelName, and apiConfig leads to potential nil dereference or malformed URL.

Several issues in this block:

  1. Line 449: Direct access a.BaseURL[region] without checking if the key exists. If the region is missing, this produces a malformed URL like /embeddings. Other methods (e.g., ChatWithMessages at line 99) use baseURLForRegion() which properly validates and returns an error.

  2. Line 452: *modelName is dereferenced without a nil check. If callers pass nil, this will panic.

  3. Line 467: *apiConfig.ApiKey is dereferenced without validating that apiConfig and apiConfig.ApiKey are non-nil. Other methods (e.g., ChatWithMessages at lines 87-88) validate apiConfig == nil || apiConfig.ApiKey == nil || *apiConfig.ApiKey == "".

🐛 Proposed fix to add validation and use baseURLForRegion
 func (a *HunyuanModel) Embed(modelName *string, texts []string, apiConfig *APIConfig, embeddingConfig *EmbeddingConfig) ([]EmbeddingData, error) {
 	if len(texts) == 0 {
 		return []EmbeddingData{}, nil
 	}
+	if apiConfig == nil || apiConfig.ApiKey == nil || *apiConfig.ApiKey == "" {
+		return nil, fmt.Errorf("api key is required")
+	}
+	if modelName == nil || *modelName == "" {
+		return nil, fmt.Errorf("model name is required")
+	}
 
 	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)
+	baseURL, err := a.baseURLForRegion(region)
+	if err != nil {
+		return nil, err
+	}
+	url := fmt.Sprintf("%s/%s", baseURL, a.URLSuffix.Embedding)
🤖 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/hunyuan.go` around lines 449 - 467, Replace the direct
indexed lookup and unchecked dereferences by reusing baseURLForRegion() to
obtain and validate the base URL (instead of a.BaseURL[region]), check that
modelName is non-nil and non-empty before using it, and validate apiConfig and
apiConfig.ApiKey (non-nil and non-empty) before dereferencing; return
descriptive errors on validation failure (similar to ChatWithMessages), then
build the URL with the validated base and URLSuffix.Embedding and proceed to
marshal and create the request only after these checks succeed.

Comment on lines +461 to +472
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 := a.httpClient.Do(req)
if err != nil {
return nil, fmt.Errorf("failed to send request: %w", err)
}

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

Missing request timeout — request could hang indefinitely.

Unlike other non-streaming methods in this file (ChatWithMessages at line 139, ListModels at line 383), this method uses http.NewRequest without a context timeout. Since httpClient has no Timeout field set (only transport.ResponseHeaderTimeout), the request has no overall deadline after headers are received.

⏱️ Proposed fix to add context timeout
+	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))
 	if err != nil {
 		return nil, fmt.Errorf("failed to create request: %w", err)
 	}
📝 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
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 := a.httpClient.Do(req)
if err != nil {
return nil, fmt.Errorf("failed to send request: %w", err)
}
ctx, cancel := context.WithTimeout(context.Background(), nonStreamCallTimeout)
defer cancel()
req, err := http.NewRequestWithContext(ctx, "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 := a.httpClient.Do(req)
if err != nil {
return nil, fmt.Errorf("failed to send request: %w", err)
}
🤖 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/hunyuan.go` around lines 461 - 472, The POST request
is created without a context timeout so it can hang; update the request creation
in this method to use a context with timeout (matching the same timeout used by
ChatWithMessages and ListModels) by calling context.WithTimeout, pass the
derived ctx into http.NewRequestWithContext, and ensure you call defer cancel()
right after creating the context; adjust error handling to use the new ctx-based
request and keep the existing headers and httpClient.Do(req) call unchanged
(refer to ChatWithMessages and ListModels for the exact timeout value and
pattern).

@codecov

codecov Bot commented May 25, 2026

Copy link
Copy Markdown

Codecov Report

✅ All modified and coverable lines are covered by tests.
✅ Project coverage is 93.12%. Comparing base (5069561) to head (b21c275).

Additional details and impacted files
@@           Coverage Diff           @@
##             main   #15207   +/-   ##
=======================================
  Coverage   93.12%   93.12%           
=======================================
  Files          10       10           
  Lines         713      713           
  Branches      116      116           
=======================================
  Hits          664      664           
  Misses         29       29           
  Partials       20       20           

☔ 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 69f301b into infiniflow:main May 25, 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:M This PR changes 30-99 lines, ignoring generated files.

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants