s05
模型工厂
能力层反射式动态加载
配置字符串 → importlib → ChatModel 实例任何 LangChain 兼容的 ChatModel 都可以通过配置接入,零代码改动
反射式动态加载
配置字符串 → importlib → ChatModel 实例任何 LangChain 兼容的 ChatModel 都可以通过配置接入,零代码改动
AI 模型生态变化极快——今天用 GPT-4o,明天可能换 Claude Sonnet,后天可能接入本地 Llama。如果每接入一个模型都要改代码、加 if-else,维护成本不可接受。DeerFlow 通过 resolve_class() + config.yaml 实现零代码模型切换:配置文件写一个类路径字符串,框架自动 import 并实例化——完全遵循开闭原则。
model:
class: langchain_openai.ChatOpenAI
model: gpt-4o
temperature: 0.7module = importlib.import_module('langchain_openai')
cls = getattr(module, 'ChatOpenAI')model = cls(
model='gpt-4o',
temperature=0.7
)agent = create_agent(
model=model,
tools=tools
)模型工厂核心 — config.yaml 中的字符串类路径 → resolve_class → 实例化 ChatModel
def create_chat_model(name=None, thinking_enabled=False, **kwargs):
config = get_app_config()
model_config = config.get_model_config(name)
# 'langchain_openai:ChatOpenAI' → ChatOpenAI 类
model_class = resolve_class(model_config.use, BaseChatModel)
# config.yaml 中的参数透传给构造函数
model_settings = model_config.model_dump(
exclude_none=True,
exclude={"use", "name", "supports_thinking", ...})
# Thinking 模式: 合并 when_thinking_enabled 配置
if thinking_enabled and has_thinking_settings:
model_settings.update(effective_wte)
return model_class(**kwargs, **model_settings)ModelConfig — 统一的模型配置 schema,extra='allow' 支持任意供应商特有参数透传
class ModelConfig(BaseModel):
name: str # 唯一标识
use: str # 类路径 e.g. 'langchain_openai:ChatOpenAI'
model: str # 模型名 e.g. 'gpt-4o'
supports_thinking: bool = False
supports_vision: bool = False
when_thinking_enabled: dict | None = None
thinking: dict | None = None # 简写: 等价于 wte["thinking"]
model_config = ConfigDict(extra="allow") # 透传任意额外参数