Repository navigation
Fix: display timeout error when checking model accessibility - #17080
Conversation
📝 WalkthroughWalkthrough
ChangesProvider verification flow
Estimated code review effort: 4 (Complex) | ~45 minutes Suggested reviewers: Poem
🚥 Pre-merge checks | ✅ 4 | ❌ 1❌ Failed checks (1 inconclusive)
✅ 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: 2
🤖 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/services/provider_api_service.py`:
- Around line 609-611: Update the asyncio.CancelledError handler in
verify_api_key to log if desired and re-raise the cancellation instead of
returning a failure tuple. Keep the existing result-tuple handling for
TimeoutError and generic exceptions unchanged.
- Around line 700-710: Update the embedding verification block around
EmbeddingModel and _run_verification to unpack result as embeddings and
used_tokens, then fail when embeddings[0] is empty or used_tokens equals zero.
Preserve the existing failure status, message, and continue behavior for invalid
results.
🪄 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: bdf9f7e1-a856-4e73-a166-7af8a4e32fba
📒 Files selected for processing (1)
api/apps/services/provider_api_service.py
| except asyncio.CancelledError: | ||
| logging.exception("Verification cancelled for %s", label) | ||
| return False, f"\n{label} verification aborted." |
There was a problem hiding this comment.
🩺 Stability & Availability | 🟠 Major | ⚡ Quick win
Don't swallow asyncio.CancelledError; re-raise it.
Catching CancelledError and returning (False, msg) breaks cooperative cancellation. When the surrounding verify_api_key task is cancelled (e.g. client disconnect / server shutdown), this converts the cancellation into a normal "failure" result and prevents propagation, so the outer task never actually unwinds. CancelledError should be logged (if at all) and re-raised; only TimeoutError and generic exceptions should be turned into result tuples.
🔧 Proposed fix
except asyncio.CancelledError:
- logging.exception("Verification cancelled for %s", label)
- return False, f"\n{label} verification aborted."
+ logging.warning("Verification cancelled for %s", label)
+ raise📝 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.
| except asyncio.CancelledError: | |
| logging.exception("Verification cancelled for %s", label) | |
| return False, f"\n{label} verification aborted." | |
| except asyncio.CancelledError: | |
| logging.warning("Verification cancelled for %s", label) | |
| raise |
🤖 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/services/provider_api_service.py` around lines 609 - 611, Update the
asyncio.CancelledError handler in verify_api_key to log if desired and re-raise
the cancellation instead of returning a failure tuple. Keep the existing
result-tuple handling for TimeoutError and generic exceptions unchanged.
| mdl = EmbeddingModel[provider_name](api_key_str, llm["llm_name"], base_url=base_url) | ||
| label = f"embedding model({llm['llm_name']})" | ||
| ok, result = await _run_verification(label, asyncio.to_thread(mdl.encode, ["Test if the api key is available"]), timeout_seconds) | ||
| if not ok: | ||
| msg += result | ||
| model_verify_result[llm["llm_name"]] = ModelVerifyStatusEnum.FAIL.value | ||
| continue | ||
| if len(result[0]) == 0: | ||
| msg += f"\nFail to access {label}." | ||
| model_verify_result[llm["llm_name"]] = ModelVerifyStatusEnum.FAIL.value | ||
| continue |
There was a problem hiding this comment.
🎯 Functional Correctness | 🟡 Minor | ⚡ Quick win
🧩 Analysis chain
🏁 Script executed:
#!/bin/bash
rg -nP -C3 '\bdef encode\s*\(' --type=py
rg -nP -C4 '\.encode\(\[.*Test if the api key' --type=pyRepository: infiniflow/ragflow
Length of output: 156
🏁 Script executed:
#!/bin/bash
set -euo pipefail
# Map the relevant file and nearby code.
ast-grep outline api/apps/services/provider_api_service.py --view expanded || true
# Find encode definitions/usages more broadly.
rg -n -C 3 "def encode\s*\(" api -g '*.py' || true
rg -n -C 4 "\.encode\(\[" api -g '*.py' || true
# Show the target section with line numbers.
sed -n '680,725p' api/apps/services/provider_api_service.py
sed -n '740,770p' api/apps/services/provider_api_service.pyRepository: infiniflow/ragflow
Length of output: 10917
🏁 Script executed:
#!/bin/bash
set -euo pipefail
python3 - <<'PY'
from pathlib import Path
p = Path('api/apps/services/provider_api_service.py')
text = p.read_text()
for start in [680, 740]:
print(f"\n--- {p}:{start}-"+str(start+45)+" ---")
lines = text.splitlines()
for i in range(start-1, min(len(lines), start+45)):
print(f"{i+1:4d}: {lines[i]}")
PY
echo
echo '--- encode definitions/usages ---'
rg -n -C 3 'class .*EmbeddingModel|def encode\s*\(' api -g '*.py' || true
rg -n -C 3 'used_tokens|token_count|arr, tc|encode\(\[' api -g '*.py' || trueRepository: infiniflow/ragflow
Length of output: 34984
🏁 Script executed:
#!/bin/bash
set -euo pipefail
# Locate the model implementation and call sites.
git ls-files | rg 'embedding|rerank|provider_api_service|provider.*service|model' || true
# Broader search for the verification label and result handling.
rg -n -C 3 'ModelVerifyStatusEnum\.FAIL|_run_verification|used_tokens|encode\(' api -g '*.py' || trueRepository: infiniflow/ragflow
Length of output: 50374
🏁 Script executed:
#!/bin/bash
set -euo pipefail
sed -n '88,112p' api/apps/llm_app.py
sed -n '320,342p' api/apps/llm_app.py
sed -n '360,378p' api/apps/llm_app.pyRepository: infiniflow/ragflow
Length of output: 3624
🏁 Script executed:
#!/bin/bash
set -euo pipefail
python3 - <<'PY'
from pathlib import Path
p = Path('api/apps/llm_app.py')
lines = p.read_text().splitlines()
for start, end in [(92, 110), (324, 336), (364, 374)]:
print(f"\n--- {p}:{start}-{end} ---")
for i in range(start-1, end):
print(f"{i+1:4d}: {lines[i]}")
PYRepository: infiniflow/ragflow
Length of output: 2787
🏁 Script executed:
#!/bin/bash
set -euo pipefail
sed -n '92,110p' api/apps/llm_app.py
sed -n '324,336p' api/apps/llm_app.py
sed -n '364,374p' api/apps/llm_app.pyRepository: infiniflow/ragflow
Length of output: 2419
Fix the embedding availability guard. mdl.encode(...) returns (embeddings, used_tokens), and len(result[0]) only checks how many embeddings came back. With a single probe text, an empty embedding vector can still pass this branch. Unpack the tuple and reject len(embeddings[0]) == 0 or used_tokens == 0 here.
🤖 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/services/provider_api_service.py` around lines 700 - 710, Update the
embedding verification block around EmbeddingModel and _run_verification to
unpack result as embeddings and used_tokens, then fail when embeddings[0] is
empty or used_tokens equals zero. Preserve the existing failure status, message,
and continue behavior for invalid results.
Source: Linters/SAST tools
wangq8
left a comment
There was a problem hiding this comment.
Review: PR #17080 – Fix: display timeout error when checking model accessibility
Overall: A solid, well-structured refactoring that significantly reduces code duplication in verify_api_key. No regressions identified.
✅ Positive
1. _run_verification helper – Extracting the try/except/timeout boilerplate into a single helper is the right call. Every model-type check now has uniform error handling:
- Timeout →
"Timeout accessing {label}." - CancelledError →
"{label} verification aborted."(previously unhandled!) - Generic exception →
"Fail to access {label}.{str(e)}"
2. passed_types set replaces individual booleans – Much cleaner than the chat_passed, embd_passed, etc. flags. The any_passed/break logic is preserved with the same semantic.
3. assert → proper if-statement – Old code used assert provider_name in EmbeddingModel etc., which could be silently skipped with -O. The new code provides explicit error messages. Good defensive practice.
4. Iterating all model types per LLM – Old code elif-chained to the first matching type. New code tries all types if the first one fails. This is an improvement — a model that advertises both chat and vision types, for example, now gets a verification attempt on each type.
🔍 Behavior verification
- OCR/ASR
check_available()return unpacking: Correct._run_verificationreturns(True, (ok, reason))→ok2, reason = result. - VISION
test_imagereference: Oldimage_data = test_image; await ...(mdl.describe, image_data)≡ newawait ...(mdl.describe, test_image). Equivalent. - Success →
msg = ""+break: Preserved from the old behavior. - model_verify_result overwrite per llm: Functionally identical — each llm gets a single SUCCESS/FAIL entry.
⚠️ Minor
- The error message format has changed slightly (e.g., no more "using this api key" suffix). Error messages are now consistent across types but may differ from what downstream consumers expect.
_run_verificationreturns a tuple(bool, Any)— callers unpackresultdifferently per type (some expectarr, tc, some a bool, some a tuple). This is the same fragility as the old code but now centralized.
Verdict: Well done. No blockers, ready to merge.
Codecov Report✅ All modified and coverable lines are covered by tests. Additional details and impacted files@@ Coverage Diff @@
## main #17080 +/- ##
=======================================
Coverage 90.65% 90.65%
=======================================
Files 10 10
Lines 717 717
Branches 118 118
=======================================
Hits 650 650
Misses 39 39
Partials 28 28 ☔ View full report in Codecov by Harness. 🚀 New features to boost your workflow:
|
Summary
As title.