"""litellm 封装，统一 LLM 调用入口。"""

from __future__ import annotations

import time

from litellm import completion


def call_llm(
    model: str,
    messages: list[dict],
    temperature: float = 0.3,
    max_tokens: int = 1000,
) -> dict:
    """
    调用 LLM，返回输出文本、token 用量和延迟。

    Returns:
        {"output": str, "token_usage": {"input": int, "output": int}, "latency_ms": float}
    """
    start = time.perf_counter()
    response = completion(
        model=model,
        messages=messages,
        temperature=temperature,
        max_tokens=max_tokens,
    )
    latency_ms = (time.perf_counter() - start) * 1000

    return {
        "output": response.choices[0].message.content,
        "token_usage": {
            "input": response.usage.prompt_tokens,
            "output": response.usage.completion_tokens,
        },
        "latency_ms": round(latency_ms, 2),
    }
