trace.ts
10.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
/**
* 多智能体推理轨迹:把后端事件折叠成「主 Agent → 子 Agent → 工具调用」的状态树。
*
* 实时流和历史回放用的是同一个 reducer:回放就是把落库的事件按原来的节奏重新喂一遍。
* 另外从事件里拼出「本体图谱」—— 链接到的概念、知识检索每一跳的路径、关系网遍历与影响分析的对象,
* 随推理进行一点点长出来。
*/
import type { GraphPayload } from "@/lib/types";
export type NodeStatus = "running" | "done" | "error";
export interface AgentNode {
span: string; agent: string; label: string; task: string; status: NodeStatus;
thought: string; summary: string; findings: string[]; insights: string[]; confidence?: number;
tools: string[]; startTs: number; ms?: number;
}
export interface ToolNode {
span: string; parent: string; agent: string; tool: string; label: string; args: any; why: string;
status: NodeStatus; summary: string; error: string; result: any; events: any[]; startTs: number; ms?: number;
}
export interface TraceState {
agents: Record<string, AgentNode>;
order: string[]; // agent span 顺序
tools: Record<string, ToolNode>;
links: { concepts: any[]; instances: any[]; time: any } | null;
/** 这一轮实际执行过的本体元素(指标、规则、决策表、查过定义的概念),区别于问句里「匹配到」的 */
used: { id: string; name: string; kind_label: string; how: string }[];
memory: { cases: any[]; facts: any[]; fast: string } | null;
plan: any | null;
reflect: any[];
lastTs: number;
events: number;
}
export const emptyTrace = (): TraceState => ({
agents: {}, order: [], tools: {}, links: null, used: [], memory: null, plan: null, reflect: [], lastTs: 0, events: 0,
});
const arr = <T,>(v: unknown): T[] => (Array.isArray(v) ? (v as T[]) : []);
/** 纯函数:返回新状态(浅拷贝被改动的部分),React 里直接 setState。 */
export function applyEvent(s: TraceState, ev: any): TraceState {
if (!ev || typeof ev !== "object") return s;
const ts = typeof ev.ts === "number" ? ev.ts : s.lastTs;
const next: TraceState = { ...s, lastTs: Math.max(s.lastTs, ts), events: s.events + 1 };
switch (ev.type) {
case "link":
next.links = { concepts: arr(ev.concepts), instances: arr(ev.instances), time: ev.time ?? null };
return next;
case "onto_used":
next.used = arr(ev.items);
return next;
case "memory":
next.memory = { cases: arr(ev.cases), facts: arr(ev.facts), fast: ev.fast || "" };
return next;
case "plan":
next.plan = ev;
return next;
case "reflect":
next.reflect = [...s.reflect, ev];
return next;
case "agent_start": {
const span = String(ev.span || "");
if (!span) return next;
const prev = s.agents[span];
next.agents = { ...s.agents, [span]: {
span, agent: ev.agent || "", label: ev.label || ev.agent || "", task: ev.task || "",
status: "running", thought: prev?.thought || "", summary: "", findings: [], insights: [],
tools: prev?.tools || [], startTs: ts } };
next.order = s.order.includes(span) ? s.order : [...s.order, span];
return next;
}
case "thought": {
const span = String(ev.span || "");
const a = s.agents[span] || {
span, agent: ev.agent || span, label: ev.agent || span, task: "", status: "running" as NodeStatus,
thought: "", summary: "", findings: [], insights: [], tools: [], startTs: ts };
next.agents = { ...s.agents, [span]: { ...a, thought: a.thought + (ev.text || "") } };
if (!s.order.includes(span)) next.order = [...s.order, span];
return next;
}
case "agent_done": {
const a = s.agents[ev.span];
if (!a) return next;
next.agents = { ...s.agents, [ev.span]: {
...a, status: ev.ok === false ? "error" : "done", summary: ev.summary || "",
findings: arr<string>(ev.findings), insights: arr<string>(ev.insights),
confidence: typeof ev.confidence === "number" ? ev.confidence : undefined, ms: ev.ms } };
return next;
}
case "tool_start": {
const span = String(ev.span || "");
next.tools = { ...s.tools, [span]: {
span, parent: ev.parent || "", agent: ev.agent || "", tool: ev.tool || "", label: ev.label || ev.tool || "",
args: ev.args ?? {}, why: ev.why || "", status: "running", summary: "", error: "", result: null,
events: [], startTs: ts } };
const a = s.agents[ev.parent];
if (a && !a.tools.includes(span)) next.agents = { ...s.agents, [ev.parent]: { ...a, tools: [...a.tools, span] } };
return next;
}
case "tool_event": {
const t = s.tools[ev.span];
if (!t) return next;
next.tools = { ...s.tools, [ev.span]: { ...t, events: [...t.events, ev.event] } };
return next;
}
case "tool_done": {
const t = s.tools[ev.span];
if (!t) return next;
next.tools = { ...s.tools, [ev.span]: {
...t, status: ev.ok ? "done" : "error", summary: ev.summary || "", error: ev.error || "",
result: ev.result ?? null, ms: ev.ms } };
return next;
}
default:
return next;
}
}
export function foldEvents(events: any[]): TraceState {
return arr<any>(events).reduce(applyEvent, emptyTrace());
}
/** 一句话摘要:给折叠后的思考卡用。 */
export function traceSummary(s: TraceState, durationMs?: number): string {
const subs = s.order.filter((sp) => s.agents[sp]?.agent !== "lead").length;
const tools = Object.values(s.tools);
const hops = tools.reduce((n, t) => n + t.events.filter((e) => e?.type === "hop").length, 0);
const sqls = tools.reduce((n, t) => n + t.events.filter((e) => e?.type === "sql").length, 0)
+ tools.filter((t) => t.result?.run_id && !t.events.some((e) => e?.type === "sql")).length;
const cases = s.memory?.cases?.length || 0;
return [
subs && `调度 ${subs} 个智能体`,
tools.length && `${tools.length} 次工具调用`,
hops && `图谱 ${hops} 轮扩展`,
sqls && `取数 ${sqls} 次`,
cases && `参考 ${cases} 个历史案例`,
s.memory?.fast && "复用已验证路径",
durationMs ? `${(durationMs / 1000).toFixed(1)}s` : "",
].filter(Boolean).join(" · ");
}
// ------------------------------------------------------------------ 图谱
export interface GraphBuild { payload: GraphPayload | null; emphasis: { nodes: Set<string>; edges: Set<string>; seeds: Set<string> } | null }
const KIND_TYPE: Record<string, string> = {
object_type: "对象", link_type: "关系", aggregate: "指标", rule: "规则", object_set: "对象集",
decision: "决策表", ai: "AI 分析", action: "动作", function: "函数", value_type: "值类型",
};
/**
* 从轨迹拼出一张子图:
* - 本体概念(链接到的指标、对象、规则…)作为种子
* - 知识检索:link 命中的实体为种子、每一跳 hop 的路径逐条加进来
* - 关系网遍历 / 影响分析:对象实例与关系边
*/
export function buildGraph(s: TraceState): GraphBuild {
const nodes = new Map<string, { label: string; type: string; seed: boolean; degree: number }>();
const edges = new Map<string, { source: string; target: string; relation: string; occurrence: number }>();
const seeds = new Set<string>();
const add = (id: string, label?: string, type?: string, seed = false) => {
if (!id) return;
const cur = nodes.get(id);
nodes.set(id, { label: label || cur?.label || id, type: type || cur?.type || "其他",
seed: seed || cur?.seed || false, degree: (cur?.degree || 1) + 1 });
if (seed) seeds.add(id);
};
const edge = (id: string, source: string, target: string, relation: string, occurrence = 1) => {
if (!source || !target || source === target) return;
edges.set(id || `${source}|${relation}|${target}`, { source, target, relation, occurrence });
};
for (const c of s.links?.concepts || []) {
add(`c:${c.id}`, c.name, KIND_TYPE[c.type_key || c.kind] || "概念", true);
}
for (const i of s.links?.instances || []) {
add(`${i.concept_id}:${i.key}`, `${i.label}`, i.type_name || "对象", true);
}
for (const t of Object.values(s.tools)) {
for (const ev of t.events) {
if (ev?.type === "link") {
for (const l of arr<any>(ev.links)) for (const m of arr<any>(l.matches)) add(m.id, m.label, m.type, true);
} else if (ev?.type === "hop") {
for (const p of arr<any>(ev.paths)) {
add(p.source); add(p.target);
edge(p.id, p.source, p.target, p.relation, p.occurrence || 1);
}
}
}
const r = t.result;
if (!r || typeof r !== "object") continue;
if (r.subgraph && Array.isArray(r.subgraph.nodes)) {
for (const n of r.subgraph.nodes) add(n.id, n.label, n.type, !!n.seed);
for (const e of arr<any>(r.subgraph.edges)) edge(e.id, e.source, e.target, e.relation, e.occurrence || 1);
}
if (Array.isArray(r.nodes) && r.root) { // traverse_link / impact_analysis
for (const n of r.nodes) add(n.id, n.label, n.type_name, n.id === r.root.id);
for (const e of arr<any>(r.edges)) edge(`${e.from}|${e.link_id}|${e.to}`, e.from, e.to, e.link || "", 1);
}
}
if (!nodes.size) return { payload: null, emphasis: null };
// 本体概念和检索到的实体往往同名:同名的连一条虚线,图不会碎成两块
const byLabel = new Map<string, string>();
for (const [id, n] of nodes) {
const k = n.label.trim();
const other = byLabel.get(k);
if (other && other !== id) edge(`same:${other}:${id}`, other, id, "即", 1);
else byLabel.set(k, id);
}
const payload: GraphPayload = {
nodes: [...nodes].map(([key, v]) => ({
key, attributes: { label: v.label, type: v.type, degree: v.degree, size: v.seed ? 11 : 6 + Math.min(6, v.degree),
community: null, occurrence: 1, doc_ids: [], verified: false },
})),
edges: [...edges].filter(([, e]) => nodes.has(e.source) && nodes.has(e.target)).map(([key, e]) => ({
key, source: e.source, target: e.target,
attributes: { label: e.relation, relation: e.relation, occurrence: e.occurrence,
size: 1 + Math.min(2.5, e.occurrence * 0.25), verified: false },
})),
truncated: false, total_matched: nodes.size,
};
return { payload, emphasis: { nodes: new Set(nodes.keys()), edges: new Set(edges.keys()), seeds } };
}