skills.py 6.75 KB
"""对话技能登记处:智能助手在会话里能做的每一件事(单次补货、定时补货进度 …)都是一个技能。

功能(Feature)管业务域:开通开关、业务参数、定时任务、后台接口、单据表。
技能(Skill)只管对话:一个技能 = 名称 + 一段说明(提示词片段)+ 若干工具;参数、当前状态、试聊沙盒都是可选项。

一句话进来,大模型根据「已启用技能的说明 + 当前状态 + 最近聊天记录」选一个工具;工具是确定性代码,自己把结果发回会话。
大模型只负责「选哪个工具、从话里取参数」,下单相关的硬规则都在业务代码里(见 restock/single_service.py)。

门店的技能开关和参数存 atrs_sys_store_skill(没有这一行 = 用技能的默认值);提示词片段是可在后台改的话术(prompt_key)。
"""
from __future__ import annotations

import time
from dataclasses import dataclass
from typing import TYPE_CHECKING, Any, Callable, Iterable

from ..core import db
from ..core.db import insert, select, update
from ..models import store_skills_t

if TYPE_CHECKING:
    from pydantic import BaseModel

    from . import AgentTool, ChatContext, Feature, SandboxBox


@dataclass
class Skill:
    key: str                                    # 全局唯一,如 restock.single
    feature: str                                # 所属功能;功能没开通 → 技能不可用
    name: str                                   # 「单次补货」:提示词标题、后台、拒答话术
    description: str                            # 一句话能力说明(后台展示、拒答「我能帮你…」)
    tools: Callable[[], list["AgentTool"]]
    prompt_key: str = ""                        # 可选:提示词片段(告诉大模型什么时候用哪个工具,后台可改)
    config_model: type["BaseModel"] | None = None   # 可选:参数(后台按 schema 自动渲染表单)
    # 可选:本会话的当前状态(拼进给大模型的【当前状态】,并决定这句话关联哪张单)
    state: Callable[..., "ChatContext | None"] | None = None      # (store_id, sender_id, sender, box, target_id)
    # 可选:试聊用的同名工具(只改沙盒,不查 DMS、不建单、不发企微);没提供的工具在试聊里只回「试聊里不执行」
    sandbox_tools: Callable[["SandboxBox"], list["AgentTool"]] | None = None
    sandbox_view: Callable[["SandboxBox"], dict | None] | None = None
    # 可选:聊天记录里一条助手消息关联的单据(消息的 ref,如 restock:run:12)现在怎样了,如「SP-20261112-1-03 现在:已取消」。
    # 给大模型看聊天记录时拼在这条消息前面,让它知道那是当时的通知、现在的状态已经变了;不认识这个 ref 返回空。
    describe_ref: Callable[[int, str], str] | None = None          # (store_id, ref)
    default_enabled: bool = True


SKILLS: dict[str, Skill] = {}
_cache: dict[tuple[int, str], tuple[float, dict | None]] = {}


def load(features: Iterable["Feature"]) -> None:
    """启动时(features.load_all)从各功能收集技能并校验。重复调用会重建登记表。"""
    from ..services import texts
    found: dict[str, Skill] = {}
    tool_owner: dict[str, str] = {}
    for f in features:
        for s in f.skills():
            if s.key in found:
                raise RuntimeError(f"技能代码重复:{s.key}")
            if s.feature != f.key:
                raise RuntimeError(f"技能 {s.key} 声明属于 {s.feature},却登记在功能 {f.key} 下")
            if s.prompt_key and s.prompt_key not in texts.DEFAULTS:
                raise RuntimeError(f"技能 {s.key} 的提示词片段 {s.prompt_key} 没有登记默认内容")
            for t in s.tools():
                if t.name in tool_owner:
                    raise RuntimeError(f"工具名 {t.name} 同时出现在技能 {tool_owner[t.name]} 和 {s.key}")
                tool_owner[t.name] = s.key
            found[s.key] = s
    SKILLS.clear()
    SKILLS.update(found)
    texts.set_extra_editable([s.prompt_key for s in SKILLS.values() if s.prompt_key])
    _cache.clear()


def all_skills() -> list[Skill]:
    return list(SKILLS.values())


def get(key: str) -> Skill:
    return SKILLS[key]


def _row(store_id: int, key: str) -> dict | None:
    hit = _cache.get((store_id, key))
    if hit and time.time() - hit[0] < 5:
        return hit[1]
    r = db.one(select(store_skills_t).where(store_skills_t.c.store_id == store_id, store_skills_t.c.skill == key))
    _cache[(store_id, key)] = (time.time(), r)
    return r


def switched_on(store_id: int, key: str) -> bool:
    """技能自己的开关(不看所属功能有没有开通)。"""
    r = _row(store_id, key)
    return bool(r["enabled"]) if r else SKILLS[key].default_enabled


def is_enabled(store_id: int, key: str) -> bool:
    from . import is_enabled as feature_enabled
    s = SKILLS.get(key)
    return bool(s) and feature_enabled(store_id, s.feature) and switched_on(store_id, key)


def enabled(store_id: int) -> list[Skill]:
    """门店当前可用的技能(所属功能已开通 + 技能开关打开),按登记顺序。"""
    return [s for s in SKILLS.values() if is_enabled(store_id, s.key)]


def config(store_id: int, key: str) -> Any:
    s = SKILLS[key]
    if not s.config_model:
        return None
    r = _row(store_id, key)
    vals = db.jload(r["config"], {}) if r else {}
    try:
        return s.config_model(**(vals or {}))
    except Exception:  # noqa: BLE001  库里的值不合法(参数定义改过):退回默认,不让流程停摆
        return s.config_model()


def save(store_id: int, key: str, *, enabled: bool | None = None, values: dict | None = None) -> tuple[dict, dict]:
    """保存技能开关与参数(values 合并到现有参数后整体校验)。返回 (改前, 改后)。"""
    s = SKILLS[key]
    cur = _row(store_id, key)
    before_cfg = config(store_id, key).model_dump(mode="json") if s.config_model else {}
    before = {"enabled": switched_on(store_id, key), "config": before_cfg}
    cfg = before_cfg if (values is None or not s.config_model) else \
        s.config_model.model_validate(before_cfg | values).model_dump(mode="json")
    en = before["enabled"] if enabled is None else bool(enabled)
    with db.tx() as c:
        if cur:
            c.execute(update(store_skills_t).where(store_skills_t.c.store_id == store_id,
                                                   store_skills_t.c.skill == key)
                      .values(enabled=en, config=cfg))
        else:
            c.execute(insert(store_skills_t).values(store_id=store_id, skill=key, enabled=en, config=cfg))
    _cache.clear()
    return before, {"enabled": en, "config": cfg}


def clear_cache() -> None:
    _cache.clear()