Skip to content

Feat: openrouter embedding - #17213

Merged
wangq8 merged 3 commits into
infiniflow:mainfrom
Lynn-Inf:feat/openrouter-embedding
Jul 22, 2026
Merged

wangq8 merged 3 commits into
infiniflow:mainfrom
Lynn-Inf:feat/openrouter-embedding

Conversation

@Lynn-Inf

Copy link
Copy Markdown
Contributor

Summary

Support OpenRouter embedding model.

@Lynn-Inf
Lynn-Inf requested a review from wangq8 July 22, 2026 03:21
@dosubot dosubot Bot added the size:S This PR changes 10-29 lines, ignoring generated files. label Jul 22, 2026
@Lynn-Inf Lynn-Inf added the ci Continue Integration label Jul 22, 2026
@coderabbitai

coderabbitai Bot commented Jul 22, 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: 8fa27e8a-763e-4db6-a7d9-5b36a9da3772

📥 Commits

Reviewing files that changed from the base of the PR and between 2d65060 and 92e4579.

📒 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

Adds an OpenRouterEmbed provider that initializes an OpenAI-compatible client, submits batched embedding requests, truncates inputs to 8191 tokens, and returns vectors with aggregated token counts.

Changes

OpenRouter embedding support

Layer / File(s) Summary
OpenRouter provider implementation
rag/llm/embedding_model.py
Adds OpenRouterEmbed with normalized client configuration, JSON API-key extraction, OpenRouter embedding requests, batched encoding, 8191-token truncation, and query encoding.

Estimated code review effort: 2 (Simple) | ~10 minutes

Poem

A rabbit hops through vectors bright,
OpenRouter brings embeddings to light.
Batches march in a tidy queue,
Truncated tokens keep limits true.
“Hop!” says Bun, “the model’s new!”

🚥 Pre-merge checks | ✅ 4 | ❌ 1

❌ Failed checks (1 warning)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 0.00% which is insufficient. The required threshold is 80.00%. Write docstrings for the functions missing them to satisfy the coverage threshold.
✅ Passed checks (4 passed)
Check name Status Explanation
Title check ✅ Passed The title clearly matches the main change: adding OpenRouter embedding support.
Description check ✅ Passed The description includes the required Summary section and states the PR's purpose, though it is brief.
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.

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.

@dosubot dosubot Bot added the 💞 feature Feature request, pull request that fullfill a new feature. label Jul 22, 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 (2)
rag/llm/embedding_model.py (2)

1328-1352: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick win

Add logging for the new provider flow.

Add debug-level logs for provider/model initialization and batch requests, excluding API keys and input text. The shared helper logs failures, but this new provider currently provides no flow-level diagnostics.

As per coding guidelines, **/*.py: Add logging for new flows.

🤖 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 `@rag/llm/embedding_model.py` around lines 1328 - 1352, Add debug-level logging
in OpenRouterEmbed.__init__ for provider/model initialization and in _call for
each batch request, including only non-sensitive metadata such as model name,
batch size, and base URL; never log API keys or input text. Keep the existing
embedding behavior and shared failure logging unchanged.

Source: Coding guidelines


1344-1345: 🎯 Functional Correctness | 🔵 Trivial | ⚡ Quick win

Remove drop_params from the request body.

OpenAI’s extra_body option adds JSON properties to the wire request; it does not configure client-side parameter filtering. This therefore sends drop_params to OpenRouter on every request, although it is not documented as an embeddings request field. (github.com)

🤖 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 `@rag/llm/embedding_model.py` around lines 1344 - 1345, Remove the extra_body
argument containing drop_params from the embeddings request in the
client.embeddings.create call, leaving the input, model, and encoding_format
parameters unchanged.
🤖 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 1335-1345: Store the parsed provider_order in the embedding model
instance during initialization, then update _call to include provider: {"order":
provider_order} in extra_body when a provider order is present. Preserve the
existing drop_params behavior and omit the provider field when no order was
supplied.
- Around line 1335-1339: Update the key parsing logic in the surrounding
embedding-model flow to call json.loads(key) once, verify the decoded value is a
dict before accessing api_key or provider_order, and otherwise fall back to the
raw key without allowing AttributeError. Preserve both extracted values for
dictionary payloads.
- Around line 1340-1348: Update _call, used by encode and the async
_bind_embedding_model flow, so the synchronous self.client.embeddings.create
invocation cannot block the event loop; offload the embedding request to a
worker thread using the project’s existing async/threading mechanism, or use an
AsyncOpenAI client while preserving response ordering and token-count handling.
- Around line 1347-1351: Update encode and encode_queries to derive truncate_to
from the selected OpenRouter model’s metadata or an existing configurable
input-limit setting instead of hardcoding 8191; pass that model-specific limit
to _batched_encode while preserving the current batching behavior.

---

Nitpick comments:
In `@rag/llm/embedding_model.py`:
- Around line 1328-1352: Add debug-level logging in OpenRouterEmbed.__init__ for
provider/model initialization and in _call for each batch request, including
only non-sensitive metadata such as model name, batch size, and base URL; never
log API keys or input text. Keep the existing embedding behavior and shared
failure logging unchanged.
- Around line 1344-1345: Remove the extra_body argument containing drop_params
from the embeddings request in the client.embeddings.create call, leaving the
input, model, and encoding_format parameters unchanged.
🪄 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: 9669a2fb-f388-4aa2-bc0f-14325bdc13d7

📥 Commits

Reviewing files that changed from the base of the PR and between b175ed5 and 2d65060.

📒 Files selected for processing (1)
  • rag/llm/embedding_model.py

Comment thread rag/llm/embedding_model.py Resolved
Comment thread rag/llm/embedding_model.py Resolved
Comment on lines +1340 to +1348
self.client = OpenAI(api_key=api_key, base_url=self.base_url)
self.model_name = model_name

def _call(self, batch):
res = self.client.embeddings.create(input=batch, model=self.model_name, encoding_format="float", extra_body={"drop_params": True})
return [d.embedding for d in _sorted_by_index(res.data)], total_token_count_from_response(res)

def encode(self, texts: list):
return self._batched_encode(texts, self._call, batch_size=16, truncate_to=8191)

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.

🚀 Performance & Scalability | 🟡 Minor | ⚡ Quick win

🧩 Analysis chain

🏁 Script executed:

#!/bin/bash
rg -nP '\b(OpenRouterEmbed|\.encode_queries?\s*\()' --glob '*.py'

Repository: infiniflow/ragflow

Length of output: 156


🏁 Script executed:

#!/bin/bash
set -euo pipefail

# Map the relevant file first
ast-grep outline rag/llm/embedding_model.py --view expanded

# Inspect the surrounding implementation
sed -n '1280,1385p' rag/llm/embedding_model.py

# Find direct callers of the embedding model encode path
rg -n --glob '*.py' '\.encode\(' rag

# Find where this model is instantiated/used
rg -n --glob '*.py' 'embedding_model|EmbeddingModel|OpenAI\(' rag

Repository: infiniflow/ragflow

Length of output: 37596


🏁 Script executed:

#!/bin/bash
set -euo pipefail

# Inspect the async callers that invoke encode directly
sed -n '300,345p' rag/svr/task_executor_refactor/task_handler.py
printf '\n---\n'
sed -n '80,130p' rag/svr/task_executor_refactor/embedding_service.py
printf '\n---\n'
sed -n '250,300p' rag/svr/task_executor_refactor/dataflow_service.py
printf '\n---\n'
sed -n '80,115p' rag/flow/tokenizer/tokenizer.py
printf '\n---\n'
sed -n '95,115p' rag/flow/compiler/compiler.py

Repository: infiniflow/ragflow

Length of output: 8567


Avoid the sync embeddings call on async paths. self.client.embeddings.create(...) can block the event loop when encode() is reached from async task flow (_bind_embedding_model()); offload it to a worker thread or switch this path to AsyncOpenAI.

🤖 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 `@rag/llm/embedding_model.py` around lines 1340 - 1348, Update _call, used by
encode and the async _bind_embedding_model flow, so the synchronous
self.client.embeddings.create invocation cannot block the event loop; offload
the embedding request to a worker thread using the project’s existing
async/threading mechanism, or use an AsyncOpenAI client while preserving
response ordering and token-count handling.

Source: Coding guidelines

Comment on lines +1347 to +1351
def encode(self, texts: list):
return self._batched_encode(texts, self._call, batch_size=16, truncate_to=8191)

def encode_queries(self, text):
vectors, token_count = self._batched_encode([text], self._call, batch_size=16, truncate_to=8191)

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.

🎯 Functional Correctness | 🟠 Major | 🏗️ Heavy lift

🧩 Analysis chain

🏁 Script executed:

#!/bin/bash
set -euo pipefail

# Map the target file and nearby symbols
ast-grep outline rag/llm/embedding_model.py --view expanded || true

# Show relevant lines around the reported section
sed -n '1280,1385p' rag/llm/embedding_model.py

# Search for truncation limits, model_name usage, and embedding-related config
rg -n "truncate_to|model_name|max input|max_length|max tokens|embedding" rag/llm -g '!**/__pycache__/**'

Repository: infiniflow/ragflow

Length of output: 50374


🏁 Script executed:

#!/bin/bash
set -euo pipefail

# Inspect the base batching helper and OpenRouter-specific implementation.
sed -n '145,220p' rag/llm/embedding_model.py
sed -n '1328,1360p' rag/llm/embedding_model.py

# Check whether OpenRouter model metadata or token limits are defined elsewhere in the codebase.
rg -n "OpenRouter|8191|8192|max_tokens|max_len|max_len|context length|context_length|truncate_to" rag/llm -g '!**/__pycache__/**'

Repository: infiniflow/ragflow

Length of output: 13089


🌐 Web query:

OpenRouter embeddings model max input length varies by model documentation 8191 truncation

💡 Result:

The maximum input length for embedding models on OpenRouter varies significantly by model, as OpenRouter acts as a gateway to models from various providers [1][2]. There is no universal maximum input length or automatic truncation behavior across all models [3]. Key points regarding embedding model limits: - Model-Specific Limits: Each model has its own defined context window [1][4]. For example, many models derived from the OpenAI ecosystem (such as text-embedding-3-small or text-embedding-3-large) typically support up to 8,191 tokens [3][5][6]. In contrast, other models may have significantly smaller limits (e.g., some Cohere models support 512 tokens) or larger ones [3][6]. - Checking Specifications: Users should verify the specific context length for any model they intend to use [1][3]. This information can be retrieved programmatically by querying the OpenRouter models list API, which returns a context_length property for each model [1][4][7]. - Truncation and Handling: OpenRouter documentation states that texts exceeding a model's maximum input length will either be truncated or rejected [1][4]. Because behavior can differ between models, it is recommended practice to handle chunking or truncation on the client side before sending the request to ensure consistency and avoid errors [1][2].

Citations:


🏁 Script executed:

#!/bin/bash
set -euo pipefail

# Inspect OpenRouter model metadata handling to see whether max_tokens is already surfaced.
sed -n '317,410p' rag/llm/model_meta.py

Repository: infiniflow/ragflow

Length of output: 3572


Use the selected OpenRouter model’s input limit.
This path truncates every request to 8191 tokens, but OpenRouter embedding models have different context windows. Pull the limit from the selected model’s metadata or make it configurable to avoid rejected or needlessly clipped inputs.

🤖 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 `@rag/llm/embedding_model.py` around lines 1347 - 1351, Update encode and
encode_queries to derive truncate_to from the selected OpenRouter model’s
metadata or an existing configurable input-limit setting instead of hardcoding
8191; pass that model-specific limit to _batched_encode while preserving the
current batching behavior.

@wangq8 wangq8 left a comment

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Thanks for adding OpenRouter embedding support.

The implementation follows the established patterns closely (OpenAIEmbed, ZhipuEmbed), and auto-registration via _FACTORY_NAME will work correctly.

A few observations:

  1. JSON key parsing — Handling both {api_key, provider_order} format and plain string keys is consistent with how chat models handle OpenRouter credentials. Nice.

  2. extra_body={"drop_params": True} — Good call; this prevents OpenRouter from rejecting unknown parameters that the OpenAI client may send.

  3. Error handling — The _call method does not wrap the API call with _raise_model_exception_if_failed or similar explicit error handling as some other embedding models do. Relying on the OpenAI client to raise exceptions is generally fine, but you may want to verify that OpenRouter error responses (e.g., 402 for billing, 429 for rate limits) surface a clear enough message to the user through the existing embedding error flow.

Otherwise LGTM.

@dosubot dosubot Bot added size:M This PR changes 30-99 lines, ignoring generated files. and removed size:S This PR changes 10-29 lines, ignoring generated files. labels Jul 22, 2026
@Lynn-Inf Lynn-Inf added ci Continue Integration and removed ci Continue Integration labels Jul 22, 2026
@wangq8
wangq8 merged commit fc7d4bd into infiniflow:main Jul 22, 2026
6 of 9 checks passed
@codecov

codecov Bot commented Jul 22, 2026

Copy link
Copy Markdown

Codecov Report

✅ All modified and coverable lines are covered by tests.
✅ Project coverage is 90.65%. Comparing base (6a85d1c) to head (92e4579).
⚠️ Report is 14 commits behind head on main.

Additional details and impacted files
@@            Coverage Diff             @@
##             main   #17213      +/-   ##
==========================================
- Coverage   94.56%   90.65%   -3.91%     
==========================================
  Files          10       10              
  Lines         717      717              
  Branches      118      118              
==========================================
- Hits          678      650      -28     
- Misses         25       39      +14     
- Partials       14       28      +14     

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

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

ci Continue Integration 💞 feature Feature request, pull request that fullfill a new feature. size:M This PR changes 30-99 lines, ignoring generated files.

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants