Repository navigation
Feat: openrouter embedding - #17213
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)
📝 WalkthroughWalkthroughAdds an ChangesOpenRouter embedding support
Estimated code review effort: 2 (Simple) | ~10 minutes Poem
🚥 Pre-merge checks | ✅ 4 | ❌ 1❌ Failed checks (1 warning)
✅ Passed checks (4 passed)
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 (2)
rag/llm/embedding_model.py (2)
1328-1352: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick winAdd 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 winRemove
drop_paramsfrom the request body.OpenAI’s
extra_bodyoption adds JSON properties to the wire request; it does not configure client-side parameter filtering. This therefore sendsdrop_paramsto 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
📒 Files selected for processing (1)
rag/llm/embedding_model.py
| 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) |
There was a problem hiding this comment.
🚀 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\(' ragRepository: 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.pyRepository: 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
| 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) |
There was a problem hiding this comment.
🎯 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:
- 1: https://openrouter.ai/docs/api_reference/embeddings
- 2: https://openrouter.ai/docs/api/reference/embeddings
- 3: https://www.codewords.ai/blog/openrouter-embedding-models
- 4: https://openrouter.ai/docs/api/reference/embeddings.mdx
- 5: https://mastra.ai/models/embeddings
- 6: https://docs.uniterouter.ai/api-reference/openai/embeddings
- 7: https://openrouter.ai/docs/api/api-reference/embeddings/list-embeddings-models.mdx
🏁 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.pyRepository: 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
left a comment
There was a problem hiding this comment.
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:
-
JSON key parsing — Handling both
{api_key, provider_order}format and plain string keys is consistent with how chat models handle OpenRouter credentials. Nice. -
extra_body={"drop_params": True}— Good call; this prevents OpenRouter from rejecting unknown parameters that the OpenAI client may send. -
Error handling — The
_callmethod does not wrap the API call with_raise_model_exception_if_failedor 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.
Codecov Report✅ All modified and coverable lines are covered by tests. 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. 🚀 New features to boost your workflow:
|
Summary
Support OpenRouter embedding model.