Skip to content

fix(llm): correct error handling, token accounting, and truncation in embedding providers - #15424

Merged
yingfeng merged 5 commits into
infiniflow:mainfrom
Dexterity104:fix/embedding-provider-correctness
Jun 11, 2026
Merged

yingfeng merged 5 commits into
infiniflow:mainfrom
Dexterity104:fix/embedding-provider-correctness

Conversation

@Dexterity104

@Dexterity104 Dexterity104 commented May 29, 2026 •

Copy link
Copy Markdown
Contributor

Summary

Closes #15423

rag/llm/embedding_model.py hosts 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 by raise Exception(f"Error: {res}"). Because log_exception always raises, the second line was dead code, and the surfaced exception varied with whether the SDK response exposed a .text attribute. Every failure path now raises a single EmbeddingError that includes the underlying response detail, so the cause of a failed embedding is consistent and visible.

Fabricated token counts. LocalAIEmbed returned a hardcoded 1024 and OllamaEmbed added 128 per text. These values feed used_tokens and therefore billing and usage tracking. Both now report the real count from the API (Ollama prompt_eval_count, LocalAI usage) and fall back to a local token count only when the server omits it.

Truncation overshoot. The 8196 limit used by Mistral and Bedrock exceeded the standard 8192 ceiling and could push boundary sized inputs past the model limit. Limits are corrected to 8192 and made intentional per provider, and providers that rely on server side truncation now request it explicitly (Ollama truncate=True, Cohere truncate="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 response index so a chunk always keeps its own vector.

A shared Base._batched_encode helper 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 public encode() and encode_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

  • Bug Fix (non-breaking change which fixes an issue)

@dosubot dosubot Bot added size:XL This PR changes 500-999 lines, ignoring generated files. 🌈 python Pull requests that update Python code 🐞 bug Something isn't working, pull request that fix bug. 🧪 test Pull requests that update test cases. labels May 29, 2026
@coderabbitai

coderabbitai Bot commented May 29, 2026 •

Copy link
Copy Markdown
Contributor

Review Change Stack

No actionable comments were generated in the recent review. 🎉

ℹ️ Recent review info
⚙️ Run configuration

Configuration used: Organization UI

Review profile: CHILL

Plan: Pro

Run ID: 948c2cb2-c41f-42f6-aed9-44564865504e

📥 Commits

Reviewing files that changed from the base of the PR and between 76bf180 and 7301d75.

📒 Files selected for processing (1)
  • rag/llm/embedding_model.py
🚧 Files skipped from review as they are similar to previous changes (1)
  • rag/llm/embedding_model.py

📝 Walkthrough

Walkthrough

The PR standardizes embedding provider error handling, batching, token counting, and truncation limits. It introduces shared infrastructure (DEFAULT_MAX_TOKENS=8192, EmbeddingError, _batched_encode, _openai_http_embeddings) that multiple providers now use via provider-specific _call helpers. OpenAI-style, Zhipu, Ollama, Bedrock, and others now batch requests deterministically and surface real errors instead of masking them.

Changes

Embedding provider standardization

Layer / File(s) Summary
Shared batching infrastructure
rag/llm/embedding_model.py
DEFAULT_MAX_TOKENS=8192, EmbeddingError exception, _sorted_by_index() helper, Base._batched_encode() for iterative batching with optional per-text truncation, and Base._openai_http_embeddings() for parsing OpenAI-compatible responses with index-based realignment.
OpenAI-style and HTTP provider migration
rag/llm/embedding_model.py
OpenAIEmbed, LocalAIEmbed, XinferenceEmbed, NvidiaEmbed (with document/query input_type differentiation), and SILICONFLOWEmbed now use _batched_encode with per-provider _call helpers that sort responses by index and compute or fall back to local token counting.
Zhipu and Ollama batching
rag/llm/embedding_model.py
ZhipuEmbed adds model-specific _max_len() truncation ceiling and _call(batch) for per-batch requests; OllamaEmbed adds _strip_special() for token sanitization, _call(batch) with server-side truncation and prompt_eval_count token extraction with local fallback, eliminating the old fabricated +128 per-text constant.
Mistral, Bedrock, Jina, Gemini, Cohere refactors
rag/llm/embedding_model.py
MistralEmbed truncation switched to DEFAULT_MAX_TOKENS; BedrockEmbed adds _extract_vector() for Titan/Cohere response shapes, batch-size-1 _batched_encode, and error wrapping; JinaMultiVecEmbed normalizes string-vs-bytes inputs (bytes→base64 images); GeminiEmbed routes through _batched_encode with local token counting; CoHereEmbed uses _call(batch) with _batched_encode.
Error handling unification
rag/llm/embedding_model.py
QWenEmbed, BaiduYiyanEmbed, VoyageEmbed, HuggingFaceEmbed (now purely local token counting), VolcEngineEmbed, and PerplexityEmbed now log and raise deterministic EmbeddingError on failures, ensuring response payloads and parse exceptions reach the caller.
Comprehensive unit test suite
test/unit_test/rag/llm/test_embedding_model.py
Tests verify deterministic EmbeddingError for SDK exceptions, malformed payloads with/without .text attributes, HTTP non-2xx responses, and mismatched JSON shapes; verify token accounting uses provider-reported usage or local fallback (no fabricated constants); validate DEFAULT_MAX_TOKENS=8192 truncation boundary; test batching/alignment for Zhipu and Ollama with ceil(n/batch_size) request counts and output order preservation; verify realignment when providers return out-of-order embeddings; test Nvidia input_type differentiation and Bedrock Titan/Cohere response shape parsing.
Test infrastructure and tooling
test/unit_test/conftest.py, download_deps.py
conftest.py provisions NLTK datasets (punkt_tab, wordnet) from local nltk_data directory when available, downloading only missing resources; download_deps.py installs browser-like User-Agent header to urllib to avoid HTTP 403 rejections from mirrors during URL downloads.

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
Loading

Estimated code review effort

🎯 4 (Complex) | ⏱️ ~60 minutes

Possibly related PRs

  • infiniflow/ragflow#15346: Both PRs modify rag/llm/embedding_model.py to centralize provider HTTP failure handling and re-throw consistent exceptions during embedding encode/encode_queries, so this PR's embedding-error refactor builds on the retrieved PR's embedding error-message/exception improvements.

Suggested labels

☯️ refactor, size:L

Suggested reviewers

  • Haruko386

Poem

🐰 Embeddings now batch in harmony,
Errors sing true, no masquerade,
Eight thousand one-nine-two's the ceiling so free,
Token counts honest, no longer betrayed,
A rabbit rejoices in order and light! 🌟

🚥 Pre-merge checks | ✅ 4 | ❌ 1

❌ Failed checks (1 warning)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 7.69% 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 clearly and concisely summarizes the main changes: error handling, token accounting, and truncation fixes across embedding providers.
Description check ✅ Passed The PR description thoroughly addresses the template requirements with a detailed problem summary, specific examples of the four bugs fixed, and correctly marks the 'Bug Fix' type.
Linked Issues check ✅ Passed All four objectives from issue #15423 are met: consistent EmbeddingError handling across 27 sites, corrected token accounting for LocalAI and Ollama, truncation limits fixed to 8192, and batching added for ZhipuEmbed and OllamaEmbed.
Out of Scope Changes check ✅ Passed Changes to download_deps.py and test/unit_test/conftest.py are reasonable supporting infrastructure; the core embedding_model.py changes directly address issue #15423 without unrelated modifications.

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

Warning

Review ran into problems

🔥 Problems

Stopped 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 @coderabbit review after the pipeline has finished.


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.

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

📥 Commits

Reviewing files that changed from the base of the PR and between cd18cfa and 1cf81e7.

📒 Files selected for processing (2)
  • rag/llm/embedding_model.py
  • test/unit_test/rag/llm/test_embedding_model.py

Comment thread rag/llm/embedding_model.py Resolved
Comment thread rag/llm/embedding_model.py Resolved
@Dexterity104

Copy link
Copy Markdown
Contributor Author

Hi, @JinHai-CN @Haruko386
Could you please review this PR?

@Dexterity104

Copy link
Copy Markdown
Contributor Author

Hi, @JinHai-CN @Haruko386
Could you please review this PR?

@Dexterity104

Copy link
Copy Markdown
Contributor Author

Hi @JinHai-CN can you check this PR?

@yingfeng
yingfeng requested a review from Lynn-Inf June 4, 2026 10:03
@yingfeng

yingfeng commented Jun 4, 2026

Copy link
Copy Markdown
Member

Remove unnecessary files from this PR, thanks~

@Dexterity104

Copy link
Copy Markdown
Contributor Author

@yingfeng
I'm really sorry. I removed those unnecessary files.

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

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.

@Dexterity104

Dexterity104 commented Jun 5, 2026 •

Copy link
Copy Markdown
Contributor Author

@Lynn-Inf
Thanks for catching this! I can see how the diff reads that way, but VoyageEmbed.encode() still returns an np.ndarray. The list(...) was inside the per-batch _call helper, not the encode() return, which goes through Base._batched_encode and wraps everything in np.array(...) (empty input still returns an empty np.ndarray). I've dropped the redundant list() to avoid the confusion.

@Dexterity104

Copy link
Copy Markdown
Contributor Author

@Lynn-Inf @yingfeng
Could you please check this PR? Thanks!

@Lynn-Inf

Copy link
Copy Markdown
Contributor

LGTM

@yingfeng yingfeng added the ci Continue Integration label Jun 10, 2026
@yingfeng
yingfeng marked this pull request as draft June 10, 2026 02:07
@yingfeng
yingfeng marked this pull request as ready for review June 10, 2026 02:07
@codecov

codecov Bot commented Jun 10, 2026

Copy link
Copy Markdown

Codecov Report

✅ All modified and coverable lines are covered by tests.
✅ Project coverage is 93.16%. Comparing base (3aea80f) to head (7301d75).
⚠️ Report is 179 commits behind head on main.

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

@yingfeng
yingfeng merged commit bde2b1f into infiniflow:main Jun 11, 2026
2 checks passed
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

🐞 bug Something isn't working, pull request that fix bug. ci Continue Integration 🌈 python Pull requests that update Python code size:XL This PR changes 500-999 lines, ignoring generated files. 🧪 test Pull requests that update test cases.

Projects

None yet

Development

Successfully merging this pull request may close these issues.

Embedding providers mask real errors, report fabricated token counts, and overshoot the truncation limit

3 participants