|
|
@@ -0,0 +1,280 @@
|
|
|
+package com.zsjz.ai.module.agent.tools;
|
|
|
+
|
|
|
+import com.zsjz.ai.common.utils.Json;
|
|
|
+import com.zsjz.ai.module.agent.mapper.SqlQueryMapper;
|
|
|
+import io.agentscope.core.message.ToolResultBlock;
|
|
|
+import io.agentscope.core.tool.Tool;
|
|
|
+import io.agentscope.core.tool.ToolParam;
|
|
|
+import lombok.extern.slf4j.Slf4j;
|
|
|
+import org.springframework.util.StringUtils;
|
|
|
+
|
|
|
+import java.sql.Timestamp;
|
|
|
+import java.time.LocalDate;
|
|
|
+import java.time.LocalDateTime;
|
|
|
+import java.time.format.DateTimeFormatter;
|
|
|
+import java.time.format.DateTimeParseException;
|
|
|
+import java.util.ArrayList;
|
|
|
+import java.util.LinkedHashMap;
|
|
|
+import java.util.List;
|
|
|
+import java.util.Map;
|
|
|
+
|
|
|
+/**
|
|
|
+ * 底层关系表 {@code rel_edge} 查询工具。
|
|
|
+ *
|
|
|
+ * <h3>表结构</h3>
|
|
|
+ * 一行是一条关系边:{@code node1}/{@code node2} 是两端节点,{@code node1cn}/{@code node2cn}
|
|
|
+ * 是显示名,{@code clazz} 是关系类别,{@code mc} 是关系名称,{@code num} 是金额/次数,
|
|
|
+ * {@code sj} 是关系时间,{@code fx} 是方向,{@code lx} 是对方类型。
|
|
|
+ *
|
|
|
+ * <h3>节点类型从 clazz 推导</h3>
|
|
|
+ * {@code clazz} 按 {@code '_'} 拆分:<b>第 1 段是 node1 的类型,第 3 段(下标 2)是 node2 的类型</b>。
|
|
|
+ * 真实数据既有两段({@code card_card}、{@code tel_tel}、{@code obj_card}、{@code obj_tel}),
|
|
|
+ * 此时 node2 取第 2 段;三段及以上时按约定取第 3 段(下标 2)。
|
|
|
+ *
|
|
|
+ * <p>数据源与 {@code execute_sql} 相同:{@link SqlQueryMapper} 走当前案件的 DuckDB(slave)。
|
|
|
+ * 工具只读,查询条件全部由服务端拼装并对字符串做转义,不接受模型传入原始 SQL。
|
|
|
+ */
|
|
|
+@Slf4j
|
|
|
+public class RelEdgeQueryTool {
|
|
|
+
|
|
|
+ /** 默认返回条数 */
|
|
|
+ private static final int DEFAULT_LIMIT = 100;
|
|
|
+
|
|
|
+ /** 单次返回条数上限(避免一次把整张关系表塞进模型上下文) */
|
|
|
+ private static final int MAX_LIMIT = 500;
|
|
|
+
|
|
|
+ /** node1 类型:clazz 第 1 段 */
|
|
|
+ private static final String NODE1_TYPE_EXPR = "split_part(clazz, '_', 1)";
|
|
|
+
|
|
|
+ /**
|
|
|
+ * node2 类型:clazz 第 3 段(下标 2)。
|
|
|
+ *
|
|
|
+ * <p>真实数据是两段(card_card / tel_tel / obj_card / obj_tel),此时取第 2 段;
|
|
|
+ * 三段及以上(自定义 node1_关系_node2)按约定取第 3 段。
|
|
|
+ */
|
|
|
+ private static final String NODE2_TYPE_EXPR =
|
|
|
+ "case when len(string_split(clazz, '_')) >= 3 "
|
|
|
+ + "then split_part(clazz, '_', 3) else split_part(clazz, '_', 2) end";
|
|
|
+
|
|
|
+ private static final DateTimeFormatter TIME_FORMAT = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
|
|
|
+
|
|
|
+ private final SqlQueryMapper sqlQueryMapper;
|
|
|
+
|
|
|
+ public RelEdgeQueryTool(SqlQueryMapper sqlQueryMapper) {
|
|
|
+ this.sqlQueryMapper = sqlQueryMapper;
|
|
|
+ }
|
|
|
+
|
|
|
+ /**
|
|
|
+ * 查询 rel_edge 关系边,并同时返回从 node1/node2 派生的节点清单。
|
|
|
+ */
|
|
|
+ @Tool(name = "query_rel_edge",
|
|
|
+ description = "查询案件关系图谱底层 rel_edge 关系表(关系边 + 从 node1/node2 派生的节点)。"
|
|
|
+ + "一行关系包含:node1/node2(两端节点标识)、node1cn/node2cn(显示名)、"
|
|
|
+ + "clazz(关系类别,按 '_' 拆分:第 1 段是 node1 类型、第 3 段(下标 2,"
|
|
|
+ + "两段数据时取第 2 段)是 node2 类型;"
|
|
|
+ + "card_card=资金、tel_tel=通话、obj_card=人员对象-卡、obj_tel=人员对象-号码)、"
|
|
|
+ + "mc(关系名称)、num(金额/次数)、sj(时间)、fx(方向)、lx(对方类型)。"
|
|
|
+ + "返回 JSON:{totalEdges, returnedEdges, nodeCount, edges:[...], nodes:[{node,name,type}]};"
|
|
|
+ + "nodes 是本次结果里两端节点去重后的清单。"
|
|
|
+ + "可选条件:node 模糊匹配任一节点/名称、nodeType 过滤 card/tel/obj、"
|
|
|
+ + "clazz 精确过滤关系类别、relation 模糊匹配关系名称、startDate/endDate 过滤关系时间、"
|
|
|
+ + "limit 限制返回条数(默认 100,最大 500,按时间倒序)。"
|
|
|
+ + "需要画完整关系图或按人取全量图谱请用 get_case_graph。",
|
|
|
+ readOnly = true)
|
|
|
+ public ToolResultBlock queryRelEdge(
|
|
|
+ @ToolParam(name = "query",
|
|
|
+ description = "关系边查询条件;不传则返回最近的关系边。结构:"
|
|
|
+ + "{\"node\":\"卡号/号码/姓名\",\"nodeType\":\"card|tel|obj\","
|
|
|
+ + "\"clazz\":\"card_card\",\"relation\":\"交易\","
|
|
|
+ + "\"startDate\":\"2024-01-01\",\"endDate\":\"2024-12-31\",\"limit\":100}")
|
|
|
+ GraphToolSpecs.RelEdgeQuerySpec query) {
|
|
|
+ GraphToolSpecs.RelEdgeQuerySpec spec =
|
|
|
+ query == null ? new GraphToolSpecs.RelEdgeQuerySpec() : query;
|
|
|
+ try {
|
|
|
+ int limit = normalizeLimit(spec.limit);
|
|
|
+ String from = " from rel_edge" + buildWhere(spec);
|
|
|
+ long total = count(from);
|
|
|
+ String sql = "select node1, node2, node1cn, node2cn, "
|
|
|
+ + NODE1_TYPE_EXPR + " as node1_type, "
|
|
|
+ + NODE2_TYPE_EXPR + " as node2_type, "
|
|
|
+ + "clazz, mc, num, sj, fx, lx"
|
|
|
+ + from
|
|
|
+ + " order by sj desc nulls last, id desc limit " + limit;
|
|
|
+ List<LinkedHashMap<String, Object>> rows = sqlQueryMapper.executeQuery(sql);
|
|
|
+ return ToolResults.ok(Json.toStr(buildResult(rows, total, limit)));
|
|
|
+ } catch (IllegalArgumentException e) {
|
|
|
+ return ToolResults.error(e.getMessage());
|
|
|
+ } catch (Exception e) {
|
|
|
+ log.error("查询 rel_edge 失败: {}", e.getMessage(), e);
|
|
|
+ return ToolResults.error("查询 rel_edge 失败: " + e.getMessage());
|
|
|
+ }
|
|
|
+ }
|
|
|
+
|
|
|
+ private long count(String from) {
|
|
|
+ List<LinkedHashMap<String, Object>> rows =
|
|
|
+ sqlQueryMapper.executeQuery("select count(*) as total" + from);
|
|
|
+ if (rows == null || rows.isEmpty()) {
|
|
|
+ return 0L;
|
|
|
+ }
|
|
|
+ Object value = rows.getFirst().get("total");
|
|
|
+ if (value instanceof Number n) {
|
|
|
+ return n.longValue();
|
|
|
+ }
|
|
|
+ if (value instanceof String s && StringUtils.hasText(s)) {
|
|
|
+ try {
|
|
|
+ return Long.parseLong(s.trim());
|
|
|
+ } catch (NumberFormatException ignored) {
|
|
|
+ return 0L;
|
|
|
+ }
|
|
|
+ }
|
|
|
+ return 0L;
|
|
|
+ }
|
|
|
+
|
|
|
+ /**
|
|
|
+ * 组装 WHERE:所有字符串都走 {@link #literal(String)} 转义,模型无法注入原始 SQL。
|
|
|
+ */
|
|
|
+ private static String buildWhere(GraphToolSpecs.RelEdgeQuerySpec spec) {
|
|
|
+ List<String> conditions = new ArrayList<>();
|
|
|
+ if (StringUtils.hasText(spec.node)) {
|
|
|
+ String pattern = likeLiteral(spec.node);
|
|
|
+ conditions.add("(node1 like " + pattern
|
|
|
+ + " or node2 like " + pattern
|
|
|
+ + " or coalesce(node1cn, '') like " + pattern
|
|
|
+ + " or coalesce(node2cn, '') like " + pattern + ")");
|
|
|
+ }
|
|
|
+ if (StringUtils.hasText(spec.nodeType)) {
|
|
|
+ String type = literal(spec.nodeType.trim());
|
|
|
+ conditions.add("(" + NODE1_TYPE_EXPR + " = " + type
|
|
|
+ + " or " + NODE2_TYPE_EXPR + " = " + type + ")");
|
|
|
+ }
|
|
|
+ if (StringUtils.hasText(spec.clazz)) {
|
|
|
+ conditions.add("clazz = " + literal(spec.clazz.trim()));
|
|
|
+ }
|
|
|
+ if (StringUtils.hasText(spec.relation)) {
|
|
|
+ conditions.add("coalesce(mc, '') like " + likeLiteral(spec.relation));
|
|
|
+ }
|
|
|
+ if (StringUtils.hasText(spec.startDate)) {
|
|
|
+ conditions.add("sj >= timestamp '" + parseDate(spec.startDate, "startDate") + " 00:00:00'");
|
|
|
+ }
|
|
|
+ if (StringUtils.hasText(spec.endDate)) {
|
|
|
+ conditions.add("sj <= timestamp '" + parseDate(spec.endDate, "endDate") + " 23:59:59'");
|
|
|
+ }
|
|
|
+ return conditions.isEmpty() ? "" : " where " + String.join(" and ", conditions);
|
|
|
+ }
|
|
|
+
|
|
|
+ private static Map<String, Object> buildResult(List<LinkedHashMap<String, Object>> rows,
|
|
|
+ long total, int limit) {
|
|
|
+ List<Map<String, Object>> edges = new ArrayList<>();
|
|
|
+ Map<String, Map<String, Object>> nodes = new LinkedHashMap<>();
|
|
|
+ if (rows != null) {
|
|
|
+ for (LinkedHashMap<String, Object> row : rows) {
|
|
|
+ String node1 = text(row.get("node1"));
|
|
|
+ String node2 = text(row.get("node2"));
|
|
|
+ String node1cn = text(row.get("node1cn"));
|
|
|
+ String node2cn = text(row.get("node2cn"));
|
|
|
+ String node1Type = text(row.get("node1_type"));
|
|
|
+ String node2Type = text(row.get("node2_type"));
|
|
|
+
|
|
|
+ Map<String, Object> edge = new LinkedHashMap<>();
|
|
|
+ edge.put("node1", node1);
|
|
|
+ edge.put("node2", node2);
|
|
|
+ edge.put("node1cn", node1cn);
|
|
|
+ edge.put("node2cn", node2cn);
|
|
|
+ edge.put("node1Type", node1Type);
|
|
|
+ edge.put("node2Type", node2Type);
|
|
|
+ edge.put("clazz", text(row.get("clazz")));
|
|
|
+ edge.put("mc", text(row.get("mc")));
|
|
|
+ edge.put("num", text(row.get("num")));
|
|
|
+ edge.put("sj", formatTime(row.get("sj")));
|
|
|
+ edge.put("fx", row.get("fx"));
|
|
|
+ edge.put("lx", row.get("lx"));
|
|
|
+ edges.add(edge);
|
|
|
+
|
|
|
+ addNode(nodes, node1, node1cn, node1Type);
|
|
|
+ addNode(nodes, node2, node2cn, node2Type);
|
|
|
+ }
|
|
|
+ }
|
|
|
+
|
|
|
+ Map<String, Object> result = new LinkedHashMap<>();
|
|
|
+ // total 可能是 Long;Json 全局把 Long 序列化成字符串,这里转 int 让模型拿到数字
|
|
|
+ result.put("totalEdges", (int) Math.min(total, Integer.MAX_VALUE));
|
|
|
+ result.put("returnedEdges", edges.size());
|
|
|
+ result.put("nodeCount", nodes.size());
|
|
|
+ result.put("limit", limit);
|
|
|
+ result.put("truncated", total > edges.size());
|
|
|
+ result.put("edges", edges);
|
|
|
+ result.put("nodes", new ArrayList<>(nodes.values()));
|
|
|
+ if (total == 0) {
|
|
|
+ result.put("note", "没有符合条件的关系边");
|
|
|
+ } else if (total > edges.size()) {
|
|
|
+ result.put("note", "仅返回最近 " + edges.size() + " 条(共 " + total
|
|
|
+ + " 条);可增加筛选条件缩小范围,或把 limit 提高到 500");
|
|
|
+ }
|
|
|
+ return result;
|
|
|
+ }
|
|
|
+
|
|
|
+ /**
|
|
|
+ * 节点去重:同一 node 可能在不同边里分别作为 node1/node2 出现,名称和类型按「先到先得」补齐。
|
|
|
+ */
|
|
|
+ private static void addNode(Map<String, Map<String, Object>> nodes,
|
|
|
+ String node, String name, String type) {
|
|
|
+ if (!StringUtils.hasText(node)) {
|
|
|
+ return;
|
|
|
+ }
|
|
|
+ Map<String, Object> item = nodes.computeIfAbsent(node, key -> {
|
|
|
+ Map<String, Object> created = new LinkedHashMap<>();
|
|
|
+ created.put("node", key);
|
|
|
+ created.put("name", null);
|
|
|
+ created.put("type", null);
|
|
|
+ return created;
|
|
|
+ });
|
|
|
+ if (!StringUtils.hasText((String) item.get("name")) && StringUtils.hasText(name)) {
|
|
|
+ item.put("name", name);
|
|
|
+ }
|
|
|
+ if (!StringUtils.hasText((String) item.get("type")) && StringUtils.hasText(type)) {
|
|
|
+ item.put("type", type);
|
|
|
+ }
|
|
|
+ }
|
|
|
+
|
|
|
+ private static int normalizeLimit(Integer limit) {
|
|
|
+ if (limit == null || limit <= 0) {
|
|
|
+ return DEFAULT_LIMIT;
|
|
|
+ }
|
|
|
+ return Math.min(limit, MAX_LIMIT);
|
|
|
+ }
|
|
|
+
|
|
|
+ private static String parseDate(String value, String field) {
|
|
|
+ try {
|
|
|
+ return LocalDate.parse(value.trim()).toString();
|
|
|
+ } catch (DateTimeParseException e) {
|
|
|
+ throw new IllegalArgumentException(field + " 格式错误,应为 yyyy-MM-dd:" + value);
|
|
|
+ }
|
|
|
+ }
|
|
|
+
|
|
|
+ /** 字符串字面量转义(单引号翻倍),用于拼进只读 SQL。 */
|
|
|
+ private static String literal(String value) {
|
|
|
+ return "'" + value.replace("'", "''") + "'";
|
|
|
+ }
|
|
|
+
|
|
|
+ /** LIKE 模式字面量:转义单引号后两侧加 %。 */
|
|
|
+ private static String likeLiteral(String value) {
|
|
|
+ return "'%" + value.trim().replace("'", "''") + "%'";
|
|
|
+ }
|
|
|
+
|
|
|
+ private static String text(Object value) {
|
|
|
+ if (value == null) {
|
|
|
+ return null;
|
|
|
+ }
|
|
|
+ String text = String.valueOf(value);
|
|
|
+ return text.isBlank() ? null : text;
|
|
|
+ }
|
|
|
+
|
|
|
+ private static String formatTime(Object value) {
|
|
|
+ return switch (value) {
|
|
|
+ case null -> null;
|
|
|
+ case Timestamp ts -> ts.toLocalDateTime().format(TIME_FORMAT);
|
|
|
+ case LocalDateTime dt -> dt.format(TIME_FORMAT);
|
|
|
+ default -> String.valueOf(value);
|
|
|
+ };
|
|
|
+ }
|
|
|
+}
|