agent.py
12.3 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
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
"""问数 Agent:「这个数怎么取」由它全权负责,总编排器只决定「要不要取数」。
为什么独立出来:
- 总规划器既要管知识、流程、动作,又要在「按指标取数」和「让模型写 SQL」之间挑,经常挑错;
表结构塞进规划器的上下文也太贵。问数有自己的循环、自己的提示词、自己的评测集,才能单独调优。
为什么不自带语义层:
- 指标、口径、周期、对象都只在本体里定义一次(聚合函数 / 规则函数 / 周期函数 / 对象绑定),
这里只读。两套定义迟早会漂移 —— 这正是之前「物理指标」和本体指标各写一份的教训。
循环:
概念链接(不调 LLM)
→ 选路(命中带绑定的聚合函数时 1 次小 LLM:走指标 / 走 SQL / 反问)
→ 指标路:确定性编译 SQL(kernel.metrics),失败自动降级到 SQL 路
→ SQL 路:text2sql 管线(召回 → 计划 → 生成 → guard → 执行 → 自愈),问句里附上本体给出的口径与时间
→ 结果体检:空结果、整列 NULL、截断 → 写进 notes,作答时如实说明
"""
from __future__ import annotations
import logging
from typing import Any, Callable
from fastapi import HTTPException
from ..core import llm
from ..kernel import calendar as cal
from ..kernel import linker, metrics, service as ksvc
log = logging.getLogger(__name__)
Emit = Callable[[dict], None]
ROUTE_SYSTEM = """你是取数路由器。系统已从问题里识别出一些「聚合函数」(已定义好口径、能确定性取数的指标)。
判断这个问题能不能直接用其中一个聚合函数取数,并给出参数。
【可用的聚合函数】
{metrics}
【问题里识别出的对象实例】
{instances}
【识别出的时间】
{time}
输出 JSON,三选一:
1. 能用聚合函数:{{"route":"metric","metric":"函数名","dimensions":["拆分维度"],"filters":{{"维度名":"值"}},
"time":"current|last|YYYY-MM|null","object_key":"只取某个对象时填主键,否则空","order":"desc|asc","limit":数字}}
- dimensions / filters 只能用该函数列出的可拆分维度
- 问题带了时间(上周、本月……)但该函数「不能按时间过滤」(库存、缺口这类时点数)时,**仍然走 metric**,
time 填 null —— 系统会说明按当前值回答;不要因此改走 sql,自己写 SQL 很容易算错口径
- 问排名、分布、各 X 的时候要给 dimensions;问单个对象时给 object_key
2. 聚合函数覆盖不到(要的是明细、要跨多个指标运算、要的维度不支持……):{{"route":"sql","why":"原因"}}
3. 问题缺关键信息、无法取数:{{"route":"clarify","clarify":"向用户追问的一句话"}}
只输出 JSON。"""
def _metric_catalog(funcs: list[dict]) -> str:
lines = []
for f in funcs:
b = ksvc.rt_binding(f, "metric_expr")
ref = (b or {}).get("ref") or {}
spec = f.get("spec") or {}
lines.append(
f"- {f['name']}(别名:{'、'.join(f.get('synonyms') or []) or '无'}):{(f.get('description') or '')[:60]}"
f";单位 {spec.get('unit') or '无'};可拆分维度:{'、'.join(ref.get('dimensions') or {}) or '无'}"
f";{'可按单个对象取值' if ref.get('object_key_column') else '不能按单个对象取值'}"
f";{'可按时间过滤' if ref.get('time_column') else '不能按时间过滤'}")
return "\n".join(lines)
def _bound_aggregates(links: dict) -> list[dict]:
out = []
for c in (links.get("by_kind") or {}).get("aggregate") or []:
f = ksvc.rt_get(c["id"])
if f and ksvc.rt_binding(f, "metric_expr"):
out.append(f)
return out
def _context_notes(links: dict) -> list[str]:
"""本体能给 SQL 路的提示:命中的口径规则、统计周期解析出的起止日期、点名的对象。"""
notes = []
for c in (links.get("by_kind") or {}).get("rule") or []:
r = ksvc.rt_get(c["id"]) or {}
text = (r.get("spec") or {}).get("text") or r.get("description") or ""
if text:
notes.append(f"口径「{r['name']}」:{text}")
t = links.get("time")
if t and t.get("ref"):
# 统计周期是指标自己的口径:问句里点到的指标有业务月这类口径就按它解析,否则按自然月
m = next((ksvc.rt_get(c["id"]) for c in (links.get("by_kind") or {}).get("aggregate") or []), None)
period_spec = ((m or {}).get("spec") or {}).get("period") or None
try:
period = cal.resolve({**cal.NATURAL_MONTH, **period_spec} if period_spec else None, str(t["ref"]))
notes.append(f"时间「{t.get('text') or t['ref']}」按{metrics.period_label(period_spec or {})}"
f"解析为 {period['start']} ~ {period['end']}(含首尾)")
except Exception: # noqa: BLE001
pass
for i in links.get("instances") or []:
notes.append(f"问题里的「{i['label']}」是{i['type_name']},主键 {i['key']}")
return notes
def _route(question: str, funcs: list[dict], links: dict) -> dict:
inst = "\n".join(f"- {i['type_name']}「{i['label']}」主键={i['key']}"
for i in links.get("instances") or []) or "(无)"
msgs = [{"role": "system", "content": ROUTE_SYSTEM.format(
metrics=_metric_catalog(funcs), instances=inst, time=links.get("time") or "(无)")},
{"role": "user", "content": question}]
try:
r = llm.chat_json(msgs, temperature=0.0)
except Exception as e: # noqa: BLE001
log.warning("问数选路失败,走 SQL:%s", str(e)[:200])
return {"route": "sql", "why": "选路失败"}
return r if isinstance(r, dict) else {"route": "sql"}
def _metric_time(r: dict, links: dict, notes: list[str]) -> Any:
"""按指标取数用的时间。
- 问句里识别出了具体起止(上周、近 2 周、今天、本季度……),直接用识别结果:路由器只会说
current/last/YYYY-MM(月粒度),「上周」曾被它说成 last,结果查成了上个月;
- 指标没有时间列(库存、缺口这类时点数)时不带时间,并在备注里说明按当前值回答,
而不是报错降级到自由 SQL。"""
t = r.get("time")
lt = links.get("time") or {}
if lt.get("start") and lt.get("end"):
t = {"start": lt["start"], "end": lt["end"], "period": lt.get("phrase") or ""}
if t in (None, "", "null"):
return None
m = ksvc.rt_fn(str(r["metric"]), "aggregate") or {}
b = ksvc.rt_binding(m, "metric_expr") or {}
if m and not (b.get("ref") or {}).get("time_column"):
notes.append(f"「{m['name']}」是时点数(没有时间列),按当前值回答,没有按「{lt.get('phrase') or t}」过滤")
return None
return t
def _default_ds() -> int:
from ..text2sql import semantic
items = semantic.list_datasources()
if not items:
raise HTTPException(422, "还没有接入任何数据源")
return int(items[0]["id"])
def _check(out: dict) -> None:
"""结果体检。发现的问题写进 notes,作答时如实交代,而不是把一格 NULL 当结论。"""
rows = out.get("rows") or []
notes = out.setdefault("notes", [])
if not rows:
notes.append("查询成功但没有返回任何行:可能确实没有数据,也可能是时间或过滤条件过严")
elif all(v is None for r in rows for v in r):
notes.append("返回的值全是空(NULL):通常是过滤条件没匹配到任何数据")
if out.get("truncated"):
notes.append("结果行数超过上限,只返回了前面一部分")
def ask(question: str, *, ds_id: int = 0, history: list[dict] | None = None,
emit: Emit | None = None) -> dict:
"""问数主入口。返回 {route, sql, columns, rows, run_id, value, period, metric, calibre, notes, summary}。"""
def say(ev: dict) -> None:
if emit:
emit(ev)
links = linker.link(question)
funcs = _bound_aggregates(links)
notes: list[str] = []
fallback_why = ""
if funcs:
r = _route(question, funcs, links)
say({"type": "data_route", "route": r.get("route"), "detail": r})
if r.get("route") == "clarify" and r.get("clarify"):
return {"route": "clarify", "clarify": str(r["clarify"]), "columns": [], "rows": [],
"summary": f"需要补充信息:{r['clarify']}"}
if r.get("route") == "metric" and r.get("metric"):
try:
t = _metric_time(r, links, notes)
res = metrics.query(str(r["metric"]), dimensions=list(r.get("dimensions") or []),
filters=r.get("filters") if isinstance(r.get("filters"), dict) else {},
time=None if t in (None, "", "null") else t,
object_key=str(r.get("object_key") or ""),
order="asc" if r.get("order") == "asc" else "desc",
limit=int(r.get("limit") or 200), question=question)
res["notes"] = notes + list(res.get("notes") or []) # 时间说明 + 取数时的说明
say({"type": "sql", "sql": res["sql"], "run_id": res["run_id"]})
say({"type": "rows", "columns": res["columns"], "rows": res["rows"][:200]})
res["route"] = "metric"
_check(res)
m = res["metric"]
res["summary"] = (f"{m['name']} = {res['value']}{m['unit']}"
if res["value"] is not None else f"{m['name']} 共 {len(res['rows'])} 行")
return res
except HTTPException as e:
fallback_why = str(e.detail)
say({"type": "data_route", "route": "sql", "detail": {"why": f"指标取数失败,改写 SQL:{fallback_why}"}})
notes.append(f"按聚合函数取数失败({fallback_why}),改为生成 SQL")
elif r.get("why"):
fallback_why = str(r["why"])
else:
say({"type": "data_route", "route": "sql", "detail": {"why": "问题里没有命中已绑定数据的聚合函数"}})
# ---------- SQL 路 ----------
from ..text2sql.pipeline import run_ask
if not ds_id and funcs:
b = ksvc.rt_binding(funcs[0], "metric_expr")
ds_id = int((b or {}).get("ds_id") or 0)
ds_id = ds_id or _default_ds()
ctx = _context_notes(links)
q = question + (("\n(本体提示:" + ";".join(ctx) + ")") if ctx else "")
out: dict[str, Any] = {"route": "sql", "ds_id": ds_id, "columns": [], "rows": [], "notes": notes}
hist = [{"role": "user", "content": h["question"]} for h in history or []]
for ev in run_ask(ds_id, q, history=hist or None, summarize=False):
t = ev.get("type")
if t == "rows":
out["columns"], out["rows"] = ev["columns"], ev["rows"]
elif t == "execute":
out["sql"] = ev.get("sql")
out["truncated"] = ev.get("truncated")
elif t == "plan":
out["plan"] = ev.get("plan")
# 与指标路同形:{name, text}(前端按这个形状显示口径,以前 SQL 路给的是裸字符串,显示成空)
c = ev.get("calibre")
out["calibre"] = {"name": "取数口径", "text": c} if isinstance(c, str) and c else (c or None)
elif t == "answer":
out["answer"] = ev.get("text")
elif t == "error":
out["error"] = ev.get("error")
elif t == "done":
out["run_id"] = ev.get("run_id") or 0
out["outcome"] = ev.get("outcome")
if ev.get("clarify"):
out["clarify"] = ev["clarify"]
out["route"] = "clarify"
if t in ("plan", "sql_draft", "validate", "repair", "execute", "rows", "error"):
say(ev)
if out.get("route") == "clarify":
out["summary"] = f"需要补充信息:{out['clarify']}"
return out
if out.get("error") and not out["rows"]:
raise HTTPException(422, f"取数失败:{out['error']}")
if out.get("answer") and not out.get("sql"):
out["summary"] = out["answer"][:200]
return out
_check(out)
out["summary"] = f"返回 {len(out['rows'])} 行"
return out