"""LangChain 聊天模型适配:把项目现有的 litellm 路由(MiniMax/DeepSeek + 自定义端点)
包成一个 `ChatLiteLLM`,供 LangGraph 大脑使用——模型/密钥沿用 .env,零迁移成本。

为什么不直接复用 LiteLLMClient:LangGraph 节点需要一个 LangChain Runnable(支持
.invoke/.with_structured_output/LangSmith 追踪),而 LiteLLMClient 只是裸 .complete()。
两者共享同一份 config,确保换厂商仍是只改 .env。
"""

from __future__ import annotations

from langchain_litellm import ChatLiteLLM

from genesis import config

# 关闭思考模式的默认参数(两家厂商共用 extra_body.thinking;思考=分钟级长尾,日常决策不开)
_THINKING_OFF = {"thinking": {"type": "disabled"}}


def build_chat_model(*, temperature: float = 0.85, max_tokens: int | None = None,
                     request_timeout: float = 25.0, thinking: bool = False) -> ChatLiteLLM:
    """按 config.LLM_PROVIDER 构建 ChatLiteLLM(与 LiteLLMClient 路由一致)。"""
    if config.LLM_PROVIDER == "minimax":
        model = f"openai/{config.MINIMAX_MODEL}"      # OpenAI 兼容端点
        api_key = config.MINIMAX_API_KEY
        api_base = config.MINIMAX_BASE_URL
        on_type = "adaptive"
    else:
        model = f"deepseek/{config.DEEPSEEK_MODEL}"
        api_key = config.DEEPSEEK_API_KEY
        api_base = config.DEEPSEEK_BASE_URL
        on_type = "enabled"

    extra_body = {"thinking": {"type": on_type}} if thinking else dict(_THINKING_OFF)
    kw: dict = {
        "model": model,
        "api_key": api_key,
        "api_base": api_base,
        "temperature": temperature,
        "request_timeout": request_timeout,
        "model_kwargs": {"extra_body": extra_body},
    }
    if max_tokens:
        kw["max_tokens"] = max_tokens
    return ChatLiteLLM(**kw)
