Skip to content

Fix: model provider - #15517

Merged
wangq8 merged 20 commits into
infiniflow:mainfrom
Lynn-Inf:fix/model-provider
Jun 2, 2026
Merged

wangq8 merged 20 commits into
infiniflow:mainfrom
Lynn-Inf:fix/model-provider

Conversation

@Lynn-Inf

@Lynn-Inf Lynn-Inf commented Jun 2, 2026

Copy link
Copy Markdown
Contributor

What problem does this PR solve?

Fix:

  • Handle siliconflow and siliconflow_intl api_key

Type of change

  • Bug Fix (non-breaking change which fixes an issue)

@dosubot dosubot Bot added size:M This PR changes 30-99 lines, ignoring generated files. 🐞 bug Something isn't working, pull request that fix bug. labels Jun 2, 2026
@coderabbitai

coderabbitai Bot commented Jun 2, 2026 •

Copy link
Copy Markdown
Contributor

Review Change Stack

📝 Walkthrough

Walkthrough

Adds region-aware provider verification across UI, REST, and services, including SiliconFlow intl mapping; filters certain factories from lists; updates tenant/region-based factory selection for model resolution; and makes the browser LLM lookup tenant-aware.

Changes

Region-aware provider and model selection

Layer / File(s) Summary
Client contracts and region derivation
web/src/interfaces/request/llm.ts, web/src/pages/user-setting/setting-model/hooks.tsx
Adds optional region to request body and derives SiliconFlow intl region from base_url in settings hook; conditionally includes region in requests.
REST endpoints pass region and adjust create flow
api/apps/restful_apis/provider_api.py
create_provider_instance removes verify flag and forwards base_url/region; verify_provider_api_key reads region (default "default") and passes it to the service.
Service verification, filtering, and region-aware factory mapping
api/apps/services/provider_api_service.py
Skips specific factories when listing; create always verifies with region; verify_api_key maps siliconflow to siliconflow_intl for region "intl".
Tenant/region-aware model resolution
api/db/joint_services/tenant_model_service.py
Normalizes json import; uses region from instance extra to choose factory, switching to siliconflow_intl when applicable in config and type lookups.
Browser LLM uses tenant-aware model lookup
agent/component/browser.py
get_model_type_by_name now receives tenant id when resolving browser LLM type.

Sequence Diagram(s)

sequenceDiagram
  participant User
  participant WebUI as Web UI (hooks.tsx)
  participant ProviderAPI as REST Provider API
  participant ProviderSvc as provider_api_service
  participant TenantSvc as tenant_model_service
  participant Factory as Factory Registry

  User->>WebUI: Enter provider API key/base_url
  WebUI->>WebUI: Derive region (intl for SiliconFlow host)
  WebUI->>ProviderAPI: POST { api_key, base_url, region? }
  ProviderAPI->>ProviderSvc: create/verify(..., region)
  ProviderSvc->>Factory: Select factory (intl mapping)
  ProviderSvc->>TenantSvc: Resolve model type as needed
  TenantSvc->>Factory: Lookup by tenant and region
  Factory-->>ProviderSvc: Verification result
  ProviderSvc-->>ProviderAPI: Response
  ProviderAPI-->>WebUI: HTTP 200/4xx
  WebUI-->>User: Show result
Loading

Estimated code review effort

🎯 4 (Complex) | ⏱️ ~45 minutes

Possibly related PRs

  • infiniflow/ragflow#15460: Also modifies provider creation and API-key verification paths; closely related to region-aware changes here.

Suggested labels

🐞 bug, size:L

Suggested reviewers

  • Haruko386

Poem

A rabbit taps the region key, hop-hop, all set,
Maps SiliconFlow to intl—no sweat.
Through web to API, the signals align,
Services verify, factories refine.
Tenants guide models, browsers comply—
Little ears perked, watching requests fly. 🐇✨

🚥 Pre-merge checks | ✅ 3 | ❌ 2

❌ Failed checks (1 warning, 1 inconclusive)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 70.00% which is insufficient. The required threshold is 80.00%. Write docstrings for the functions missing them to satisfy the coverage threshold.
Title check ❓ Inconclusive The title "Fix: model provider" is vague and overly broad, using non-descriptive language that doesn't convey the specific change (handling siliconflow region variants). Use a more specific title that describes the actual change, such as "Fix: handle siliconflow and siliconflow_intl provider regions" or "Fix: add region support for siliconflow API key verification".
✅ Passed checks (3 passed)
Check name Status Explanation
Description check ✅ Passed The description covers the required template structure with a problem statement and type of change, though the problem description is brief and could be more detailed.
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.

✏️ 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.

❤️ Share

Comment @coderabbitai help to get the list of available commands and usage tips.

@Lynn-Inf Lynn-Inf added the ci Continue Integration label Jun 2, 2026
@Lynn-Inf
Lynn-Inf marked this pull request as draft June 2, 2026 09:25
@Lynn-Inf
Lynn-Inf marked this pull request as ready for review June 2, 2026 09:25

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

Caution

Some comments are outside the diff and can’t be posted inline due to platform limitations.

⚠️ Outside diff range comments (1)
api/apps/services/provider_api_service.py (1)

212-258: ⚠️ Potential issue | 🔴 Critical | ⚖️ Poor tradeoff

Critical: Use target_factory_name for model class lookups and instantiation.

After mapping provider_name to target_factory_name based on region (lines 309-313), the verification logic in verify_api_key must use target_factory_name consistently. Currently:

  1. Line 314 correctly uses target_factory_name for factory lookup ✓
  2. Lines 329, 342, 363 incorrectly assert provider_name exists in model classes ✗
  3. Lines 330, 343, 364 incorrectly instantiate models using provider_name as key ✗

When region="intl" and provider_name="siliconflow", the code will:

  • Look up models from "siliconflow_intl" factory
  • Assert that "siliconflow" exists in EmbeddingModel/ChatModel/RerankModel (will fail or find wrong entry)
  • Try to instantiate EmbeddingModel["siliconflow"] instead of EmbeddingModel["siliconflow_intl"]

This breaks the region-aware provider mapping.

🐛 Proposed fix to use target_factory_name consistently

In the verify_api_key function, update lines 325-375 to use target_factory_name:

     timeout_seconds = int(os.environ.get("LLM_TIMEOUT_SECONDS", 10))
-    extra = {"provider": provider_name}
+    extra = {"provider": target_factory_name}
     msg = ""
     for llm in factory_llms:
         if not embd_passed and llm["model_type"] == LLMType.EMBEDDING.value:
-            assert provider_name in EmbeddingModel, f"Embedding model from {provider_name} is not supported yet."
-            mdl = EmbeddingModel[provider_name](api_key, llm["llm_name"], base_url=base_url)
+            assert target_factory_name in EmbeddingModel, f"Embedding model from {target_factory_name} is not supported yet."
+            mdl = EmbeddingModel[target_factory_name](api_key, llm["llm_name"], base_url=base_url)
             try:
                 arr, tc = asyncio.wait_for(
                     asyncio.to_thread(mdl.encode, ["Test if the api key is available"]),
@@ -338,8 +338,8 @@
             except Exception as e:
                 msg += f"\nFail to access embedding model({llm['llm_name']}) using this api key." + str(e)
         elif not chat_passed and llm["model_type"] == LLMType.CHAT.value:
-            assert provider_name in ChatModel, f"Chat model from {provider_name} is not supported yet."
-            mdl = ChatModel[provider_name](api_key, llm["llm_name"], base_url=base_url, **extra)
+            assert target_factory_name in ChatModel, f"Chat model from {target_factory_name} is not supported yet."
+            mdl = ChatModel[target_factory_name](api_key, llm["llm_name"], base_url=base_url, **extra)
             try:
                 async def check_streamly():
                     async for chunk in mdl.async_chat_streamly(
@@ -359,12 +359,12 @@
             except Exception as e:
-                msg += f"\nFail to access model({provider_name}/{llm['llm_name']}) using this api key." + str(e)
+                msg += f"\nFail to access model({target_factory_name}/{llm['llm_name']}) using this api key." + str(e)
         elif not rerank_passed and llm["model_type"] == LLMType.RERANK.value:
-            assert provider_name in RerankModel, f"Rerank model from {provider_name} is not supported yet."
-            mdl = RerankModel[provider_name](api_key, llm["llm_name"], base_url=base_url)
+            assert target_factory_name in RerankModel, f"Rerank model from {target_factory_name} is not supported yet."
+            mdl = RerankModel[target_factory_name](api_key, llm["llm_name"], base_url=base_url)
             try:
                 arr, tc = await asyncio.wait_for(
                     asyncio.to_thread(mdl.similarity, "What's the weather?", ["Is it sunny today?"]),
@@ -373,7 +373,7 @@
                 rerank_passed = True
                 logging.debug(f"passed model rerank {llm['llm_name']}")
             except Exception as e:
-                msg += f"\nFail to access model({provider_name}/{llm['llm_name']}) using this api key." + str(e)
+                msg += f"\nFail to access model({target_factory_name}/{llm['llm_name']}) using this api key." + str(e)
🤖 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 212 - 258, The
verify_api_key function currently mixes provider_name and target_factory_name
causing wrong model lookups/instantiations for region-mapped factories; update
verify_api_key so all checks and instantiations use target_factory_name (not
provider_name) when resolving factory/model classes and creating EmbeddingModel,
ChatModel, and RerankModel instances—replace occurrences where
EmbeddingModel[provider_name], ChatModel[provider_name],
RerankModel[provider_name] or assertions check provider_name in model registries
with target_factory_name and ensure any related existence assertions use
target_factory_name as well.
🧹 Nitpick comments (3)
api/db/joint_services/tenant_model_service.py (2)

175-181: ⚡ Quick win

Add logging for region-aware factory mapping in model type lookup.

Similar to the comment on lines 126-131, add logging when the provider is remapped based on region.

📝 Add logging
         region = extra_fields.get("region", "default")
         if region == "intl" and provider_name.lower() == "siliconflow":
             target_factory_name = "siliconflow_intl"
+            logger.info(f"Mapped provider {provider_name} to {target_factory_name} for tenant {tenant_id}, region={region} in get_model_type_by_name")
         else:
             target_factory_name = provider_name

As per coding guidelines, add logging for new flows in Python files.

🤖 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/db/joint_services/tenant_model_service.py` around lines 175 - 181, The
region-aware provider remapping currently sets target_factory_name without
logging; update the block that reads instance_obj.extra, computes region, and
sets target_factory_name (the code that produces fac_list from
settings.FACTORY_LLM_INFOS) to emit a debug/info log whenever provider_name is
altered due to region (e.g., when region == "intl" and provider_name.lower() ==
"siliconflow" resulting in "siliconflow_intl"), including original
provider_name, region, and the chosen target_factory_name so downstream lookups
of fac_list can be traced.

126-131: ⚡ Quick win

Add logging for region-aware factory mapping.

When region="intl" and provider_name="siliconflow", the code silently maps to siliconflow_intl. Add logging to track this mapping for debugging tenant model resolution issues.

📝 Add logging
         region = extra_fields.get("region", "default")
         if region == "intl" and provider_name.lower() == "siliconflow":
             target_factory_name = "siliconflow_intl"
+            logger.info(f"Mapped provider {provider_name} to {target_factory_name} for tenant {tenant_id}, region={region}")
         else:
             target_factory_name = provider_name

As per coding guidelines, add logging for new flows in Python files.

🤖 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/db/joint_services/tenant_model_service.py` around lines 126 - 131, Add a
log statement that records the region-aware mapping when region == "intl" and
provider_name.lower() == "siliconflow": before computing fac_list, log the
original provider_name, extra_fields.get("region"), and the computed
target_factory_name (e.g., "mapping provider='siliconflow' region='intl' ->
target_factory='siliconflow_intl'") using the module logger (getLogger(__name__)
or the existing logger in tenant_model_service.py) at INFO or DEBUG level so the
tenant model resolution can be traced; place the log immediately after setting
target_factory_name and before reading settings.FACTORY_LLM_INFOS.
api/apps/services/provider_api_service.py (1)

296-316: ⚡ Quick win

Add logging for region-aware provider mapping.

The new region-aware mapping logic should be logged for observability, especially when siliconflow is mapped to siliconflow_intl.

📝 Add logging for region mapping
     if region and region == "intl" and provider_name.lower() == "siliconflow":
         target_factory_name = "siliconflow_intl"
+        logging.info(f"Mapped provider {provider_name} to {target_factory_name} for region={region}")
     else:
         target_factory_name = provider_name

As per coding guidelines, add logging for new flows in Python files.

🤖 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 296 - 316, Add an
info/debug log in verify_api_key to record the region-aware mapping when region
== "intl" and provider_name.lower() == "siliconflow" so it's clear that
provider_name is being remapped to target_factory_name; use the module logger
(create logging.getLogger(__name__) if one doesn't exist) and include
provider_name, region, and resulting target_factory_name in the message (and
keep existing behavior of looking up FACTORY_LLM_INFOS 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.

Outside diff comments:
In `@api/apps/services/provider_api_service.py`:
- Around line 212-258: The verify_api_key function currently mixes provider_name
and target_factory_name causing wrong model lookups/instantiations for
region-mapped factories; update verify_api_key so all checks and instantiations
use target_factory_name (not provider_name) when resolving factory/model classes
and creating EmbeddingModel, ChatModel, and RerankModel instances—replace
occurrences where EmbeddingModel[provider_name], ChatModel[provider_name],
RerankModel[provider_name] or assertions check provider_name in model registries
with target_factory_name and ensure any related existence assertions use
target_factory_name as well.

---

Nitpick comments:
In `@api/apps/services/provider_api_service.py`:
- Around line 296-316: Add an info/debug log in verify_api_key to record the
region-aware mapping when region == "intl" and provider_name.lower() ==
"siliconflow" so it's clear that provider_name is being remapped to
target_factory_name; use the module logger (create logging.getLogger(__name__)
if one doesn't exist) and include provider_name, region, and resulting
target_factory_name in the message (and keep existing behavior of looking up
FACTORY_LLM_INFOS unchanged).

In `@api/db/joint_services/tenant_model_service.py`:
- Around line 175-181: The region-aware provider remapping currently sets
target_factory_name without logging; update the block that reads
instance_obj.extra, computes region, and sets target_factory_name (the code that
produces fac_list from settings.FACTORY_LLM_INFOS) to emit a debug/info log
whenever provider_name is altered due to region (e.g., when region == "intl" and
provider_name.lower() == "siliconflow" resulting in "siliconflow_intl"),
including original provider_name, region, and the chosen target_factory_name so
downstream lookups of fac_list can be traced.
- Around line 126-131: Add a log statement that records the region-aware mapping
when region == "intl" and provider_name.lower() == "siliconflow": before
computing fac_list, log the original provider_name, extra_fields.get("region"),
and the computed target_factory_name (e.g., "mapping provider='siliconflow'
region='intl' -> target_factory='siliconflow_intl'") using the module logger
(getLogger(__name__) or the existing logger in tenant_model_service.py) at INFO
or DEBUG level so the tenant model resolution can be traced; place the log
immediately after setting target_factory_name and before reading
settings.FACTORY_LLM_INFOS.

ℹ️ Review info
⚙️ Run configuration

Configuration used: Organization UI

Review profile: CHILL

Plan: Pro

Run ID: 45f0999e-0b0c-4c1e-a09c-7258be21b539

📥 Commits

Reviewing files that changed from the base of the PR and between a98889c and 04f5373.

📒 Files selected for processing (6)
  • agent/component/browser.py
  • api/apps/restful_apis/provider_api.py
  • api/apps/services/provider_api_service.py
  • api/db/joint_services/tenant_model_service.py
  • web/src/interfaces/request/llm.ts
  • web/src/pages/user-setting/setting-model/hooks.tsx

@Lynn-Inf
Lynn-Inf requested a review from dcc123456 June 2, 2026 09:55
@codecov

codecov Bot commented Jun 2, 2026

Copy link
Copy Markdown

Codecov Report

✅ All modified and coverable lines are covered by tests.
✅ Project coverage is 93.16%. Comparing base (a98889c) to head (a308cc9).
⚠️ Report is 2 commits behind head on main.

Additional details and impacted files
@@           Coverage Diff           @@
##             main   #15517   +/-   ##
=======================================
  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.
📢 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 36357a6 into infiniflow:main Jun 2, 2026
1 check passed
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: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