ml.py 3.28 KB
"""模型推理函数(category=ml):调用登记过的模型端点,按输入 / 输出定义取预测值。

模型本身在外面(MLflow、自建推理服务……),本体只管:参数按声明校验、凭据由系统保管、
结果按声明取字段、每次调用可追溯。和 AI 分析不同,它的结果是确定的模型输出,可以作为依据。
"""
from __future__ import annotations

from typing import Any

import requests
from fastapi import HTTPException

from ..core.dbx import jload


def _pick(body: Any, path: str) -> Any:
    cur = body
    for part in [p for p in (path or "").split(".") if p]:
        if isinstance(cur, dict):
            cur = cur.get(part)
        elif isinstance(cur, list) and part.isdigit() and int(part) < len(cur):
            cur = cur[int(part)]
        else:
            return None
    return cur


def evaluate(fn: dict, inputs: dict) -> dict:
    from ..capability import defs
    spec = fn.get("spec") or {}
    if not spec.get("endpoint"):
        raise HTTPException(422, "模型推理函数还没有选择模型端点")
    ep = defs.find(spec["endpoint"], "endpoint")
    if ep is None or ep["status"] != "published":
        raise HTTPException(422, f"模型端点「{spec['endpoint']}」不存在或未发布")
    args = {}
    for f in spec.get("inputs") or []:
        v = (inputs or {}).get(f["name"])
        if v in (None, ""):
            raise HTTPException(422, f"缺少输入「{f.get('label') or f['name']}」")
        if f.get("type") == "number":
            try:
                v = float(v)
            except (TypeError, ValueError) as e:
                raise HTTPException(422, f"输入「{f.get('label') or f['name']}」应为数字") from e
        args[f["name"]] = v
    secret = defs.endpoint_secret(ep["id"])
    headers = {"Content-Type": "application/json", **(jload(secret, {}) if secret else {})}
    try:
        # request_path:输入放在请求体的哪个字段下(如 inputs / data.features);空 = 整个请求体就是输入
        body: dict = dict(args)
        for part in reversed([p for p in str(spec.get("request_path", "inputs") or "").split(".") if p]):
            body = {part: body}
        resp = requests.request(ep["spec"].get("method", "POST"), ep["spec"]["url"],
                                json=body, headers=headers,
                                timeout=float(spec.get("timeout") or ep["spec"].get("timeout") or 15))
    except requests.RequestException as e:
        raise HTTPException(502, f"模型端点调用失败:{str(e)[:200]}") from e
    if resp.status_code >= 400:
        raise HTTPException(502, f"模型端点返回 {resp.status_code}:{resp.text[:200]}")
    try:
        body = resp.json()
    except ValueError as e:
        raise HTTPException(502, "模型端点没有返回 JSON") from e
    data = _pick(body, spec.get("result_path") or "") if spec.get("result_path") else body
    outs = spec.get("outputs") or []
    if outs and isinstance(data, dict):
        # 每个输出可以单独写取值路径(path),不写就按输出名取
        result = {o["name"]: _pick(data, o.get("path") or o["name"]) for o in outs}
    else:
        result = data
    return {"result": result, "inputs": args, "endpoint": ep["name"],
            "summary": f"{fn.get('name')} → {result}"}