Repository navigation
Fix: model provider - #15517
Fix: model provider#15517
Conversation
… fix/model-provider
📝 WalkthroughWalkthroughAdds 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. ChangesRegion-aware provider and model selection
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
Estimated code review effort🎯 4 (Complex) | ⏱️ ~45 minutes Possibly related PRs
Suggested labels
Suggested reviewers
Poem
🚥 Pre-merge checks | ✅ 3 | ❌ 2❌ Failed checks (1 warning, 1 inconclusive)
✅ Passed checks (3 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.
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 tradeoffCritical: Use
target_factory_namefor model class lookups and instantiation.After mapping
provider_nametotarget_factory_namebased on region (lines 309-313), the verification logic inverify_api_keymust usetarget_factory_nameconsistently. Currently:
- Line 314 correctly uses
target_factory_namefor factory lookup ✓- Lines 329, 342, 363 incorrectly assert
provider_nameexists in model classes ✗- Lines 330, 343, 364 incorrectly instantiate models using
provider_nameas key ✗When
region="intl"andprovider_name="siliconflow", the code will:
- Look up models from
"siliconflow_intl"factory- Assert that
"siliconflow"exists inEmbeddingModel/ChatModel/RerankModel(will fail or find wrong entry)- Try to instantiate
EmbeddingModel["siliconflow"]instead ofEmbeddingModel["siliconflow_intl"]This breaks the region-aware provider mapping.
🐛 Proposed fix to use target_factory_name consistently
In the
verify_api_keyfunction, update lines 325-375 to usetarget_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 winAdd 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_nameAs 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 winAdd logging for region-aware factory mapping.
When
region="intl"andprovider_name="siliconflow", the code silently maps tosiliconflow_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_nameAs 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 winAdd logging for region-aware provider mapping.
The new region-aware mapping logic should be logged for observability, especially when
siliconflowis mapped tosiliconflow_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_nameAs 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
📒 Files selected for processing (6)
agent/component/browser.pyapi/apps/restful_apis/provider_api.pyapi/apps/services/provider_api_service.pyapi/db/joint_services/tenant_model_service.pyweb/src/interfaces/request/llm.tsweb/src/pages/user-setting/setting-model/hooks.tsx
Codecov Report✅ All modified and coverable lines are covered by tests. 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. 🚀 New features to boost your workflow:
|
What problem does this PR solve?
Fix:
Type of change