Elffuss BraidHub

kikocis/utopia public

dev · 9.3 KiBRawPermalink
1//! 问数语义映射的 Agentic 探索:读挂载源的 schema + KB 既有概念,让 LLM 提议
2//! "业务概念(Metric/Dimension 实体)→ 数据资产定义" 的映射。
3//!
4//! 提议写进 `concept_mappings`(status = proposed)→ Review 页自成一档,
5//! Confirm / Reject 之后 status 变 confirmed,问数只读确认过的那些。
6//!
7//! **从前它是一条 0.6 置信的 `mapped_to` 事实**,借「低置信事实」那一档露面。
8//! 搬出来的理由见 0011:它不是关于世界的断言,是配置——而「确认」这个动作
9//! 当时是 `UPDATE facts SET confidence = 1.0`,原地改一张不许原地改的表。
10//! agent 只提议,口径生效权在人——与消解"宁分勿合"同一哲学。
11
12use crate::llm_util;
13use crate::state::AppState;
14use uuid::Uuid;
15
16const MAX_SCHEMA_CHARS: usize = 12_000;
17
18/// 探索把 schema 里的量与维度落成 Metric / Dimension 实体,而这两个类不在任何
19/// 内置本体包里——0009 之后建库不再自带类。没有它们,下面的 `type_id` 查不到,
20/// 每条提议都被 `continue` 吞掉,页面只说"已排队"就再无下文(#223)。
21/// 所以探索前把两个类补上:builtin,描述给抽取提示词,本体页可以改
22async fn ensure_concept_types(pool: &sqlx::PgPool, kb_id: Uuid) -> anyhow::Result<()> {
23 for (key, label, description) in [
24 (
25 "metric",
26 "Metric",
27 "An aggregatable business quantity (revenue, order count, average ticket) that maps to a definition in a mounted database.",
28 ),
29 (
30 "dimension",
31 "Dimension",
32 "A group-by attribute (region, month, product line) that maps to a column in a mounted database.",
33 ),
34 ] {
35 sqlx::query(
36 "INSERT INTO entity_types (id, kb_id, key, label, builtin, description)
37 SELECT $1, $2, $3, $4, TRUE, $5
38 WHERE NOT EXISTS (SELECT 1 FROM entity_types WHERE kb_id = $2 AND key = $3)",
39 )
40 .bind(Uuid::now_v7())
41 .bind(kb_id)
42 .bind(key)
43 .bind(label)
44 .bind(description)
45 .execute(pool)
46 .await?;
47 }
48 Ok(())
49}
50
51pub async fn explore_mappings(state: &AppState, kb_id: Uuid) -> anyhow::Result<()> {
52 let kb = utopia_store::kbs::get(&state.pool, kb_id).await?;
53 let settings = utopia_store::settings::get(&state.pool, kb.workspace_id)
54 .await?
55 .ok_or_else(|| anyhow::anyhow!("Chat model not configured"))?;
56 let client = llm_util::chat_client(&settings)
57 .ok_or_else(|| anyhow::anyhow!("Chat model not configured"))?;
58
59 let sources = utopia_store::datasources::mounted(&state.pool, kb_id).await?;
60 if sources.is_empty() {
61 anyhow::bail!("No data sources mounted");
62 }
63 ensure_concept_types(&state.pool, kb_id).await?;
64
65 // 各源 schema(引擎直读,保证新鲜;限量防 prompt 爆炸)
66 let mut schema_txt = String::new();
67 for ds in &sources {
68 let (engine, conn) = utopia_store::datasources::engine_and_conn(&state.pool, ds.id).await?;
69 let cols = crate::query_engine::engine_for(&engine, &conn)?
70 .fetch_schema()
71 .await?;
72 schema_txt.push_str(&format!("\n=== source: {} ===\n", ds.name));
73 let mut current = String::new();
74 for c in cols {
75 let key = format!("{}.{}", c.schema, c.table);
76 if key != current {
77 current = key.clone();
78 schema_txt.push_str(&format!("table {key}:\n"));
79 }
80 schema_txt.push_str(&format!(
81 " {} {}{}\n",
82 c.column,
83 c.data_type,
84 c.comment.map(|x| format!(" -- {x}")).unwrap_or_default()
85 ));
86 if schema_txt.len() > MAX_SCHEMA_CHARS {
87 schema_txt.push_str("(truncated)\n");
88 break;
89 }
90 }
91 }
92
93 // 既有概念(供归并复用,避免重复起名)
94 let existing: Vec<(String,)> = sqlx::query_as(
95 "SELECT e.canonical_name FROM entities e
96 JOIN entity_types t ON t.id = e.type_id
97 WHERE e.kb_id = $1 AND e.merged_into IS NULL AND t.key IN ('metric','dimension')
98 ORDER BY e.canonical_name LIMIT 100",
99 )
100 .bind(kb_id)
101 .fetch_all(&state.pool)
102 .await?;
103 let existing_names: Vec<String> = existing.into_iter().map(|(n,)| n).collect();
104
105 let prompt = format!(
106 "You are building the semantic layer of a BI system. Given database schemas, propose \
107 business concepts a user would ask about, each mapped to a concrete definition.\n\
108 Existing concepts (reuse these names when the meaning matches): {}\n\
109 Schemas:\n{}\n\
110 Reply with ONLY a JSON array, each item:\n\
111 {{\"name\": \"business concept name\", \"kind\": \"metric\"|\"dimension\", \
112 \"source\": \"data source name\", \
113 \"definition\": {{\"table\": \"schema.table\", \"expr\": \"SQL expression\", \
114 \"sql\": \"full SELECT if joins are needed (optional)\", \"unit\": \"optional\"}}, \
115 \"summary\": \"one line: source + expression, shown to reviewers\", \
116 \"rationale\": \"why this mapping, citing column comments\"}}\n\
117 Metrics are aggregatable quantities (use sum/count/avg in expr); dimensions are \
118 group-by columns. Propose at most 12, only well-grounded ones.",
119 if existing_names.is_empty() {
120 "(none)".into()
121 } else {
122 existing_names.join(", ")
123 },
124 schema_txt
125 );
126
127 let _permit = llm_util::acquire_chat(state, &settings).await;
128 let reply = client
129 .chat(&[utopia_llm::ChatMessage {
130 role: "user".into(),
131 content: prompt,
132 }])
133 .await?;
134 let json_str = reply
135 .trim()
136 .trim_start_matches("```json")
137 .trim_start_matches("```")
138 .trim_end_matches("```")
139 .trim();
140 let proposals: Vec<serde_json::Value> = serde_json::from_str(json_str)
141 .map_err(|e| anyhow::anyhow!("Mapping proposal parse error: {e}"))?;
142
143 let source_names: Vec<&str> = sources.iter().map(|d| d.name.as_str()).collect();
144 let mut accepted = 0usize;
145 for p in proposals.iter().take(12) {
146 let name = p["name"].as_str().map(str::trim).unwrap_or("");
147 let kind = p["kind"].as_str().unwrap_or("");
148 let source = p["source"].as_str().map(str::trim).unwrap_or("");
149 if name.is_empty()
150 || !matches!(kind, "metric" | "dimension")
151 || !source_names.iter().any(|s| s.eq_ignore_ascii_case(source))
152 {
153 continue;
154 }
155 let type_id: Option<(Uuid,)> =
156 sqlx::query_as("SELECT id FROM entity_types WHERE kb_id = $1 AND key = $2")
157 .bind(kb_id)
158 .bind(kind)
159 .fetch_optional(&state.pool)
160 .await?;
161 let Some((type_id,)) = type_id else { continue };
162
163 // 概念实体:走消解(同名归并;无向量上下文按 v1 兼容归并)
164 let resolved = utopia_store::resolution::resolve_mention(
165 &state.pool,
166 kb_id,
167 Some(type_id),
168 name,
169 None,
170 )
171 .await?;
172
173 // 定义拆成列写进 concept_mappings(0011)。从前它是一份塞进
174 // `object_value` 的 JSON,宾语挂在一条叫 mapped_to 的关系上——
175 // 而那条关系是本体里的一行,跟 works_at 并列。**它不是关于世界的
176 // 断言,是配置**,所以搬去自己的表
177 let def = &p["definition"];
178 if !def.is_object() {
179 continue;
180 }
181 let s = |k: &str| {
182 def[k]
183 .as_str()
184 .filter(|x| !x.is_empty())
185 .map(str::to_string)
186 };
187 utopia_store::mappings::propose(
188 &state.pool,
189 kb_id,
190 resolved.entity_id,
191 source,
192 s("table").as_deref(),
193 s("expr").as_deref(),
194 s("sql").as_deref(),
195 s("unit").as_deref(),
196 // summary 是给人看的那句:Review 列表与问数 prompt 都靠它
197 p["summary"].as_str().or(def["summary"].as_str()),
198 def["derived"].as_bool().unwrap_or(false),
199 )
200 .await?;
201 accepted += 1;
202 }
203
204 tracing::info!(%kb_id, proposals = accepted, "映射探索完成,提议已入审核队列");
205 // 一条都没提出来时页面上什么都不会变——Pending 还是 0,而"已排队"那句
206 // 早就翻篇了。走告警中心说一声,人才知道该去刷新结构或给列加注释
207 if accepted == 0 {
208 if let Err(e) = utopia_store::alerts::raise(
209 &state.pool,
210 utopia_store::alerts::NewAlert {
211 kb_id: Some(kb_id),
212 severity: "info",
213 kind: utopia_store::alerts::kind::MAPPING_EXPLORATION_EMPTY,
214 min_role: utopia_core::models::Role::Editor,
215 subject_type: None,
216 subject_id: None,
217 detail: serde_json::json!({ "proposals": 0, "sources": source_names }),
218 },
219 )
220 .await
221 {
222 tracing::warn!(%kb_id, error = %e, "映射探索空结果的告警没写进去");
223 }
224 state.emit_alert();
225 }
226 state.emit_review(kb_id);
227 Ok(())
228}