Repository navigation
Go CLI: embed and rerank - #14735
Go CLI: embed and rerank#14735
Conversation
Signed-off-by: Jin Hai <[email protected]>
📝 WalkthroughWalkthroughThis pull request adds embedding and reranking APIs to RAG Flow by refactoring the model driver interface, adding CLI commands, HTTP endpoints, and service methods. The Rerank method signature changes across all model drivers to accept configuration and return structured responses. New utility functions for float comparisons are introduced. ChangesEmbedding and Reranking Feature
Estimated code review effort🎯 4 (Complex) | ⏱️ ~60 minutes Possibly related issues
Possibly related PRs
Suggested labels
Suggested reviewers
Poem
🚥 Pre-merge checks | ✅ 4 | ❌ 1❌ Failed checks (1 warning)
✅ Passed checks (4 passed)
✏️ Tip: You can configure your own custom pre-merge checks in the settings. Tip 💬 Introducing Slack Agent: The best way for teams to turn conversations into code.Slack Agent is built on CodeRabbit's deep understanding of your code, so your team can collaborate across the entire SDLC without losing context.
Built for teams:
One agent for your entire SDLC. Right inside Slack. 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: 13
Caution
Some comments are outside the diff and can’t be posted inline due to platform limitations.
⚠️ Outside diff range comments (1)
internal/service/nlp/reranker.go (1)
137-156:⚠️ Potential issue | 🔴 Critical | ⚡ Quick winMap rerank scores back by
Indexbefore combining them.Providers return rerank hits in ranked order, not chunk order. With the PR's own example (
indices 0 and 2), this loop assigns the second score to chunk 1, and it also panics when the provider returns fewer thanchunkCountitems or the rerank call failed andrerankResponseis nil.💡 Suggested fix
- var modelSim []float64 + modelSim = make([]float64, chunkCount) // Get similarity scores from reranker model rerankResponse, err := rerankModel.ModelDriver.Rerank(rerankModel.ModelName, query, docs, rerankModel.APIConfig, &models.RerankConfig{}) if err != nil { common.Error("RerankByModel: rerankModel.Rerank failed; falling back to token-only similarity", err) - // If model fails, fall back to token similarity only - modelSim = make([]float64, len(tsim)) - } - - loopCount := min(chunkCount, len(rerankResponse.Data)) - for i := 0; i < loopCount; i++ { - modelSim = append(modelSim, rerankResponse.Data[i].RelevanceScore) + } else if rerankResponse != nil { + for _, item := range rerankResponse.Data { + if item.Index < 0 || item.Index >= chunkCount { + continue + } + modelSim[item.Index] = item.RelevanceScore + } }🤖 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/service/nlp/reranker.go` around lines 137 - 156, The code currently appends rerankResponse.Data scores in ranked order which misaligns them with chunk indices and can panic if rerankResponse is nil or has fewer items than chunkCount; instead, initialize modelSim as a zeroed slice of length chunkCount, check that rerankResponse != nil, then iterate rerankResponse.Data and for each hit use its Index field (bounds-checking against chunkCount) to assign modelSim[hit.Index] = hit.RelevanceScore; finally compute sim using tsim, tkWeight, and vtWeight as before so scores are correctly mapped by chunk index and missing scores default to zero.
🧹 Nitpick comments (1)
internal/cli/user_parser.go (1)
2718-2718: ⚡ Quick winStandardize command type spelling to
rerank_user_document.
rarank_user_documentworks only because dispatch currently mirrors the typo. Renaming it now will reduce future command-routing mistakes.🤖 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/cli/user_parser.go` at line 2718, The command name is misspelled: replace the call NewCommand("rarank_user_document") with NewCommand("rerank_user_document") to standardize the command type; then update any dispatch/registration references that expect "rarank_user_document" (e.g., routing maps or handlers that match that literal) to the corrected "rerank_user_document" so dispatching continues to work after the rename.
🤖 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/cli/user_command.go`:
- Around line 1786-1788: The auth kind is hardcoded to "web" but these methods
must pick authKind dynamically based on whether c.HTTPClient.APIToken is set;
update EmbedUserText, RerankUserDocument, CheckProviderConnection, and
AddCustomModel to call c.HTTPClient.Headers with authKind = "api" when
c.HTTPClient.APIToken != "" and "web" otherwise (preserve the existing HTTP
method argument like "GET"/"POST" per call), so the Authorization header is set
correctly for API-token-only workflows.
In `@internal/cli/user_parser.go`:
- Around line 2609-2611: The parser error messages are copy/pasted and mention
the wrong expected token/context; update the fmt.Errorf messages in the checks
that inspect p.curToken.Type so they report the actual expected token and
context (e.g., when checking for TokenText or TokenQuery after EMBED, change the
message to "expected TEXT after EMBED" or "expected QUERY after EMBED"
respectively). Locate the conditional checks around the TokenText/TokenQuery
validations in the user parser (the if blocks shown and the similar checks at
the other occurrences) and make each error string accurately reflect the token
constant and the command context; apply the same fix to the other two sites
referenced (the blocks at the other two occurrences).
- Around line 2650-2657: parseEmbedCommand (and likewise parseRerankCommand)
currently return without consuming a trailing semicolon, leaving the parser
state dirty; before returning from these functions check whether the current
token is a semicolon (';') and if so call p.nextToken() to consume it. Locate
the return in parseEmbedCommand and parseRerankCommand and add a conditional
like "if current token == ';' { p.nextToken() }" (use the parser's existing
token accessors such as p.curToken/p.peekToken and p.nextToken) so both
functions behave consistently with other user parsers.
In `@internal/common/float.go`:
- Around line 22-30: Float64IsZero currently misses exactly 0.0 because it only
checks signed ranges; update the logic in Float64IsZero (and keep using
epsilon64) to return true when f == 0.0 or, simpler and safer, replace the
signed comparisons with an absolute-value check like math.Abs(f) <= epsilon64 so
zero and near-zero values both return true; ensure math is imported if not
already.
- Around line 32-40: The function Float32IsNotZero currently returns true when f
is within the epsilon range (i.e., near zero) which is inverted; change it to
return true only when the absolute value exceeds epsilon32 (e.g., use abs check:
|f| > epsilon32) so exact 0.0 yields false and values sufficiently far from zero
yield true; update the implementation in Float32IsNotZero (referencing
epsilon32) accordingly.
In `@internal/entity/models/siliconflow.go`:
- Around line 660-665: RerankByModel for SiliconFlow is sending TopN==0 directly
which can cause zero scores; update the SiliconflowRerankRequest construction so
that when rerankConfig.TopN is 0 you set TopN to len(documents) (same
normalization as other drivers) before assigning to the Model request (look for
SiliconflowRerankRequest, RerankByModel, rerankConfig.TopN and documents) so the
payload never contains top_n: 0.
In `@internal/entity/models/types.go`:
- Around line 42-50: EmbeddingResult currently omits the actual vector payload
so callers can't consume embeddings; restore the embedding field by adding
Embedding []float64 `json:"embedding"` to the EmbeddingResult struct (you can
un-comment the existing commented line), ensure EmbeddingResponse.Data continues
to use []EmbeddingResult, and update any constructors/serializers that build
EmbeddingResult (e.g., code that sets Index/Dimension) to populate Embedding
with the vector and keep Dimension consistent (or derive Dimension =
len(Embedding)).
In `@internal/handler/providers.go`:
- Around line 1018-1027: In RerankDocument handler add upfront validation to
reject empty or malformed rerank inputs: check req.Query is non-empty,
req.Documents is non-empty (length > 0) and req.TopN is a positive integer (>0)
before constructing models.RerankConfig or calling providers; if any check fails
return an immediate client error response (HTTP 400) with a clear message.
Locate the validation near where userID, apiConfig and rerankConfig are created
(references: RerankDocument, req, models.RerankConfig, rerankConfig, c) and
ensure the early-return prevents downstream provider calls when inputs are
invalid.
- Around line 917-950: The handler (EmbedText) must validate the embedding
payload before calling the provider: ensure req.Texts is not nil and has at
least one non-empty string (reject with HTTP 400 and a clear message like "texts
is required") and validate req.Dimension is a positive integer (reject with HTTP
400 and message like "dimension must be > 0"); perform these checks before
constructing apiConfig/embeddingConfig and before invoking the provider service
(referencing the EmbedText handler and the EmbeddingConfig struct) and apply the
same validation at the other occurrence around line 957 where embeddings are
processed.
- Line 909: The println calls using printf verbs (e.g. println("JSON bind error:
%v (type: %T)", err, err)) must be replaced with a formatted logging API; update
each occurrence of println in internal/handler/providers.go (the JSON bind error
and the other %v/%T usages) to use a proper formatter such as fmt.Printf or
log.Printf (or the project's logger like processLogger.Errorf/Warningf if
available), pass err as the formatting argument, and add the necessary import
(fmt or log) so the message prints with the intended %v/%T formatting.
In `@internal/service/model_service.go`:
- Around line 992-999: The code dereferences newProviderInfo returned from
providerInfo.ModelDriver.NewInstance (used before calling Encode) which can be
nil for some drivers; add a nil-check after creating newProviderInfo (both where
embeddings are created and in RerankDocument) and return a clear error if
NewInstance returned nil instead of proceeding to call newProviderInfo.Encode or
other methods, so requests fail gracefully rather than panic.
- Around line 1068-1069: The error message in the branch that checks
model.ModelTypeMap["rerank"] is incorrect: it currently says "is not an
embedding model" but should indicate rerank capability. Update the error
returned in the rerank check (the branch using model.ModelTypeMap["rerank"] and
variables providerName and modelName) to a clear message like "provider %s model
%s is not a rerank model" (or "not rerank-capable") so API/CLI callers receive
the correct model type information.
- Around line 942-953: The tenant_model fallback path currently always calls
providerInfo.ModelDriver.Encode which ignores an instance-level base_url; update
the fallback branch that parses instance.Extra (the map extra) so that if
extra["base_url"] (or similar key present in extra) is set you select the
instance-local driver the same way other branches do before calling
providerInfo.ModelDriver.Encode — ensure apiConfig (Region/ApiKey) is still
populated from instance and pass the chosen driver into the Encode call; make
the identical fix for the RerankDocument usage around the later block (lines
referenced as 1072-1083) so both embedding and rerank requests honor
instance.Extra["base_url"] and use the local instance driver when configured.
---
Outside diff comments:
In `@internal/service/nlp/reranker.go`:
- Around line 137-156: The code currently appends rerankResponse.Data scores in
ranked order which misaligns them with chunk indices and can panic if
rerankResponse is nil or has fewer items than chunkCount; instead, initialize
modelSim as a zeroed slice of length chunkCount, check that rerankResponse !=
nil, then iterate rerankResponse.Data and for each hit use its Index field
(bounds-checking against chunkCount) to assign modelSim[hit.Index] =
hit.RelevanceScore; finally compute sim using tsim, tkWeight, and vtWeight as
before so scores are correctly mapped by chunk index and missing scores default
to zero.
---
Nitpick comments:
In `@internal/cli/user_parser.go`:
- Line 2718: The command name is misspelled: replace the call
NewCommand("rarank_user_document") with NewCommand("rerank_user_document") to
standardize the command type; then update any dispatch/registration references
that expect "rarank_user_document" (e.g., routing maps or handlers that match
that literal) to the corrected "rerank_user_document" so dispatching continues
to work after the rename.
🪄 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: d732a3fa-345f-4f70-ae4c-0edac9d55392
📒 Files selected for processing (31)
conf/models/zhipu-ai.jsoninternal/cli/client.gointernal/cli/lexer.gointernal/cli/parser.gointernal/cli/types.gointernal/cli/user_command.gointernal/cli/user_parser.gointernal/common/float.gointernal/entity/models/aliyun.gointernal/entity/models/deepseek.gointernal/entity/models/dummy.gointernal/entity/models/gitee.gointernal/entity/models/google.gointernal/entity/models/huggingface.gointernal/entity/models/lmstudio.gointernal/entity/models/minimax.gointernal/entity/models/moonshot.gointernal/entity/models/nvidia.gointernal/entity/models/ollama.gointernal/entity/models/openai.gointernal/entity/models/openrouter.gointernal/entity/models/siliconflow.gointernal/entity/models/types.gointernal/entity/models/vllm.gointernal/entity/models/volcengine.gointernal/entity/models/xai.gointernal/entity/models/zhipu-ai.gointernal/handler/providers.gointernal/router/router.gointernal/service/model_service.gointernal/service/nlp/reranker.go
| if c.HTTPClient.APIToken == "" && c.HTTPClient.LoginToken == "" { | ||
| return nil, fmt.Errorf("API token not set. Please login first") | ||
| } |
There was a problem hiding this comment.
🧩 Analysis chain
🏁 Script executed:
#!/bin/bash
# Verify how authKind is interpreted by HTTP client implementation.
rg -n --type=go -C4 'func \(.*\) Request\(' internal/cli
rg -n --type=go -C3 'authKind|useAPIToken|LoginToken|APIToken' internal/cliRepository: infiniflow/ragflow
Length of output: 22740
🏁 Script executed:
# Extract full implementation of EmbedUserText and RerankUserDocument methods
sed -n '1785,1850p' internal/cli/user_command.go
sed -n '1852,1920p' internal/cli/user_command.goRepository: infiniflow/ragflow
Length of output: 4265
🏁 Script executed:
# Check the other methods mentioned in "Also applies to" section
sed -n '1925,1950p' internal/cli/user_command.go | head -30
sed -n '1965,1990p' internal/cli/user_command.go | head -30
sed -n '2017,2042p' internal/cli/user_command.go | head -30
sed -n '2089,2114p' internal/cli/user_command.go | head -30Repository: infiniflow/ragflow
Length of output: 3240
🏁 Script executed:
# Get complete AddCustomModel implementation
sed -n '2017,2087p' internal/cli/user_command.goRepository: infiniflow/ragflow
Length of output: 2046
Auth mode is hardcoded to "web" but should respect API token mode in multiple methods.
These methods accept either API token or login token but always use authKind="web" which only supports login tokens. API-token-only workflows will fail when the HTTPClient.Headers method cannot set the Authorization header.
Affected methods:
EmbedUserText(line 1834)RerankUserDocument(line 1907)CheckProviderConnection(line 1945)AddCustomModel(line 2062)
🔧 Suggested fix
For each method, replace the hardcoded auth kind with dynamic selection:
- resp, err := c.HTTPClient.Request("POST", url, "web", nil, payload)
+ authKind := "web"
+ if c.HTTPClient.useAPIToken {
+ authKind = "api"
+ }
+ resp, err := c.HTTPClient.Request("POST", url, authKind, nil, payload)(Use "GET" or "POST" as appropriate for each method's call.)
🤖 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/cli/user_command.go` around lines 1786 - 1788, The auth kind is
hardcoded to "web" but these methods must pick authKind dynamically based on
whether c.HTTPClient.APIToken is set; update EmbedUserText, RerankUserDocument,
CheckProviderConnection, and AddCustomModel to call c.HTTPClient.Headers with
authKind = "api" when c.HTTPClient.APIToken != "" and "web" otherwise (preserve
the existing HTTP method argument like "GET"/"POST" per call), so the
Authorization header is set correctly for API-token-only workflows.
| if p.curToken.Type != TokenText { | ||
| return nil, fmt.Errorf("expected WITH after EMBED") | ||
| } |
There was a problem hiding this comment.
Fix copy/paste parser error messages for easier debugging.
The current messages reference the wrong expected tokens/command context (e.g., “expected WITH after EMBED” while checking TokenText or TokenQuery).
Also applies to: 2662-2664, 2696-2698
🤖 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/cli/user_parser.go` around lines 2609 - 2611, The parser error
messages are copy/pasted and mention the wrong expected token/context; update
the fmt.Errorf messages in the checks that inspect p.curToken.Type so they
report the actual expected token and context (e.g., when checking for TokenText
or TokenQuery after EMBED, change the message to "expected TEXT after EMBED" or
"expected QUERY after EMBED" respectively). Locate the conditional checks around
the TokenText/TokenQuery validations in the user parser (the if blocks shown and
the similar checks at the other occurrences) and make each error string
accurately reflect the token constant and the command context; apply the same
fix to the other two sites referenced (the blocks at the other two occurrences).
| p.nextToken() | ||
|
|
||
| cmd := NewCommand("embed_user_text") | ||
| cmd.Params["composite_model_name"] = compositeModelName | ||
| cmd.Params["texts"] = texts | ||
| cmd.Params["dimension"] = dimension | ||
| return cmd, nil | ||
| } |
There was a problem hiding this comment.
Consume optional semicolon before returning from new parsers.
parseEmbedCommand and parseRerankCommand do not consume trailing ;, unlike the rest of user parsers. This can leave parser state dirty for subsequent statements.
🔧 Suggested fix
cmd := NewCommand("embed_user_text")
cmd.Params["composite_model_name"] = compositeModelName
cmd.Params["texts"] = texts
cmd.Params["dimension"] = dimension
+ if p.curToken.Type == TokenSemicolon {
+ p.nextToken()
+ }
return cmd, nil
}
@@
cmd := NewCommand("rarank_user_document")
cmd.Params["composite_model_name"] = compositeModelName
cmd.Params["query"] = query
cmd.Params["documents"] = documents
cmd.Params["top_n"] = topN
+ if p.curToken.Type == TokenSemicolon {
+ p.nextToken()
+ }
return cmd, nil
}Also applies to: 2716-2724
🤖 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/cli/user_parser.go` around lines 2650 - 2657, parseEmbedCommand (and
likewise parseRerankCommand) currently return without consuming a trailing
semicolon, leaving the parser state dirty; before returning from these functions
check whether the current token is a semicolon (';') and if so call
p.nextToken() to consume it. Locate the return in parseEmbedCommand and
parseRerankCommand and add a conditional like "if current token == ';' {
p.nextToken() }" (use the parser's existing token accessors such as
p.curToken/p.peekToken and p.nextToken) so both functions behave consistently
with other user parsers.
| func Float64IsZero(f float64) bool { | ||
| if f < 0 && f >= -epsilon64 { | ||
| return true | ||
| } | ||
| if f > 0 && f <= epsilon64 { | ||
| return true | ||
| } | ||
| return false | ||
| } |
There was a problem hiding this comment.
Critical: Float64IsZero returns false for exactly 0.0.
The function returns false when f is exactly 0.0 because neither f < 0 nor f > 0 is true. A function named "IsZero" must return true for the value 0.0.
🐛 Proposed fix
func Float64IsZero(f float64) bool {
- if f < 0 && f >= -epsilon64 {
- return true
- }
- if f > 0 && f <= epsilon64 {
- return true
- }
- return false
+ return f >= -epsilon64 && f <= epsilon64
}🤖 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/common/float.go` around lines 22 - 30, Float64IsZero currently
misses exactly 0.0 because it only checks signed ranges; update the logic in
Float64IsZero (and keep using epsilon64) to return true when f == 0.0 or,
simpler and safer, replace the signed comparisons with an absolute-value check
like math.Abs(f) <= epsilon64 so zero and near-zero values both return true;
ensure math is imported if not already.
| func Float32IsNotZero(f float32) bool { | ||
| if f < 0 && f >= -epsilon32 { | ||
| return true | ||
| } | ||
| if f > 0 && f <= epsilon32 { | ||
| return true | ||
| } | ||
| return false | ||
| } |
There was a problem hiding this comment.
Critical: Float32IsNotZero has inverted logic.
The function name suggests it should return true when the value is NOT zero (i.e., when |f| > epsilon32), but the implementation returns true when the value IS near zero (within the epsilon range). This is the exact opposite of what the name implies and will cause incorrect behavior in calling code.
Additionally, the function returns false for exactly 0.0, which is inconsistent regardless of the intended semantics.
🐛 Proposed fixes
Option 1: Rename to Float32IsZero and fix the exact-zero bug
-func Float32IsNotZero(f float32) bool {
- if f < 0 && f >= -epsilon32 {
- return true
- }
- if f > 0 && f <= epsilon32 {
- return true
- }
- return false
+func Float32IsZero(f float32) bool {
+ return f >= -epsilon32 && f <= epsilon32
}Option 2: Keep the name and invert the logic
func Float32IsNotZero(f float32) bool {
- if f < 0 && f >= -epsilon32 {
- return true
- }
- if f > 0 && f <= epsilon32 {
- return true
- }
- return false
+ return f < -epsilon32 || f > epsilon32
}📝 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.
| func Float32IsNotZero(f float32) bool { | |
| if f < 0 && f >= -epsilon32 { | |
| return true | |
| } | |
| if f > 0 && f <= epsilon32 { | |
| return true | |
| } | |
| return false | |
| } | |
| func Float32IsZero(f float32) bool { | |
| return f >= -epsilon32 && f <= epsilon32 | |
| } |
| func Float32IsNotZero(f float32) bool { | |
| if f < 0 && f >= -epsilon32 { | |
| return true | |
| } | |
| if f > 0 && f <= epsilon32 { | |
| return true | |
| } | |
| return false | |
| } | |
| func Float32IsNotZero(f float32) bool { | |
| return f < -epsilon32 || f > epsilon32 | |
| } |
🤖 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/common/float.go` around lines 32 - 40, The function Float32IsNotZero
currently returns true when f is within the epsilon range (i.e., near zero)
which is inverted; change it to return true only when the absolute value exceeds
epsilon32 (e.g., use abs check: |f| > epsilon32) so exact 0.0 yields false and
values sufficiently far from zero yield true; update the implementation in
Float32IsNotZero (referencing epsilon32) accordingly.
| if req.ProviderName == nil || *req.ProviderName == "" { | ||
| c.JSON(http.StatusBadRequest, gin.H{ | ||
| "code": 400, | ||
| "message": "Provider name is required", | ||
| }) | ||
| return | ||
| } | ||
|
|
||
| if req.InstanceName == nil || *req.InstanceName == "" { | ||
| c.JSON(http.StatusBadRequest, gin.H{ | ||
| "code": 400, | ||
| "message": "Instance name is required", | ||
| }) | ||
| return | ||
| } | ||
|
|
||
| if req.ModelName == nil || *req.ModelName == "" { | ||
| c.JSON(http.StatusBadRequest, gin.H{ | ||
| "code": 400, | ||
| "message": "Model name is required", | ||
| }) | ||
| return | ||
| } | ||
|
|
||
| userID := c.GetString("user_id") | ||
|
|
||
| apiConfig := models.APIConfig{ | ||
| ApiKey: nil, | ||
| Region: nil, | ||
| } | ||
|
|
||
| embeddingConfig := models.EmbeddingConfig{ | ||
| Dimension: req.Dimension, | ||
| } |
There was a problem hiding this comment.
Validate embedding payload before calling provider service.
EmbedText currently accepts empty texts and invalid dimension values, which should be rejected at the handler boundary.
🛡️ Suggested validation patch
if req.ModelName == nil || *req.ModelName == "" {
c.JSON(http.StatusBadRequest, gin.H{
"code": 400,
"message": "Model name is required",
})
return
}
+ if len(req.Texts) == 0 {
+ c.JSON(http.StatusBadRequest, gin.H{
+ "code": 400,
+ "message": "Texts are required",
+ })
+ return
+ }
+ if req.Dimension < 0 {
+ c.JSON(http.StatusBadRequest, gin.H{
+ "code": 400,
+ "message": "Dimension must be greater than or equal to 0",
+ })
+ return
+ }Also applies to: 957-957
🤖 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/handler/providers.go` around lines 917 - 950, The handler
(EmbedText) must validate the embedding payload before calling the provider:
ensure req.Texts is not nil and has at least one non-empty string (reject with
HTTP 400 and a clear message like "texts is required") and validate
req.Dimension is a positive integer (reject with HTTP 400 and message like
"dimension must be > 0"); perform these checks before constructing
apiConfig/embeddingConfig and before invoking the provider service (referencing
the EmbedText handler and the EmbeddingConfig struct) and apply the same
validation at the other occurrence around line 957 where embeddings are
processed.
| userID := c.GetString("user_id") | ||
|
|
||
| apiConfig := models.APIConfig{ | ||
| ApiKey: nil, | ||
| Region: nil, | ||
| } | ||
|
|
||
| rerankConfig := models.RerankConfig{ | ||
| TopN: req.TopN, | ||
| } |
There was a problem hiding this comment.
Reject invalid rerank inputs (query, documents, top_n) up front.
RerankDocument does not guard empty query/documents or non-positive top_n, so malformed requests can reach downstream providers.
🛡️ Suggested validation patch
if req.ModelName == nil || *req.ModelName == "" {
c.JSON(http.StatusBadRequest, gin.H{
"code": 400,
"message": "Model name is required",
})
return
}
+ if strings.TrimSpace(req.Query) == "" {
+ c.JSON(http.StatusBadRequest, gin.H{
+ "code": 400,
+ "message": "Query is required",
+ })
+ return
+ }
+ if len(req.Documents) == 0 {
+ c.JSON(http.StatusBadRequest, gin.H{
+ "code": 400,
+ "message": "Documents are required",
+ })
+ return
+ }
+ if req.TopN <= 0 {
+ c.JSON(http.StatusBadRequest, gin.H{
+ "code": 400,
+ "message": "top_n must be greater than 0",
+ })
+ return
+ }Also applies to: 1034-1034
🤖 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/handler/providers.go` around lines 1018 - 1027, In RerankDocument
handler add upfront validation to reject empty or malformed rerank inputs: check
req.Query is non-empty, req.Documents is non-empty (length > 0) and req.TopN is
a positive integer (>0) before constructing models.RerankConfig or calling
providers; if any check fails return an immediate client error response (HTTP
400) with a clear message. Locate the validation near where userID, apiConfig
and rerankConfig are created (references: RerankDocument, req,
models.RerankConfig, rerankConfig, c) and ensure the early-return prevents
downstream provider calls when inputs are invalid.
| var extra map[string]string | ||
| err = json.Unmarshal([]byte(instance.Extra), &extra) | ||
| if err != nil { | ||
| return nil, common.CodeServerError, err | ||
| } | ||
|
|
||
| region := extra["region"] | ||
| apiConfig.Region = ®ion | ||
| apiConfig.ApiKey = &instance.APIKey | ||
|
|
||
| var embeddingList [][]float64 | ||
| embeddingList, err = providerInfo.ModelDriver.Encode(&modelName, texts, apiConfig, modelConfig) |
There was a problem hiding this comment.
Honor base_url in the registry-model fallback path.
When tenant_model lookup misses, these branches still call the shared provider driver even if the instance has a local base_url. That sends embed/rerank requests to the provider default endpoint instead of the configured local instance.
💡 Suggested fix
region := extra["region"]
apiConfig.Region = ®ion
apiConfig.ApiKey = &instance.APIKey
+ driver := providerInfo.ModelDriver
+ if baseURL, ok := extra["base_url"]; ok && baseURL != "" {
+ driver = driver.NewInstance(map[string]string{region: baseURL})
+ }
var embeddingList [][]float64
- embeddingList, err = providerInfo.ModelDriver.Encode(&modelName, texts, apiConfig, modelConfig)
+ embeddingList, err = driver.Encode(&modelName, texts, apiConfig, modelConfig)Apply the same driver selection to RerankDocument.
Also applies to: 1072-1083
🤖 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/service/model_service.go` around lines 942 - 953, The tenant_model
fallback path currently always calls providerInfo.ModelDriver.Encode which
ignores an instance-level base_url; update the fallback branch that parses
instance.Extra (the map extra) so that if extra["base_url"] (or similar key
present in extra) is set you select the instance-local driver the same way other
branches do before calling providerInfo.ModelDriver.Encode — ensure apiConfig
(Region/ApiKey) is still populated from instance and pass the chosen driver into
the Encode call; make the identical fix for the RerankDocument usage around the
later block (lines referenced as 1072-1083) so both embedding and rerank
requests honor instance.Extra["base_url"] and use the local instance driver when
configured.
| newURL := map[string]string{ | ||
| region: extra["base_url"], | ||
| } | ||
| newProviderInfo := providerInfo.ModelDriver.NewInstance(newURL) | ||
|
|
||
| var embeddingList [][]float64 | ||
| embeddingList, err = newProviderInfo.Encode(&modelName, texts, apiConfig, modelConfig) | ||
| if err != nil { |
There was a problem hiding this comment.
Avoid a nil-driver panic on local model requests.
Several drivers in this PR still return nil from NewInstance, so dereferencing newProviderInfo here can crash the request instead of returning a normal error.
💡 Suggested fix
newURL := map[string]string{
region: extra["base_url"],
}
newProviderInfo := providerInfo.ModelDriver.NewInstance(newURL)
+ if newProviderInfo == nil {
+ return nil, common.CodeServerError, fmt.Errorf("provider %s does not support instance-specific base_url", providerName)
+ }
var embeddingList [][]float64
embeddingList, err = newProviderInfo.Encode(&modelName, texts, apiConfig, modelConfig)Apply the same guard in RerankDocument.
Also applies to: 1108-1115
🤖 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/service/model_service.go` around lines 992 - 999, The code
dereferences newProviderInfo returned from providerInfo.ModelDriver.NewInstance
(used before calling Encode) which can be nil for some drivers; add a nil-check
after creating newProviderInfo (both where embeddings are created and in
RerankDocument) and return a clear error if NewInstance returned nil instead of
proceeding to call newProviderInfo.Encode or other methods, so requests fail
gracefully rather than panic.
| if !model.ModelTypeMap["rerank"] { | ||
| return nil, common.CodeNotFound, errors.New(fmt.Sprintf("provider %s model %s is not an embedding model", providerName, modelName)) |
There was a problem hiding this comment.
Return the correct model type in this error.
This branch is validating rerank capability, but the message says "embedding model", which is misleading for API and CLI callers.
🤖 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/service/model_service.go` around lines 1068 - 1069, The error
message in the branch that checks model.ModelTypeMap["rerank"] is incorrect: it
currently says "is not an embedding model" but should indicate rerank
capability. Update the error returned in the rerank check (the branch using
model.ModelTypeMap["rerank"] and variables providerName and modelName) to a
clear message like "provider %s model %s is not a rerank model" (or "not
rerank-capable") so API/CLI callers receive the correct model type information.
Codecov Report✅ All modified and coverable lines are covered by tests. Additional details and impacted files@@ Coverage Diff @@
## main #14735 +/- ##
=======================================
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:
|
The EmbeddingConfig type added a Dimension field in infiniflow#14735 so callers can request a specific output dimension on providers that support it (OpenAI text-embedding-3-* among them). Pass dimensions through to the OpenAI /v1/embeddings request when embeddingConfig is non-nil and Dimension is greater than zero, matching the pattern the merged ZhipuAI Encode now uses.
The EmbeddingConfig type added a Dimension field in infiniflow#14735 so callers can request a specific output dimension on providers that support it. Pass dimensions through to the vLLM /v1/embeddings request when embeddingConfig is non-nil and Dimension is greater than zero, matching the pattern the merged ZhipuAI Encode now uses.
### What problem does this PR solve? The Baidu (Qianfan) `Encode` method silently swallowed malformed responses. If a `data[]` item from the API was missing a field (`index`, `embedding`, or unexpected shape), the loop did `continue` instead of returning an error, leaving `nil` entries in the result slice. Callers got back partial results with no indication anything went wrong, which then crashes downstream consumers when they try to use a `nil` vector. Concrete gaps fixed: - No count-mismatch check between `data` length and input texts (only checked for empty) - No duplicate-index detection (a duplicate would silently overwrite) - No missing-index final scan - No empty-embedding rejection - No per-call context timeout - `EmbeddingConfig.Dimension` (added in #14735) was not propagated This PR replaces `map[string]interface{}` parsing with a typed `baiduEmbeddingResponse` struct, applies the standard four-layer validation (count → out-of-range → duplicate → empty → final missing-index scan), adds `context.WithTimeout(nonStreamCallTimeout)`, and forwards `embeddingConfig.Dimension` as the `dimensions` parameter (Baidu Qianfan v2 uses an OpenAI-compatible API). ### Type of change - [x] Bug Fix (non-breaking change which fixes an issue)
### What problem does this PR solve? Fixes #14893 The Novita Go driver landed in #14850 and shipped a stub `Embed` method that returned `"novita, no such method"`, so Novita could not be used as an embedding provider in RAGFlow. This PR fills that gap. Novita exposes a public embeddings endpoint at `POST https://api.novita.ai/v3/embeddings` that accepts the standard OpenAI-compatible request shape (`{model, input}`) with `Authorization: Bearer <api_key>`. Two embedding models are documented in Novita's model library: `baai/bge-m3` (multilingual, 8192 tokens) and `baai/bge-large-en-v1.5`. ### Changes - `internal/entity/models/novita.go`: implement `NovitaModel.Embed`. - Validate inputs (api key, model name) and short-circuit on empty texts. - Resolve region with the existing `baseURLForRegion` helper. - Build URL from `URLSuffix.Embedding` (the embeddings path lives under `/v3/`, separate from the chat path under `/openai/v1/`). - Send `{model, input}` POST body, add `dimensions` when `embeddingConfig.Dimension > 0` (matches the pattern in #14735). - Bearer auth + JSON content type, mirroring the chat path. - Parse `{data: [{embedding, index}]}` and reorder by `index`, rejecting out-of-range indices, duplicates, and missing entries so the output always lines up with the input. Same shape as the merged Mistral and Upstage Embed implementations. - `conf/models/novita.json`: - Add `"embedding": "v3/embeddings"` to `url_suffix`. - Add default embedding model entries for `baai/bge-m3` and `baai/bge-large-en-v1.5` so they appear in the model picker. ### Type of change - [x] New Feature (non-breaking change which adds functionality) --------- Co-authored-by: Jin Hai <[email protected]>
### What problem does this PR solve? Fixes #15015 The TogetherAI Go driver in `internal/entity/models/togetherai.go` shipped a stub `Embed` method that returned `"TogetherAI, no such method"`, so TogetherAI could not be used as an embedding provider in RAGFlow. This PR fills that gap. TogetherAI exposes a public OpenAI-compatible embeddings endpoint at `POST https://api.together.ai/v1/embeddings` that accepts the standard `{model, input}` shape with `Authorization: Bearer <api_key>` (confirmed in TogetherAI's official docs: https://docs.together.ai/docs/embeddings-overview). Documented embedding models include `intfloat/multilingual-e5-large-instruct`, `BAAI/bge-large-en-v1.5`, and `BAAI/bge-base-en-v1.5`. ### Changes - `internal/entity/models/togetherai.go`: implement `TogetherAIModel.Embed`. - Validate inputs (api key, model name) and short-circuit on empty texts. - Resolve region with the existing `baseURLForRegion` helper. - Build URL from `URLSuffix.Embedding`. - Send `{model, input}` POST body, add `dimensions` when `embeddingConfig.Dimension > 0` (matches the pattern in #14735). - Bearer auth + JSON content type, mirroring the chat path. - Parse `{data: [{embedding, index}]}` and reorder by `index`, rejecting out-of-range indices, duplicates, and missing entries so the output always lines up with the input. Same shape as the merged Mistral, Upstage, and Novita Embed implementations. - `conf/models/togetherai.json`: - Add `"embedding": "embeddings"` to `url_suffix`. - Add default embedding model entries for `intfloat/multilingual-e5-large-instruct`, `BAAI/bge-large-en-v1.5`, and `BAAI/bge-base-en-v1.5`. ### Type of change - [x] New Feature (non-breaking change which adds functionality)
### What problem does this PR solve? ``` RAGFlow(user)> embed text 'what is rag' 'who are you' with 'embedding-3@test@zhipu-ai' dimension 16; +-----------+-------+ | dimension | index | +-----------+-------+ | 16 | 0 | | 16 | 1 | +-----------+-------+ RAGFlow(user)> rerank query 'what is rag' document 'rag is retrieval augment generation' 'rag need llm' 'famous rag project includes ragflow' with 'rerank@test@zhipu-ai' top 2; +-------+-----------------+ | index | relevance_score | +-------+-----------------+ | 0 | 1 | | 2 | 0.99999976 | +-------+-----------------+ ``` ### Type of change - [x] New Feature (non-breaking change which adds functionality) Signed-off-by: Jin Hai <[email protected]>
…flow#14721) ### What problem does this PR solve? The Baidu (Qianfan) `Encode` method silently swallowed malformed responses. If a `data[]` item from the API was missing a field (`index`, `embedding`, or unexpected shape), the loop did `continue` instead of returning an error, leaving `nil` entries in the result slice. Callers got back partial results with no indication anything went wrong, which then crashes downstream consumers when they try to use a `nil` vector. Concrete gaps fixed: - No count-mismatch check between `data` length and input texts (only checked for empty) - No duplicate-index detection (a duplicate would silently overwrite) - No missing-index final scan - No empty-embedding rejection - No per-call context timeout - `EmbeddingConfig.Dimension` (added in infiniflow#14735) was not propagated This PR replaces `map[string]interface{}` parsing with a typed `baiduEmbeddingResponse` struct, applies the standard four-layer validation (count → out-of-range → duplicate → empty → final missing-index scan), adds `context.WithTimeout(nonStreamCallTimeout)`, and forwards `embeddingConfig.Dimension` as the `dimensions` parameter (Baidu Qianfan v2 uses an OpenAI-compatible API). ### Type of change - [x] Bug Fix (non-breaking change which fixes an issue)
What problem does this PR solve?
Type of change