Repository navigation
Go: implement embed for Tencent Hunyuan - #15207
Conversation
📝 WalkthroughWalkthroughThis 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. ChangesHunyuan Embedding Implementation
Model Configuration Name Updates
Possibly Related PRs
Estimated Code Review Effort🎯 2 (Simple) | ⏱️ ~12 minutes Poem
🚥 Pre-merge checks | ✅ 5✅ Passed checks (5 passed)
✏️ 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. Comment |
There was a problem hiding this comment.
Actionable comments posted: 2
🧹 Nitpick comments (1)
internal/entity/models/hunyuan.go (1)
499-505: 💤 Low valuePre-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
📒 Files selected for processing (6)
conf/models/hunyuan.jsonconf/models/mineru.jsonconf/models/mineru_local.jsonconf/models/paddleocr.jsonconf/models/paddleocr_local.jsoninternal/entity/models/hunyuan.go
| 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)) |
There was a problem hiding this comment.
Missing validation for region, modelName, and apiConfig leads to potential nil dereference or malformed URL.
Several issues in this block:
-
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.,ChatWithMessagesat line 99) usebaseURLForRegion()which properly validates and returns an error. -
Line 452:
*modelNameis dereferenced without a nil check. If callers passnil, this will panic. -
Line 467:
*apiConfig.ApiKeyis dereferenced without validating thatapiConfigandapiConfig.ApiKeyare non-nil. Other methods (e.g.,ChatWithMessagesat lines 87-88) validateapiConfig == 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.
| 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) | ||
| } |
There was a problem hiding this comment.
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.
| 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 Report✅ All modified and coverable lines are covered by tests. 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. 🚀 New features to boost your workflow:
|
What problem does this PR solve?
Implement embed for Tencent Hunyuan
Verified from CLI
Type of change