| 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 | |
| 12 | use crate::llm_util; |
| 13 | use crate::state::AppState; |
| 14 | use uuid::Uuid; |
| 15 | |
| 16 | const MAX_SCHEMA_CHARS: usize = 12_000; |
| 17 | |
| 18 | pub async fn explore_mappings(state: &AppState, kb_id: Uuid) -> anyhow::Result<()> { |
| 19 | let kb = utopia_store::kbs::get(&state.pool, kb_id).await?; |
| 20 | let settings = utopia_store::settings::get(&state.pool, kb.workspace_id) |
| 21 | .await? |
| 22 | .ok_or_else(|| anyhow::anyhow!("Chat model not configured"))?; |
| 23 | let client = llm_util::chat_client(&settings) |
| 24 | .ok_or_else(|| anyhow::anyhow!("Chat model not configured"))?; |
| 25 | |
| 26 | let sources = utopia_store::datasources::mounted(&state.pool, kb_id).await?; |
| 27 | if sources.is_empty() { |
| 28 | anyhow::bail!("No data sources mounted"); |
| 29 | } |
| 30 | |
| 31 | // 各源 schema(引擎直读,保证新鲜;限量防 prompt 爆炸) |
| 32 | let mut schema_txt = String::new(); |
| 33 | for ds in &sources { |
| 34 | let (engine, conn) = utopia_store::datasources::engine_and_conn(&state.pool, ds.id).await?; |
| 35 | let cols = crate::query_engine::engine_for(&engine, &conn)? |
| 36 | .fetch_schema() |
| 37 | .await?; |
| 38 | schema_txt.push_str(&format!("\n=== source: {} ===\n", ds.name)); |
| 39 | let mut current = String::new(); |
| 40 | for c in cols { |
| 41 | let key = format!("{}.{}", c.schema, c.table); |
| 42 | if key != current { |
| 43 | current = key.clone(); |
| 44 | schema_txt.push_str(&format!("table {key}:\n")); |
| 45 | } |
| 46 | schema_txt.push_str(&format!( |
| 47 | " {} {}{}\n", |
| 48 | c.column, |
| 49 | c.data_type, |
| 50 | c.comment.map(|x| format!(" -- {x}")).unwrap_or_default() |
| 51 | )); |
| 52 | if schema_txt.len() > MAX_SCHEMA_CHARS { |
| 53 | schema_txt.push_str("(truncated)\n"); |
| 54 | break; |
| 55 | } |
| 56 | } |
| 57 | } |
| 58 | |
| 59 | // 既有概念(供归并复用,避免重复起名) |
| 60 | let existing: Vec<(String,)> = sqlx::query_as( |
| 61 | "SELECT e.canonical_name FROM entities e |
| 62 | JOIN entity_types t ON t.id = e.type_id |
| 63 | WHERE e.kb_id = $1 AND e.merged_into IS NULL AND t.key IN ('metric','dimension') |
| 64 | ORDER BY e.canonical_name LIMIT 100", |
| 65 | ) |
| 66 | .bind(kb_id) |
| 67 | .fetch_all(&state.pool) |
| 68 | .await?; |
| 69 | let existing_names: Vec<String> = existing.into_iter().map(|(n,)| n).collect(); |
| 70 | |
| 71 | let prompt = format!( |
| 72 | "You are building the semantic layer of a BI system. Given database schemas, propose \ |
| 73 | business concepts a user would ask about, each mapped to a concrete definition.\n\ |
| 74 | Existing concepts (reuse these names when the meaning matches): {}\n\ |
| 75 | Schemas:\n{}\n\ |
| 76 | Reply with ONLY a JSON array, each item:\n\ |
| 77 | {{\"name\": \"business concept name\", \"kind\": \"metric\"|\"dimension\", \ |
| 78 | \"source\": \"data source name\", \ |
| 79 | \"definition\": {{\"table\": \"schema.table\", \"expr\": \"SQL expression\", \ |
| 80 | \"sql\": \"full SELECT if joins are needed (optional)\", \"unit\": \"optional\"}}, \ |
| 81 | \"summary\": \"one line: source + expression, shown to reviewers\", \ |
| 82 | \"rationale\": \"why this mapping, citing column comments\"}}\n\ |
| 83 | Metrics are aggregatable quantities (use sum/count/avg in expr); dimensions are \ |
| 84 | group-by columns. Propose at most 12, only well-grounded ones.", |
| 85 | if existing_names.is_empty() { |
| 86 | "(none)".into() |
| 87 | } else { |
| 88 | existing_names.join(", ") |
| 89 | }, |
| 90 | schema_txt |
| 91 | ); |
| 92 | |
| 93 | let _permit = llm_util::acquire_chat(state, &settings).await; |
| 94 | let reply = client |
| 95 | .chat(&[utopia_llm::ChatMessage { |
| 96 | role: "user".into(), |
| 97 | content: prompt, |
| 98 | }]) |
| 99 | .await?; |
| 100 | let json_str = reply |
| 101 | .trim() |
| 102 | .trim_start_matches("```json") |
| 103 | .trim_start_matches("```") |
| 104 | .trim_end_matches("```") |
| 105 | .trim(); |
| 106 | let proposals: Vec<serde_json::Value> = serde_json::from_str(json_str) |
| 107 | .map_err(|e| anyhow::anyhow!("Mapping proposal parse error: {e}"))?; |
| 108 | |
| 109 | let source_names: Vec<&str> = sources.iter().map(|d| d.name.as_str()).collect(); |
| 110 | let mut accepted = 0usize; |
| 111 | for p in proposals.iter().take(12) { |
| 112 | let name = p["name"].as_str().map(str::trim).unwrap_or(""); |
| 113 | let kind = p["kind"].as_str().unwrap_or(""); |
| 114 | let source = p["source"].as_str().map(str::trim).unwrap_or(""); |
| 115 | if name.is_empty() |
| 116 | || !matches!(kind, "metric" | "dimension") |
| 117 | || !source_names.iter().any(|s| s.eq_ignore_ascii_case(source)) |
| 118 | { |
| 119 | continue; |
| 120 | } |
| 121 | let type_id: Option<(Uuid,)> = |
| 122 | sqlx::query_as("SELECT id FROM entity_types WHERE kb_id = $1 AND key = $2") |
| 123 | .bind(kb_id) |
| 124 | .bind(kind) |
| 125 | .fetch_optional(&state.pool) |
| 126 | .await?; |
| 127 | let Some((type_id,)) = type_id else { continue }; |
| 128 | |
| 129 | // 概念实体:走消解(同名归并;无向量上下文按 v1 兼容归并) |
| 130 | let resolved = utopia_store::resolution::resolve_mention( |
| 131 | &state.pool, |
| 132 | kb_id, |
| 133 | Some(type_id), |
| 134 | name, |
| 135 | None, |
| 136 | ) |
| 137 | .await?; |
| 138 | |
| 139 | // 定义拆成列写进 concept_mappings(0011)。从前它是一份塞进 |
| 140 | // `object_value` 的 JSON,宾语挂在一条叫 mapped_to 的关系上—— |
| 141 | // 而那条关系是本体里的一行,跟 works_at 并列。**它不是关于世界的 |
| 142 | // 断言,是配置**,所以搬去自己的表 |
| 143 | let def = &p["definition"]; |
| 144 | if !def.is_object() { |
| 145 | continue; |
| 146 | } |
| 147 | let s = |k: &str| { |
| 148 | def[k] |
| 149 | .as_str() |
| 150 | .filter(|x| !x.is_empty()) |
| 151 | .map(str::to_string) |
| 152 | }; |
| 153 | utopia_store::mappings::propose( |
| 154 | &state.pool, |
| 155 | kb_id, |
| 156 | resolved.entity_id, |
| 157 | source, |
| 158 | s("table").as_deref(), |
| 159 | s("expr").as_deref(), |
| 160 | s("sql").as_deref(), |
| 161 | s("unit").as_deref(), |
| 162 | // summary 是给人看的那句:Review 列表与问数 prompt 都靠它 |
| 163 | p["summary"].as_str().or(def["summary"].as_str()), |
| 164 | def["derived"].as_bool().unwrap_or(false), |
| 165 | ) |
| 166 | .await?; |
| 167 | accepted += 1; |
| 168 | } |
| 169 | |
| 170 | tracing::info!(%kb_id, proposals = accepted, "映射探索完成,提议已入审核队列"); |
| 171 | state.emit_review(kb_id); |
| 172 | Ok(()) |
| 173 | } |