| 1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980 |
- # -*- coding: utf-8 -*-
- """
- LLM 模型实例缓存 —— 避免每次请求重复 init_chat_model
- 直接读取 .env 配置,确保模型字符串带有 provider 前缀(如 openai:),
- 避免 init_chat_model 根据模型名猜测错误的 provider(如将 deepseek-v4-pro
- 解析为 ChatDeepSeek 而非 ChatOpenAI)。
- """
- # Fast 模式模型实例缓存(模块级单例,避免每次请求重复 init_chat_model)
- # _fast_model: fast_mode=True 使用 SUMMARY_MODEL(低延迟 flash 模型)
- # _chat_model: fast_mode=False 使用 DEEPAGENT_MODEL(pro 模型)
- _fast_model = None
- _chat_model = None
- def get_chat_model(fast_mode: bool = True):
- """获取 LangChain ChatModel 实例,用于 Fast 模式直接调用 LLM。
- fast_mode=True 时使用 SUMMARY_MODEL(默认 deepseek-v4-flash),
- 延迟更低,适合直接模板填充任务;fast_mode=False 时使用 DEEPAGENT_MODEL。
- 模型实例按 mode 分别缓存,后续请求直接复用。
- """
- global _fast_model, _chat_model
- if fast_mode and _fast_model is not None:
- return _fast_model
- if not fast_mode and _chat_model is not None:
- return _chat_model
- from dotenv import dotenv_values
- from pathlib import Path as _Path
- from langchain.chat_models import init_chat_model
- _env_file = _Path(__file__).parent.parent / ".env"
- _cfg = dotenv_values(str(_env_file))
- # Fast 模式优先使用 SUMMARY_MODEL(低延迟),否则 fallback 到 DEEPAGENT_MODEL
- if fast_mode:
- model_str = _cfg.get("SUMMARY_MODEL", "") or _cfg.get("DEEPAGENT_MODEL", "openai:gpt-4o")
- else:
- model_str = _cfg.get("DEEPAGENT_MODEL", "openai:gpt-4o")
- base_url = _cfg.get("OPENAI_BASE_URL", "")
- api_key = _cfg.get("OPENAI_API_KEY", "")
- timeout_str = _cfg.get("OPENAI_TIMEOUT", "180")
- # 清理可能带入的引号
- api_key = api_key.strip().strip('"').strip("'") if api_key else ""
- base_url = base_url.strip().strip('"').strip("'") if base_url else ""
- # 解析超时时间
- try:
- timeout = float(timeout_str.strip())
- except (ValueError, TypeError):
- timeout = 180.0
- # 确保模型字符串带有 provider 前缀,否则 init_chat_model 可能猜错 provider
- if ":" not in model_str:
- model_str = f"openai:{model_str}"
- if base_url and api_key:
- model_instance = init_chat_model(
- model_str,
- openai_api_key=api_key,
- openai_api_base=base_url,
- temperature=0,
- timeout=timeout,
- max_retries=2,
- )
- else:
- model_instance = init_chat_model(model_str, temperature=0, timeout=timeout, max_retries=2)
- # 按模式分别缓存
- if fast_mode:
- _fast_model = model_instance
- else:
- _chat_model = model_instance
- return model_instance
|