Repository navigation
Go: implement provider: HuggingFace - #14722
Conversation
📝 WalkthroughWalkthroughA new HuggingFace model provider driver is added to the ragflow platform, with configuration, chat operations (streaming and non-streaming), embeddings, model discovery, and factory routing. An unrelated fix corrects the Aliyun provider's identifier. ChangesHuggingFace Model Provider
Estimated code review effort🎯 3 (Moderate) | ⏱️ ~25 minutes Possibly related PRs
Suggested labels
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: 5
🧹 Nitpick comments (1)
internal/entity/models/huggingface.go (1)
38-52: ⚡ Quick winEliminate code duplication in
NewInstance.The
NewInstancemethod duplicates the HTTP client construction logic fromNewHuggingFaceModel. This creates a maintenance burden—any change to the client configuration must be applied in two places.♻️ Proposed refactor
func (h *HuggingFaceModel) NewInstance(baseURL map[string]string) ModelDriver { - return &HuggingFaceModel{ - BaseURL: baseURL, - URLSuffix: h.URLSuffix, - httpClient: &http.Client{ - Timeout: 120 * time.Second, - Transport: &http.Transport{ - MaxIdleConns: 10, - MaxIdleConnsPerHost: 100, - IdleConnTimeout: 90 * time.Second, - DisableCompression: false, - }, - }, - } + newModel := NewHuggingFaceModel(baseURL, h.URLSuffix) + return newModel }🤖 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/huggingface.go` around lines 38 - 52, The NewInstance method duplicates the http.Client construction found in NewHuggingFaceModel; to eliminate duplication, refactor so NewInstance reuses the existing client-construction path — e.g., have NewInstance call NewHuggingFaceModel (or a new private helper like buildHuggingFaceClient) and then set/override BaseURL and URLSuffix as needed; update HuggingFaceModel.NewInstance to return a model created via that shared constructor instead of rebuilding the http.Client inline.
🤖 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 `@conf/models/huggingface.json`:
- Around line 1-21: The Encode method in huggingface.go currently builds a
hardcoded URL ("https://router.huggingface.co/hf-inference/models/%s") and the
streaming method hardcodes "chat/completions"; update both to use the configured
base and suffix values instead: construct the endpoint for embeddings in Encode
by combining BaseURL with URLSuffix.Embedding (e.g., BaseURL +
URLSuffix.Embedding + "/%s" or equivalent) and construct the chat streaming
endpoint by using BaseURL + URLSuffix.Chat; ensure you reference the existing
variables/struct fields (BaseURL, URLSuffix.Embedding, URLSuffix.Chat) used
elsewhere in the file so all requests honor the values from
conf/models/huggingface.json.
In `@internal/entity/models/huggingface.go`:
- Around line 27-35: The HTTP transport in the HuggingFace client has inverted
pool limits; in the struct where the http.Client is created (the httpClient
field initialization in huggingface.go), swap the values so MaxIdleConns is the
larger total pool and MaxIdleConnsPerHost is the smaller per-host limit (e.g.,
set MaxIdleConns to 100 and MaxIdleConnsPerHost to 10) to match the pattern used
in AliyunModel and ensure consistent connection pooling.
- Line 207: The URL for the chat completions endpoint is hardcoded in the
variable `url` within huggingface.go (currently set to "chat/completions");
replace that hardcoded path with the configured suffix `h.URLSuffix.Chat` so the
function uses the same configuration as `ChatWithMessages` and respects
`conf/models/huggingface.json` customization; update the construction that uses
`h.BaseURL[region]` to append `h.URLSuffix.Chat` instead of the literal string
so the endpoint path is configurable.
- Around line 360-413: The Encode method in HuggingFaceModel currently
constructs a hardcoded endpoint
("https://router.huggingface.co/hf-inference/models/%s"); update it to use the
configured values from APIConfig (or the model's config) by composing the
request URL from apiConfig.BaseURL plus the URLSuffix.Embedding template (or
equivalent fields in the config) and the modelName (e.g.,
fmt.Sprintf(apiConfig.BaseURL+apiConfig.URLSuffix.Embedding, *modelName)),
preserving existing behavior when those fields are empty by falling back to the
current hardcoded path; modify the code in HuggingFaceModel.Encode where url is
built and ensure tests/usage still set Authorization and Content-Type headers as
before.
- Around line 464-469: The loop over result["data"] uses unchecked type
assertions that can panic; update the code in
internal/entity/models/huggingface.go to validate types using the comma-ok idiom
before casting: first check result["data"] exists and is a []interface{} (if
not, return or log and exit), then for each item assert it is a
map[string]interface{} before accessing "id", and finally assert the "id" value
is a string before appending to models; on any failed assertion handle
gracefully (log the malformed entry and skip it or return a descriptive error)
so the function (where models and result are used) no longer panics on malformed
API responses.
---
Nitpick comments:
In `@internal/entity/models/huggingface.go`:
- Around line 38-52: The NewInstance method duplicates the http.Client
construction found in NewHuggingFaceModel; to eliminate duplication, refactor so
NewInstance reuses the existing client-construction path — e.g., have
NewInstance call NewHuggingFaceModel (or a new private helper like
buildHuggingFaceClient) and then set/override BaseURL and URLSuffix as needed;
update HuggingFaceModel.NewInstance to return a model created via that shared
constructor instead of rebuilding the http.Client inline.
🪄 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: c2c9edf3-755a-4321-aaa9-968c48dd1f15
📒 Files selected for processing (4)
conf/models/huggingface.jsoninternal/entity/models/aliyun.gointernal/entity/models/factory.gointernal/entity/models/huggingface.go
| { | ||
| "name": "HuggingFace", | ||
| "url": { | ||
| "default": "https://router.huggingface.co/v1/" | ||
| }, | ||
| "url-suffix": { | ||
| "chat": "chat/completions", | ||
| "models": "models", | ||
| "embedding": "hf-inference/models" | ||
| }, | ||
| "class": "huggingface", | ||
| "models": [ | ||
| { | ||
| "name": "openai/gpt-oss-120b:fastest", | ||
| "max_tokens": 32768, | ||
| "model_types": [ | ||
| "chat" | ||
| ] | ||
| } | ||
| ] | ||
| } No newline at end of file |
There was a problem hiding this comment.
Configuration structure looks good, but verify implementation usage.
The JSON structure and provider configuration are well-formed. However, the implementation in internal/entity/models/huggingface.go does not consistently use the configured url-suffix values:
- Line 382 in huggingface.go: The
Encodemethod hardcodes the entire URL (https://router.huggingface.co/hf-inference/models/%s) instead of usingBaseURL+URLSuffix.Embedding - Line 207 in huggingface.go: The streaming method hardcodes
"chat/completions"instead of usingURLSuffix.Chat
See detailed comments in huggingface.go for the specific issues.
🤖 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 `@conf/models/huggingface.json` around lines 1 - 21, The Encode method in
huggingface.go currently builds a hardcoded URL
("https://router.huggingface.co/hf-inference/models/%s") and the streaming
method hardcodes "chat/completions"; update both to use the configured base and
suffix values instead: construct the endpoint for embeddings in Encode by
combining BaseURL with URLSuffix.Embedding (e.g., BaseURL + URLSuffix.Embedding
+ "/%s" or equivalent) and construct the chat streaming endpoint by using
BaseURL + URLSuffix.Chat; ensure you reference the existing variables/struct
fields (BaseURL, URLSuffix.Embedding, URLSuffix.Chat) used elsewhere in the file
so all requests honor the values from conf/models/huggingface.json.
| httpClient: &http.Client{ | ||
| Timeout: 120 * time.Second, | ||
| Transport: &http.Transport{ | ||
| MaxIdleConns: 10, | ||
| MaxIdleConnsPerHost: 100, | ||
| IdleConnTimeout: 90 * time.Second, | ||
| DisableCompression: false, | ||
| }, | ||
| }, |
There was a problem hiding this comment.
🛠️ Refactor suggestion | 🟠 Major | ⚡ Quick win
Swap MaxIdleConns and MaxIdleConnsPerHost values.
The HTTP transport configuration has inverted connection pool limits:
MaxIdleConns: 10(total pool limit)MaxIdleConnsPerHost: 100(per-host limit)
This allows 100 idle connections per host but only 10 total, which is contradictory. Typically, MaxIdleConns (total pool) should be >= MaxIdleConnsPerHost (per-host). Other providers like AliyunModel (lines 47-48 in aliyun.go) use MaxIdleConns: 100 and MaxIdleConnsPerHost: 10.
🔧 Proposed fix
httpClient: &http.Client{
Timeout: 120 * time.Second,
Transport: &http.Transport{
- MaxIdleConns: 10,
- MaxIdleConnsPerHost: 100,
+ MaxIdleConns: 100,
+ MaxIdleConnsPerHost: 10,
IdleConnTimeout: 90 * time.Second,
DisableCompression: false,
},
},📝 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.
| httpClient: &http.Client{ | |
| Timeout: 120 * time.Second, | |
| Transport: &http.Transport{ | |
| MaxIdleConns: 10, | |
| MaxIdleConnsPerHost: 100, | |
| IdleConnTimeout: 90 * time.Second, | |
| DisableCompression: false, | |
| }, | |
| }, | |
| httpClient: &http.Client{ | |
| Timeout: 120 * time.Second, | |
| Transport: &http.Transport{ | |
| MaxIdleConns: 100, | |
| MaxIdleConnsPerHost: 10, | |
| IdleConnTimeout: 90 * time.Second, | |
| DisableCompression: false, | |
| }, | |
| }, |
🤖 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/huggingface.go` around lines 27 - 35, The HTTP
transport in the HuggingFace client has inverted pool limits; in the struct
where the http.Client is created (the httpClient field initialization in
huggingface.go), swap the values so MaxIdleConns is the larger total pool and
MaxIdleConnsPerHost is the smaller per-host limit (e.g., set MaxIdleConns to 100
and MaxIdleConnsPerHost to 10) to match the pattern used in AliyunModel and
ensure consistent connection pooling.
| region = *apiConfig.Region | ||
| } | ||
|
|
||
| url := fmt.Sprintf("%s/chat/completions", h.BaseURL[region]) |
There was a problem hiding this comment.
Use configured URLSuffix.Chat instead of hardcoded path.
Line 207 hardcodes "chat/completions", while ChatWithMessages (line 68) correctly uses h.URLSuffix.Chat. This inconsistency breaks the configuration contract defined in conf/models/huggingface.json and prevents customization of the chat endpoint path.
🐛 Proposed fix
- url := fmt.Sprintf("%s/chat/completions", h.BaseURL[region])
+ url := fmt.Sprintf("%s/%s", h.BaseURL[region], h.URLSuffix.Chat)📝 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.
| url := fmt.Sprintf("%s/chat/completions", h.BaseURL[region]) | |
| url := fmt.Sprintf("%s/%s", h.BaseURL[region], h.URLSuffix.Chat) |
🤖 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/huggingface.go` at line 207, The URL for the chat
completions endpoint is hardcoded in the variable `url` within huggingface.go
(currently set to "chat/completions"); replace that hardcoded path with the
configured suffix `h.URLSuffix.Chat` so the function uses the same configuration
as `ChatWithMessages` and respects `conf/models/huggingface.json` customization;
update the construction that uses `h.BaseURL[region]` to append
`h.URLSuffix.Chat` instead of the literal string so the endpoint path is
configurable.
| func (h *HuggingFaceModel) Encode(modelName *string, texts []string, apiConfig *APIConfig, embeddingConfig *EmbeddingConfig) ([][]float64, error) { | ||
| if len(texts) == 0 { | ||
| return [][]float64{}, nil | ||
| } | ||
|
|
||
| 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") | ||
| } | ||
|
|
||
| reqBody := map[string]interface{}{ | ||
| "inputs": texts, | ||
| } | ||
|
|
||
| jsonData, err := json.Marshal(reqBody) | ||
| if err != nil { | ||
| return nil, err | ||
| } | ||
|
|
||
| url := fmt.Sprintf("https://router.huggingface.co/hf-inference/models/%s", *modelName) | ||
|
|
||
| req, err := http.NewRequest("POST", url, bytes.NewBuffer(jsonData)) | ||
| if err != nil { | ||
| return nil, err | ||
| } | ||
|
|
||
| req.Header.Set("Content-Type", "application/json") | ||
| req.Header.Set("Authorization", fmt.Sprintf("Bearer %s", *apiConfig.ApiKey)) | ||
|
|
||
| resp, err := h.httpClient.Do(req) | ||
| if err != nil { | ||
| return nil, err | ||
| } | ||
| defer resp.Body.Close() | ||
|
|
||
| body, err := io.ReadAll(resp.Body) | ||
| if err != nil { | ||
| return nil, err | ||
| } | ||
|
|
||
| if resp.StatusCode != http.StatusOK { | ||
| return nil, fmt.Errorf("HF embeddings API error: %s", string(body)) | ||
| } | ||
|
|
||
| var result [][]float64 | ||
| if err = json.Unmarshal(body, &result); err != nil { | ||
| return nil, err | ||
| } | ||
|
|
||
| return result, nil | ||
| } |
There was a problem hiding this comment.
Use configured BaseURL and URLSuffix.Embedding instead of hardcoded URL.
Line 382 hardcodes the entire URL (https://router.huggingface.co/hf-inference/models/%s), completely ignoring the configured BaseURL and URLSuffix.Embedding defined in conf/models/huggingface.json (line 9). This breaks the configuration contract, prevents users from customizing the embedding endpoint, and makes testing with alternative endpoints impossible.
🐛 Proposed fix
+ region := "default"
+ if apiConfig.Region != nil && *apiConfig.Region != "" {
+ region = *apiConfig.Region
+ }
+
reqBody := map[string]interface{}{
"inputs": texts,
}
jsonData, err := json.Marshal(reqBody)
if err != nil {
return nil, err
}
- url := fmt.Sprintf("https://router.huggingface.co/hf-inference/models/%s", *modelName)
+ url := fmt.Sprintf("%s/%s/%s", h.BaseURL[region], h.URLSuffix.Embedding, *modelName)
req, err := http.NewRequest("POST", url, bytes.NewBuffer(jsonData))🤖 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/huggingface.go` around lines 360 - 413, The Encode
method in HuggingFaceModel currently constructs a hardcoded endpoint
("https://router.huggingface.co/hf-inference/models/%s"); update it to use the
configured values from APIConfig (or the model's config) by composing the
request URL from apiConfig.BaseURL plus the URLSuffix.Embedding template (or
equivalent fields in the config) and the modelName (e.g.,
fmt.Sprintf(apiConfig.BaseURL+apiConfig.URLSuffix.Embedding, *modelName)),
preserving existing behavior when those fields are empty by falling back to the
current hardcoded path; modify the code in HuggingFaceModel.Encode where url is
built and ensure tests/usage still set Authorization and Content-Type headers as
before.
| models := make([]string, 0) | ||
| for _, model := range result["data"].([]interface{}) { | ||
| modelMap := model.(map[string]interface{}) | ||
| modelName := modelMap["id"].(string) | ||
| models = append(models, modelName) | ||
| } |
There was a problem hiding this comment.
Add type assertion checks to prevent runtime panics.
Lines 464-469 perform multiple unchecked type assertions that will panic if the API response format is unexpected or malformed:
result["data"].([]interface{})(line 465)model.(map[string]interface{})(line 466)modelMap["id"].(string)(line 467)
If HuggingFace changes their API response format or returns an error in an unexpected structure, this code will crash.
🛡️ Proposed fix with proper error handling
models := make([]string, 0)
- for _, model := range result["data"].([]interface{}) {
- modelMap := model.(map[string]interface{})
- modelName := modelMap["id"].(string)
+ data, ok := result["data"].([]interface{})
+ if !ok {
+ return nil, fmt.Errorf("invalid response format: 'data' field is not an array")
+ }
+
+ for _, model := range data {
+ modelMap, ok := model.(map[string]interface{})
+ if !ok {
+ continue
+ }
+ modelName, ok := modelMap["id"].(string)
+ if !ok {
+ continue
+ }
models = append(models, modelName)
}🤖 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/huggingface.go` around lines 464 - 469, The loop over
result["data"] uses unchecked type assertions that can panic; update the code in
internal/entity/models/huggingface.go to validate types using the comma-ok idiom
before casting: first check result["data"] exists and is a []interface{} (if
not, return or log and exit), then for each item assert it is a
map[string]interface{} before accessing "id", and finally assert the "id" value
is a string before appending to models; on any failed assertion handle
gracefully (log the malformed entry and skip it or return a descriptive error)
so the function (where models and result are used) no longer panics on malformed
API responses.
Codecov Report✅ All modified and coverable lines are covered by tests. Additional details and impacted files@@ Coverage Diff @@
## main #14722 +/- ##
=======================================
Coverage 94.16% 94.16%
=======================================
Files 10 10
Lines 703 703
Branches 112 112
=======================================
Hits 662 662
Misses 25 25
Partials 16 16 ☔ View full report in Codecov by Sentry. 🚀 New features to boost your workflow:
|
### What problem does this PR solve? Implement `HuggingFace` provider ### Type of change - [x] New Feature (non-breaking change which adds functionality)
What problem does this PR solve?
Implement
HuggingFaceproviderType of change