Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
125 changes: 103 additions & 22 deletions apps/models_provider/constants/model_provider_constants.py
Original file line number Diff line number Diff line change
@@ -1,8 +1,11 @@
# coding=utf-8
import importlib
import os
import threading
from typing import Iterator

from django.utils.translation import gettext_lazy as _

# 供应商注册表:模型供应商不再用 Enum 硬编码实例,而是注册为"模块路径 + 类名"的
# 惰性工厂。__getitem__ 首次访问某供应商时才 importlib 加载对应模块并缓存实例,
# 因此导入 models_provider 时不会连带加载 21 个供应商的重依赖(openai/bedrock/
Expand All @@ -12,11 +15,15 @@
class _ProviderRegistry:
def __init__(self):
self._factories: dict[str, tuple[str, str]] = {}
self._provider_info: dict[str, tuple[str, str]] = {}
self._instances: dict[str, object] = {}
self._lock = threading.Lock()

def register(self, name: str, provider_dir: str, class_name: str) -> "_ProviderRegistry":
def register(
self, name: str, provider_dir: str, class_name: str, display_name: str, icon_name: str
) -> "_ProviderRegistry":
self._factories[name] = (f"models_provider.impl.{provider_dir}.{provider_dir}", class_name)
self._provider_info[name] = (display_name, icon_name)
return self

def __getitem__(self, name: str):
Expand All @@ -40,32 +47,106 @@ def __contains__(self, name: object) -> bool:
def __len__(self) -> int:
return len(self._factories)

def get_provider_info_list(self) -> list[dict]:
"""返回供应商展示信息,不加载供应商实现及其重型依赖。"""
from common.utils.common import get_file_content
from maxkb.conf import PROJECT_DIR

provider_info_list = []
for name, (display_name, icon_name) in self._provider_info.items():
provider_dir = self._factories[name][0].rsplit(".", 1)[-1]
icon = get_file_content(
os.path.join(PROJECT_DIR, "apps", "models_provider", "impl", provider_dir, "icon", icon_name)
)
provider_info_list.append({"provider": name, "name": display_name, "icon": icon})
return provider_info_list

@property
def __members__(self) -> dict:
return self._factories


ModelProvideConstants = (
_ProviderRegistry()
.register("model_azure_provider", "azure_model_provider", "AzureModelProvider")
.register("model_qianfan_provider", "qianfan_model_provider", "QianfanModelProvider")
.register("model_ollama_provider", "ollama_model_provider", "OllamaModelProvider")
.register("model_openai_provider", "openai_model_provider", "OpenAIModelProvider")
.register("model_docker_ai_provider", "docker_ai_model_provider", "DockerModelProvider")
.register("model_kimi_provider", "kimi_model_provider", "KimiModelProvider")
.register("model_zhipu_provider", "zhipu_model_provider", "ZhiPuModelProvider")
.register("model_xf_provider", "xf_model_provider", "XunFeiModelProvider")
.register("model_deepseek_provider", "deepseek_model_provider", "DeepSeekModelProvider")
.register("model_gemini_provider", "gemini_model_provider", "GeminiModelProvider")
.register("model_volcanic_engine_provider", "volcanic_engine_model_provider", "VolcanicEngineModelProvider")
.register("model_tencent_provider", "tencent_model_provider", "TencentModelProvider")
.register("model_aws_bedrock_provider", "aws_bedrock_model_provider", "BedrockModelProvider")
.register("model_local_provider", "local_model_provider", "LocalModelProvider")
.register("model_xinference_provider", "xinference_model_provider", "XinferenceModelProvider")
.register("model_vllm_provider", "vllm_model_provider", "VllmModelProvider")
.register("aliyun_bai_lian_model_provider", "aliyun_bai_lian_model_provider", "AliyunBaiLianModelProvider")
.register("model_anthropic_provider", "anthropic_model_provider", "AnthropicModelProvider")
.register("model_siliconCloud_provider", "siliconCloud_model_provider", "SiliconCloudModelProvider")
.register("model_regolo_provider", "regolo_model_provider", "RegoloModelProvider")
.register("model_minimax_provider", "minimax_model_provider", "MiniMaxModelProvider")
.register("model_azure_provider", "azure_model_provider", "AzureModelProvider", "Azure OpenAI", "azure_icon_svg")
.register(
"model_qianfan_provider",
"qianfan_model_provider",
"QianfanModelProvider",
_("Thousand sails large model"),
"qianfan_icon_svg",
)
.register("model_ollama_provider", "ollama_model_provider", "OllamaModelProvider", "Ollama", "ollama_icon_svg")
.register("model_openai_provider", "openai_model_provider", "OpenAIModelProvider", "OpenAI", "openai_icon_svg")
.register(
"model_docker_ai_provider",
"docker_ai_model_provider",
"DockerModelProvider",
"Docker AI",
"docker_ai_icon_svg",
)
.register("model_kimi_provider", "kimi_model_provider", "KimiModelProvider", "Kimi", "kimi_icon_svg")
.register("model_zhipu_provider", "zhipu_model_provider", "ZhiPuModelProvider", _("zhipu AI"), "zhipuai_icon_svg")
.register("model_xf_provider", "xf_model_provider", "XunFeiModelProvider", _("iFlytek Spark"), "xf_icon_svg")
.register(
"model_deepseek_provider",
"deepseek_model_provider",
"DeepSeekModelProvider",
"DeepSeek",
"deepseek_icon_svg",
)
.register("model_gemini_provider", "gemini_model_provider", "GeminiModelProvider", "Gemini", "gemini_icon_svg")
.register(
"model_volcanic_engine_provider",
"volcanic_engine_model_provider",
"VolcanicEngineModelProvider",
_("volcano engine"),
"volcanic_engine_icon_svg",
)
.register(
"model_tencent_provider",
"tencent_model_provider",
"TencentModelProvider",
_("Tencent Cloud"),
"tencent_icon_svg",
)
.register(
"model_aws_bedrock_provider",
"aws_bedrock_model_provider",
"BedrockModelProvider",
"Amazon Bedrock",
"bedrock_icon_svg",
)
.register("model_local_provider", "local_model_provider", "LocalModelProvider", _("local model"), "local_icon_svg")
.register(
"model_xinference_provider",
"xinference_model_provider",
"XinferenceModelProvider",
"Xorbits Inference",
"xinference_icon_svg",
)
.register("model_vllm_provider", "vllm_model_provider", "VllmModelProvider", "vLLM", "vllm_icon_svg")
.register(
"aliyun_bai_lian_model_provider",
"aliyun_bai_lian_model_provider",
"AliyunBaiLianModelProvider",
_("Alibaba Cloud Bailian"),
"aliyun_bai_lian_icon_svg",
)
.register(
"model_anthropic_provider",
"anthropic_model_provider",
"AnthropicModelProvider",
"Anthropic",
"anthropic_icon_svg",
)
.register(
"model_siliconCloud_provider",
"siliconCloud_model_provider",
"SiliconCloudModelProvider",
"SILICONFLOW",
"siliconCloud_icon_svg",
)
.register("model_regolo_provider", "regolo_model_provider", "RegoloModelProvider", "Regolo", "regolo_icon_svg")
.register("model_minimax_provider", "minimax_model_provider", "MiniMaxModelProvider", "MiniMax", "minimax_icon_svg")
)

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Code Review

Potential Issues

1. Thread safety in get_provider_info_list / register

_provider_info is written without the lock in register, while _instances uses self._lock. If registration is only done once at import time this is fine, but it's inconsistent — consider guarding both or documenting that register is import-time-only.

2. get_provider_info_list does I/O every call (no caching)

  • It reads and serializes icon files on every invocation. These are static assets; cache the result (e.g., functools.lru_cache on a module-level helper, or store loaded icons after first build).
  • from common.utils.common import get_file_content and PROJECT_DIR are imported inside the method — fine for avoiding circular imports, but repeated per-call imports add overhead; hoist if safe.
  • Errors are not handled: if an icon file is missing/misnamed, get_file_content will throw and break the whole list. Consider try/except with a log + skip (or empty string).

3. Fragile dir extraction

provider_dir = self._factories[name][0].rsplit(".", 1)[-1]

This couples display-info lookup to the factory module path. Cleaner: store provider_dir directly in _provider_info, e.g.:

self._provider_info[name] = (display_name, icon_name)

and pass the dir you already have in register() (you do — provider_dir param), so just key by it.

4. Lazy translation (gettext_lazy) mixed with plain strings

Some entries use _("..."), others are hardcoded ("OpenAI", "DeepSeek", ...). That's probably intentional (brand names unchanged), but verify consistency. More importantly — display_name may be a lazy proxy object stored in a dict; when returned in a plain list[dict], it will render per current locale at access time, which is usually desired, but make sure callers don't need concrete str (e.g., for JSONKeyError with ensure_ascii). If serialized elsewhere, force str(...).

5. Naming typos / inconsistencies

  • "model_siliconCloud_provider" and "siliconCloud_model_provider" use camelCase inconsistently with the rest (snake_case). Changing keys is a breaking change, but worth flagging.
  • Icon filenames end in _svg (e.g., "azure_icon_svg") — presumably .svg extension appended internally. Ensure get_file_content handles this correctly. Double-check names like "zhipuai_icon_svg" vs provider name "zhipu", "bedrock_icon_svg" vs dir "aws_bedrock_model_provider" — easy to mismatch.

6. Return type docstring/signature

-> list[dict] is vague; prefer list[ProviderInfo] with a TypedDict / dataclass for clarity.

7. _provider_info may desync from _factories

Two parallel dicts keyed by name must stay in sync. If register ever fails partway (exception between assignments), state is inconsistent. Consider a single dict of small records, e.g.:

self._providers[name] = ProviderRecord(module=..., class_name=..., display_name=..., icon_name=..., dir=...)

Optimization suggestions

  • Cache get_provider_info_list() results (icons rarely change).
  • Use a dict-comprehension / loop over a declarative list instead of a 60-line .register(...) chain — easier to maintain and test:
    _PROVIDERS = [
        ("model_openai_provider", "openai_model_provider", "OpenAIModelProvider", "OpenAI", "openai_icon_svg"),
        ...
    ]
  • Add validation in register (duplicate name check, non-empty args) to fail fast.
  • Consider storing icon bytes lazily and a get_icon(name) accessor, so callers who only need names/icons don't pay full cost.

Summary

Main concerns: no caching on file I/O, fragile path-to-dir derivation, dual-dict desync risk, and a few naming typos. None are blocking, but addressing #2, #3, and #7 would improve robustness significantly.

4 changes: 1 addition & 3 deletions apps/models_provider/views/provide.py
Original file line number Diff line number Diff line change
Expand Up @@ -90,9 +90,7 @@ def get(self, request: Request):
):
providers.append(ModelProvideConstants[key].get_model_provide_info().to_dict())
return result.success(providers)
return result.success(
[ModelProvideConstants[key].get_model_provide_info().to_dict() for key in ModelProvideConstants.__members__]
)
return result.success(ModelProvideConstants.get_provider_info_list())

class ModelTypeList(APIView):
authentication_classes = [TokenAuth]

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Looking at this diff, here's my analysis:

What the change does

It replaces an inline list comprehension (that iterated ModelProvideConstants.__members__) with a call to a new class method ModelProvideConstants.get_provider_info_list().

Potential issues & suggestions

  1. Verify the new method exists and behaves identically

    • Confirm get_provider_info_list() is actually defined on the enum. If it's missing or still in progress, this will raise AttributeError at runtime.
    • Ensure it iterates over __members__ (not something like list(EnumClass)), because __members__ includes aliases, whereas plain iteration may not. Behavior could silently differ if aliases exist.
  2. Consistency between branches

    • The non-return branch above still calls key.get_model_provide_info().to_dict() per key individually. If get_provider_info_list() encapsulates this logic, consider refactoring the earlier branch to reuse it too, to avoid duplication and drift.
  3. Encapsulation is good, but watch for hidden side effects

    • Moving logic into the enum couples data (the enum) with serialization/API concerns (to_dict, result-list building). Consider whether provider-info listing belongs in a service layer rather than on the enum. This improves testability and separation of concerns.
  4. Ordering guarantees

    • Previously the list order followed __members__ insertion order. Verify the new method preserves the same deterministic ordering; otherwise API clients relying on order may break.
  5. Caching / performance

    • If the provider info is static, consider caching the result (e.g., @lru_cache or module-level constant) since this endpoint may be hit frequently, avoiding repeated dict construction.
  6. Return type / mutation safety

    • If get_provider_info_list() returns a shared/cached list, callers mutating it could corrupt state across requests. Return a fresh copy or ensure immutability.
  7. Missing context / truncation

    • The diff snippet appears truncated (line ends with + return result.success(ModelProvideConstants.get_provider_info_list())). Confirm there are no leftover/unreachable lines after this return and that the indentation aligns with the enclosing method.
  8. Test coverage

    • Add/adjust unit tests asserting the endpoint output is identical before and after this refactor (same content, order, and structure), especially if any enum members are aliases.

Summary: The refactor is reasonable and reduces duplication, but verify the new method exists, preserves iteration semantics (__members__ vs aliases), maintains ordering, and avoids returning mutable shared state.

Expand Down
Loading