Repository navigation
fix(llm): correct error handling, token accounting, and truncation in embedding providers - #15424
Conversation
|
No actionable comments were generated in the recent review. 🎉 ℹ️ Recent review info⚙️ Run configurationConfiguration used: Organization UI Review profile: CHILL Plan: Pro Run ID: 📒 Files selected for processing (1)
🚧 Files skipped from review as they are similar to previous changes (1)
📝 WalkthroughWalkthroughThe PR standardizes embedding provider error handling, batching, token counting, and truncation limits. It introduces shared infrastructure ( ChangesEmbedding provider standardization
Sequence Diagram(s)sequenceDiagram
participant Client as Client code
participant Embed as Provider.encode()
participant Batch as Base._batched_encode()
participant Call as Provider._call()
participant API as Embedding API
Client->>Embed: texts, batch_size
Embed->>Batch: texts, call_fn, batch_size, truncate_to
loop For each batch in texts
Batch->>Call: batch (truncated if needed)
Call->>API: HTTP request or SDK call
alt Provider returns success
API-->>Call: embedding indices + vectors + usage
Call-->>Batch: sorted_embeddings, token_count
else Provider returns error or malformed JSON
API-->>Call: error response or invalid JSON
Call->>Call: raise EmbeddingError with response payload
Call-->>Batch: exception
Batch->>Batch: wrap in EmbeddingError if needed
Batch-->>Embed: exception
Embed-->>Client: EmbeddingError
end
end
Batch->>Batch: concatenate vectors, sum token counts
Batch-->>Embed: np.ndarray, total_tokens
Embed-->>Client: embeddings, token_count
Estimated code review effort🎯 4 (Complex) | ⏱️ ~60 minutes Possibly related PRs
Suggested labels
Suggested reviewers
Poem
🚥 Pre-merge checks | ✅ 4 | ❌ 1❌ Failed checks (1 warning)
✅ Passed checks (4 passed)
✏️ Tip: You can configure your own custom pre-merge checks in the settings. Warning Review ran into problems🔥 ProblemsStopped waiting for pipeline failures after 30000ms. One of your pipelines takes longer than our 30000ms fetch window to run, so review may not consider pipeline-failure results for inline comments if any failures occurred after the fetch window. Increase the timeout if you want to wait longer or run a 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: 3
🤖 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 `@rag/llm/embedding_model.py`:
- Around line 773-789: NVIDIAEmbed currently hardcodes input_type="query" in
_call causing document embeddings to be treated as queries; change _call to
accept an input_type parameter (default "query") and use it in the payload, then
pass input_type="passage" from encode and input_type="query" from encode_queries
when calling _batched_encode; update the calls to _batched_encode in encode and
encode_queries to provide the bound _call with the appropriate input_type (or
wrap a small lambda/partial) so _openai_http_embeddings behavior remains
unchanged.
- Around line 648-672: BedrockEmbed is parsing Cohere-on-Bedrock responses using
model_response["embedding"] which raises KeyError because Cohere returns
"embeddings"; update parsing in BedrockEmbed.encode/_call and
BedrockEmbed.encode_queries to branch by provider: when self.is_cohere read
model_response["embeddings"][0] (or wrap as np.array where expected), otherwise
keep model_response["embedding"]; ensure returned types match existing contract
(list/np.array) and preserve token_count handling and exception behavior.
In `@test/unit_test/rag/llm/test_embedding_model.py`:
- Line 103: The test class TestDeterministicErrors lacks a pytest priority
marker; import pytest if missing and annotate the class or its individual test
functions with the appropriate priority marker (e.g., add `@pytest.mark.p1` above
class TestDeterministicErrors or above specific test_* methods) so the module
follows the p1/p2/p3 priority convention.
🪄 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: 196a25c6-dd40-4e18-860b-bf1825a5f9c1
📒 Files selected for processing (2)
rag/llm/embedding_model.pytest/unit_test/rag/llm/test_embedding_model.py
|
Hi, @JinHai-CN @Haruko386 |
|
Hi, @JinHai-CN @Haruko386 |
|
Hi @JinHai-CN can you check this PR? |
|
Remove unnecessary files from this PR, thanks~ |
|
@yingfeng |
Lynn-Inf
left a comment
There was a problem hiding this comment.
I’d rather not change the return type of VoyageEmbed.encode() to list without also updating the callers that rely on it (e.g., for empty-result checks). Let's keep the EmbeddingModel.encode() interface consistent across all implementations.
|
@Lynn-Inf |
|
LGTM |
Codecov Report✅ All modified and coverable lines are covered by tests. Additional details and impacted files@@ Coverage Diff @@
## main #15424 +/- ##
==========================================
- Coverage 94.56% 93.16% -1.40%
==========================================
Files 10 10
Lines 717 717
Branches 118 118
==========================================
- Hits 678 668 -10
- Misses 25 29 +4
- Partials 14 20 +6 ☔ View full report in Codecov by Harness. 🚀 New features to boost your workflow:
|
Summary
Closes #15423
rag/llm/embedding_model.pyhosts about 40 embedding providers that shared several defects affecting indexing reliability, cost accounting, and error visibility. This PR fixes four concrete bugs.Masked, inconsistent errors (27 sites). Nearly every provider ran
log_exception(_e, res)followed byraise Exception(f"Error: {res}"). Becauselog_exceptionalways raises, the second line was dead code, and the surfaced exception varied with whether the SDK response exposed a.textattribute. Every failure path now raises a singleEmbeddingErrorthat includes the underlying response detail, so the cause of a failed embedding is consistent and visible.Fabricated token counts.
LocalAIEmbedreturned a hardcoded1024andOllamaEmbedadded128per text. These values feedused_tokensand therefore billing and usage tracking. Both now report the real count from the API (Ollamaprompt_eval_count, LocalAIusage) and fall back to a local token count only when the server omits it.Truncation overshoot. The
8196limit used by Mistral and Bedrock exceeded the standard8192ceiling and could push boundary sized inputs past the model limit. Limits are corrected to8192and made intentional per provider, and providers that rely on server side truncation now request it explicitly (Ollamatruncate=True, Coheretruncate="END").Missing batching on Zhipu and Ollama. Both issued one request per text. They now batch like the other OpenAI compatible providers, turning N round trips into
ceil(N / batch_size). Batched results are realigned by responseindexso a chunk always keeps its own vector.A shared
Base._batched_encodehelper owns the batch loop, optional truncation, result accumulation, and the single error path. It is the mechanism that lets these fixes live in one place instead of across 27 duplicated sites. The publicencode()andencode_queries()contract stays the same, so existing callers are unaffected.Tests covering all four fixes are added under
test/unit_test/rag/llm/test_embedding_model.py.Type of change