Repository navigation
Bug fix: Enhance embeding model to give better error message - #15346
Conversation
📝 WalkthroughWalkthroughAdds ModelException and an app error handler; centralizes embedding HTTP-status handling and bounded retries across providers; adds a Docker admin launch script with retries and cleanup; fixes CI readiness log denominator messages; refactors PerplexityEmbed tests to use a shared mock helper. ChangesError Handling Infrastructure Refactor
Admin Service Launch Script
Workflow Service Readiness Logging Fixes
PerplexityEmbed Tests
Estimated code review effort🎯 4 (Complex) | ⏱️ ~45 minutes Suggested reviewers
🚥 Pre-merge checks | ✅ 2 | ❌ 3❌ Failed checks (2 warnings, 1 inconclusive)
✅ Passed checks (2 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: 7
🤖 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 `@api/apps/__init__.py`:
- Around line 365-368: The handler for ModelException in handle_model_exception
currently returns repr(error) which exposes the exception class wrapper; change
the returned message to the underlying error text (use str(error) or error.msg
if ModelException defines msg) so the API response contains the provider error
message. Update the return in handle_model_exception to call
get_json_result(..., message=str(error)) (or message=error.msg) and keep the
same status/structure.
In `@api/apps/restful_apis/dataset_api.py`:
- Around line 500-504: The dataset-scoped search route currently swallows
provider/ModelException by catching broad exceptions; change its handler (the
/datasets/<dataset_id>/search function that calls
dataset_api_service.search_datasets for a dataset) to use the same flow as the
tenant-level route: call dataset_api_service.search_datasets(...) and then if
success return get_result(data=result) else return
get_error_data_result(message=result), and remove the broad try/except that
catches Exception (or ensure it re-raises ModelException) so ModelException can
propagate to the global handler.
In `@api/utils/api_utils.py`:
- Around line 147-148: The "not_found" branch in api_utils.py is catching errors
before the more specific "index_not_found_exception" case, changing the intended
response; update the exception-ordering so you check for the specific
index-missing case (e.g., look for "index_not_found_exception" in str(e) or use
the existing index-checking condition) before the generic if "not_found" in
str(e) branch, and ensure the index-missing path returns the original specific
message via get_error_data_result while the generic "not_found" branch remains
as a fallback.
In `@common/exceptions.py`:
- Around line 30-33: ModelException currently assigns self.msg and
self.retryable but never initializes the base Exception, causing Exception.args
to be empty and server_error_response to show ModelException() instead of the
message; update ModelException.__init__ to call super().__init__(msg) (and keep
self.retryable) so the message is preserved in Exception.args and repr/str(e)
will include the provider message (or alternatively implement __str__ to return
self.msg if you prefer).
In `@docker/launch_admin_service.sh`:
- Around line 54-63: cleanup() currently only kills wrapper PIDs stored in PIDS
but not the actual admin_server.py process started inside run_server, so the
Python server can be left running; fix by either modifying run_server to capture
the child PID of admin/server/admin_server.py and append that PID to PIDS (e.g.,
launch the Python server in background inside run_server and export/echo its PID
so the outer script can add it to PIDS) or make run_server start its processes
in a new process group (setsid or set -m) and then have cleanup() kill the
entire group (kill -TERM -PGID) instead of only the wrapper PID; ensure you
update run_server, the code that adds to PIDS, and cleanup() to handle the real
admin_server.py PID or PGID.
- Around line 73-76: The retry logic fails under set -e because a non-zero exit
from "$PY admin/server/admin_server.py" causes the script to exit before
EXIT_CODE is captured and retry logic in the loop can run; wrap the call so the
exit is captured without aborting (for example temporarily disable errexit
around the invocation or append "|| true" and then set EXIT_CODE=$?), using the
existing variables ($PY, admin/server/admin_server.py, EXIT_CODE, retry_count,
MAX_RETRIES, STOP) and keep the loop semantics. Also ensure cleanup() actually
stops the real admin_server.py child: when run_server backgrounds the wrapper,
record and kill the actual child PID (or start admin_server.py in its own
process group and kill the group) instead of only killing the wrapper PID;
update run_server and cleanup() to track and kill the child process or process
group so admin_server.py is not orphaned.
In `@rag/llm/embedding_model.py`:
- Around line 313-327: The retry loop in the DashScope embedding call
incorrectly uses "if retry < retry_max" which is always true because retry
iterates from range(retry_max); update the exhaustion logic in the method
containing this loop (the block using variables retry_max, retry_wait_secs, and
calling dashscope.TextEmbedding.call with self.model_name/self.key) so that you
either check "if retry < retry_max - 1" before sleeping and retrying, or move
the final ModelException to run after the for-loop if no successful 200 response
is received; ensure 4XX non-retryable errors still raise immediately and that
the final raise includes status_code and resp.
🪄 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: e235bf02-d67c-42d8-930f-f0ba792d3c0d
📒 Files selected for processing (7)
.github/workflows/tests.ymlapi/apps/__init__.pyapi/apps/restful_apis/dataset_api.pyapi/utils/api_utils.pycommon/exceptions.pydocker/launch_admin_service.shrag/llm/embedding_model.py
| success, result = await dataset_api_service.search_datasets(tenant_id, req) | ||
| if success: | ||
| return get_result(data=result) | ||
| else: | ||
| return get_error_data_result(message=result) |
There was a problem hiding this comment.
Apply the same exception flow to the dataset-scoped search route.
/datasets/search now lets ModelException reach the global handler, but the sibling /datasets/<dataset_id>/search route still catches broad exceptions and collapses provider failures into "Internal server error". That leaves the dataset-level retrieval test path without the improved model message this PR is targeting.
🤖 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 `@api/apps/restful_apis/dataset_api.py` around lines 500 - 504, The
dataset-scoped search route currently swallows provider/ModelException by
catching broad exceptions; change its handler (the /datasets/<dataset_id>/search
function that calls dataset_api_service.search_datasets for a dataset) to use
the same flow as the tenant-level route: call
dataset_api_service.search_datasets(...) and then if success return
get_result(data=result) else return get_error_data_result(message=result), and
remove the broad try/except that catches Exception (or ensure it re-raises
ModelException) so ModelException can propagate to the global handler.
| cleanup() { | ||
| echo "Termination signal received. Shutting down..." | ||
| STOP=true | ||
| # Terminate all child processes | ||
| for pid in "${PIDS[@]}"; do | ||
| if kill -0 "$pid" 2>/dev/null; then | ||
| echo "Killing process $pid" | ||
| kill "$pid" | ||
| fi | ||
| done |
There was a problem hiding this comment.
🧩 Analysis chain
🏁 Script executed:
#!/bin/bash
# Verify only wrapper PID is tracked and no dedicated admin_server PID is managed.
rg -n -C3 'PIDS|run_server &|cleanup\(\)|kill ' docker/launch_admin_service.shRepository: infiniflow/ragflow
Length of output: 682
🏁 Script executed:
#!/bin/bash
set -euo pipefail
# Show run_server implementation and where admin_server.py is launched
nl -ba docker/launch_admin_service.sh | sed -n '40,120p'
# Confirm all occurrences of admin_server.py and how it's started
rg -n 'admin/server/admin_server\.py' docker/launch_admin_service.sh || trueRepository: infiniflow/ragflow
Length of output: 105
🏁 Script executed:
#!/bin/bash
set -euo pipefail
# Show the relevant portion of the script with line numbers (using cat -n instead of nl)
cat -n docker/launch_admin_service.sh | sed -n '35,140p'
# Find how admin_server.py is started
rg -n 'admin/server/admin_server\.py' docker/launch_admin_service.sh || true
# Find how PIDS is used
rg -n 'PIDS|\bcleanup\(\)|kill ' docker/launch_admin_service.shRepository: infiniflow/ragflow
Length of output: 2248
Shutdown may not reliably terminate admin_server.py
docker/launch_admin_service.sh starts run_server in the background and stores only that wrapper PID in PIDS (run_server & / PIDS+=($!)). cleanup() then kills only the PIDs in PIDS, but admin/server/admin_server.py is launched in the foreground inside the run_server subshell—so SIGTERM handling can leave the Python server running/orphaned.
Update shutdown to track and kill the actual admin_server.py PID (or kill its process group) from cleanup() instead of only killing the wrapper PID.
🤖 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 `@docker/launch_admin_service.sh` around lines 54 - 63, cleanup() currently
only kills wrapper PIDs stored in PIDS but not the actual admin_server.py
process started inside run_server, so the Python server can be left running; fix
by either modifying run_server to capture the child PID of
admin/server/admin_server.py and append that PID to PIDS (e.g., launch the
Python server in background inside run_server and export/echo its PID so the
outer script can add it to PIDS) or make run_server start its processes in a new
process group (setsid or set -m) and then have cleanup() kill the entire group
(kill -TERM -PGID) instead of only the wrapper PID; ensure you update
run_server, the code that adds to PIDS, and cleanup() to handle the real
admin_server.py PID or PGID.
| while ! $STOP && [ $retry_count -lt $MAX_RETRIES ]; do | ||
| echo "Starting admin_server.py (Attempt $((retry_count+1)))" | ||
| $PY admin/server/admin_server.py | ||
| EXIT_CODE=$? |
There was a problem hiding this comment.
🧩 Analysis chain
🏁 Script executed:
#!/bin/bash
# Verify retry flow is vulnerable to errexit short-circuiting.
rg -n -C2 'set -e|run_server\(\)|admin/server/admin_server.py|EXIT_CODE=\$\?' docker/launch_admin_service.shRepository: infiniflow/ragflow
Length of output: 606
🏁 Script executed:
#!/bin/bash
set -euo pipefail
nl -ba docker/launch_admin_service.sh | sed -n '1,140p'Repository: infiniflow/ragflow
Length of output: 105
🏁 Script executed:
#!/bin/bash
awk '{printf "%4d:%s\n", NR, $0}' docker/launch_admin_service.sh | sed -n '1,180p'Repository: infiniflow/ragflow
Length of output: 3097
Fix retry logic under set -e (and improve shutdown to avoid orphaning admin_server.py)
set -eat line 4 prevents the retry path from running: if$PY admin/server/admin_server.py(line 75) exits non-zero, the script exits immediately beforeEXIT_CODE=$?(line 76) and the retry branch (lines 77-84) can execute.- Shutdown may not stop the actual server:
run_serveris backgrounded (line 94) andcleanup()only kills that wrapper PID (lines 58-62), not theadmin_server.pychild it spawned.
Suggested fix (retry logic)
run_server(){
local retry_count=0
while ! $STOP && [ $retry_count -lt $MAX_RETRIES ]; do
echo "Starting admin_server.py (Attempt $((retry_count+1)))"
- $PY admin/server/admin_server.py
- EXIT_CODE=$?
+ if $PY admin/server/admin_server.py; then
+ EXIT_CODE=0
+ else
+ EXIT_CODE=$?
+ fi
if [ $EXIT_CODE -eq 0 ]; then
echo "admin_server.py exited successfully."
break📝 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.
| while ! $STOP && [ $retry_count -lt $MAX_RETRIES ]; do | |
| echo "Starting admin_server.py (Attempt $((retry_count+1)))" | |
| $PY admin/server/admin_server.py | |
| EXIT_CODE=$? | |
| while ! $STOP && [ $retry_count -lt $MAX_RETRIES ]; do | |
| echo "Starting admin_server.py (Attempt $((retry_count+1)))" | |
| if $PY admin/server/admin_server.py; then | |
| EXIT_CODE=0 | |
| else | |
| EXIT_CODE=$? | |
| fi |
🤖 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 `@docker/launch_admin_service.sh` around lines 73 - 76, The retry logic fails
under set -e because a non-zero exit from "$PY admin/server/admin_server.py"
causes the script to exit before EXIT_CODE is captured and retry logic in the
loop can run; wrap the call so the exit is captured without aborting (for
example temporarily disable errexit around the invocation or append "|| true"
and then set EXIT_CODE=$?), using the existing variables ($PY,
admin/server/admin_server.py, EXIT_CODE, retry_count, MAX_RETRIES, STOP) and
keep the loop semantics. Also ensure cleanup() actually stops the real
admin_server.py child: when run_server backgrounds the wrapper, record and kill
the actual child PID (or start admin_server.py in its own process group and kill
the group) instead of only killing the wrapper PID; update run_server and
cleanup() to track and kill the child process or process group so
admin_server.py is not orphaned.
There was a problem hiding this comment.
🧹 Nitpick comments (1)
api/utils/api_utils.py (1)
150-152: ⚡ Quick winAdd logging for the new not_found error flow.
This new error-handling path should include a logging statement before returning the error response, as per coding guidelines: "Add logging for new flows".
📝 Suggested addition
if "not_found" in str(e): + logging.warning(f"Chunk not found: {e}") return get_error_data_result(message="No chunk found! Check the chunk status please!")As per coding guidelines, new flows in
**/*.pyshould add logging.🤖 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 `@api/utils/api_utils.py` around lines 150 - 152, The new "not_found" error branch in api_utils.py should log the error before returning—add a logging call (e.g., logger.error or logging.getLogger(__name__).error) right before the return in the if "not_found" in str(e) block, include the exception details (e) and a clear message such as "No chunk found" to aid debugging, and ensure the module has a logger available (import logging or use the existing module-level logger) so get_error_data_result is returned after the log.
🤖 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.
Nitpick comments:
In `@api/utils/api_utils.py`:
- Around line 150-152: The new "not_found" error branch in api_utils.py should
log the error before returning—add a logging call (e.g., logger.error or
logging.getLogger(__name__).error) right before the return in the if "not_found"
in str(e) block, include the exception details (e) and a clear message such as
"No chunk found" to aid debugging, and ensure the module has a logger available
(import logging or use the existing module-level logger) so
get_error_data_result is returned after the log.
ℹ️ Review info
⚙️ Run configuration
Configuration used: Organization UI
Review profile: CHILL
Plan: Pro
Run ID: 05f1fc5c-7016-4506-b9a1-6c283b26485c
📒 Files selected for processing (3)
api/utils/api_utils.pycommon/exceptions.pyrag/llm/embedding_model.py
🚧 Files skipped from review as they are similar to previous changes (2)
- common/exceptions.py
- rag/llm/embedding_model.py
There was a problem hiding this comment.
🧹 Nitpick comments (1)
test/unit_test/rag/llm/test_perplexity_embed.py (1)
136-239: ⚡ Quick winAdd pytest priority markers to the updated tests.
The refactored tests are still unmarked. Please add
@pytest.mark.p1/p2/p3(class-level is fine) so these cases participate correctly in priority-based test selection.Proposed change
class TestPerplexityEmbedStandardEncode: + pytestmark = pytest.mark.p2 `@patch`("rag.llm.embedding_model.requests.post") def test_encode_single_text(self, mock_post): ... class TestPerplexityEmbedContextualizedEncode: + pytestmark = pytest.mark.p2 `@patch`("rag.llm.embedding_model.requests.post") def test_contextualized_encode(self, mock_post): ... class TestPerplexityEmbedEncodeQueries: + pytestmark = pytest.mark.p2 `@patch`("rag.llm.embedding_model.requests.post") def test_encode_queries_returns_single_vector(self, mock_post): ...As per coding guidelines,
test/**/*.py: Use pytest with priority markers (p1/p2/p3) for Python backend tests.🤖 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 `@test/unit_test/rag/llm/test_perplexity_embed.py` around lines 136 - 239, The tests lack pytest priority markers; add appropriate decorators (e.g., `@pytest.mark.p1` or p2/p3 as required) at the class level for TestPerplexityEmbed, TestPerplexityEmbedContextualizedEncode, and TestPerplexityEmbedEncodeQueries so they participate in priority-based selection, and ensure pytest is imported at the top of the file; place the marker directly above each class definition (or on individual test methods if class-level is not desired).
🤖 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.
Nitpick comments:
In `@test/unit_test/rag/llm/test_perplexity_embed.py`:
- Around line 136-239: The tests lack pytest priority markers; add appropriate
decorators (e.g., `@pytest.mark.p1` or p2/p3 as required) at the class level for
TestPerplexityEmbed, TestPerplexityEmbedContextualizedEncode, and
TestPerplexityEmbedEncodeQueries so they participate in priority-based
selection, and ensure pytest is imported at the top of the file; place the
marker directly above each class definition (or on individual test methods if
class-level is not desired).
ℹ️ Review info
⚙️ Run configuration
Configuration used: Organization UI
Review profile: CHILL
Plan: Pro
Run ID: 74e8d4a2-5a9e-429f-89ca-674aa622d20a
📒 Files selected for processing (1)
test/unit_test/rag/llm/test_perplexity_embed.py
Codecov Report✅ All modified and coverable lines are covered by tests. Additional details and impacted files@@ Coverage Diff @@
## main #15346 +/- ##
=======================================
Coverage 93.16% 93.16%
=======================================
Files 10 10
Lines 717 717
Branches 118 118
=======================================
Hits 668 668
Misses 29 29
Partials 20 20 ☔ View full report in Codecov by Sentry. 🚀 New features to boost your workflow:
|
To resolve #15343 enhance the model embedding message to give extact failure message to customer.
QWen
Retrieval
Chat
SiliconFlow
Retrieval
Chat
Baichuan
Retrieval
Chat
Zhipu
zhipu is good.