llm_models.py 8.01 KB
from __future__ import annotations

import logging
import os
from dataclasses import dataclass
from typing import Any

logger = logging.getLogger(__name__)


DASHSCOPE_CLIENT = "dashscope"
OPENAI_COMPATIBLE_CLIENT = "openai_compatible"
DEFAULT_DASHSCOPE_COMPATIBLE_BASE_URL = "https://dashscope.aliyuncs.com/compatible-mode/v1"

SUPPORTED_CHAT_MODELS = tuple(
    dict.fromkeys(
        (
            "qwen3.7-plus",
            "qwen3.6-plus",
            "qwen3.5-plus",
            "qwen-plus",
            "qwen3.6-flash",
            "qwen3.5-flash",
            "qwen-flash",
            "deepseek-v4.1-flash",
            "deepseek-v4-pro",
            "deepseek-v3.2",
        )
    )
)


@dataclass(frozen=True)
class ChatModelProfile:
    name: str
    client: str = DASHSCOPE_CLIENT
    multimodal: bool = False
    supports_enable_thinking: bool = False
    temperature: float | None = 0.5


_CHAT_MODEL_PROFILES: dict[str, ChatModelProfile] = {
    "qwen3.7-plus": ChatModelProfile(
        name="qwen3.7-plus",
        client=OPENAI_COMPATIBLE_CLIENT,
        supports_enable_thinking=True,
    ),
    "qwen3.6-plus": ChatModelProfile(
        name="qwen3.6-plus",
        client=OPENAI_COMPATIBLE_CLIENT,
        supports_enable_thinking=True,
    ),
    "qwen3.5-plus": ChatModelProfile(
        name="qwen3.5-plus",
        client=OPENAI_COMPATIBLE_CLIENT,
        supports_enable_thinking=True,
    ),
    "qwen-plus": ChatModelProfile(name="qwen-plus"),
    "qwen3.6-flash": ChatModelProfile(
        name="qwen3.6-flash",
        client=OPENAI_COMPATIBLE_CLIENT,
        supports_enable_thinking=True,
    ),
    "qwen3.5-flash": ChatModelProfile(
        name="qwen3.5-flash",
        client=OPENAI_COMPATIBLE_CLIENT,
        supports_enable_thinking=True,
    ),
    "qwen-flash": ChatModelProfile(name="qwen-flash"),
    "deepseek-v4.1-flash": ChatModelProfile(
        name="deepseek-v4.1-flash",
        client=OPENAI_COMPATIBLE_CLIENT,  # 原生 text-generation 端点对该模型报 url error,只能走兼容模式
        supports_enable_thinking=True,
        temperature=None,
    ),
    "deepseek-v4-pro": ChatModelProfile(
        name="deepseek-v4-pro",
        supports_enable_thinking=True,
        temperature=None,
    ),
    "deepseek-v3.2": ChatModelProfile(
        name="deepseek-v3.2",
        supports_enable_thinking=True,
        temperature=None,
    ),
}

_TRUE_VALUES = {"1", "true", "yes", "y", "on"}
_FALSE_VALUES = {"0", "false", "no", "n", "off"}
_AUTO_VALUES = {"", "auto", "default"}


def get_chat_model_profile(model_name: str) -> ChatModelProfile:
    normalized = _normalize_model_name(model_name)
    try:
        return _CHAT_MODEL_PROFILES[normalized]
    except KeyError as exc:
        supported = ", ".join(SUPPORTED_CHAT_MODELS)
        raise ValueError(f"Unsupported chat model: {model_name!r}. Supported models: {supported}") from exc


def build_model_init_kwargs(
    model_name: str,
    *,
    api_key: str,
    purpose: str | None = None,
    temperature: float | None = None,
    enable_thinking: bool | None = None,
) -> dict[str, Any]:
    profile = get_chat_model_profile(model_name)
    kwargs: dict[str, Any] = _base_model_kwargs(profile, api_key)
    generate_kwargs: dict[str, Any] = {}

    # 显式传入的 enable_thinking 优先于 env 解析:调用方(如 Map 阶段)可强制关思考。
    if enable_thinking is None:
        enable_thinking = resolve_enable_thinking(purpose)
    if enable_thinking is not None:
        if profile.supports_enable_thinking:
            if profile.client == OPENAI_COMPATIBLE_CLIENT:
                generate_kwargs.setdefault("extra_body", {})["enable_thinking"] = enable_thinking
            else:
                kwargs["enable_thinking"] = enable_thinking
        elif enable_thinking:
            raise ValueError(f"Model {profile.name!r} does not support enable_thinking")

    # profile.temperature 为 None 表示该模型不接受 temperature 参数(如 deepseek 系列),
    # 此时调用方的显式取值也不下发,否则会把这份刻意配置冲掉。
    if profile.temperature is None:
        if temperature is not None:
            logger.warning(
                "[LLM] model=%s does not accept temperature; ignoring temperature=%s",
                profile.name,
                temperature,
            )
    else:
        effective = temperature if temperature is not None else profile.temperature
        generate_kwargs["temperature"] = _validate_temperature(effective)

    if generate_kwargs:
        kwargs["generate_kwargs"] = generate_kwargs
    return kwargs


def _validate_temperature(value: Any) -> float:
    try:
        temperature = float(value)
    except (TypeError, ValueError) as exc:
        raise ValueError(f"temperature must be a number, got {value!r}") from exc
    if not 0.0 <= temperature <= 2.0:
        raise ValueError(f"temperature must be within [0, 2], got {temperature}")
    return temperature


def resolve_enable_thinking(purpose: str | None = None) -> bool | None:
    for env_name in _thinking_env_names(purpose):
        if env_name not in os.environ:
            continue
        return _parse_thinking_env(os.environ.get(env_name, ""), env_name)
    return None


def is_multimodal_model(model_name: str) -> bool:
    return get_chat_model_profile(model_name).multimodal


def is_default_thinking_enabled(model_name: str) -> bool:
    get_chat_model_profile(model_name)
    return False


def formatter_name_for_model(model_name: str) -> str:
    profile = get_chat_model_profile(model_name)
    if profile.client == OPENAI_COMPATIBLE_CLIENT:
        return "openai"
    return "dashscope"


def extract_text_content(content: Any) -> str:
    if content is None:
        return ""
    if isinstance(content, str):
        return content
    if isinstance(content, list):
        return "".join(extract_text_content(item) for item in content)
    if isinstance(content, dict):
        if content.get("type") == "thinking":
            return ""
        if "text" in content:
            return str(content.get("text") or "")
        if "content" in content:
            return extract_text_content(content.get("content"))
        return ""
    return str(content)


def extract_thinking_content(content: Any) -> str:
    if content is None or isinstance(content, str):
        return ""
    if isinstance(content, list):
        return "".join(extract_thinking_content(item) for item in content)
    if isinstance(content, dict):
        parts = []
        if "thinking" in content:
            parts.append(str(content.get("thinking") or ""))
        if "reasoning_content" in content:
            parts.append(str(content.get("reasoning_content") or ""))
        if "content" in content:
            parts.append(extract_thinking_content(content.get("content")))
        return "".join(parts)
    return ""


def _normalize_model_name(model_name: str) -> str:
    return str(model_name or "").strip().lower()


def _thinking_env_names(purpose: str | None) -> tuple[str, ...]:
    if not purpose:
        return ("LLM_ENABLE_THINKING",)
    normalized = purpose.strip().upper().replace("-", "_")
    return (
        f"{normalized}_ENABLE_THINKING",
        f"{normalized}_MODEL_ENABLE_THINKING",
        "LLM_ENABLE_THINKING",
    )


def _parse_thinking_env(raw_value: str, env_name: str) -> bool | None:
    value = str(raw_value).strip().lower()
    if value in _AUTO_VALUES:
        return None
    if value in _TRUE_VALUES:
        return True
    if value in _FALSE_VALUES:
        return False
    raise ValueError(f"{env_name} must be one of: auto, true, false")


def _base_model_kwargs(profile: ChatModelProfile, api_key: str) -> dict[str, Any]:
    kwargs: dict[str, Any] = {
        "model_name": profile.name,
        "api_key": api_key,
    }
    if profile.client == OPENAI_COMPATIBLE_CLIENT:
        kwargs["client_kwargs"] = {
            "base_url": os.environ.get(
                "DASHSCOPE_COMPATIBLE_BASE_URL",
                DEFAULT_DASHSCOPE_COMPATIBLE_BASE_URL,
            ),
        }
    else:
        kwargs["multimodality"] = profile.multimodal
    return kwargs