action.py
9.8 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
"""行动 Agent:把知识与数据的结论变成可提交审批的动作卡、可运行的流程卡。只建议,不执行。"""
from __future__ import annotations
import json
import logging
import time
from fastapi import HTTPException
from ..capability import actions, defs
from ..core import llm
from ..kernel import service as ksvc
from . import prompts
from .base import AGENT_META, think_json
from .trace import Tracer
log = logging.getLogger(__name__)
def actions_catalog() -> str:
out = []
for a in defs.list_defs("action", "published"):
ps = ", ".join(f"{p['name']}({p['label']}{',必填' if p['required'] else ''}"
f"{',可选值 ' + '/'.join(p['enum']) if p['enum'] else ''})"
for p in a["spec"].get("params") or [])
tgt = a["spec"].get("target_type")
tname = ""
if tgt:
t = ksvc.rt_get(tgt)
tname = t["name"] if t else tgt
out.append(f"- {a['name']}({a['display_name'] or a['name']}):{a['description']} 参数 [{ps}]"
+ (f" 作用于对象类型「{tname}」,需给 object_key" if tgt else ""))
return "\n".join(out) or "(无)"
def sops_catalog() -> str:
"""已发布流程卡:标题、说明、要填的参数、步骤概要。
以前只给标题和一句说明,模型既不知道该填哪些参数,也不知道批了之后会发生什么,
给出来的流程卡建议全是自创的参数名,对不上号。"""
from ..sop import service as sop_service
out = []
for brief in sop_service.list_defs(status="published")[:20]:
try:
d = sop_service.get(brief["id"])
except Exception: # noqa: BLE001
continue
ps = "、".join(f"{p['name']}({p.get('label') or p['name']}"
f"{',必填' if p.get('required', True) else ',可选'})"
for p in d["spec"].get("params") or []) or "无"
steps = "→".join(st["title"] for st in sop_service.published_outline(d)[:6])
out.append(f"- {d['title']}:{d['description'] or '(无说明)'};参数 [{ps}];步骤:{steps}")
return "\n".join(out) or "(无)"
def sops_brief() -> str:
"""只列标题:纯查询时给主 Agent 知道「有这些流程」就够了,参数和步骤用不上。"""
from ..sop import service as sop_service
return "、".join(d["title"] for d in sop_service.list_defs(status="published")[:20]) or "(无)"
def run(tracer: Tracer, question: str, links: dict, links_text: str, results: dict,
results_text: str, task: str = "") -> dict:
span = tracer.span("agent")
started = time.time()
label = AGENT_META["action"]["label"]
tracer.emit({"type": "agent_start", "span": span, "parent": "lead", "agent": "action", "label": label,
"task": task or "根据结论给出可提交审批的动作与要发起的流程卡"})
try:
d = think_json(tracer, span, "action", [
{"role": "system", "content": prompts.ACTION_SYSTEM.format(actions=actions_catalog(),
sops=sops_catalog())},
{"role": "user", "content": prompts.ACTION_USER.format(
task=task or "(主 Agent 没有特别交代,自己判断)", question=question, links=links_text,
results=llm.truncate_to_tokens(results_text, 9000))}])
except Exception as e: # noqa: BLE001
log.warning("行动 Agent 失败:%s", str(e)[:200])
d = {}
suggest = [a for a in d.get("suggest_actions") or [] if isinstance(a, dict)][:3]
cards = prepare_cards(suggest, links, results, results_text, question)
sops = prepare_sop_cards([x for x in d.get("suggest_sops") or [] if isinstance(x, dict)][:2], results)
ok_cards = [c for c in cards if not c.get("error")]
ok_sops = [c for c in sops if not c.get("error")]
summary = ("、".join(x for x in (f"建议 {len(ok_cards)} 个动作" if ok_cards else "",
f"建议发起 {len(ok_sops)} 张流程卡" if ok_sops else "") if x)
or "没有需要执行的动作")
tracer.emit({"type": "agent_done", "span": span, "parent": "lead", "agent": "action", "label": label,
"summary": summary,
"findings": [f"{c['display_name']}:{c.get('reason', '')}" for c in ok_cards + ok_sops],
"insights": [], "confidence": 0.8 if (ok_cards or ok_sops) else 0.5, "ok": True,
"ms": int((time.time() - started) * 1000)})
return {"cards": cards, "sops": sops, "summary": summary}
def prepare_sop_cards(suggest: list[dict], results: dict) -> list[dict]:
"""流程卡建议 → 「确认发起」卡片。
模型写的标题解析成真实的已发布流程卡,参数按定义过滤(模型爱自创参数名)。卡片不建任何审批单:
提问的人核对参数后点「确认并发起」,流程就以他本人的身份跑起来(审计记「AI 建议,某某确认」),
流程里的动作再按各自的审批策略走。以前是先提一张「发起流程卡」的审批单,批完流程里的动作还要再批一次。"""
from ..sop import service as sop_service
out = []
for s in suggest:
ref = str(s.get("sop") or s.get("title") or "")
params = actions.render(s.get("params") or {}, results or {})
card = {"kind": "sop", "sop": ref, "display_name": ref, "object_key": "",
"params": params if isinstance(params, dict) else {},
"reason": s.get("reason") or ""}
d = sop_service.resolve_published(ref)
if d is None:
card["error"] = "没有找到这张已发布的流程卡"
out.append(card)
continue
defs_ = d["spec"].get("params") or []
names = {x["name"] for x in defs_}
card.update(sop_id=d["id"], sop=d["title"], display_name=d["title"], description=d["description"],
version=d["current_version"], param_defs=defs_, steps=sop_service.published_outline(d),
params={k: v for k, v in card["params"].items() if k in names})
missing = [p["label"] for p in defs_ if p.get("required") and p.get("default") in (None, "")
and card["params"].get(p["name"]) in (None, "")]
if missing:
card["missing"] = missing
out.append(card)
return out
def prepare_cards(suggest: list[dict], links: dict, results: dict, results_text: str,
question: str) -> list[dict]:
"""动作建议 → 可提交的卡片。参数常常要等取数之后才定得下来:先替换 $k1.字段 引用;
还不能通过校验,就拿执行结果让模型补一次参数。卡片带参数定义,人可以改了再提交。"""
out = []
for s in suggest:
ref = str(s.get("action") or "")
a = defs.find(ref, "action")
params = actions.render(s.get("params") or {}, results or {})
card = {"action": ref, "display_name": (a or {}).get("display_name") or ref,
"params": params if isinstance(params, dict) else {},
"object_key": str(actions.render(s.get("object_key") or "", results or {}) or ""),
"reason": s.get("reason") or ""}
if a is None or a["status"] != "published":
card["error"] = "动作不存在或未发布"
out.append(card)
continue
spec = a["spec"]
card["action_id"] = a["id"]
card["param_defs"] = spec.get("params") or []
card["target_type"] = spec.get("target_type") or ""
if not card["object_key"] and spec.get("target_type"):
inst = next((i for i in links.get("instances") or []
if i["concept_id"] == spec["target_type"]), None)
if inst:
card["object_key"] = inst["key"]
try:
card["preview"] = actions.prepare(a["id"], card["params"], card["object_key"])
except HTTPException as e:
card["error"] = str(e.detail)
fixed = _fill_params(a, card, results_text, links, question) if results_text else None
if fixed:
try:
card["preview"] = actions.prepare(a["id"], fixed["params"], fixed["object_key"])
card.update(params=fixed["params"], object_key=fixed["object_key"])
card.pop("error", None)
except HTTPException as e2:
card["error"] = str(e2.detail)
out.append(card)
return out
def _fill_params(a: dict, card: dict, results_text: str, links: dict, question: str) -> dict | None:
from .lead import links_text
spec = a["spec"]
target = ""
if spec.get("target_type"):
ot = ksvc.rt_get(spec["target_type"]) or {}
target = ot.get("name") or spec["target_type"]
try:
res = llm.chat_json([{"role": "user", "content": prompts.FILL_PROMPT.format(
name=a.get("display_name") or a["name"], desc=a.get("description") or "", target=target or "无",
params=json.dumps(spec.get("params") or [], ensure_ascii=False),
criteria=";".join(c["expression"] for c in spec.get("criteria") or []) or "无",
question=question or card.get("reason") or "", links=links_text(links),
results=llm.truncate_to_tokens(results_text, 6000))}], temperature=0)
except Exception as e: # noqa: BLE001
log.info("补全动作参数失败:%s", str(e)[:120])
return None
if not isinstance(res, dict):
return None
params = {k: v for k, v in (res.get("params") or {}).items() if v not in ("", None)}
if res.get("why"):
card["reason"] = f"{card.get('reason') or ''}({res['why']})".strip()
return {"params": params, "object_key": str(res.get("object_key") or card.get("object_key") or "")}