Elffuss BraidHub

kikocis/utopia public

dev · 8.8 KiBRawPermalink
1//! 实体消解攒批裁决任务:消费审核队列中 stage=adjudicating 的灰区对。
2//! 先查裁决缓存,缓存未命中的攒成一批(一次 LLM 调用裁多对);
3//! 高置信 same → 自动合并(可回滚),高置信 different → 自动保持分开,
4//! 其余转人工。未配模型时全部转人工——本任务失败或缺席都不影响抽取与查询。
5
6use crate::llm_util;
7use crate::state::AppState;
8use sha2::{Digest, Sha256};
9use std::collections::HashMap;
10use utopia_core::models::ReviewItem;
11use utopia_core::AppError;
12use uuid::Uuid;
13
14const BATCH_SIZE: i64 = 12;
15const AUTO_CONF: f32 = 0.8;
16const MAX_ROUNDS: usize = 20;
17
18/// 缓存键:类型 + 双方名字 + 事实摘要(与实体 id 无关——重传文档不重复付费)。
19fn pair_key(item: &ReviewItem) -> String {
20 let side = |s: &utopia_core::models::ReviewSide| {
21 format!(
22 "{}|{}|{}",
23 s.name.to_lowercase(),
24 // 没判出类型的一侧照样要能缓存(0009)
25 s.type_label.as_deref().unwrap_or("untyped"),
26 s.top_facts.join(";")
27 )
28 };
29 let mut sides = [side(&item.left), side(&item.right)];
30 sides.sort();
31 let digest = Sha256::digest(sides.join("##").as_bytes());
32 digest.iter().map(|b| format!("{b:02x}")).collect()
33}
34
35pub async fn adjudicate_entities(state: &AppState, kb_id: Uuid) -> anyhow::Result<()> {
36 let kb = utopia_store::kbs::get(&state.pool, kb_id).await?;
37 let settings = utopia_store::settings::get(&state.pool, kb.workspace_id).await?;
38 let client = settings.as_ref().and_then(llm_util::chat_client);
39 let model = settings
40 .as_ref()
41 .and_then(|s| s.chat_model.clone())
42 .unwrap_or_default();
43
44 let Some(client) = client else {
45 // 无模型可用:全部转人工,任务本身成功结束
46 let items =
47 utopia_store::resolution::pending_adjudications(&state.pool, kb_id, 500).await?;
48 for item in items {
49 utopia_store::resolution::escalate_review(&state.pool, item.id, "escalate_no_model")
50 .await?;
51 }
52 state.emit_review(kb_id);
53 return Ok(());
54 };
55
56 for _ in 0..MAX_ROUNDS {
57 let items =
58 utopia_store::resolution::pending_adjudications(&state.pool, kb_id, BATCH_SIZE).await?;
59 if items.is_empty() {
60 break;
61 }
62
63 // 第一层:裁决缓存
64 let mut to_ask: Vec<(ReviewItem, String)> = Vec::new();
65 for item in items {
66 let key = pair_key(&item);
67 match utopia_store::resolution::get_verdict(&state.pool, kb_id, &key).await? {
68 Some((same, conf)) => {
69 apply_verdict(state, kb_id, &item, same, conf, "cached").await?
70 }
71 None => to_ask.push((item, key)),
72 }
73 }
74 if to_ask.is_empty() {
75 continue;
76 }
77
78 // 第二层:攒批 LLM 裁决
79 let pairs: Vec<utopia_extract::AdjudicationPair> = to_ask
80 .iter()
81 .map(|(item, _)| utopia_extract::AdjudicationPair {
82 left: utopia_extract::AdjudicationSide {
83 name: item.left.name.clone(),
84 type_label: item
85 .left
86 .type_label
87 .clone()
88 .unwrap_or_else(|| "untyped".into()),
89 facts: item.left.top_facts.clone(),
90 },
91 right: utopia_extract::AdjudicationSide {
92 name: item.right.name.clone(),
93 type_label: item
94 .right
95 .type_label
96 .clone()
97 .unwrap_or_else(|| "untyped".into()),
98 facts: item.right.top_facts.clone(),
99 },
100 })
101 .collect();
102 let messages = utopia_extract::build_adjudication_messages(&pairs);
103 // 调用/解析失败 → 任务按退避重试;重试耗尽后行停留在队列里,人工仍可定夺
104 let _permit = settings.as_ref().map(|s| llm_util::acquire_chat(state, s));
105 let _permit = match _permit {
106 Some(f) => f.await,
107 None => None,
108 };
109 let reply = client.chat(&messages).await?;
110 let verdicts = utopia_extract::parse_adjudication(&reply)?;
111 let by_i: HashMap<usize, &utopia_extract::AdjudicationVerdict> =
112 verdicts.iter().map(|v| (v.i, v)).collect();
113
114 for (idx, (item, key)) in to_ask.iter().enumerate() {
115 match by_i.get(&idx) {
116 Some(v) => {
117 let same = match v.verdict.as_str() {
118 "same" => Some(true),
119 "different" => Some(false),
120 _ => None,
121 };
122 let conf = v.confidence.unwrap_or(0.5).clamp(0.0, 1.0);
123 utopia_store::resolution::put_verdict(
124 &state.pool,
125 kb_id,
126 key,
127 same,
128 conf,
129 &model,
130 )
131 .await?;
132 apply_verdict(state, kb_id, item, same, conf, "adjudicated").await?;
133 }
134 None => {
135 utopia_store::resolution::escalate_review(
136 &state.pool,
137 item.id,
138 "escalate_no_verdict",
139 )
140 .await?;
141 }
142 }
143 }
144 // 本轮裁决落库完毕,推给前端刷新审核队列
145 state.emit_review(kb_id);
146 }
147 Ok(())
148}
149
150async fn apply_verdict(
151 state: &AppState,
152 kb_id: Uuid,
153 item: &ReviewItem,
154 same: Option<bool>,
155 conf: f32,
156 via: &str,
157) -> anyhow::Result<()> {
158 match same {
159 Some(true) if conf >= AUTO_CONF => {
160 let (target, source) =
161 utopia_store::resolution::merge_direction(&state.pool, item.left.id, item.right.id)
162 .await?;
163 let reason = format!("auto_merged|{via} {conf:.2}");
164 match utopia_store::resolution::merge_entities(
165 &state.pool,
166 kb_id,
167 source,
168 target,
169 None,
170 &reason,
171 )
172 .await
173 {
174 Ok(_) => {
175 utopia_store::resolution::close_review_auto(
176 &state.pool,
177 item.id,
178 "merged",
179 &reason,
180 )
181 .await?;
182 // 决策台账:AI 自动合并(actor 为空 = 系统)
183 let _ = utopia_store::audit::record_opt(
184 &state.pool,
185 Some(kb_id),
186 None,
187 "review.merge",
188 "review",
189 Some(item.id),
190 serde_json::json!({
191 "left": item.left.name, "right": item.right.name,
192 "score": item.score, "confidence": conf, "via": via,
193 }),
194 )
195 .await;
196 }
197 // 同批次连锁合并可能已吞掉其中一方:转人工而不是让任务失败
198 Err(AppError::Conflict(_)) | Err(AppError::NotFound) => {
199 utopia_store::resolution::escalate_review(
200 &state.pool,
201 item.id,
202 "escalate_entity_changed",
203 )
204 .await?;
205 }
206 Err(e) => return Err(e.into()),
207 }
208 }
209 Some(false) if conf >= AUTO_CONF => {
210 utopia_store::resolution::close_review_auto(
211 &state.pool,
212 item.id,
213 "kept",
214 &format!("kept_apart|{via} {conf:.2}"),
215 )
216 .await?;
217 let _ = utopia_store::audit::record_opt(
218 &state.pool,
219 Some(kb_id),
220 None,
221 "review.keep",
222 "review",
223 Some(item.id),
224 serde_json::json!({
225 "left": item.left.name, "right": item.right.name,
226 "score": item.score, "confidence": conf, "via": via,
227 }),
228 )
229 .await;
230 }
231 _ => {
232 utopia_store::resolution::escalate_review(
233 &state.pool,
234 item.id,
235 &format!("escalate_unsure|{via} {conf:.2}"),
236 )
237 .await?;
238 }
239 }
240 Ok(())
241}