Skip to content

Go: refactor embedding interface - #14757

Merged
JinHai-CN merged 6 commits into
infiniflow:mainfrom
JinHai-CN:fix424
May 11, 2026
Merged

JinHai-CN merged 6 commits into
infiniflow:mainfrom
JinHai-CN:fix424

Conversation

@JinHai-CN

Copy link
Copy Markdown
Member

What problem does this PR solve?

Provide embedding index according to the input text

Type of change

  • Refactoring

JinHai-CN added 2 commits May 10, 2026 23:30
Signed-off-by: Jin Hai <[email protected]>
@coderabbitai

coderabbitai Bot commented May 11, 2026 •

Copy link
Copy Markdown
Contributor

Review Change Stack

📝 Walkthrough

Walkthrough

This PR replaces embedding APIs across model drivers and consumers by renaming Encode(...) ([][]float64, error) to Embed(...) ([]EmbeddingData, error) and adding a typed EmbeddingData (vector + index). CLI, service orchestration, handlers, and index/search/retrieval consumers are updated to use the new shape.

Changes

Embedding API Refactoring

Layer / File(s) Summary
Type System & Interface
internal/entity/models/types.go
ModelDriver.Encode(...) → ModelDriver.Embed(...); adds EmbeddingData (Embedding []float64, Index int); removes EmbeddingResult/EmbeddingResponse.
CLI Response Types
internal/cli/response.go, internal/cli/user_command.go
Adds EmbeddingData and EmbeddingsResponse with PrintOut() rendering index and vector dimension; EmbedUserText decodes into EmbeddingsResponse.
Fully-Implemented Drivers
internal/entity/models/{aliyun,baidu,gitee,google,lmstudio,nvidia,ollama,openai,openrouter,siliconflow,vllm,volcengine,zhipu-ai}
Drivers parse provider responses into typed structs and return []EmbeddingData (Index + Embedding) instead of [][]float64; per-value coercion/index reordering removed.
Updated/Stub Drivers
internal/entity/models/{deepseek,dummy,huggingface,minimax,moonshot,xai}
Drivers add or replace Embed(...) ([]EmbeddingData, error) stubs (some unimplemented) replacing former Encode signatures.
Service Orchestration
internal/service/model_service.go, internal/handler/providers.go
ModelProviderService.EmbedText now returns []modelModule.EmbeddingData and calls ModelDriver.Embed; ProviderHandler.EmbedText returns the slice directly under data.
Consumer Services
internal/service/{skill_indexer,skill_search}.go, internal/service/nlp/retrieval.go
Consumers updated to call Embed and extract vectors from EmbeddingData.Embedding; dimension detection and batch indexing adjusted.

Sequence Diagram(s)

sequenceDiagram
  participant CLI
  participant Service as ModelProviderService
  participant Driver as ModelDriver
  participant ProviderAPI
  CLI->>Service: EmbedText request
  Service->>Driver: Embed(texts, model, config)
  Driver->>ProviderAPI: HTTP POST embeddings
  ProviderAPI-->>Driver: JSON { data: [{ embedding, index }, ...] }
  Driver-->>Service: []EmbeddingData
  Service-->>CLI: JSON { data: []EmbeddingData }
Loading

Estimated code review effort

🎯 4 (Complex) | ⏱️ ~60 minutes

Possibly related PRs

Suggested labels

size:XXL

Suggested reviewers

  • Haruko386

Poem

🐰 I reshaped vectors; each one now knows its place,
Indexes hop forward with tidy grace.
Drivers sing responses, typed and bright,
Embed takes the stage and does it right.
— a little rabbit, cheering in bytes.

🚥 Pre-merge checks | ✅ 5
✅ Passed checks (5 passed)
Check name Status Explanation
Title check ✅ Passed The title 'Go: refactor embedding interface' accurately summarizes the main change—refactoring the embedding interface across multiple model drivers and related code to return structured EmbeddingData instead of raw float matrices.
Description check ✅ Passed The PR description follows the template with both required sections: 'What problem does this PR solve?' (states providing embedding index per input text) and 'Type of change' (marks Refactoring as selected). However, the explanation of the problem is minimal and could be more detailed about the interface changes.
Docstring Coverage ✅ Passed No functions found in the changed files to evaluate docstring coverage. Skipping docstring coverage check.
Linked Issues check ✅ Passed Check skipped because no linked issues were found for this pull request.
Out of Scope Changes check ✅ Passed Check skipped because no linked issues were found for this pull request.

✏️ Tip: You can configure your own custom pre-merge checks in the settings.


Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ Share

Comment @coderabbitai help to get the list of available commands and usage tips.

@JinHai-CN JinHai-CN added the ci Continue Integration label May 11, 2026
@JinHai-CN
JinHai-CN marked this pull request as ready for review May 11, 2026 05:28
@dosubot dosubot Bot added the size:XXL This PR changes 1000+ lines, ignoring generated files. label May 11, 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: 4

🧹 Nitpick comments (1)
internal/service/skill_indexer.go (1)

241-324: 💤 Low value

Consider mapping by EmbeddingData.Index instead of slice position.

vectors[i].Embedding assumes the driver returned items in the same order as vectorTexts. The Index field was added to the embedding contract precisely so consumers don't have to rely on response ordering. With the current per-driver implementations in this PR ordering happens to match input order, but a future driver (or batched provider that parallelizes internally) could legitimately return items out of order and silently mis-associate vectors with skills.

♻️ Proposed refactor
 	// Generate embeddings in batch
 	common.Info(fmt.Sprintf("Generating embeddings for %d skills with embdID=%s", len(skills), embdID))
 	var vectors []models.EmbeddingData
 	vectors, err = s.generateEmbeddings(ctx, vectorTexts, embdID, tenantID)
 	if err != nil {
 		common.Warn(fmt.Sprintf("Failed to generate embeddings: %v. Continuing with text-only index.", err))
 		vectors = nil // Continue without vectors
 	} else {
 		common.Info(fmt.Sprintf("Generated %d vectors", len(vectors)))
 	}
+
+	// Build an index → embedding map so we don't depend on response order.
+	vectorByIndex := make(map[int][]float64, len(vectors))
+	for _, v := range vectors {
+		vectorByIndex[v.Index] = v.Embedding
+	}
@@
-		// Add vector only if available
-		if vectors != nil && i < len(vectors) {
-			doc[vectorField] = vectors[i].Embedding
-		} else {
+		// Add vector only if available
+		if emb, ok := vectorByIndex[i]; ok && len(emb) > 0 {
+			doc[vectorField] = emb
+		} else {
🤖 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/skill_indexer.go` around lines 241 - 324, The code
incorrectly assumes embeddings are returned in the same order as vectorTexts by
using vectors[i].Embedding; instead, after calling generateEmbeddings (and
before the skills loop) build a map from models.EmbeddingData.Index to the
embedding (e.g., map[int][]float64) using the EmbeddingData.Index field, then in
the skills loop look up embeddingMap[i] (or a presence check) to assign
doc[vectorField]; if missing, fall back to the existing text-only/log and
Infinity zero-vector logic; update references to vectors and any nil/length
checks accordingly so ordering is no longer relied on.
🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

Inline comments:
In `@internal/entity/models/huggingface.go`:
- Around line 360-414: The HuggingFaceModel.Embed method currently always
returns the error "no such method", disabling HF embeddings; replace that
placeholder with the restored embedding implementation: validate inputs
(non-empty texts, modelName and APIConfig.ApiKey present), build the JSON body
with "inputs": texts, POST to
fmt.Sprintf("https://router.huggingface.co/hf-inference/models/%s", *modelName)
using h.httpClient, set Content-Type and Authorization headers, read and check
resp.StatusCode, unmarshal the response into the expected embedding type and
convert/return as []EmbeddingData; remove the final hardcoded error return and
ensure errors are propagated from request/response/unmarshal failures.

In `@internal/entity/models/openai.go`:
- Around line 406-422: openaiEmbeddingResponse currently references OpenRouter
types (openrouterEmbeddingData, openrouterUsage) causing coupling; change its
fields to use the local OpenAI types by setting Data to []openaiEmbeddingData
and Usage to openaiUsage, and then update any other places that imported or
relied on the OpenRouter types (e.g., code paths for lmstudio.go and ollama.go)
to keep using their intended structs; ensure there are no remaining references
to openrouterEmbeddingData/openrouterUsage where OpenAI parsing is intended so
unmarshalling for OpenAI uses openaiEmbeddingData and openaiUsage exclusively.

In `@internal/entity/models/siliconflow.go`:
- Around line 399-401: The Go SiliconFlow driver currently returns an error when
len(texts) > siliconflowMaxBatchSize (siliconflowMaxBatchSize check in
siliconflow.go) which breaks callers that expect transparent chunking (e.g.,
BatchIndexSkills -> generateEmbeddings -> driver.Embed and model_service.go
callers). Reintroduce driver-side batching: in the Embed (or equivalent export)
implementation, loop over texts in slices of siliconflowMaxBatchSize (matching
Python's 16/32 behavior) and call the underlying request per chunk, aggregating
and returning embeddings in the original order; ensure
generateEmbeddings/BatchIndexSkills can pass full slices unchanged so callers
need not pre-chunk.

In `@internal/entity/models/zhipu-ai.go`:
- Around line 405-410: The code accesses embeddingConfig.Dimension without
guarding for nil, which can cause a panic; update the logic where reqBody is
built (the block that sets reqBody["model"], reqBody["input"], and
reqBody["dimensions"]) to first check embeddingConfig != nil and only then test
embeddingConfig.Dimension > 0 (e.g., if embeddingConfig != nil &&
embeddingConfig.Dimension > 0) before setting reqBody["dimensions"], ensuring
you reference the existing variables reqBody and embeddingConfig to locate the
fix.

---

Nitpick comments:
In `@internal/service/skill_indexer.go`:
- Around line 241-324: The code incorrectly assumes embeddings are returned in
the same order as vectorTexts by using vectors[i].Embedding; instead, after
calling generateEmbeddings (and before the skills loop) build a map from
models.EmbeddingData.Index to the embedding (e.g., map[int][]float64) using the
EmbeddingData.Index field, then in the skills loop look up embeddingMap[i] (or a
presence check) to assign doc[vectorField]; if missing, fall back to the
existing text-only/log and Infinity zero-vector logic; update references to
vectors and any nil/length checks accordingly so ordering is no longer relied
on.
🪄 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: 17e6e23e-19d4-4a6b-8ce7-7ff83ffa6078

📥 Commits

Reviewing files that changed from the base of the PR and between 46897d6 and 6b08f91.

⛔ Files ignored due to path filters (1)
  • uv.lock is excluded by !**/*.lock
📒 Files selected for processing (27)
  • internal/cli/response.go
  • internal/cli/user_command.go
  • internal/entity/models/aliyun.go
  • internal/entity/models/baidu.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/service/model_service.go
  • internal/service/nlp/retrieval.go
  • internal/service/skill_indexer.go
  • internal/service/skill_search.go

Comment thread internal/entity/models/huggingface.go Resolved
Comment on lines 406 to +422
type openaiEmbeddingResponse struct {
Data []struct {
Index int `json:"index"`
Embedding []interface{} `json:"embedding"`
} `json:"data"`
Data []openrouterEmbeddingData `json:"data"`
Model string `json:"model"`
Object string `json:"object"`
Usage openrouterUsage `json:"usage"`
}

// Encode turns a list of texts into embedding vectors using the
type openaiEmbeddingData struct {
Embedding []float64 `json:"embedding"`
Object string `json:"object"`
Index int `json:"index"`
}

type openaiUsage struct {
PromptTokens int `json:"prompt_tokens"`
TotalTokens int `json:"total_tokens"`
}

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

Type mismatch: openaiEmbeddingResponse references OpenRouter types, leaving the new openaiEmbeddingData/openaiUsage types unused.

openaiEmbeddingResponse.Data and .Usage are declared as []openrouterEmbeddingData and openrouterUsage, while the matching openaiEmbeddingData and openaiUsage types added right below are never referenced. Today both struct families have identical fields so unmarshaling still works, but this couples the OpenAI driver to OpenRouter's struct definitions — any future change to the OpenRouter shape silently alters OpenAI parsing. The same struct is also reused by lmstudio.go (line 430) and ollama.go (line 428), so they inherit the coupling. Fix this at the source.

🛠️ Proposed fix
 type openaiEmbeddingResponse struct {
-	Data   []openrouterEmbeddingData `json:"data"`
-	Model  string                    `json:"model"`
-	Object string                    `json:"object"`
-	Usage  openrouterUsage           `json:"usage"`
+	Data   []openaiEmbeddingData `json:"data"`
+	Model  string                `json:"model"`
+	Object string                `json:"object"`
+	Usage  openaiUsage           `json:"usage"`
 }
📝 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
type openaiEmbeddingResponse struct {
Data []struct {
Index int `json:"index"`
Embedding []interface{} `json:"embedding"`
} `json:"data"`
Data []openrouterEmbeddingData `json:"data"`
Model string `json:"model"`
Object string `json:"object"`
Usage openrouterUsage `json:"usage"`
}
// Encode turns a list of texts into embedding vectors using the
type openaiEmbeddingData struct {
Embedding []float64 `json:"embedding"`
Object string `json:"object"`
Index int `json:"index"`
}
type openaiUsage struct {
PromptTokens int `json:"prompt_tokens"`
TotalTokens int `json:"total_tokens"`
}
type openaiEmbeddingResponse struct {
Data []openaiEmbeddingData `json:"data"`
Model string `json:"model"`
Object string `json:"object"`
Usage openaiUsage `json:"usage"`
}
type openaiEmbeddingData struct {
Embedding []float64 `json:"embedding"`
Object string `json:"object"`
Index int `json:"index"`
}
type openaiUsage struct {
PromptTokens int `json:"prompt_tokens"`
TotalTokens int `json:"total_tokens"`
}
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@internal/entity/models/openai.go` around lines 406 - 422,
openaiEmbeddingResponse currently references OpenRouter types
(openrouterEmbeddingData, openrouterUsage) causing coupling; change its fields
to use the local OpenAI types by setting Data to []openaiEmbeddingData and Usage
to openaiUsage, and then update any other places that imported or relied on the
OpenRouter types (e.g., code paths for lmstudio.go and ollama.go) to keep using
their intended structs; ensure there are no remaining references to
openrouterEmbeddingData/openrouterUsage where OpenAI parsing is intended so
unmarshalling for OpenAI uses openaiEmbeddingData and openaiUsage exclusively.

Comment on lines +399 to 401
if len(texts) > siliconflowMaxBatchSize {
return nil, fmt.Errorf("siliconflow supports a maximum of %d inputs per request", siliconflowMaxBatchSize)
}

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 | 🏗️ Heavy lift

🧩 Analysis chain

🏁 Script executed:

#!/bin/bash
# Locate callers of the Embed driver method and inspect whether they batch inputs
# before invoking the driver (especially for siliconflow's 32-item cap).

rg -nP --type=go -C4 '\.Embed\s*\(' -g '!**/*_test.go'

# Also check whether any caller is aware of siliconflowMaxBatchSize / per-provider limits.
rg -nP --type=go -C2 'MaxBatchSize|siliconflowMaxBatchSize|chunk|batch' -g 'internal/service/**' -g 'internal/handler/**'

Repository: infiniflow/ragflow

Length of output: 50374


🏁 Script executed:

# Check skill_indexer.go around the Embed call (line 982) for batch size validation
sed -n '940,1000p' internal/service/skill_indexer.go

# Search for any existing batch-size limits or chunking logic in the indexer
rg -n 'MaxBatchSize|siliconflowMaxBatchSize|chunk.*size|batch.*size' internal/service/skill_indexer.go

# Check model_service.go for batch validation before Embed calls
rg -n -B5 -A5 'ModelDriver.Embed' internal/service/model_service.go

Repository: infiniflow/ragflow

Length of output: 2731


🏁 Script executed:

# Find where generateEmbeddings is called and with what batch sizes
rg -n 'generateEmbeddings' internal/service/skill_indexer.go -B3 -A3

# Check BatchIndexSkills and how many skills it processes
rg -n -A20 'func.*BatchIndexSkills' internal/service/skill_indexer.go | head -40

# Search for any old chunking or batch-limit logic
rg -n 'chunk.*batch|batch.*chunk|split.*embed|for.*siliconflow' internal/service/

Repository: infiniflow/ragflow

Length of output: 1825


🏁 Script executed:

# Find where BatchIndexSkills is called and with what batch sizes
rg -n 'BatchIndexSkills' internal/service/ -B2 -A2

# Check the value of siliconflowMaxBatchSize in the driver
rg -n 'siliconflowMaxBatchSize\s*=' internal/entity/models/siliconflow.go

# Search for any old chunking patterns or comments about batch limits
rg -n 'chunk.*embed|split.*embed|batch.*limit' internal/service/skill_indexer.go

# Check if there's any pre-filtering or batch limiting logic before Embed calls
rg -n -B10 'generateEmbeddings' internal/service/skill_indexer.go | grep -A10 'BatchIndexSkills'

Repository: infiniflow/ragflow

Length of output: 1227


🏁 Script executed:

# Check if there's any old Encode method or chunking logic in git history or comments
rg -n 'Encode|chunk' internal/entity/models/siliconflow.go | head -20

# Look at the full siliconflow.go file to understand the structure
wc -l internal/entity/models/siliconflow.go

# Check for any loop or chunking patterns in the new Embed method
sed -n '380,420p' internal/entity/models/siliconflow.go

Repository: infiniflow/ragflow

Length of output: 1494


🏁 Script executed:

# Search for any old Encode method or chunking implementation
rg -n 'func.*Encode' internal/entity/models/siliconflow.go

# Check if there's a loop that chunks in the current file
rg -n 'for.*i.*:=' internal/entity/models/siliconflow.go

# Look for any comments about old behavior or previous implementation
rg -n -i 'previous|old|before|chunk|split' internal/entity/models/siliconflow.go

# Check git log to see what changed
git log --oneline -n 20 -- internal/entity/models/siliconflow.go 2>/dev/null || echo "Git history not available"

# Look at what other embedding providers do (e.g., OpenAI)
rg -n -A15 'func.*OpenAI.*Embed' internal/entity/models/

Repository: infiniflow/ragflow

Length of output: 1415


🏁 Script executed:

# Get the full OpenAI Embed implementation to see if it chunks
sed -n '428,500p' internal/entity/models/openai.go

# Check other embedding providers for batch handling patterns
rg -n -A30 'func.*Embed.*texts.*string' internal/entity/models/ | grep -A30 'openai\|coze\|ollama' | head -50

# Search for any MaxBatchSize constants across all drivers
rg -n 'MaxBatchSize|maxBatch' internal/entity/models/

Repository: infiniflow/ragflow

Length of output: 5858


🏁 Script executed:

# Check if there's an old Encode method or historical chunking in comments/docstrings
rg -n -B5 -A25 'func.*SiliconflowModel.*Encode' internal/entity/models/siliconflow.go

# Search for any chunking/splitting pattern in the entire siliconflow file
cat internal/entity/models/siliconflow.go | grep -n -i 'chunk\|split\|batch\|loop'

# Check if generateEmbeddings or BatchIndexSkills has any logic to limit batch size
sed -n '200,250p' internal/service/skill_indexer.go

# See the full generateEmbeddings to check for batch limiting
sed -n '949,1010p' internal/service/skill_indexer.go

Repository: infiniflow/ragflow

Length of output: 4640


🏁 Script executed:

# Check if BatchIndexSkills or callers validate against siliconflowMaxBatchSize
rg -n 'len(skills)\|len(texts)' internal/service/skill_indexer.go | head -15

# See if there's any pre-filtering or batching loop for embedding
rg -n -B5 -A5 'for.*range.*texts\|for.*i.*<.*len' internal/service/skill_indexer.go | head -30

# Check how many skills are typically indexed in a single call (look for callers of BatchIndexSkills)
rg -n -B10 'BatchIndexSkills.*skills' internal/service/skill_indexer.go | grep -E 'BatchIndexSkills|len\(|\.skills'

# Search for any Python equivalent or comments about chunking
rg -n -i 'python\|chunk.*batch\|batch.*chunk' internal/service/skill_indexer.go

Repository: infiniflow/ragflow

Length of output: 581


🏁 Script executed:

# Check for tests that might show typical batch sizes
find . -name '*skill*test*.go' -o -name '*test*skill*.go' | xargs grep -l 'BatchIndexSkills\|generateEmbeddings' 2>/dev/null

# Look for any loop-based chunking in the generate embeddings or related code
rg -n -A50 'func.*generateEmbeddings' internal/service/skill_indexer.go | grep -E 'for|chunk|batch|if.*len'

# Check model_service.go to see if it chunks before calling Embed
sed -n '930,1000p' internal/service/model_service.go

# Look for Python code that might handle chunking
find . -name '*.py' -path '*/embedding*' 2>/dev/null | head -5

Repository: infiniflow/ragflow

Length of output: 2418


🏁 Script executed:

# Check the Python embedding model to see if it has chunking logic
cat ./rag/llm/embedding_model.py | head -200

# Search for chunking or batch handling in Python embedding code
rg -n 'chunk|batch|split' ./rag/llm/embedding_model.py | head -30

Repository: infiniflow/ragflow

Length of output: 9518


🏁 Script executed:

# Search for SiliconFlow embedding implementation in Python
rg -n -A30 'class.*Silicon.*Embed\|_FACTORY_NAME.*Silicon' ./rag/llm/embedding_model.py

# Also check if there's a generic chunking mechanism or helper
rg -n 'SiliconFlow\|siliconflow' ./rag/llm/ -i

Repository: infiniflow/ragflow

Length of output: 44


🏁 Script executed:

# Search broadly for SiliconFlow in the entire repo
find . -type f \( -name '*.py' -o -name '*.go' \) -exec grep -l -i 'siliconflow' {} \;

# Check if there's a recent git history mentioning SiliconFlow
git log --all --oneline --grep -i 'siliconflow' 2>/dev/null | head -10

# Look for any batch-chunking patterns in other Go embedding drivers
rg -n 'Embed.*texts.*len' internal/entity/models/ -A10 | grep -E 'for|chunk|batch'

Repository: infiniflow/ragflow

Length of output: 343


🏁 Script executed:

# Search for SiliconFlow class in Python embedding models
rg -n 'Silicon' ./rag/llm/embedding_model.py -A20

# Check the factory to see how SiliconFlow is registered
rg -n -i 'silicon' ./internal/entity/models/factory.go -B2 -A5

# Look at the Python API app to see if chunking happens at API level
rg -n -i 'batch\|chunk.*embed' ./api/apps/llm_app.py | head -20

Repository: infiniflow/ragflow

Length of output: 377


🏁 Script executed:

# Check if SiliconFlow is in the Python embedding model at all
grep -n -i 'silicon' ./rag/llm/embedding_model.py

# Look at the entire embedding_model.py to see all supported providers
rg -n '_FACTORY_NAME.*=' ./rag/llm/embedding_model.py

# Check if there's a config or registration for SiliconFlow in Python
rg -n -i 'silicon' ./rag/llm/__init__.py -B2 -A2

# Search the entire codebase for old Encode method that might have chunked
git log -p -- internal/entity/models/siliconflow.go 2>/dev/null | grep -A20 'func.*Encode' | head -40

Repository: infiniflow/ragflow

Length of output: 2642


🏁 Script executed:

# Get the full SILICONFLOWEmbed implementation in Python
sed -n '796,850p' ./rag/llm/embedding_model.py

Repository: infiniflow/ragflow

Length of output: 2396


🏁 Script executed:

# Check if there's documentation about SiliconFlow API batch limits
rg -n 'docs.siliconflow\|batch.*32\|input.*limit' internal/entity/models/siliconflow.go

# See how many skills might be indexed at once
rg -n 'len(skills)' internal/service/skill_indexer.go -B5 | head -20

# Check if there are any limits in the caller or comments about expected batch sizes
rg -n 'TODO\|FIXME\|NOTE\|batch\|chunk' internal/service/skill_indexer.go | grep -i 'batch\|chunk\|limit'

Repository: infiniflow/ragflow

Length of output: 44


Behavior change confirmed: oversized batches now error instead of being chunked.

The Python implementation (./rag/llm/embedding_model.py, lines 796–850) chunks requests into batches of 16 before sending to the SiliconFlow API. The Go rewrite hard-rejects requests with more than 32 inputs with an error—no chunking loop.

This breaks transparent batching for callers. For example, BatchIndexSkills() in internal/service/skill_indexer.go builds vector texts for all input skills at once (line 242) and passes them directly to generateEmbeddings() (line 242), which then calls the driver's Embed() without pre-validating or chunking the batch. Similarly, model_service.go (lines 953, 987) passes texts directly without batch limiting.

Any caller that was relying on the driver to transparently chunk (as the Python version did) will now fail the first time it passes more than 32 texts—particularly during batch indexing/skill ingestion flows.

Confirm whether batch pre-validation/chunking has been moved to the caller side (e.g., skill_indexer.go), otherwise this is a regression requiring driver-side chunking to match Python's behavior.

🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@internal/entity/models/siliconflow.go` around lines 399 - 401, The Go
SiliconFlow driver currently returns an error when len(texts) >
siliconflowMaxBatchSize (siliconflowMaxBatchSize check in siliconflow.go) which
breaks callers that expect transparent chunking (e.g., BatchIndexSkills ->
generateEmbeddings -> driver.Embed and model_service.go callers). Reintroduce
driver-side batching: in the Embed (or equivalent export) implementation, loop
over texts in slices of siliconflowMaxBatchSize (matching Python's 16/32
behavior) and call the underlying request per chunk, aggregating and returning
embeddings in the original order; ensure generateEmbeddings/BatchIndexSkills can
pass full slices unchanged so callers need not pre-chunk.

Comment on lines +405 to +410
reqBody := map[string]interface{}{}
reqBody["model"] = modelName
reqBody["input"] = texts
if embeddingConfig.Dimension > 0 {
reqBody["dimensions"] = embeddingConfig.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 | 🔴 Critical | ⚡ Quick win

Nil-pointer panic risk when embeddingConfig is absent.

Line 408 accesses embeddingConfig.Dimension without checking embeddingConfig != nil, which can panic on valid nil-call paths.

🛠️ Suggested fix
 reqBody := map[string]interface{}{}
-reqBody["model"] = modelName
+reqBody["model"] = *modelName
 reqBody["input"] = texts
-if embeddingConfig.Dimension > 0 {
+if embeddingConfig != nil && embeddingConfig.Dimension > 0 {
 	reqBody["dimensions"] = embeddingConfig.Dimension
 }
📝 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
reqBody := map[string]interface{}{}
reqBody["model"] = modelName
reqBody["input"] = texts
if embeddingConfig.Dimension > 0 {
reqBody["dimensions"] = embeddingConfig.Dimension
}
reqBody := map[string]interface{}{}
reqBody["model"] = modelName
reqBody["input"] = texts
if embeddingConfig != nil && embeddingConfig.Dimension > 0 {
reqBody["dimensions"] = embeddingConfig.Dimension
}
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@internal/entity/models/zhipu-ai.go` around lines 405 - 410, The code accesses
embeddingConfig.Dimension without guarding for nil, which can cause a panic;
update the logic where reqBody is built (the block that sets reqBody["model"],
reqBody["input"], and reqBody["dimensions"]) to first check embeddingConfig !=
nil and only then test embeddingConfig.Dimension > 0 (e.g., if embeddingConfig
!= nil && embeddingConfig.Dimension > 0) before setting reqBody["dimensions"],
ensuring you reference the existing variables reqBody and embeddingConfig to
locate the fix.

@dosubot dosubot Bot added size:XL This PR changes 500-999 lines, ignoring generated files. and removed size:XXL This PR changes 1000+ lines, ignoring generated files. labels May 11, 2026
@JinHai-CN
JinHai-CN marked this pull request as draft May 11, 2026 05:44
@JinHai-CN
JinHai-CN marked this pull request as ready for review May 11, 2026 05:44

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

Caution

Some comments are outside the diff and can’t be posted inline due to platform limitations.

⚠️ Outside diff range comments (1)
internal/entity/models/huggingface.go (1)

376-414: ⚠️ Potential issue | 🟠 Major | ⚡ Quick win

Incompatible endpoint: hardcoded URL returns raw arrays, not OpenAI format.

The hardcoded URL https://router.huggingface.co/hf-inference/models/%s (HuggingFace feature-extraction task) returns a raw nested array format ([[0.1, 0.2, ...], ...]), not the OpenAI-compatible shape ({"data": [{"embedding": [...], "index": N}]}). Unmarshalling into openaiEmbeddingResponse will fail to parse the response correctly.

Additionally, conf/models/huggingface.json specifies the base URL as https://router.huggingface.co/v1/, yet the code hardcodes a different endpoint instead of building from h.BaseURL[region] (the pattern used elsewhere in ChatWithMessages and other methods).

Use the OpenAI-compatible /v1/embeddings endpoint from the configured base URL, or update the hardcoded path to match the configured /v1/ endpoint and ensure the response format aligns with openaiEmbeddingResponse.

🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@internal/entity/models/huggingface.go` around lines 376 - 414, The code is
calling the wrong HuggingFace endpoint and expecting OpenAI-shaped JSON; update
the request in the method producing embeddings to build the URL from the
configured base (use h.BaseURL[region] or h.BaseURL) and call the
OpenAI-compatible v1/embeddings path (e.g., "<base>/v1/embeddings") for the
modelName instead of the hardcoded
"https://router.huggingface.co/hf-inference/models/%s"; ensure the request body
matches the embeddings endpoint contract and keep the existing response
unmarshalling into openaiEmbeddingResponse (or adjust parsing if you
intentionally use the raw feature-extraction array format), and retain existing
headers using apiConfig.ApiKey and the same http client (h.httpClient).
🧹 Nitpick comments (1)
internal/entity/models/huggingface.go (1)

376-376: ⚡ Quick win

Inconsistent: hardcoded URL instead of h.BaseURL[region].

Other methods on this driver (ChatWithMessages, ChatStreamlyWithSender, ListModels) resolve the endpoint from h.BaseURL[region], allowing per-region/self-hosted overrides via configuration. Embed bypasses that and hardcodes https://router.huggingface.co/hf-inference/models/..., so any user-configured BaseURL for HuggingFace is ignored on embeddings only. Consider routing through the same BaseURL/URLSuffix config (and a region-aware lookup) as the chat path.

🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@internal/entity/models/huggingface.go` at line 376, The Embed method
currently hardcodes the HuggingFace router URL instead of using the configured
per-region/self-hosted endpoint; update the Embed implementation to build the
endpoint using h.BaseURL[region] (and append h.URLSuffix if applicable) the same
way ChatWithMessages, ChatStreamlyWithSender and ListModels do so that embedding
requests respect region overrides and self-hosted instances — perform a
region-aware lookup of h.BaseURL, fall back to the existing default if missing,
and replace the fmt.Sprintf("https://router.huggingface.co/...") call with the
composed base URL + model path.
🤖 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.

Outside diff comments:
In `@internal/entity/models/huggingface.go`:
- Around line 376-414: The code is calling the wrong HuggingFace endpoint and
expecting OpenAI-shaped JSON; update the request in the method producing
embeddings to build the URL from the configured base (use h.BaseURL[region] or
h.BaseURL) and call the OpenAI-compatible v1/embeddings path (e.g.,
"<base>/v1/embeddings") for the modelName instead of the hardcoded
"https://router.huggingface.co/hf-inference/models/%s"; ensure the request body
matches the embeddings endpoint contract and keep the existing response
unmarshalling into openaiEmbeddingResponse (or adjust parsing if you
intentionally use the raw feature-extraction array format), and retain existing
headers using apiConfig.ApiKey and the same http client (h.httpClient).

---

Nitpick comments:
In `@internal/entity/models/huggingface.go`:
- Line 376: The Embed method currently hardcodes the HuggingFace router URL
instead of using the configured per-region/self-hosted endpoint; update the
Embed implementation to build the endpoint using h.BaseURL[region] (and append
h.URLSuffix if applicable) the same way ChatWithMessages, ChatStreamlyWithSender
and ListModels do so that embedding requests respect region overrides and
self-hosted instances — perform a region-aware lookup of h.BaseURL, fall back to
the existing default if missing, and replace the
fmt.Sprintf("https://router.huggingface.co/...") call with the composed base URL
+ model path.

ℹ️ Review info
⚙️ Run configuration

Configuration used: Organization UI

Review profile: CHILL

Plan: Pro

Run ID: b370f285-f9bb-4f28-8f44-54a8ed2b11d5

📥 Commits

Reviewing files that changed from the base of the PR and between 6b08f91 and c36948e.

📒 Files selected for processing (1)
  • internal/entity/models/huggingface.go

@codecov

codecov Bot commented May 11, 2026

Copy link
Copy Markdown

Codecov Report

✅ All modified and coverable lines are covered by tests.
✅ Project coverage is 94.16%. Comparing base (46897d6) to head (c36948e).
⚠️ Report is 2 commits behind head on main.

Additional details and impacted files
@@           Coverage Diff           @@
##             main   #14757   +/-   ##
=======================================
  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 c55e23e into infiniflow:main May 11, 2026
1 of 2 checks passed
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?

Provide embedding index according to the input text

### Type of change

- [x] Refactoring

---------

Signed-off-by: Jin Hai <[email protected]>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

ci Continue Integration size:XL This PR changes 500-999 lines, ignoring generated files.

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant