2026-05-17 13:06:25 +08:00
|
|
|
from langchain.chat_models import BaseChatModel
|
2025-07-02 02:38:36 +08:00
|
|
|
from pydantic import SecretStr
|
2025-03-25 05:40:07 +08:00
|
|
|
|
2026-05-29 22:19:58 +08:00
|
|
|
from yuxi.models.providers.cache import model_cache
|
2026-03-17 10:16:44 +08:00
|
|
|
from yuxi.utils import get_docker_safe_url
|
|
|
|
|
from yuxi.utils.logging_config import logger
|
2025-03-29 17:33:09 +08:00
|
|
|
|
|
|
|
|
|
2026-05-17 13:06:25 +08:00
|
|
|
def load_chat_model(fully_specified_name: str, **kwargs) -> BaseChatModel:
|
|
|
|
|
if not fully_specified_name:
|
|
|
|
|
raise ValueError("model spec 不能为空")
|
2026-04-25 23:58:01 +08:00
|
|
|
|
2026-05-17 13:06:25 +08:00
|
|
|
info = model_cache.get_model_info(fully_specified_name)
|
2026-04-25 23:58:01 +08:00
|
|
|
if not info:
|
2026-05-17 13:06:25 +08:00
|
|
|
available_specs = model_cache.get_all_specs("chat")
|
|
|
|
|
available_ids = [item.spec for item in available_specs[:10]]
|
|
|
|
|
raise ValueError(
|
|
|
|
|
f"Unknown model spec: '{fully_specified_name}'. "
|
|
|
|
|
f"Available chat models ({len(available_specs)}): {available_ids}"
|
|
|
|
|
)
|
2026-04-25 23:58:01 +08:00
|
|
|
|
|
|
|
|
if info.model_type != "chat":
|
2026-05-17 13:06:25 +08:00
|
|
|
raise ValueError(f"Model {fully_specified_name} is not a chat model (type={info.model_type})")
|
2026-04-25 23:58:01 +08:00
|
|
|
|
|
|
|
|
api_key = info.api_key
|
|
|
|
|
base_url = get_docker_safe_url(info.base_url)
|
|
|
|
|
|
2026-05-17 13:06:25 +08:00
|
|
|
logger.debug(f"Loading model {fully_specified_name} with provider_type={info.provider_type}")
|
2026-04-25 23:58:01 +08:00
|
|
|
|
|
|
|
|
if info.provider_type == "anthropic":
|
|
|
|
|
from langchain_anthropic import ChatAnthropic
|
|
|
|
|
|
|
|
|
|
return ChatAnthropic(
|
|
|
|
|
model=info.model_id,
|
|
|
|
|
api_key=SecretStr(api_key),
|
|
|
|
|
base_url=base_url,
|
|
|
|
|
**kwargs,
|
|
|
|
|
)
|
2026-05-17 13:06:25 +08:00
|
|
|
if info.provider_type == "gemini":
|
2026-04-25 23:58:01 +08:00
|
|
|
from langchain_google_genai import ChatGoogleGenerativeAI
|
|
|
|
|
|
|
|
|
|
return ChatGoogleGenerativeAI(
|
|
|
|
|
model=info.model_id,
|
|
|
|
|
google_api_key=SecretStr(api_key),
|
|
|
|
|
**kwargs,
|
|
|
|
|
)
|
2025-07-02 02:38:36 +08:00
|
|
|
|
2026-05-17 13:06:25 +08:00
|
|
|
from langchain_openai import ChatOpenAI
|
2025-09-01 22:37:03 +08:00
|
|
|
|
2026-05-17 13:06:25 +08:00
|
|
|
return ChatOpenAI(
|
|
|
|
|
model=info.model_id,
|
|
|
|
|
api_key=SecretStr(api_key),
|
|
|
|
|
base_url=base_url,
|
|
|
|
|
stream_usage=True,
|
|
|
|
|
**kwargs,
|
|
|
|
|
)
|