base.py 15.8 KB
"""Agent 基础:流式思考、经 MCP 调工具、ReAct 循环。"""
from __future__ import annotations

import concurrent.futures as cf
import contextvars
import json
import logging
import time
from dataclasses import dataclass
from typing import Any

from fastapi import HTTPException

from ..capability import mcp
from ..core import identity, llm
from . import prompts
from .trace import Tracer

log = logging.getLogger(__name__)

# 工具的中文名:审计、推理链都用它
TOOL_LABEL = {
    "list_ontology_types": "本体概览", "lookup_concept": "查定义与口径", "search_knowledge": "知识图谱多跳检索",
    "query_objects": "查找对象", "get_object": "读取对象", "get_linked_objects": "查关联对象",
    "traverse_link": "关系网遍历", "impact_analysis": "影响分析", "execute_function": "执行规则/函数",
    "query_metric": "指标取数", "data_ask": "问数(实时取数)", "run_analysis": "AI 分析",
    "find_runcard": "查流程卡", "execute_runcard": "按流程卡诊断", "schema_impact": "元素影响面",
    "recall_memory": "检索经验库", "propose_action": "提议动作", "get_action_status": "查审批单",
}

AGENT_META = {
    "lead": {"label": "主 Agent", "desc": "理解问题、分派任务、反思、汇总作答"},
    "knowledge": {"label": "知识 Agent", "desc": "本体定义与口径、文档原文、关系网多跳推理、影响分析"},
    "data": {"label": "问数 Agent", "desc": "实时取数、结果解读、异常下钻"},
    "action": {"label": "行动 Agent", "desc": "把结论变成可审批的动作与可运行的流程卡"},
}


# ---------------------------------------------------------------- 流式思考 + JSON
_PREFIXES = ("思考:", "思考:", "<think>")
_STOPS = ("```", "</think>", "\n{", "{\n")


def _thought_span(text: str, final: bool) -> tuple[int, int]:
    """思考正文在 text 里的 [start, end)。流式时结尾可能是半个「```」,先扣下不推。"""
    lead = len(text) - len(text.lstrip())
    start = lead
    for p in _PREFIXES:
        if text.startswith(p, lead):
            start = lead + len(p)
            break
    else:
        if text[lead:lead + 1] in ("{", "`"):         # 模型没写思考,直接给了 JSON
            return lead, lead
    end = len(text)
    for stop in _STOPS:
        i = text.find(stop, start)
        if i != -1:
            end = min(end, i)
    if end == len(text) and not final:
        for k in range(min(3, len(text) - start), 0, -1):
            tail = text[-k:]
            if any(stop.startswith(tail) for stop in _STOPS):
                end = len(text) - k
                break
    return start, end


def think_json(tracer: Tracer, span: str, agent: str, msgs: list[dict],
               temperature: float = 0.1) -> dict:
    """调用模型:开头「思考:」后面的内容逐字作为 thought 事件推出去,之后的 JSON 解析返回。"""
    full: list[str] = []
    emitted = 0
    tracer.stats["llm"] += 1
    for piece in llm.chat_stream(msgs, temperature=temperature):
        full.append(piece)
        if tracer.cancel.is_set():
            break
        text = "".join(full)
        start, end = _thought_span(text, final=False)
        body = text[start:end].rstrip()          # 结尾的换行先不推:可能紧跟着就是 JSON
        if emitted == 0:
            emitted = len(body) - len(body.lstrip())
        if len(body) > emitted:
            tracer.thought(span, body[emitted:], agent)
            emitted = len(body)
    text = "".join(full)
    start, end = _thought_span(text, final=True)
    body = text[start:end].rstrip()
    if len(body) > emitted:
        tracer.thought(span, body[emitted:], agent)
    obj = llm.parse_json(text[end:] if end > start else text)
    if not isinstance(obj, dict):
        obj = {}
    if not body.strip() and isinstance(obj.get("thought"), str):
        tracer.thought(span, obj["thought"], agent)
    return obj


# ---------------------------------------------------------------- 结果整理
def compact_result(res: Any) -> Any:
    """给前端的工具结果:大字段瘦身。"""
    if not isinstance(res, dict):
        return res
    out = dict(res)
    if isinstance(out.get("rows"), list) and len(out["rows"]) > 100:
        out["rows"] = out["rows"][:100]
        out["rows_truncated"] = True
    if isinstance(out.get("chunks"), list):
        out["chunks"] = [{"id": c.get("id"), "heading": c.get("heading", ""), "doc_id": c.get("doc_id"),
                          "text": (c.get("text") or "")[:400]} for c in out["chunks"] if isinstance(c, dict)]
    out.pop("context_text", None)
    return out


def summarize(res: Any) -> str:
    if isinstance(res, dict):
        if res.get("summary"):
            return str(res["summary"])[:300]
        if res.get("rows") is not None:
            return f"返回 {len(res.get('rows') or [])} 行"
    return ""


def result_text(rec: dict, res: Any) -> str:
    """把一次工具调用的结果写成给模型看的文字。"""
    head = f"### [{rec['id']}] {TOOL_LABEL.get(rec['call'], rec['call'])}({rec.get('why', '')})"
    if rec.get("error"):
        return f"{head}\n执行失败:{rec['error']}"
    if not isinstance(res, dict):
        return f"{head}\n{str(res)[:1500]}"
    parts = [head]
    if res.get("run_id") and res.get("columns") is not None:
        cols = res.get("columns") or []
        rows = res.get("rows") or []
        parts.append(f"数据编号 run:{res['run_id']};共 {len(rows)} 行"
                     + (f";统计期 {res['period']}" if res.get("period") else ""))
        if isinstance(res.get("metric"), dict):
            parts.append(f"指标:{res['metric'].get('name')}(单位 {res['metric'].get('unit') or '无'})")
        if isinstance(res.get("calibre"), dict):
            parts.append(f"口径({res['calibre'].get('name')}):{res['calibre'].get('text')}")
        if res.get("route"):
            parts.append("取数方式:" + ("按已定义指标确定性取数" if res["route"] == "metric"
                                    else "问数 Agent 生成 SQL"))
        for n in res.get("notes") or []:
            parts.append(f"⚠ 数据体检:{n}")
        parts.append("| " + " | ".join(map(str, cols)) + " |")
        for r in rows[:30]:
            parts.append("| " + " | ".join("" if v is None else str(v) for v in r) + " |")
        if len(rows) > 30:
            parts.append(f"…(其余 {len(rows) - 30} 行略)")
    if res.get("chunks"):
        for c in res["chunks"][:8]:
            parts.append(f"[{c['id']}]【{c.get('heading') or '正文'}】{(c.get('text') or '')[:700]}")
    if res.get("relations"):
        parts.append("相关关系:" + ";".join(map(str, res["relations"][:15])))
    if res.get("concept"):
        c = res["concept"]
        parts.append(f"概念定义:{c.get('kind')}「{c.get('name')}」:{c.get('description')};"
                     f"定义细节:{json.dumps(c.get('spec'), ensure_ascii=False)[:600]}")
        for e in res.get("evidence") or []:
            if e.get("chunk_id"):
                parts.append(f"[{e['chunk_id']}]【{e.get('heading') or '出处'}】{e.get('snippet', '')[:400]}")
    if res.get("clarify") and not res.get("rows"):
        parts.append(f"问数需要补充信息:{res['clarify']}")
    for key in ("items", "groups", "concepts", "steps", "suggested", "output", "result",
                "properties", "value", "expression", "start", "end", "outcome", "affected", "layers"):
        if key in res and not (key == "value" and res.get("columns")):
            parts.append(f"{key}:{json.dumps(res[key], ensure_ascii=False, default=str)[:1500]}")
    if res.get("summary"):
        parts.append(f"小结:{res['summary']}")
    return "\n".join(parts)


def tools_text(names: list[str]) -> str:
    out = []
    for n in names:
        t = mcp.TOOLS.get(n)
        if t is None:
            continue
        props = "; ".join(f"{k}: {v.get('description', '')}" for k, v in (t.properties or {}).items())
        out.append(f"- {t.name}({TOOL_LABEL.get(t.name, t.name)}):{t.description} 参数 {{{props}}}")
    return "\n".join(out)


# ---------------------------------------------------------------- 工具调用
def call_tool(tracer: Tracer, parent: str, agent: str, prefix: str, call: dict,
              allowed: set[str] | None = None) -> dict:
    """经 MCP 执行一次工具调用,推送 tool_start / tool_event / tool_done。返回调用记录(含 _result)。"""
    cid = tracer.span(prefix)
    raw = str(call.get("tool") or call.get("call") or "")
    args = call.get("args") if isinstance(call.get("args"), dict) else {}
    why = str(call.get("why") or "")
    try:
        tool, args = mcp.resolve(raw, args)
        name = tool.name
    except HTTPException:
        name = raw
    if name == "execute_runcard":
        # 提问里只能「按流程诊断」(只读)。发起流程走答案下方的确认卡,由提问的人自己确认 ——
        # 以前 AI 在一次纯查询里就能真的提出一张「发起流程」的审批单。
        args = {**args, "mode": "readonly"}
    rec: dict[str, Any] = {"id": cid, "call": name, "args": args, "why": why, "agent": agent}
    tracer.emit({"type": "tool_start", "span": cid, "parent": parent, "agent": agent, "tool": name,
                 "label": TOOL_LABEL.get(name, name), "args": args, "why": why})
    started = time.time()
    if tracer.cancel.is_set():
        # 用户已经点了停止 / 切走了:排好的调用不再执行,免得白白查库
        ok, res = False, "已停止"
    elif allowed is not None and name not in allowed:
        ok, res = False, f"「{TOOL_LABEL.get(name, name)}」不在{AGENT_META[agent]['label']}的工具范围内"
    else:
        def emit(ev: dict) -> None:
            tracer.emit({"type": "tool_event", "span": cid, "parent": parent, "agent": agent, "event": ev})
        ok, res = mcp.call_logged(identity.current(), name, args, f"ask:{agent}", emit=emit)
    ms = int((time.time() - started) * 1000)
    if ok:
        rec["summary"] = summarize(res)
        tracer.emit({"type": "tool_done", "span": cid, "parent": parent, "agent": agent, "tool": name,
                     "ok": True, "summary": rec["summary"], "result": compact_result(res), "ms": ms})
    else:
        rec["error"] = str(res)[:400]
        res = {"error": rec["error"]}
        tracer.emit({"type": "tool_done", "span": cid, "parent": parent, "agent": agent, "tool": name,
                     "ok": False, "error": rec["error"], "ms": ms})
    rec["ms"] = ms
    rec["_result"] = res
    return rec


def run_parallel(fns: list) -> list:
    """在各自的上下文副本里并行跑(身份、工作区、LLM 计费标签都带过去)。"""
    if len(fns) <= 1:
        return [f() for f in fns]
    with cf.ThreadPoolExecutor(max_workers=min(4, len(fns))) as pool:
        futs = [pool.submit(contextvars.copy_context().run, f) for f in fns]
        return [f.result() for f in futs]


# ---------------------------------------------------------------- 子 Agent
@dataclass
class SubAgent:
    name: str
    role: str
    tools: list[str]
    prefix: str
    extra: str = ""
    max_rounds: int = 3

    @property
    def label(self) -> str:
        return AGENT_META[self.name]["label"]

    def run(self, tracer: Tracer, task: str, *, question: str, links_text: str, ontology: str,
            first_calls: list[dict] | None = None) -> dict:
        span = tracer.span("agent")
        started = time.time()
        tracer.emit({"type": "agent_start", "span": span, "parent": "lead", "agent": self.name,
                     "label": self.label, "task": task})
        allowed = set(self.tools)
        system = prompts.AGENT_SYSTEM.format(label=self.label, role=self.role,
                                             tools=tools_text(self.tools), ontology=ontology,
                                             extra=self.extra)
        records: list[dict] = []
        calls = [c for c in first_calls or [] if isinstance(c, dict)][:3]
        final: dict = {}
        rnd = 0
        seen: set[str] = set()
        while not tracer.cancel.is_set():
            if calls:
                todo = []
                for c in calls:
                    key = json.dumps([c.get("tool"), c.get("args")], ensure_ascii=False, sort_keys=True,
                                     default=str)
                    if key not in seen:
                        seen.add(key)
                        todo.append(c)
                if todo:
                    records += run_parallel([lambda c=c: call_tool(tracer, span, self.name, self.prefix, c, allowed)
                                             for c in todo])
                rnd += 1
                calls = []
            if tracer.cancel.is_set():
                break
            if rnd and tracer.over_budget():
                break                          # 时间预算用完:不再多想一轮,拿已有结果汇报
            force = rnd >= self.max_rounds
            if rnd:
                tracer.thought(span, "\n", self.name)        # 新一轮思考另起一段
            obs = "\n\n".join(result_text(r, r["_result"]) for r in records) or "(还没有做任何调用)"
            try:
                d = think_json(tracer, span, self.name, [
                    {"role": "system", "content": system},
                    {"role": "user", "content": prompts.AGENT_USER.format(
                        task=task, question=question, links=links_text, round=rnd + 1,
                        max_rounds=self.max_rounds, force=";本轮必须给 final" if force else "",
                        observations=llm.truncate_to_tokens(obs, 9000))}])
            except Exception as e:  # noqa: BLE001
                log.warning("%s 思考失败:%s", self.name, str(e)[:200])
                break
            if d.get("calls") and not force and isinstance(d["calls"], list):
                calls = [c for c in d["calls"] if isinstance(c, dict)][:3]
                if calls:
                    continue
            final = d.get("final") if isinstance(d.get("final"), dict) else {}
            break
        ok_recs = [r for r in records if not r.get("error")]
        summary = str(final.get("summary") or ";".join(r["summary"] for r in ok_recs if r.get("summary"))
                      or ("没有拿到有效结果" if records else "未执行"))
        try:
            conf = float(final.get("confidence", 0.7 if ok_recs else 0.2))
        except (TypeError, ValueError):
            conf = 0.5
        out = {"agent": self.name, "label": self.label, "span": span, "task": task, "summary": summary,
               "findings": [str(x) for x in final.get("findings") or []][:8],
               "insights": [str(x) for x in final.get("insights") or []][:6],
               "confidence": max(0.0, min(1.0, conf)), "ok": bool(ok_recs), "records": records,
               "ms": int((time.time() - started) * 1000)}
        tracer.emit({"type": "agent_done", "span": span, "parent": "lead", "agent": self.name,
                     "label": self.label, "summary": summary, "findings": out["findings"],
                     "insights": out["insights"], "confidence": out["confidence"], "ok": out["ok"],
                     "ms": out["ms"]})
        return out


KNOWLEDGE = SubAgent(
    "knowledge", prompts.KNOWLEDGE_ROLE,
    ["search_knowledge", "lookup_concept", "list_ontology_types", "find_runcard", "schema_impact",
     "query_objects", "get_object", "get_linked_objects", "traverse_link", "impact_analysis"],
    prefix="k", extra=prompts.KNOWLEDGE_EXTRA, max_rounds=2)

DATA = SubAgent(
    "data", prompts.DATA_ROLE,
    ["data_ask", "query_metric", "execute_function", "run_analysis", "lookup_concept", "query_objects",
     "get_object", "get_linked_objects", "execute_runcard"],
    prefix="d", extra=prompts.DATA_EXTRA, max_rounds=2)       # 一次取数 + 最多一次下钻:每次问数 20~30 秒

SUB_AGENTS = {"knowledge": KNOWLEDGE, "data": DATA}