Skip to content

Fix: verify remote model when model_list in argument and factory_llms is empty - #17364

Merged
wangq8 merged 1 commit into
infiniflow:mainfrom
Lynn-Inf:fix/simplify-verify-python
Jul 27, 2026
Merged

wangq8 merged 1 commit into
infiniflow:mainfrom
Lynn-Inf:fix/simplify-verify-python

Conversation

@Lynn-Inf

Copy link
Copy Markdown
Contributor

Summary

As title.

@dosubot dosubot Bot added size:S This PR changes 10-29 lines, ignoring generated files. 🐞 bug Something isn't working, pull request that fix bug. labels Jul 24, 2026
@Lynn-Inf
Lynn-Inf requested a review from wangq8 July 24, 2026 11:21
@Lynn-Inf Lynn-Inf added the ci Continue Integration label Jul 24, 2026
@coderabbitai

coderabbitai Bot commented Jul 24, 2026 •

Copy link
Copy Markdown
Contributor

Review Change Stack

📝 Walkthrough

Walkthrough

Changes

Provider model discovery

Layer / File(s) Summary
Remote model fallback
api/apps/services/provider_api_service.py
verify_api_key queries the provider’s remote model list when local models are unavailable, rebuilds candidates from returned model types, ignores discovery exceptions, and retains the final no-models failure.

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

Suggested reviewers: xugangqiang

Poem

I’m a bunny with models to find,
Fetching remote names from the cloud wind.
If the list hops in,
Verification can begin—
No models? The old error stays behind.

🚥 Pre-merge checks | ✅ 4 | ❌ 1

❌ Failed checks (1 warning)

Check name Status Explanation Resolution
Description check ⚠️ Warning The description only repeats the title and lacks the required summary details and background context. Expand the Summary section with the problem context, what changed, and why this fix was needed.
✅ Passed checks (4 passed)
Check name Status Explanation
Title check ✅ Passed The title matches the main fix, though the wording is awkward and slightly imprecise.
Docstring Coverage ✅ Passed No functions found in the changed files to evaluate docstring coverage. Skipping docstring coverage check.
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.

@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 this fix! The approach makes sense — when factory_llms is empty, falling back to dynamically discovering models from the remote provider is much better than immediately returning an error. This is especially useful for providers that don't pre-configure their model list in factory_llms.

What I checked:

  • The ModelMeta[provider_name](api_key, model_base_url).get_model_list() pattern is already established in the codebase (used in show_provider_llm around line 213), so this is consistent.
  • The constructed factory_llms entries (model_type / llm_name) match the format consumed by the verification loop below.
  • The try/except guard ensures this fallback is non-breaking — if the remote call fails for any reason, it falls through to the original error return.

One minor observation (non-blocking): The except Exception: pass is quite broad. In a future iteration, it might be worth logging the exception at debug level so that intermittent network errors or API issues can be traced. But as a fallback, this is perfectly fine.

LGTM! ✅

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

🧹 Nitpick comments (1)
api/apps/services/provider_api_service.py (1)

671-687: 🎯 Functional Correctness | 🔵 Trivial | ⚡ Quick win

Add regression coverage for the empty-list fallback.

Mock ModelMeta and verify that model_info=[] discovers remote models, maps name/model_types into factory_llms, and preserves the “No models found” result when discovery returns no usable models or fails.

🤖 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 671 - 687, Extend
regression tests for the provider model-discovery flow around ModelMeta and the
model_info fallback: mock ModelMeta so model_info=[] triggers remote discovery,
verify remote model name/model_types are mapped into factory_llms, and cover
both empty/unusable discovery results and discovery exceptions returning the
existing “No models found” response.

Source: Coding guidelines

🤖 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 684-685: Update the exception handling in the provider discovery
flow around the broad `except Exception` to catch only expected
discovery-related errors, log the provider and exception details without
including API keys, and re-raise unexpected exceptions instead of silently
returning “No models found.”
- Around line 671-674: Update the remote discovery call in verify_api_key around
ModelMeta[provider_name](...).get_model_list() to enforce an explicit bounded
timeout for each model-list request, using the existing LLM_TIMEOUT_SECONDS
configuration or passing it through to the provider implementation; ensure
stalled aiohttp discovery cannot exceed the API-key verification timeout.

---

Nitpick comments:
In `@api/apps/services/provider_api_service.py`:
- Around line 671-687: Extend regression tests for the provider model-discovery
flow around ModelMeta and the model_info fallback: mock ModelMeta so
model_info=[] triggers remote discovery, verify remote model name/model_types
are mapped into factory_llms, and cover both empty/unusable discovery results
and discovery exceptions returning the existing “No models found” response.
🪄 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 Plus

Run ID: 2b09ca82-e7a4-462b-a674-65905efdd9f9

📥 Commits

Reviewing files that changed from the base of the PR and between 75c9af3 and fd27c9f.

📒 Files selected for processing (1)
  • api/apps/services/provider_api_service.py

Comment on lines +671 to +674
model_base_url = base_url or factory_info[0].get("url", "")
try:
if provider_name in ModelMeta:
remote_models = await ModelMeta[provider_name](api_key, model_base_url).get_model_list()

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.

🩺 Stability & Availability | 🟠 Major | ⚡ Quick win

🧩 Analysis chain

🏁 Script executed:

#!/bin/bash
set -euo pipefail

echo "Files matching provider_api_service.py:"
fd -a 'provider_api_service\.py$' . || true

FILE="$(fd 'provider_api_service\.py$' . | head -n 1 || true)"
if [ -z "${FILE:-}" ]; then
  echo "No provider_api_service.py found"
  exit 0
fi
echo "Selected: $FILE"
wc -l "$FILE"
echo "--- outline around relevant symbols ---"
ast-grep outline "$FILE" --match ModelMeta --view expanded || true
echo "--- lines 630-720 ---"
sed -n '630,720p' "$FILE"

echo "--- search get_model_list / ModelMeta definitions ---"
rg -n "class ModelMeta|get_model_list|verify_api_key|_run_verification|aiohttp|timeout" -S .

Repository: infiniflow/ragflow

Length of output: 50375


🏁 Script executed:

#!/bin/bash
set -euo pipefail

FILE="api/apps/services/provider_api_service.py"
echo "--- provider_api_service.py lines 630-720 ---"
sed -n '630,720p' "$FILE" | cat -n -v

echo "--- provider_api_service.py imports / verify_api_key definition ---"
rg -n "from common.connection_utils import timeout|def verify_api_key|async def verify_api_key|_run_verification|`@timeout`" "$FILE"

echo "--- ProviderMeta class(s) and get_model_list implementations ---"
python3 - <<'PY'
from pathlib import Path
import ast

for path in Path('.').rglob('*.py'):
    if any(part in {'venv', '.git', '__pycache__'} for part in path.parts):
        continue
    try:
        txt = path.read_text(encoding='utf-8', errors='ignore')
    except Exception:
        continue
    if 'class ProviderMeta' in txt or 'get_model_list' in txt:
        try:
            tree = ast.parse(txt)
        except SyntaxError:
            continue
        for node in ast.walk(tree):
            if not isinstance(node, ast.ClassDef):
                continue
            if node.name in {'ProviderMeta', 'LocalAI', 'FunASR'} or any(n == 'get_model_list' for n in [node.name]):
                print(f"FILE {path}:{node.lineno}")
                print('  ', node.name)
PY

echo "--- focused ModelMeta get_model_list implementations ---"
rg -n "class ModelMeta|def get_model_list|async def get_model_list|async def _get_model_list|ClientSession|aiohttp" api tests -S --max-count 200

Repository: infiniflow/ragflow

Length of output: 10703


🌐 Web query:

aiohttp.ClientSession get timeout default None connect_timeout default aiohttp documentation

💡 Result:

In aiohttp, timeout settings are managed via the ClientTimeout data structure [1][2]. When not explicitly provided, the default timeout configuration used by ClientSession is [1][2]: aiohttp.ClientTimeout(total=300, connect=None, sock_connect=None, sock_read=None, ceil_threshold=5) Key default values include: total: 300 seconds (5 minutes) [1][2]. This is the maximum time for the entire operation [1][2]. connect: None [1][2]. Note that while the ClientTimeout object defaults to None for connect, some documentation summaries note a 30-second socket connect timeout in the broader context of the session's default behavior [3][4]. The ClientTimeout structure itself maintains None for connect and sock_connect by default [1][2][5]. sock_connect: None [1][2]. sock_read: None [1][2]. You can override these defaults by passing a custom ClientTimeout instance to the ClientSession constructor [1][3] or directly to individual request methods like ClientSession.get [1][2]. If you pass a float to the timeout parameter (for backward compatibility), it is interpreted as the total timeout in seconds [3][4]. Any field set to None or 0 disables that specific timeout check [1][2].

Citations:


Bound the remote model discovery request.

Line 684 starts remote model discovery before _run_verification can apply LLM_TIMEOUT_SECONDS; ModelMeta.get_model_list() uses aiohttp without an explicit per-model timeout, so a provider that accepts the connection but stalls can make verify_api_key wait beyond the stated API-key verification timeout. Add a bounded discovery timeout there or pass one through this call.

🤖 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 671 - 674, Update the
remote discovery call in verify_api_key around
ModelMeta[provider_name](...).get_model_list() to enforce an explicit bounded
timeout for each model-list request, using the existing LLM_TIMEOUT_SECONDS
configuration or passing it through to the provider implementation; ensure
stalled aiohttp discovery cannot exceed the API-key verification timeout.

Comment on lines +684 to +685
except Exception:
pass

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.

🩺 Stability & Availability | 🟠 Major | ⚡ Quick win

Do not silently swallow discovery failures.

This catches every exception and converts outages, authentication errors, malformed responses, and programming bugs into a misleading “No models found” result. Catch expected discovery errors, log the provider and exception without exposing the API key, and let unexpected bugs surface. As per coding guidelines, **/*.py: Add logging for new flows.

🧰 Tools
🪛 Ruff (0.15.21)

[error] 684-685: try-except-pass detected, consider logging the exception

(S110)


[warning] 684-684: Do not catch blind exception: Exception

(BLE001)

🤖 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 684 - 685, Update the
exception handling in the provider discovery flow around the broad `except
Exception` to catch only expected discovery-related errors, log the provider and
exception details without including API keys, and re-raise unexpected exceptions
instead of silently returning “No models found.”

Sources: Coding guidelines, Linters/SAST tools

@codecov

codecov Bot commented Jul 24, 2026

Copy link
Copy Markdown

Codecov Report

✅ All modified and coverable lines are covered by tests.
✅ Project coverage is 90.65%. Comparing base (cd9db94) to head (fd27c9f).
⚠️ Report is 22 commits behind head on main.

Additional details and impacted files
@@           Coverage Diff           @@
##             main   #17364   +/-   ##
=======================================
  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.
📢 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.

@wangq8
wangq8 merged commit c62853b into infiniflow:main Jul 27, 2026
9 checks passed
@coderabbitai coderabbitai Bot mentioned this pull request Jul 27, 2026
ondery added a commit to ondery/ragflow that referenced this pull request Jul 28, 2026
…er type fail

Two remaining verify-path fixes after infiniflow#17158 (api_base -> base_url rename)
and infiniflow#17364/infiniflow#17397 (empty-catalog remote model discovery) landed on main:

- useVerifyProvider now accepts a modelInfoRef carrying the models selected
  in the List-models picker (not registered as form fields) and folds them
  into the verify payload, so local/compatible providers no longer verify
  against an empty model_info.
- _record_model_verify_failure records FAIL without overwriting a prior
  SUCCESS for the same llm_name. model_info is unrolled into one
  factory_llms entry per capability type, so a later type failure must not
  erase an earlier successful capability result.
- Wrap Embedding/Chat model construction in try/except so an init failure
  is recorded as a per-model FAIL instead of aborting the whole verify.

Co-authored-by: Cursor <[email protected]>
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 size:S This PR changes 10-29 lines, ignoring generated files.

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants