Skip to content

Go CLI: embed and rerank - #14735

Merged
JinHai-CN merged 1 commit into
infiniflow:mainfrom
JinHai-CN:fix421
May 9, 2026
Merged

JinHai-CN merged 1 commit into
infiniflow:mainfrom
JinHai-CN:fix421

Conversation

@JinHai-CN

Copy link
Copy Markdown
Member

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

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

@coderabbitai

coderabbitai Bot commented May 9, 2026 •

Copy link
Copy Markdown
Contributor

Review Change Stack

📝 Walkthrough

Walkthrough

This 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.

Changes

Embedding and Reranking Feature

Layer / File(s) Summary
Type Definitions
internal/entity/models/types.go, internal/common/float.go
New types: EmbeddingResult, EmbeddingResponse, RerankResult, RerankResponse, EmbeddingConfig, RerankConfig. ModelDriver.Rerank signature updated to accept rerankConfig and return *RerankResponse. Float epsilon utilities for zero-checking added.
CLI Tokens & Lexer
internal/cli/types.go, internal/cli/lexer.go
New token constants: TokenEmbed, TokenText, TokenQuery, TokenTop, TokenDimension. Lexer keyword mappings recognize these tokens.
CLI Parser
internal/cli/parser.go, internal/cli/user_parser.go
parseUserCommand dispatch for TokenEmbed and TokenRerank. New parseEmbedCommand and parseRerankCommand parse EMBED/RERANK syntax with parameters.
CLI Command Execution
internal/cli/client.go, internal/cli/user_command.go
ExecuteUserCommand wires embed_user_text and rarank_user_document to EmbedUserText and RerankUserDocument handlers. Both call HTTP endpoints and validate responses.
Model Driver Updates
internal/entity/models/*.go (all providers)
All model drivers' Rerank method signatures updated from (texts []string) ([]float64) to (documents []string, rerankConfig) (*RerankResponse). Implementations include Aliyun, Gitee, OpenRouter, SiliconFlow, and Zhipu AI with actual response handling; others return unimplemented errors.
Service Layer
internal/service/model_service.go
EmbedText and RerankDocument methods resolve provider/instance/model, validate model capabilities, select driver instances, invoke ModelDriver methods, and construct structured responses.
HTTP API
internal/handler/providers.go, internal/router/router.go
EmbedText and RerankDocument handlers parse JSON requests, call service methods, and return responses. Routes added for POST /api/v1/embeddings and /api/v1/rerank.
Integration & Config
internal/service/nlp/reranker.go, conf/models/zhipu-ai.json
RerankByModel updated to use structured RerankResponse. Model names updated: glm-asr → glm-asr-2512, glm-rerank → rerank.

Estimated code review effort

🎯 4 (Complex) | ⏱️ ~60 minutes

Possibly related issues

  • infiniflow/ragflow#14607: PR implements ZhipuAIModel.Rerank refactor directly addressing the Zhipu reranking implementation request.
  • infiniflow/ragflow#14655: PR updates GiteeModel.Rerank signature and implementation to the new response-based API.

Possibly related PRs

  • infiniflow/ragflow#14608: Both refactor internal/entity/models/zhipu-ai.go Rerank to new signature returning *RerankResponse.
  • infiniflow/ragflow#14418: Both modify model driver types and rerank APIs including volcengine implementations.
  • infiniflow/ragflow#14398: Both perform same model driver surface refactor—embedding/rerank API changes including Zhipu config updates.

Suggested labels

💞 feature, size:XL

Suggested reviewers

  • Haruko386

Poem

🐰 Embeddings spring forth from the tokens we weave,
Reranking the docs with Zhipu's reprieve,
Through CLI and service, the data now flows,
From five dozen drivers, the new feature glows! ✨

🚥 Pre-merge checks | ✅ 4 | ❌ 1

❌ Failed checks (1 warning)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 50.00% which is insufficient. The required threshold is 80.00%. Write docstrings for the functions missing them to satisfy the coverage threshold.
✅ Passed checks (4 passed)
Check name Status Explanation
Title check ✅ Passed The title 'Go CLI: embed and rerank' accurately reflects the main changes: new CLI commands for embedding and reranking functionality.
Description check ✅ Passed The description includes a practical example demonstrating the new embed and rerank commands and identifies the type of change as a New Feature, but lacks a detailed explanation of the problem being solved.
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.

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.

  • Generate code and open pull requests
  • Plan features and break down work
  • Investigate incidents and troubleshoot customer tickets together
  • Automate recurring tasks and respond to alerts with triggers
  • Summarize progress and report instantly

Built for teams:

  • Shared memory across your entire org—no repeating context
  • Per-thread sandboxes to safely plan and execute work
  • Governance built-in—scoped access, auditability, and budget controls

One agent for your entire SDLC. Right inside Slack.

👉 Get started


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.

@JinHai-CN JinHai-CN added the ci Continue Integration label May 9, 2026
@JinHai-CN
JinHai-CN marked this pull request as ready for review May 9, 2026 08:47
@dosubot dosubot Bot added the size:XXL This PR changes 1000+ lines, ignoring generated files. label May 9, 2026

@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: 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 win

Map rerank scores back by Index before 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 than chunkCount items or the rerank call failed and rerankResponse is 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 win

Standardize command type spelling to rerank_user_document.

rarank_user_document works 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

📥 Commits

Reviewing files that changed from the base of the PR and between c11650b and 1dcb880.

📒 Files selected for processing (31)
  • conf/models/zhipu-ai.json
  • internal/cli/client.go
  • internal/cli/lexer.go
  • internal/cli/parser.go
  • internal/cli/types.go
  • internal/cli/user_command.go
  • internal/cli/user_parser.go
  • internal/common/float.go
  • internal/entity/models/aliyun.go
  • internal/entity/models/deepseek.go
  • internal/entity/models/dummy.go
  • internal/entity/models/gitee.go
  • internal/entity/models/google.go
  • internal/entity/models/huggingface.go
  • internal/entity/models/lmstudio.go
  • internal/entity/models/minimax.go
  • internal/entity/models/moonshot.go
  • internal/entity/models/nvidia.go
  • internal/entity/models/ollama.go
  • internal/entity/models/openai.go
  • internal/entity/models/openrouter.go
  • internal/entity/models/siliconflow.go
  • internal/entity/models/types.go
  • internal/entity/models/vllm.go
  • internal/entity/models/volcengine.go
  • internal/entity/models/xai.go
  • internal/entity/models/zhipu-ai.go
  • internal/handler/providers.go
  • internal/router/router.go
  • internal/service/model_service.go
  • internal/service/nlp/reranker.go

Comment on lines +1786 to +1788
if c.HTTPClient.APIToken == "" && c.HTTPClient.LoginToken == "" {
return nil, fmt.Errorf("API token not set. Please login first")
}

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

🧩 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/cli

Repository: 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.go

Repository: 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 -30

Repository: infiniflow/ragflow

Length of output: 3240


🏁 Script executed:

# Get complete AddCustomModel implementation
sed -n '2017,2087p' internal/cli/user_command.go

Repository: 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.

Comment on lines +2609 to +2611
if p.curToken.Type != TokenText {
return nil, fmt.Errorf("expected WITH after EMBED")
}

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 | 🟡 Minor | ⚡ Quick win

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

Comment on lines +2650 to +2657
p.nextToken()

cmd := NewCommand("embed_user_text")
cmd.Params["composite_model_name"] = compositeModelName
cmd.Params["texts"] = texts
cmd.Params["dimension"] = dimension
return cmd, 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

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.

Comment thread internal/common/float.go
Comment on lines +22 to +30
func Float64IsZero(f float64) bool {
if f < 0 && f >= -epsilon64 {
return true
}
if f > 0 && f <= epsilon64 {
return true
}
return false
}

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

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.

Comment thread internal/common/float.go
Comment on lines +32 to +40
func Float32IsNotZero(f float32) bool {
if f < 0 && f >= -epsilon32 {
return true
}
if f > 0 && f <= epsilon32 {
return true
}
return false
}

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

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.

Suggested change
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
}
Suggested change
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.

Comment on lines +917 to +950
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,
}

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

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.

Comment on lines +1018 to +1027
userID := c.GetString("user_id")

apiConfig := models.APIConfig{
ApiKey: nil,
Region: nil,
}

rerankConfig := models.RerankConfig{
TopN: req.TopN,
}

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

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.

Comment on lines +942 to +953
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 = &region
apiConfig.ApiKey = &instance.APIKey

var embeddingList [][]float64
embeddingList, err = providerInfo.ModelDriver.Encode(&modelName, texts, apiConfig, modelConfig)

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

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 = &region
 		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.

Comment on lines +992 to +999
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 {

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

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.

Comment on lines +1068 to +1069
if !model.ModelTypeMap["rerank"] {
return nil, common.CodeNotFound, errors.New(fmt.Sprintf("provider %s model %s is not an embedding model", providerName, 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 | 🟡 Minor | ⚡ Quick win

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

codecov Bot commented May 9, 2026

Copy link
Copy Markdown

Codecov Report

✅ All modified and coverable lines are covered by tests.
✅ Project coverage is 94.16%. Comparing base (c11650b) to head (1dcb880).

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.
📢 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 17d71e5 into infiniflow:main May 9, 2026
1 check passed
pandadev66 added a commit to pandadev66/ragflow that referenced this pull request May 9, 2026
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.
pandadev66 added a commit to pandadev66/ragflow that referenced this pull request May 9, 2026
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.
JinHai-CN pushed a commit that referenced this pull request May 13, 2026
### 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)
JinHai-CN added a commit that referenced this pull request May 18, 2026
### 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]>
@coderabbitai coderabbitai Bot mentioned this pull request May 20, 2026
6 tasks done
JinHai-CN pushed a commit that referenced this pull request May 20, 2026
### 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)
@coderabbitai coderabbitai Bot mentioned this pull request May 25, 2026
2 tasks done
Ricardo-M-L pushed a commit to Ricardo-M-L/ragflow that referenced this pull request Aug 17, 2026
### 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]>
Ricardo-M-L pushed a commit to Ricardo-M-L/ragflow that referenced this pull request Aug 17, 2026
…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)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

ci Continue Integration size:XXL This PR changes 1000+ lines, ignoring generated files.

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant