Repository navigation
Go: refactor embedding interface - #14757
Conversation
Signed-off-by: Jin Hai <[email protected]>
Signed-off-by: Jin Hai <[email protected]>
📝 WalkthroughWalkthroughThis PR replaces embedding APIs across model drivers and consumers by renaming ChangesEmbedding API Refactoring
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 }
Estimated code review effort🎯 4 (Complex) | ⏱️ ~60 minutes Possibly related PRs
Suggested labels
Suggested reviewers
Poem
🚥 Pre-merge checks | ✅ 5✅ Passed checks (5 passed)
✏️ Tip: You can configure your own custom pre-merge checks in the settings. Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out. Comment |
There was a problem hiding this comment.
Actionable comments posted: 4
🧹 Nitpick comments (1)
internal/service/skill_indexer.go (1)
241-324: 💤 Low valueConsider mapping by
EmbeddingData.Indexinstead of slice position.
vectors[i].Embeddingassumes the driver returned items in the same order asvectorTexts. TheIndexfield 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
⛔ Files ignored due to path filters (1)
uv.lockis excluded by!**/*.lock
📒 Files selected for processing (27)
internal/cli/response.gointernal/cli/user_command.gointernal/entity/models/aliyun.gointernal/entity/models/baidu.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/service/model_service.gointernal/service/nlp/retrieval.gointernal/service/skill_indexer.gointernal/service/skill_search.go
| 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"` | ||
| } |
There was a problem hiding this comment.
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.
| 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.
| if len(texts) > siliconflowMaxBatchSize { | ||
| return nil, fmt.Errorf("siliconflow supports a maximum of %d inputs per request", siliconflowMaxBatchSize) | ||
| } |
There was a problem hiding this comment.
🧩 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.goRepository: 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.goRepository: 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.goRepository: 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.goRepository: 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 -5Repository: 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 -30Repository: 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/ -iRepository: 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 -20Repository: 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 -40Repository: infiniflow/ragflow
Length of output: 2642
🏁 Script executed:
# Get the full SILICONFLOWEmbed implementation in Python
sed -n '796,850p' ./rag/llm/embedding_model.pyRepository: 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.
| reqBody := map[string]interface{}{} | ||
| reqBody["model"] = modelName | ||
| reqBody["input"] = texts | ||
| if embeddingConfig.Dimension > 0 { | ||
| reqBody["dimensions"] = embeddingConfig.Dimension | ||
| } |
There was a problem hiding this comment.
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.
| 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.
Signed-off-by: Jin Hai <[email protected]>
There was a problem hiding this comment.
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 winIncompatible 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 intoopenaiEmbeddingResponsewill fail to parse the response correctly.Additionally,
conf/models/huggingface.jsonspecifies the base URL ashttps://router.huggingface.co/v1/, yet the code hardcodes a different endpoint instead of building fromh.BaseURL[region](the pattern used elsewhere in ChatWithMessages and other methods).Use the OpenAI-compatible
/v1/embeddingsendpoint from the configured base URL, or update the hardcoded path to match the configured/v1/endpoint and ensure the response format aligns withopenaiEmbeddingResponse.🤖 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 winInconsistent: hardcoded URL instead of
h.BaseURL[region].Other methods on this driver (
ChatWithMessages,ChatStreamlyWithSender,ListModels) resolve the endpoint fromh.BaseURL[region], allowing per-region/self-hosted overrides via configuration.Embedbypasses that and hardcodeshttps://router.huggingface.co/hf-inference/models/..., so any user-configuredBaseURLfor HuggingFace is ignored on embeddings only. Consider routing through the sameBaseURL/URLSuffixconfig (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
📒 Files selected for processing (1)
internal/entity/models/huggingface.go
Codecov Report✅ All modified and coverable lines are covered by tests. 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. 🚀 New features to boost your workflow:
|
### 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]>
What problem does this PR solve?
Provide embedding index according to the input text
Type of change