guards.py 3.92 KB
"""智能体工具调用前的校验:零件号这类参数必须有出处。

工具参数 JSON Schema 里标了 "x-from-text": true 的字段(如零件号),值必须出现在这句原话里,
或出现在这次给大模型看的最近 N 条聊天记录里(忽略大小写、空格和横杠)——大模型看得到的才能用,
防止它编一个零件号去查 DMS / 下单。「先查后订」(查完库存说「那订 2 个」)靠聊天记录里的查询结果接上。
标了 "x-from-sentence": true 的字段(如数量)必须是这句话里说过的(阿拉伯数字或「两个」「十二个」这样的中文数字),
对方没说数量时不执行,让模型先问。
发给大模型的 schema 去掉 x- 开头的扩展字段。
"""
from __future__ import annotations

import copy
import re

FROM_TEXT = "x-from-text"            # 值要出现在原话或最近聊天记录里(零件号)
FROM_SENTENCE = "x-from-sentence"    # 值要出现在这句原话里(数量:不能沿用聊天记录里的数字,更不能让模型自己假设)


def squash(text: str) -> str:
    return re.sub(r"[\s\-]", "", str(text or "")).upper()


def in_text(value, text: str) -> bool:
    v = squash(value)
    return bool(v) and v in squash(text)


def from_text_fields(parameters: dict | None) -> list[str]:
    props = (parameters or {}).get("properties") or {}
    return [k for k, p in props.items() if isinstance(p, dict) and p.get(FROM_TEXT)]


_CN = "零一二三四五六七八九"


def _cn_forms(n: int) -> set[str]:
    """数量的中文写法(1~99):2 → {二, 两},12 → {十二},20 → {二十}。"""
    if not 0 < n < 100:
        return set()
    if n < 10:
        base = _CN[n]
    elif n < 20:
        base = "十" + (_CN[n % 10] if n % 10 else "")
    else:
        base = _CN[n // 10] + "十" + (_CN[n % 10] if n % 10 else "")
    return {base, base.replace("二", "两")} if base.startswith("二") or base == "二" else {base}


def number_in_text(value, text: str) -> bool:
    """数量是否在这句话里说过:阿拉伯数字(独立的数字,不能是零件号的一部分)或中文数字。"""
    try:
        n = int(value)
    except (TypeError, ValueError):
        return False
    t = re.sub(r"[xX](?=\d)", " ", str(text or ""))        # 「x2」「X10」里的 x 是乘号
    if re.search(rf"(?<![0-9A-Za-z]){n}(?![0-9A-Za-z])", t):
        return True
    return any(f in t for f in _cn_forms(n))


def check_from_text(parameters: dict | None, args: dict, text: str, history: str = "") -> str:
    """返回拒绝原因;空串 = 通过。text = 这句原话;history = 给大模型看的聊天记录原文。"""
    props = (parameters or {}).get("properties") or {}
    bad = [f"{k}={args.get(k)}" for k in from_text_fields(parameters)
           if args.get(k) not in (None, "") and not in_text(args.get(k), text) and not in_text(args.get(k), history)]
    if bad:
        return f"参数 {'、'.join(bad)} 在原话和最近聊天记录里都没有出现,没有执行(只能用对方说过、或聊天记录里出现过的值)。"
    unsaid = [f"{k}={args.get(k)}" for k, p in props.items()
              if isinstance(p, dict) and p.get(FROM_SENTENCE) and args.get(k) not in (None, "")
              and not number_in_text(args.get(k), text)]
    if unsaid:
        return (f"参数 {'、'.join(unsaid)} 对方这句话里没有说,没有执行。不要自己假设,"
                "先问对方(例如:要订几个?),回复里不要写零件号。")
    return ""


def llm_schema(parameters: dict | None) -> dict:
    """去掉 x- 扩展字段后的 schema(给大模型看)。"""
    def strip(o):
        if isinstance(o, dict):
            return {k: strip(v) for k, v in o.items() if not str(k).startswith("x-")}
        if isinstance(o, list):
            return [strip(v) for v in o]
        return o
    return strip(copy.deepcopy(parameters or {"type": "object", "properties": {}}))