Elffuss BraidHub

kikocis/utopia public

dev · 67.0 KiBRawPermalink
1//! 本体编辑器 API:类型/关系 CRUD + 未匹配统计 + LLM 扩展建议。
2//! 查看 = viewer;修改 = editor(本体直接影响后续抽取的白名单)。
3
4use axum::extract::{Path, Query, State};
5use axum::Json;
6use serde::Deserialize;
7use serde_json::json;
8use utopia_core::models::Role;
9use utopia_core::AppError;
10use utopia_llm::ChatMessage;
11use uuid::Uuid;
12
13use crate::auth::AuthUser;
14use crate::error::ApiResult;
15use crate::llm_util;
16use crate::state::AppState;
17
18async fn require_kb(
19 state: &AppState,
20 user: &utopia_core::models::User,
21 kb_id: Uuid,
22 min: Role,
23) -> Result<utopia_core::models::KnowledgeBase, AppError> {
24 utopia_store::access::require_kb(&state.pool, user, kb_id, min).await
25}
26
27pub async fn get(
28 State(state): State<AppState>,
29 AuthUser(user): AuthUser,
30 Path(kb_id): Path<Uuid>,
31) -> ApiResult<Json<serde_json::Value>> {
32 require_kb(&state, &user, kb_id, Role::Viewer).await?;
33 let entity_types = utopia_store::ontology::entity_type_views(&state.pool, kb_id).await?;
34 let relation_types = utopia_store::ontology::relation_type_views(&state.pool, kb_id).await?;
35 let misses = utopia_store::ontology::list_misses(&state.pool, kb_id).await?;
36 // 已忽略的单列一路:抑制照旧(提案与自动扩本体只看上面那份),
37 // 但让人看得见抑制掉了什么、现在涨到多少
38 let dismissed_misses =
39 utopia_store::ontology::list_dismissed_misses(&state.pool, kb_id).await?;
40 Ok(Json(json!({
41 "entity_types": entity_types,
42 "relation_types": relation_types,
43 "misses": misses,
44 "dismissed_misses": dismissed_misses,
45 })))
46}
47
48#[derive(Deserialize)]
49pub struct InstancesQuery {
50 #[serde(default)]
51 pub page: i64,
52 #[serde(default = "default_per")]
53 pub per: i64,
54}
55
56fn default_per() -> i64 {
57 12
58}
59
60/// 某个类下的实体实例列表(详情区右侧,分页)。
61pub async fn list_entity_instances(
62 State(state): State<AppState>,
63 AuthUser(user): AuthUser,
64 Path((kb_id, type_id)): Path<(Uuid, Uuid)>,
65 Query(q): Query<InstancesQuery>,
66) -> ApiResult<Json<serde_json::Value>> {
67 require_kb(&state, &user, kb_id, Role::Viewer).await?;
68 let per = q.per.clamp(1, 100);
69 let page = q.page.max(0);
70 let (rows, total) =
71 utopia_store::ontology::entity_instances(&state.pool, kb_id, type_id, per, page * per)
72 .await?;
73 Ok(Json(json!({ "entities": rows, "total": total })))
74}
75
76#[derive(Deserialize)]
77pub struct EntityTypeReq {
78 pub key: Option<String>,
79 pub label: String,
80 #[serde(default)]
81 pub color: Option<String>,
82 /// circle | square
83 #[serde(default)]
84 pub shape: Option<String>,
85 /// 全部父类,**第一个当主父**(左栏画在那一支下)。
86 /// 界面上写明了这条,所以不额外给一个"选主父"的控件
87 #[serde(default)]
88 pub parents: Vec<Uuid>,
89 /// 与它互斥的类。**缺省 = 不动**——不管互斥的调用方(提案采纳、冷启动)
90 /// 不该因为一次建类就把已有的声明清空
91 #[serde(default)]
92 pub disjoint: Option<Vec<Uuid>>,
93 /// 语义指引,注入抽取 prompt
94 #[serde(default)]
95 pub description: Option<String>,
96}
97
98pub async fn create_entity_type(
99 State(state): State<AppState>,
100 AuthUser(user): AuthUser,
101 Path(kb_id): Path<Uuid>,
102 Json(req): Json<EntityTypeReq>,
103) -> ApiResult<Json<serde_json::Value>> {
104 require_kb(&state, &user, kb_id, Role::Editor).await?;
105 let key = req
106 .key
107 .as_deref()
108 .map(str::trim)
109 .filter(|s| !s.is_empty())
110 .ok_or_else(|| AppError::invalid("key_required", "key is required"))?;
111 let id = utopia_store::ontology::create_entity_type(
112 &state.pool,
113 kb_id,
114 key,
115 req.label.trim(),
116 // 不给颜色就按 key 取一个,而不是所有类共用一个灰蓝
117 req.color
118 .as_deref()
119 .unwrap_or_else(|| utopia_store::palette::color_for_key(key)),
120 req.shape.as_deref().unwrap_or("circle"),
121 &req.parents,
122 req.description.as_deref().unwrap_or("").trim(),
123 )
124 .await?;
125 // 互斥缺省 = 不动:不管它的调用方(提案采纳、冷启动)不该因为建一个类
126 // 就把已有的声明清空
127 if let Some(d) = req.disjoint.as_deref() {
128 utopia_store::ontology::set_disjoint_for(&state.pool, kb_id, id, d).await?;
129 }
130 // 审计只记不阻断
131 let _ = utopia_store::audit::record(
132 &state.pool,
133 Some(kb_id),
134 user.id,
135 "entity_type.created",
136 "entity_type",
137 Some(id),
138 json!({ "key": key, "label": req.label.trim() }),
139 )
140 .await;
141 Ok(Json(json!({ "id": id })))
142}
143
144pub async fn update_entity_type(
145 State(state): State<AppState>,
146 AuthUser(user): AuthUser,
147 Path((kb_id, id)): Path<(Uuid, Uuid)>,
148 Json(req): Json<EntityTypeReq>,
149) -> ApiResult<Json<serde_json::Value>> {
150 require_kb(&state, &user, kb_id, Role::Editor).await?;
151 utopia_store::ontology::update_entity_type(
152 &state.pool,
153 kb_id,
154 id,
155 req.label.trim(),
156 // **不给颜色 = 保持原色**,不是重置。这里按 id 改,压根拿不到 key;
157 // 而从前无条件写 "#8ea5bd" 意味着任何一次不带颜色的改名
158 // 都会把用户挑过的颜色抹掉
159 req.color.as_deref(),
160 req.shape.as_deref().unwrap_or("circle"),
161 &req.parents,
162 req.description.as_deref().unwrap_or("").trim(),
163 )
164 .await?;
165 if let Some(d) = req.disjoint.as_deref() {
166 utopia_store::ontology::set_disjoint_for(&state.pool, kb_id, id, d).await?;
167 }
168 let _ = utopia_store::audit::record(
169 &state.pool,
170 Some(kb_id),
171 user.id,
172 "entity_type.updated",
173 "entity_type",
174 Some(id),
175 json!({ "label": req.label.trim(), "color": req.color, "shape": req.shape,
176 "description": req.description }),
177 )
178 .await;
179 Ok(Json(json!({ "ok": true })))
180}
181
182pub async fn delete_entity_type(
183 State(state): State<AppState>,
184 AuthUser(user): AuthUser,
185 Path((kb_id, id)): Path<(Uuid, Uuid)>,
186) -> ApiResult<Json<serde_json::Value>> {
187 require_kb(&state, &user, kb_id, Role::Editor).await?;
188 utopia_store::ontology::delete_entity_type(&state.pool, kb_id, id).await?;
189 let _ = utopia_store::audit::record(
190 &state.pool,
191 Some(kb_id),
192 user.id,
193 "entity_type.deleted",
194 "entity_type",
195 Some(id),
196 json!({}),
197 )
198 .await;
199 Ok(Json(json!({ "ok": true })))
200}
201
202#[derive(Deserialize)]
203pub struct RelationTypeReq {
204 pub key: Option<String>,
205 pub label: String,
206 #[serde(default = "default_temporal")]
207 pub temporal: String,
208 #[serde(default)]
209 pub functional: bool,
210 #[serde(default)]
211 pub inverse_functional: bool,
212 /// 其余四条 OWL 公理。**必须能在界面上编**——推理机(0002)的判据全部
213 /// 来自这几位,而它们从前只能靠导入 OWL 文件带进来:一个在界面上手工建
214 /// 本体的用户,永远开不了那台机器。
215 ///
216 /// 与 `functional` / `inverse_functional` 并排,因为它们本来就是同一族,
217 /// 只是那两个先落库了
218 #[serde(default)]
219 pub is_transitive: bool,
220 #[serde(default)]
221 pub is_symmetric: bool,
222 #[serde(default)]
223 pub is_asymmetric: bool,
224 #[serde(default)]
225 pub is_irreflexive: bool,
226 /// 指向另一个关系的两条(`inverseOf` / `subPropertyOf`)。
227 ///
228 /// **缺省 = 清空,与上面六位同一条规矩。** 它们是同一个表单一次提交的
229 /// 一组声明;一半覆盖一半保留,会让「我把逆去掉了」和「我没碰逆」
230 /// 长得一模一样。属性表单不填这两个,而属性本来就不许有——
231 /// store 层会拦,落库也照样是 NULL
232 #[serde(default)]
233 pub inverse_of: Option<Uuid>,
234 #[serde(default)]
235 pub sub_property_of: Option<Uuid>,
236 #[serde(default)]
237 pub description: Option<String>,
238 /// relation | attribute(创建时定死,更新时忽略)
239 #[serde(default)]
240 pub kind: Option<String>,
241 /// 可以当主语的类。attribute 至少一个;relation 留空 = 不限。
242 /// **更新时缺省 = 不动**,所以是 Option 而不是 Vec——不管 domain 的
243 /// 调用方(属性表单)不该因为一次改名就把 domain 清空
244 #[serde(default)]
245 pub domains: Option<Vec<Uuid>>,
246 /// 可以当宾语的类。只对 relation 有意义
247 #[serde(default)]
248 pub ranges: Option<Vec<Uuid>>,
249 /// attribute 专用:text | number | date | bool
250 #[serde(default)]
251 pub datatype: Option<String>,
252 #[serde(default)]
253 pub unit: Option<String>,
254}
255
256impl RelationTypeReq {
257 /// 公理打包。**散着传迟早传错顺序**——六位都是 bool,编译器帮不上忙;
258 /// 后两位都是 `Option<Uuid>`,一样。
259 fn axioms(&self) -> utopia_core::models::RelationAxioms {
260 utopia_core::models::RelationAxioms {
261 functional: self.functional,
262 inverse_functional: self.inverse_functional,
263 transitive: self.is_transitive,
264 symmetric: self.is_symmetric,
265 asymmetric: self.is_asymmetric,
266 irreflexive: self.is_irreflexive,
267 inverse_of: self.inverse_of,
268 sub_property_of: self.sub_property_of,
269 }
270 }
271}
272
273fn default_temporal() -> String {
274 "state".into()
275}
276
277pub async fn create_relation_type(
278 State(state): State<AppState>,
279 AuthUser(user): AuthUser,
280 Path(kb_id): Path<Uuid>,
281 Json(req): Json<RelationTypeReq>,
282) -> ApiResult<Json<serde_json::Value>> {
283 require_kb(&state, &user, kb_id, Role::Editor).await?;
284 let key = req
285 .key
286 .as_deref()
287 .map(str::trim)
288 .filter(|s| !s.is_empty())
289 .ok_or_else(|| AppError::invalid("key_required", "key is required"))?;
290 let kind = req.kind.as_deref().unwrap_or("relation");
291 let id = utopia_store::ontology::create_relation_type(
292 &state.pool,
293 kb_id,
294 key,
295 req.label.trim(),
296 &req.temporal,
297 req.axioms(),
298 req.description.as_deref().unwrap_or("").trim(),
299 kind,
300 req.domains.as_deref().unwrap_or(&[]),
301 req.ranges.as_deref().unwrap_or(&[]),
302 req.datatype.as_deref(),
303 req.unit.as_deref().map(str::trim).filter(|s| !s.is_empty()),
304 )
305 .await?;
306 let _ = utopia_store::audit::record(
307 &state.pool,
308 Some(kb_id),
309 user.id,
310 "relation_type.created",
311 "relation_type",
312 Some(id),
313 json!({ "key": key, "label": req.label.trim(), "temporal": req.temporal, "kind": kind }),
314 )
315 .await;
316 Ok(Json(json!({ "id": id })))
317}
318
319pub async fn update_relation_type(
320 State(state): State<AppState>,
321 AuthUser(user): AuthUser,
322 Path((kb_id, id)): Path<(Uuid, Uuid)>,
323 Json(req): Json<RelationTypeReq>,
324) -> ApiResult<Json<serde_json::Value>> {
325 require_kb(&state, &user, kb_id, Role::Editor).await?;
326 utopia_store::ontology::update_relation_type(
327 &state.pool,
328 kb_id,
329 id,
330 req.label.trim(),
331 &req.temporal,
332 req.axioms(),
333 req.description.as_deref().unwrap_or("").trim(),
334 req.datatype.as_deref(),
335 req.unit.as_deref().map(str::trim).filter(|s| !s.is_empty()),
336 // 请求里没带这两个字段就不动它们——属性表单不管 domain
337 req.domains.as_deref(),
338 req.ranges.as_deref(),
339 )
340 .await?;
341 let _ = utopia_store::audit::record(
342 &state.pool,
343 Some(kb_id),
344 user.id,
345 "relation_type.updated",
346 "relation_type",
347 Some(id),
348 json!({ "label": req.label.trim(), "temporal": req.temporal,
349 "functional": req.functional, "inverse_functional": req.inverse_functional,
350 "description": req.description }),
351 )
352 .await;
353 Ok(Json(json!({ "ok": true })))
354}
355
356pub async fn delete_relation_type(
357 State(state): State<AppState>,
358 AuthUser(user): AuthUser,
359 Path((kb_id, id)): Path<(Uuid, Uuid)>,
360) -> ApiResult<Json<serde_json::Value>> {
361 require_kb(&state, &user, kb_id, Role::Editor).await?;
362 utopia_store::ontology::delete_relation_type(&state.pool, kb_id, id).await?;
363 let _ = utopia_store::audit::record(
364 &state.pool,
365 Some(kb_id),
366 user.id,
367 "relation_type.deleted",
368 "relation_type",
369 Some(id),
370 json!({}),
371 )
372 .await;
373 Ok(Json(json!({ "ok": true })))
374}
375
376#[derive(Deserialize)]
377pub struct DismissMissReq {
378 pub kind: String,
379 pub key: String,
380}
381
382pub async fn dismiss_miss(
383 State(state): State<AppState>,
384 AuthUser(user): AuthUser,
385 Path(kb_id): Path<Uuid>,
386 Json(req): Json<DismissMissReq>,
387) -> ApiResult<Json<serde_json::Value>> {
388 require_kb(&state, &user, kb_id, Role::Editor).await?;
389 utopia_store::ontology::dismiss_miss(&state.pool, kb_id, &req.kind, &req.key).await?;
390 Ok(Json(json!({ "ok": true })))
391}
392
393pub async fn restore_miss(
394 State(state): State<AppState>,
395 AuthUser(user): AuthUser,
396 Path(kb_id): Path<Uuid>,
397 Json(req): Json<DismissMissReq>,
398) -> ApiResult<Json<serde_json::Value>> {
399 require_kb(&state, &user, kb_id, Role::Editor).await?;
400 utopia_store::ontology::restore_miss(&state.pool, kb_id, &req.kind, &req.key).await?;
401 Ok(Json(json!({ "ok": true })))
402}
403
404/// LLM 本体扩展建议:现有本体 + 未匹配统计 → 提案(人审后经 create 端点合入)。
405/// `locale` 是**调用方**说的,不是后端的设置。reason 只给人看,而人就在这次请求的
406/// 另一端;界面语言在客户端(docs/decisions/0004),所以它只能这样传进来。
407#[derive(Deserialize, Default)]
408pub struct SuggestReq {
409 #[serde(default)]
410 pub locale: Option<String>,
411}
412
413pub async fn suggest(
414 State(state): State<AppState>,
415 AuthUser(user): AuthUser,
416 Path(kb_id): Path<Uuid>,
417 body: Option<Json<SuggestReq>>,
418) -> ApiResult<Json<serde_json::Value>> {
419 require_kb(&state, &user, kb_id, Role::Editor).await?;
420 let locale = body
421 .and_then(|Json(b)| b.locale)
422 .filter(|l| matches!(l.as_str(), "en" | "zh"))
423 .unwrap_or_else(|| "en".into());
424 // 人工那条路 min_docs = 0:面板上「出现在 1 篇」这个数字是显示给人看的,
425 // 他自己判断得了。替他滤掉,只是让他少一条信息
426 let proposals = build_proposals(&state, kb_id, &locale, 0).await?;
427 // 算完就写下来(见 `ontology_proposals`)。从前这批结果只回给前端、存进一个 useState,
428 // 刷新一次就没了——而重算要再调一次模型,且未必给出同一批归并
429 persist_proposals(&state, kb_id, &proposals).await;
430 Ok(Json(proposals))
431}
432
433/// 四个小节里的每一条都记一行。**失败不拦住返回**——提案已经算出来了,
434/// 存不下只是下次要重算,把整个请求判失败反而把算出来的也丢了。
435async fn persist_proposals(state: &AppState, kb_id: Uuid, proposals: &serde_json::Value) {
436 const SECTIONS: [&str; 4] = [
437 "entity_types",
438 "relation_types",
439 "attribute_types",
440 "map_to",
441 ];
442 let mut rows: Vec<(String, String, serde_json::Value)> = Vec::new();
443 for section in SECTIONS {
444 let Some(items) = proposals.get(section).and_then(|v| v.as_array()) else {
445 continue;
446 };
447 for it in items {
448 // key 是这一条的身份(迁移里的唯一约束用的就是它)。没有 key 的
449 // 存不了,也没法在采纳时对回来——跳过而不是编一个
450 let Some(key) = it.get("key").and_then(|k| k.as_str()) else {
451 continue;
452 };
453 rows.push((section.to_string(), key.to_string(), it.clone()));
454 }
455 }
456 if let Err(e) = utopia_store::ontology::save_proposals(&state.pool, kb_id, &rows).await {
457 tracing::warn!(%kb_id, error = %e, "本体提案落库失败,这一批只在本次响应里");
458 }
459}
460
461/// 还等着人看的提案,按接口原来的形状拼回去。
462///
463/// 前端因此不必区分「刚算出来的」与「上次存下的」——两者同一个类型、同一套渲染。
464pub async fn stored_proposals(
465 State(state): State<AppState>,
466 AuthUser(user): AuthUser,
467 Path(kb_id): Path<Uuid>,
468) -> ApiResult<Json<serde_json::Value>> {
469 require_kb(&state, &user, kb_id, Role::Viewer).await?;
470 let stored = utopia_store::ontology::open_proposals(&state.pool, kb_id).await?;
471 let mut out = json!({
472 "entity_types": [], "relation_types": [], "attribute_types": [], "map_to": []
473 });
474 for p in stored {
475 if let Some(arr) = out.get_mut(&p.section).and_then(|v| v.as_array_mut()) {
476 arr.push(p.payload);
477 }
478 }
479 Ok(Json(out))
480}
481
482#[derive(Deserialize)]
483pub struct DecideProposalReq {
484 pub section: String,
485 pub key: String,
486 /// adopted | rejected
487 pub status: String,
488}
489
490/// 一条提案有人表态了。**改状态不删行**:采纳发生过、拒绝也发生过,
491/// 而拒绝留痕正是下一轮 Suggest 不再把它刷回待看的依据。
492pub async fn decide_proposal(
493 State(state): State<AppState>,
494 AuthUser(user): AuthUser,
495 Path(kb_id): Path<Uuid>,
496 Json(req): Json<DecideProposalReq>,
497) -> ApiResult<Json<serde_json::Value>> {
498 require_kb(&state, &user, kb_id, Role::Editor).await?;
499 if !matches!(req.status.as_str(), "adopted" | "rejected") {
500 return Err(AppError::invalid("bad_status", "status 只能是 adopted 或 rejected").into());
501 }
502 utopia_store::ontology::decide_proposal(
503 &state.pool,
504 kb_id,
505 &req.section,
506 &req.key,
507 &req.status,
508 user.id,
509 )
510 .await?;
511 Ok(Json(json!({ "ok": true })))
512}
513
514/// 生成本体扩展提案。人工点 Suggest 与冷启动自动扩本体走同一条路——
515/// 自动那条不该是另一套判断,只是少了点头那一步。
516/// 每个说法检索几个候选。
517///
518/// 小是刻意的:候选是给模型判断"是不是已经有了"用的,不是让它挑一个最像的凑合。
519/// 开大了只会让它在一堆勉强相关的条目里硬选一个映射过去。
520const CANDIDATES_PER_PROBE: i64 = 5;
521
522/// `min_docs`:**只把出现在这么多篇文档里的说法交给模型**。0 = 全给。
523///
524/// 这一位存在的理由是它曾经不存在。`ProposedPredicate.doc_count` 的注释写着
525/// 「自动扩展据此设门槛,人工提案只作参考不拦」,但接线没接完:
526/// `bootstrap_ontology` 把门槛算出来只用于 `forms.len()` 判断值不值得跑一次
527/// LLM,随后调这个函数时只传 kb_id,于是这里重查一遍**没过滤的**全量。
528///
529/// 实测后果(ai-timeline,348 块):交给模型 526 个说法,其中 456 个只在一篇
530/// 里出现过——**86.7% 是噪声**。模型从这堆里只挑出 9 个,`runs_on`(8 篇都有)
531/// 和 `founded_by`(4 篇)没被挑中,275 条事实继续没有谓词。反方向也漏:
532/// 5 个单篇说法被采纳了,其中两个还建成了新属性,门槛形同虚设。
533pub async fn build_proposals(
534 state: &AppState,
535 kb_id: Uuid,
536 reason_lang: &str,
537 min_docs: i64,
538) -> Result<serde_json::Value, AppError> {
539 let kb = utopia_store::kbs::get(&state.pool, kb_id).await?;
540 let settings = utopia_store::settings::get(&state.pool, kb.workspace_id)
541 .await?
542 .ok_or_else(|| AppError::invalid("no_chat_model", "Chat model not configured"))?;
543 let client = llm_util::chat_client(&settings)
544 .ok_or_else(|| AppError::invalid("no_chat_model", "Chat model not configured"))?;
545
546 let mut misses = utopia_store::ontology::list_misses(&state.pool, kb_id).await?;
547 // 表层谓词比 misses 多一样东西:它连着具体事实,所以提案能承诺"改写 N 条"。
548 //
549 // **两条线严格分开**,按宾语是实体还是字面值:`收购` 要的是一条关系,
550 // `founding_date = "2015"` 要的是一个属性。混起来的后果具体——后者会被
551 // 提成关系,于是长出一条指向「2015」这个假实体的边
552 let mut forms = utopia_store::graph::proposed_predicates(&state.pool, kb_id).await?;
553 let mut value_forms = utopia_store::graph::proposed_attributes(&state.pool, kb_id).await?;
554 if min_docs > 0 {
555 forms.retain(|f| f.doc_count >= min_docs);
556 value_forms.retain(|f| f.doc_count >= min_docs);
557 // **三份清单都要滤,滤一份等于没滤。** 同一个说法在提示词里出现两次:
558 // miss 行("seen N times")和表层谓词行("on N fact(s)")。
559 // `OntologyMiss` 没有文档维度,所以按活下来的说法集合筛——留下的是
560 // 那些既跨了篇、又还没有谓词的。类那一路不动:`ProposedType`
561 // 同样没有 doc_count,硬滤等于按另一个判据拦,而不是按这个
562 let kept: std::collections::HashSet<&str> = forms.iter().map(|f| f.form.as_str()).collect();
563 misses.retain(|m| m.kind != "relation_type" || kept.contains(m.key.as_str()));
564 }
565 if misses.is_empty() && forms.is_empty() && value_forms.is_empty() {
566 return Ok(json!({
567 "entity_types": [], "relation_types": [], "attribute_types": [], "map_to": []
568 }));
569 }
570
571 // **本体的相关切片,不是它的全文。**
572 //
573 // 从前这里内联两串全量 key。两个毛病:一份 965 类的本体就是 1949 个 key
574 // 的提示词;而且只有 key 没有描述,模型据此判断不了"这个说法是不是某个
575 // 已有类型的同义",于是它只会新建,本体里就稳定长出重复。
576 //
577 // 现在按每个说法各检索几个最近的候选,带着描述给它看。提示词大小从此
578 // 与本体规模无关,而"已经有一个了"这件事第一次变得可判断。
579 let _ = crate::ontology_index::refresh(state, kb_id).await;
580 // 谓词那一路:表层说法 + 关系类的 miss。样例给向量更多着落——
581 // 光一个 acquires 太短,带上"星云科技 → 深蓝存储"就有了语境
582 let pred_probes: Vec<String> = forms
583 .iter()
584 .map(|f| match f.example.as_deref() {
585 Some(ex) if !ex.is_empty() => format!("{} — {ex}", f.form),
586 _ => f.form.clone(),
587 })
588 .chain(
589 misses
590 .iter()
591 .filter(|m| m.kind == "relation_type")
592 .map(|m| m.key.clone()),
593 )
594 .collect();
595 // 类那一路。**必须分开检索**:两张表的描述写的是完全不同的东西,
596 // 拿一个词表外的类名去关系里找,回来的一定是勉强相关的关系
597 let class_probes: Vec<String> = misses
598 .iter()
599 .filter(|m| m.kind == "entity_type")
600 .map(|m| m.key.clone())
601 .collect();
602 let per_pred = crate::ontology_index::nearest_for_each(
603 state,
604 kb_id,
605 &pred_probes,
606 CANDIDATES_PER_PROBE,
607 crate::ontology_index::Target::Predicate(None),
608 )
609 .await
610 .unwrap_or_default();
611 let per_class = crate::ontology_index::nearest_for_each(
612 state,
613 kb_id,
614 &class_probes,
615 CANDIDATES_PER_PROBE,
616 crate::ontology_index::Target::Class,
617 )
618 .await
619 .unwrap_or_default();
620 // 属性那一路:只在属性里找。这里若不限 kind,"成立日期"最近的往往是
621 // 某条关系,模型就会把一个字面值映射到一条边上去
622 let attr_probes: Vec<String> = value_forms
623 .iter()
624 .map(|f| match f.example.as_deref() {
625 Some(ex) if !ex.is_empty() => format!("{} = {ex}", f.form),
626 _ => f.form.clone(),
627 })
628 .chain(
629 misses
630 .iter()
631 .filter(|m| m.kind == "attribute_type")
632 .map(|m| m.key.clone()),
633 )
634 .collect();
635 let per_attr = crate::ontology_index::nearest_for_each(
636 state,
637 kb_id,
638 &attr_probes,
639 CANDIDATES_PER_PROBE,
640 crate::ontology_index::Target::Predicate(Some("attribute")),
641 )
642 .await
643 .unwrap_or_default();
644 // 并集去重:几个说法常常指向同一个候选,逐个说法各列一遍是白费令牌
645 let mut seen: std::collections::HashSet<String> = std::collections::HashSet::new();
646 let mut candidate_lines: Vec<String> = Vec::new();
647 // 模型抄回来的 key 要能对回本体:候选表同时按 key、归一化 key、标签建索引
648 let mut by_name: std::collections::HashMap<String, String> = std::collections::HashMap::new();
649 // 每个候选是关系还是属性。映射到已有类型时,采纳走哪条改写路径由它定
650 let mut kind_of_key: std::collections::HashMap<String, String> =
651 std::collections::HashMap::new();
652 for c in per_pred
653 .iter()
654 .chain(per_class.iter())
655 .chain(per_attr.iter())
656 .flatten()
657 {
658 if !seen.insert(c.key.clone()) {
659 continue;
660 }
661 by_name.insert(normalize_name(&c.key), c.key.clone());
662 by_name.insert(normalize_name(&c.label), c.key.clone());
663 // 关系行自带 relation / attribute,类行没有 kind
664 let kind = c.kind.as_deref().unwrap_or("entity type");
665 kind_of_key.insert(c.key.clone(), kind.to_string());
666 let d = c.description.trim();
667 // **标签只在它确实多说了点什么的时候才写。**
668 // 导进来的本体里 label 常常只是 key 的驼峰写法(acquired_from /
669 // acquiredFrom),两个几乎一样的名字并排摆着,模型抄走的就是错的那个。
670 // 中文标签配英文 key 那种才是标签有信息量的情形,那时才留
671 let name = if normalize_name(&c.label) == normalize_name(&c.key) {
672 String::new()
673 } else {
674 format!(" ({})", c.label)
675 };
676 candidate_lines.push(if d.is_empty() {
677 format!("- {} [{kind}]{name}", c.key)
678 } else {
679 format!("- {} [{kind}]{name}: {d}", c.key)
680 });
681 }
682 // 一个候选都没有(没配嵌入模型,或本体是空的)时如实说,别让模型
683 // 以为"本体里什么都没有"从而放开手建
684 let candidates_block = if candidate_lines.is_empty() {
685 "(no candidates retrieved — the ontology may be empty, or embeddings are unavailable)"
686 .to_string()
687 } else {
688 candidate_lines.join(
689 "
690",
691 )
692 };
693 let miss_lines: Vec<String> = misses
694 .iter()
695 .map(|m| {
696 format!(
697 "- [{}] \"{}\" seen {} times, e.g. {}",
698 m.kind,
699 m.key,
700 m.count,
701 m.example.as_deref().unwrap_or("-")
702 )
703 })
704 .collect();
705
706 // 表层谓词行带上事实数与样例:模型据此判断这是不是一个真关系,
707 // 而 forms 字段让采纳时知道该改写哪些事实
708 let form_lines: Vec<String> = forms
709 .iter()
710 .map(|f| {
711 format!(
712 "- \"{}\" on {} fact(s), e.g. {}",
713 f.form,
714 f.fact_count,
715 f.example.as_deref().unwrap_or("-")
716 )
717 })
718 .collect();
719
720 // 字面值那一路多带两样:一条样例值(模型据此判断该是 number 还是 date),
721 // 和这个说法实际挂在哪些类上。后者不是给模型看的,是采纳时直接拿来当
722 // domain 的——属性的 domain 猜错,主语类型对不上就整条丢弃
723 let value_lines: Vec<String> = value_forms
724 .iter()
725 .map(|f| {
726 format!(
727 "- \"{}\" on {} fact(s), value e.g. {}, seen on: {}",
728 f.form,
729 f.fact_count,
730 f.example.as_deref().unwrap_or("-"),
731 if f.domain_keys.is_empty() {
732 "-".to_string()
733 } else {
734 f.domain_keys.join(", ")
735 }
736 )
737 })
738 .collect();
739
740 let prompt = format!(
741 "You are an ontology engineer.\n\
742 \n\
743 Below are the ontology entries closest in meaning to the unmatched wordings that \
744 follow. This is a retrieved slice, not the whole ontology, so \"not in this list\" \
745 does not mean \"not in the ontology\" — it means nothing close to it was found:\n{}\n\
746 \n\
747 During extraction, the LLM repeatedly produced types/relations OUTSIDE this ontology:\n{}\n\
748 \n\
749 These predicates were taken from the source text because nothing in the ontology fit. \
750 Their facts are currently filed under \"related_to\", which says nothing:\n{}\n\
751 \n\
752 These carried a literal VALUE rather than pointing at another entity, so each one \
753 wants an attribute, never a relation. Turning one into a relation manufactures an \
754 entity out of the value — a node named \"2015\" that stands for nothing:\n{}\n\
755 \n\
756 Each wording gets exactly ONE answer. Do not both map it and propose for it, and do \
757 not propose it as a relation and as an attribute — a wording listed above as carrying \
758 a value is an attribute, full stop.\n\
759 \n\
760 For each wording, decide one of two things.\n\
761 \n\
762 **If one of the candidates above already means it, map to it** — name that \
763 candidate's key in \"map_to\". Do this whenever the meaning matches even though the \
764 spelling differs (\"founding date\" is founding_date; \"headquartered in\" is \
765 location). Adding a second entry for a meaning the ontology already carries is the \
766 worst outcome available here: it splits the same facts across two keys permanently, \
767 and nothing downstream can tell they were the same.\n\
768 \n\
769 **Otherwise propose a new entry.** Rules:\n\
770 - Merge near-duplicates into ONE relation and list every spelling it covers in \
771 \"forms\" (e.g. available_on / available_from / \"available through\" are one relation).\n\
772 - Skip generic verbs that carry no domain meaning (is, has, includes, provides, brings).\n\
773 - A relation is worth adding when the ontology genuinely lacks that meaning, not merely \
774 because a word was frequent.\n\
775 - \"functional\" must be false unless the relation truly permits at most one object per \
776 subject at a time. Getting this wrong makes the temporal engine manufacture conflicts.\n\
777 - An attribute needs a \"datatype\": text, number, date or bool. Read it off the example \
778 value. Choose text when unsure — a value that will not convert to the declared type \
779 is dropped, and a date stored as text is still the value.\n\
780 \n\
781 Every proposal needs a \"description\" as well as a \"reason\", and they are not the \
782 same thing. The reason argues for adding it and is read by a person. **The description \
783 is injected verbatim into the extraction prompt and is the only thing telling the model \
784 what belongs here** — write it as a definition: say what the type is, then say what it \
785 is not and which existing type those cases belong to. A type that arrives with a weak \
786 description becomes the next dumping ground.\n\
787 \n\
788 Output exactly one JSON object:\n\
789 {{\"entity_types\":[{{\"key\":\"snake_case\",\"label\":\"Display Name\",\"description\":\"what belongs here, and what does not\",\"reason\":\"why add it\"}}],\n\
790 \"relation_types\":[{{\"key\":\"snake_case\",\"label\":\"display label\",\"temporal\":\"state|event|eternal\",\"functional\":false,\"forms\":[\"surface spellings this covers\"],\"description\":\"what this relation asserts, and what it does not\",\"reason\":\"why add it\"}}],\n\
791 \"attribute_types\":[{{\"key\":\"snake_case\",\"label\":\"display label\",\"datatype\":\"text|number|date|bool\",\"unit\":\"optional, e.g. CNY\",\"forms\":[\"surface spellings this covers\"],\"description\":\"what this attribute records, and what it does not\",\"reason\":\"why add it\"}}],\n\
792 \"map_to\":[{{\"key\":\"an existing key, copied from the candidate list above\",\"forms\":[\"surface spellings that mean it\"],\"reason\":\"why these are the same thing\"}}]}}\n\
793 \n\
794 Language, and it overrides the skeleton above — that skeleton is written in English \
795 only because these instructions are. Write every \"label\" and \"description\" in {}: \
796 they become this knowledge base's own ontology, and the description is read by the \
797 extraction model while it reads documents in that language. Write every \"reason\" \
798 in {}: a person reads it. \"key\" and \"forms\" stay lowercase ASCII either way.",
799 candidates_block,
800 miss_lines.join("\n"),
801 form_lines.join("\n"),
802 value_lines.join("\n"),
803 lang_name(&kb.ontology_lang),
804 lang_name(reason_lang)
805 );
806
807 let reply = client
808 .chat(&[ChatMessage {
809 role: "user".into(),
810 content: prompt,
811 }])
812 .await
813 .map_err(AppError::Other)?;
814 let block = utopia_extract::json_block(&reply).map_err(AppError::Other)?;
815 let mut proposals: serde_json::Value =
816 serde_json::from_str(&block).map_err(|e| AppError::Other(e.into()))?;
817 resolve_map_targets(&mut proposals, &by_name, &kind_of_key);
818 // 说法归哪一档,服务端说了算——它手里有事实。实测模型会把同一个
819 // \"founded_in\" 既提成关系又提成属性,两条都采纳就是同一批事实被抢两次
820 let value_only: std::collections::HashSet<&str> =
821 value_forms.iter().map(|f| f.form.as_str()).collect();
822 let entity_only: std::collections::HashSet<&str> =
823 forms.iter().map(|f| f.form.as_str()).collect();
824 keep_forms(&mut proposals, "relation_types", &entity_only, &value_only);
825 keep_forms(&mut proposals, "attribute_types", &value_only, &entity_only);
826 Ok(proposals)
827}
828
829/// 把 `map_to` 里的 key 对回本体真正的 key,对不上的整条丢掉。
830///
831/// 模型抄错很常见,而且抄的往往是候选行里挨着的那个标签——`acquiredFrom`
832/// 而不是 `acquired_from`。**这一步必须在服务端做**:界面上那个"用已有的"
833/// 按钮承诺的是把一批事实挂到某个已有谓词上,key 对不上时它只会报错,
834/// 而承诺已经说出去了。对不上就不该显示这条。
835/// 顺带标上目标是关系还是属性:采纳时两条路的改写不一样,而模型答的是
836/// 一个 key,看不出这个 key 落在哪张表的哪一档。
837fn resolve_map_targets(
838 proposals: &mut serde_json::Value,
839 by_name: &std::collections::HashMap<String, String>,
840 kind_of_key: &std::collections::HashMap<String, String>,
841) {
842 let Some(items) = proposals.get_mut("map_to").and_then(|v| v.as_array_mut()) else {
843 return;
844 };
845 items.retain_mut(|m| {
846 let Some(raw) = m.get("key").and_then(|v| v.as_str()) else {
847 return false;
848 };
849 match by_name.get(&normalize_name(raw)) {
850 Some(real) => {
851 m["kind"] = json!(kind_of_key
852 .get(real)
853 .map(String::as_str)
854 .unwrap_or("relation"));
855 m["key"] = json!(real);
856 true
857 }
858 None => {
859 tracing::debug!(key = raw, "map_to 指向了候选之外的 key,丢弃");
860 false
861 }
862 }
863 });
864}
865
866/// 只保留说法确实属于这一档的提案,并把不属于的那些说法从 `forms` 里剔掉。
867///
868/// **判据在服务端手里**:一个说法带的是字面值还是实体宾语,事实里写着,
869/// 不必问模型。实测模型会把同一个 `founded_in` 既提成关系又提成属性——
870/// 两条都采纳的话,同一批事实被抢两次,先跑的那条赢,结果取决于循环顺序。
871///
872/// `forms` 全被剔光的提案整条丢掉:它承诺的"改写 N 条"已经是零了。
873fn keep_forms(
874 proposals: &mut serde_json::Value,
875 section: &str,
876 mine: &std::collections::HashSet<&str>,
877 theirs: &std::collections::HashSet<&str>,
878) {
879 let Some(items) = proposals.get_mut(section).and_then(|v| v.as_array_mut()) else {
880 return;
881 };
882 items.retain_mut(|p| {
883 let Some(forms) = p.get_mut("forms").and_then(|v| v.as_array_mut()) else {
884 // 没有 forms 的提案只是"加一个类型",不改写事实,与归档无关
885 return true;
886 };
887 forms.retain(|f| {
888 let Some(s) = f.as_str() else { return false };
889 // 另一档明确认领的才剔掉。两边都不认识的说法(比如来自 misses
890 // 而不是表层谓词)原样留着——剔掉它等于替模型否决了一条提案
891 !theirs.contains(s) || mine.contains(s)
892 });
893 !forms.is_empty()
894 });
895}
896
897/// key 与标签的比较形式:小写,只留字母数字。
898///
899/// **分隔符整个扔掉**,因为要对齐的正是分隔符的差异:`acquiredFrom`、
900/// `acquired_from`、`Acquired From` 都归到 `acquiredfrom`。折成下划线是不够的
901/// ——驼峰里根本没有分隔符可折。
902///
903/// 只做写法对齐,不做同义判断——那是检索与模型的活。
904fn normalize_name(s: &str) -> String {
905 s.chars()
906 .filter(|c| c.is_alphanumeric())
907 .flat_map(|c| c.to_lowercase())
908 .collect()
909}
910
911#[derive(Deserialize)]
912pub struct AdoptReq {
913 pub key: String,
914 /// true = 这个 key 指的是**已有**的关系/属性,别再建一个。
915 ///
916 /// 这一位是本体消解的落点:检索告诉模型本体里已经有 `founding_date` 了,
917 /// 模型说"这些说法就是它",采纳时只做改写那一半。少了这一位,同一个意思
918 /// 会长出第二个 key,往后这批事实就永久分在两处。
919 #[serde(default)]
920 pub existing: bool,
921 #[serde(default)]
922 pub label: String,
923 #[serde(default)]
924 pub description: Option<String>,
925 #[serde(default = "default_temporal")]
926 pub temporal: String,
927 /// 缺省 false,且刻意不由建议方决定——本体声明的唯一性会驱动时态引擎自动
928 /// 闭合事实,猜错就是成批的假冲突(part_of 就这么烧过一次)
929 #[serde(default)]
930 pub functional: bool,
931 #[serde(default)]
932 pub inverse_functional: bool,
933 /// 归入这个关系的表层说法("available_on"、"available through"…)
934 pub forms: Vec<String>,
935 /// `relation`(缺省)或 `attribute`。
936 ///
937 /// 属性走另一条改写路径:宾语是字面值,要按 datatype 换算过才能落到
938 /// 新属性上;domain 也不由请求带,从事实的主语类型里取
939 #[serde(default)]
940 pub kind: Option<String>,
941 /// 属性专用:text | number | date | bool
942 #[serde(default)]
943 pub datatype: Option<String>,
944 #[serde(default)]
945 pub unit: Option<String>,
946}
947
948/// 采纳一个表层谓词:建关系类型 **并把等着它的 related_to 事实改写过去**。
949///
950/// 与单纯 create 的区别就在后半句。只建类型的话本体长大了、图没变好——
951/// 那 57 条事实会继续是"有关联"。改写走追加(新行 + supersedes),
952/// 实体历史里读得到"先记成 related to,后精化成 available on"。
953///
954/// `existing` 为真时跳过前半句:本体里已经有这个意思了,这一次只做改写。
955/// 这是消解与增长的分界——同一个入口,因为对图做的事完全一样。
956pub async fn adopt_predicate(
957 State(state): State<AppState>,
958 AuthUser(user): AuthUser,
959 Path(kb_id): Path<Uuid>,
960 Json(req): Json<AdoptReq>,
961) -> ApiResult<Json<serde_json::Value>> {
962 require_kb(&state, &user, kb_id, Role::Editor).await?;
963 let key = req.key.trim();
964 if req.forms.is_empty() {
965 return Err(AppError::invalid("forms_required", "forms cannot be empty").into());
966 }
967 if req.kind.as_deref() == Some("attribute") {
968 return adopt_attribute(&state, &user, kb_id, &req).await;
969 }
970 let predicate_id = if req.existing {
971 // 按 key 找已有的那一条。找不到就报错而不是退回新建——
972 // 前端说的是"映射到已有的",静默改成新建就是它最不想要的结果
973 utopia_store::ontology::relation_type_id_by_key(&state.pool, kb_id, key)
974 .await?
975 .ok_or_else(|| {
976 AppError::invalid("unknown_relation_key", "no relation type with that key")
977 })?
978 } else {
979 utopia_store::ontology::create_relation_type(
980 &state.pool,
981 kb_id,
982 key,
983 req.label.trim(),
984 &req.temporal,
985 // 采纳一个提案不替人声明公理。**functional 是唯一的例外**,
986 // 因为它是这个表单本来就问过的一项;其余四条要人去关系页显式勾——
987 // 推理机的判据必须是人写下来的,不是采纳时顺手带上的
988 utopia_core::models::RelationAxioms {
989 functional: req.functional,
990 inverse_functional: req.inverse_functional,
991 ..Default::default()
992 },
993 req.description.as_deref().unwrap_or("").trim(),
994 "relation",
995 // 提案与冷启动只建关系,不声明 domain/range —— 留空 = 不限主宾类型
996 &[],
997 &[],
998 None,
999 None,
1000 )
1001 .await?
1002 };
1003 // **人工路径不对调主宾。**
1004 //
1005 // 不是因为它不需要——把 `produced_by` 映射到 `produces` 同样该对调——而是
1006 // 这里的 forms 是人在面板上勾的,完全可能同时勾了 `produced` 和 `produced_by`,
1007 // 而一个 swap 标志伺候不了混合。自动那条路不存在这个问题:同组说法共享屈折基,
1008 // 结尾有没有 `by` 必然一致。真要修得让 adopt 逐条判方向,那是另一件事。
1009 let utopia_store::graph::Adopted {
1010 batch_id,
1011 moved: remapped,
1012 left_off,
1013 corrected,
1014 } = utopia_store::graph::adopt_proposed_predicates(
1015 &state.pool,
1016 kb_id,
1017 predicate_id,
1018 &req.forms,
1019 false,
1020 )
1021 .await?;
1022 // 采纳同时清掉对应的未匹配统计——本体已经覆盖它们了
1023 for form in &req.forms {
1024 let _ = utopia_store::ontology::clear_miss(&state.pool, kb_id, "relation_type", form).await;
1025 }
1026 let _ = utopia_store::audit::record(
1027 &state.pool,
1028 Some(kb_id),
1029 user.id,
1030 "ontology.predicate_adopted",
1031 "relation_type",
1032 Some(predicate_id),
1033 json!({
1034 "key": key, "label": req.label, "forms": req.forms,
1035 "facts_remapped": remapped, "facts_left_off": left_off,
1036 "facts_direction_corrected": corrected, "batch": batch_id,
1037 }),
1038 )
1039 .await;
1040 state.emit_review(kb_id);
1041 Ok(Json(json!({
1042 "id": predicate_id, "remapped": remapped, "left_off": left_off,
1043 "corrected": corrected, "batch": batch_id,
1044 })))
1045}
1046
1047/// 撤销一次采纳:新写的行作废、旧行复活。关系类型留着(有事实指向过它,
1048/// 而且一个没人用的关系是惰性的)。
1049pub async fn unadopt_predicate(
1050 State(state): State<AppState>,
1051 AuthUser(user): AuthUser,
1052 Path((kb_id, batch_id)): Path<(Uuid, Uuid)>,
1053) -> ApiResult<Json<serde_json::Value>> {
1054 require_kb(&state, &user, kb_id, Role::Editor).await?;
1055 // 归因要按关系类型找回这次撤销,所以先拿到它
1056 let predicate_id: Option<(Uuid,)> = sqlx::query_as(
1057 "SELECT predicate_id FROM fact_adoptions WHERE batch_id = $1 AND kb_id = $2 LIMIT 1",
1058 )
1059 .bind(batch_id)
1060 .bind(kb_id)
1061 .fetch_optional(&state.pool)
1062 .await
1063 .map_err(utopia_core::AppError::Db)?;
1064 // 一次采纳可能同时产生事实改写与实体改类的批次,调用方拿到的是一串
1065 // 不分种类的批次号——这里两边都试,谁认领谁生效
1066 if predicate_id.is_none() {
1067 let n = utopia_store::resolution::unadopt_types(&state.pool, kb_id, batch_id).await?;
1068 let _ = utopia_store::audit::record(
1069 &state.pool,
1070 Some(kb_id),
1071 user.id,
1072 "ontology.adoption_reverted",
1073 "kb",
1074 Some(kb_id),
1075 json!({ "batch": batch_id, "entities_reverted": n }),
1076 )
1077 .await;
1078 state.emit_review(kb_id);
1079 return Ok(Json(json!({ "reverted": n })));
1080 }
1081 let reverted = utopia_store::graph::unadopt(&state.pool, kb_id, batch_id).await?;
1082 let _ = utopia_store::audit::record(
1083 &state.pool,
1084 Some(kb_id),
1085 user.id,
1086 "ontology.adoption_reverted",
1087 "relation_type",
1088 predicate_id.map(|(id,)| id),
1089 json!({ "batch": batch_id, "facts_reverted": reverted }),
1090 )
1091 .await;
1092 state.emit_review(kb_id);
1093 Ok(Json(json!({ "reverted": reverted })))
1094}
1095
1096/// 待认领的表层谓词:原文说过、本体没有、事实降级成了 related_to。
1097pub async fn proposed_predicates(
1098 State(state): State<AppState>,
1099 AuthUser(user): AuthUser,
1100 Path(kb_id): Path<Uuid>,
1101) -> ApiResult<Json<serde_json::Value>> {
1102 require_kb(&state, &user, kb_id, Role::Viewer).await?;
1103 let forms = utopia_store::graph::proposed_predicates(&state.pool, kb_id).await?;
1104 Ok(Json(json!({ "forms": forms })))
1105}
1106
1107/// 最近一次自动扩本体做了什么,以及还能不能撤销。
1108///
1109/// 默认开启的前提是它的动作**可见且可退**。只记在审计台账里不算可见——
1110/// 那是查证用的,不是通知用的。这里给 Ontology 页一条明确的横幅。
1111pub async fn last_auto_extension(
1112 State(state): State<AppState>,
1113 AuthUser(user): AuthUser,
1114 Path(kb_id): Path<Uuid>,
1115) -> ApiResult<Json<serde_json::Value>> {
1116 require_kb(&state, &user, kb_id, Role::Viewer).await?;
1117 let row: Option<(serde_json::Value, chrono::DateTime<chrono::Utc>)> = sqlx::query_as(
1118 "SELECT detail, created_at FROM audit_events
1119 WHERE kb_id = $1 AND action = 'ontology.bootstrapped'
1120 ORDER BY id DESC LIMIT 1",
1121 )
1122 .bind(kb_id)
1123 .fetch_optional(&state.pool)
1124 .await
1125 .map_err(AppError::Db)?;
1126 let Some((detail, at)) = row else {
1127 return Ok(Json(json!({ "run": null })));
1128 };
1129 // 已经被撤销干净的就不再提示——那一轮已经没有任何痕迹留在图上了
1130 let batches: Vec<Uuid> = detail
1131 .get("batches")
1132 .and_then(|v| v.as_array())
1133 .map(|a| {
1134 a.iter()
1135 .filter_map(|s| s.as_str().and_then(|x| x.parse().ok()))
1136 .collect()
1137 })
1138 .unwrap_or_default();
1139 let (live,): (i64,) = sqlx::query_as(
1140 "SELECT count(*) FROM fact_adoptions
1141 WHERE kb_id = $1 AND batch_id = ANY($2) AND reverted_at IS NULL",
1142 )
1143 .bind(kb_id)
1144 .bind(&batches)
1145 .fetch_one(&state.pool)
1146 .await
1147 .map_err(AppError::Db)?;
1148 if live == 0 {
1149 return Ok(Json(json!({ "run": null })));
1150 }
1151 Ok(Json(json!({ "run": {
1152 "at": at,
1153 "relations": detail.get("relations"),
1154 "classes": detail.get("classes"),
1155 "facts_remapped": detail.get("facts_remapped"),
1156 "batches": batches,
1157 }})))
1158}
1159
1160/// OWL 导入:先看会发生什么,确认了才落库。
1161///
1162/// **绝不让上传一个文件就不可逆地改掉本体**——预览与落库走同一个 plan,
1163/// 两条独立路径迟早分叉,而分叉的后果是确认之后发生的事与刚看过的不一样。
1164pub async fn preview_import(
1165 State(state): State<AppState>,
1166 AuthUser(user): AuthUser,
1167 Path(kb_id): Path<Uuid>,
1168 multipart: axum::extract::Multipart,
1169) -> ApiResult<Json<serde_json::Value>> {
1170 require_kb(&state, &user, kb_id, Role::Editor).await?;
1171 let (filename, bytes) = read_upload(multipart).await?;
1172 let (plan, _, _) = crate::owl_import::plan(&state, kb_id, &filename, &bytes).await?;
1173 Ok(Json(json!({ "filename": filename, "plan": plan })))
1174}
1175
1176pub async fn apply_import(
1177 State(state): State<AppState>,
1178 AuthUser(user): AuthUser,
1179 Path(kb_id): Path<Uuid>,
1180 multipart: axum::extract::Multipart,
1181) -> ApiResult<Json<serde_json::Value>> {
1182 require_kb(&state, &user, kb_id, Role::Editor).await?;
1183 let (filename, bytes) = read_upload(multipart).await?;
1184 let (import_id, plan) =
1185 crate::owl_import::apply(&state, kb_id, user.id, &filename, &bytes).await?;
1186 // 公理刚变,这是最该重算一致性的时刻——用户导进来的正是判据本身。
1187 // 失败不影响导入本身:本体已经落库了,检查跑不动是另一件事,
1188 // Review 页那个按钮还能再跑一次
1189 let violations = match utopia_store::reasoning::run(&state.pool, kb_id).await {
1190 Ok(r) => r.found,
1191 Err(e) => {
1192 tracing::warn!(?e, "导入后的一致性检查没跑成");
1193 0
1194 }
1195 };
1196 state.emit_review(kb_id);
1197 Ok(Json(
1198 json!({ "import_id": import_id, "plan": plan, "violations": violations }),
1199 ))
1200}
1201
1202pub async fn list_imports(
1203 State(state): State<AppState>,
1204 AuthUser(user): AuthUser,
1205 Path(kb_id): Path<Uuid>,
1206) -> ApiResult<Json<serde_json::Value>> {
1207 require_kb(&state, &user, kb_id, Role::Viewer).await?;
1208 let imports = utopia_store::ontology::list_imports(&state.pool, kb_id).await?;
1209 Ok(Json(json!({ "imports": imports })))
1210}
1211
1212/// 取 multipart 里的第一个文件。上限 8 MB——FOAF 44 KB、DCTerms 48 KB,
1213/// FIBO 那种大部头分模块也在几百 KB 量级;再大多半是传错了东西。
1214const MAX_ONTOLOGY_BYTES: usize = 8 * 1024 * 1024;
1215
1216async fn read_upload(
1217 mut multipart: axum::extract::Multipart,
1218) -> Result<(String, Vec<u8>), AppError> {
1219 while let Some(field) = multipart.next_field().await.map_err(|e| {
1220 AppError::invalid_detail("bad_upload", "Could not read the upload", e.to_string())
1221 })? {
1222 let Some(filename) = field.file_name().map(String::from) else {
1223 continue;
1224 };
1225 let bytes = field.bytes().await.map_err(|e| {
1226 AppError::invalid_detail(
1227 "upload_read_failed",
1228 "Could not read the uploaded file",
1229 e.to_string(),
1230 )
1231 })?;
1232 if bytes.len() > MAX_ONTOLOGY_BYTES {
1233 return Err(AppError::invalid(
1234 "file_too_large",
1235 "Ontology file is too large (max 8 MB)",
1236 ));
1237 }
1238 if bytes.is_empty() {
1239 return Err(AppError::invalid("empty_file", "Ontology file is empty"));
1240 }
1241 return Ok((filename, bytes.to_vec()));
1242 }
1243 Err(AppError::invalid("no_files", "No file in the upload"))
1244}
1245
1246/// 语言代码 → 提示词里写给模型看的名字。模型认得懂 "Chinese",未必认得懂 "zh"。
1247fn lang_name(code: &str) -> &'static str {
1248 match code {
1249 "zh" => "Chinese",
1250 _ => "English",
1251 }
1252}
1253
1254/// 采纳一个**字面值**说法:建(或指向已有的)属性,并把等着它的事实改挂过去。
1255///
1256/// 跟关系那条路有三处不同,每一处都是属性特有的:
1257///
1258/// 1. **domain 从数据里取,不由请求带。** 属性必须声明能挂在哪些类下,而猜错
1259/// 的代价是硬的——主语类型对不上就整条丢弃(`attr_domain_mismatch`)。
1260/// 这些事实的主语现在是什么类是事实不是判断,直接读。
1261/// 2. **值要按 datatype 换算。** 库里存的是抽取当时的原样(字符串 "2015"),
1262/// 落到一个 date 属性上得先变成日期。
1263/// 3. **换不出来的不改写。** 宁可让它继续没有谓词,等下一次,也不把
1264/// 一个换不动的值硬塞进类型化的属性里——那是"宁缺勿脏"的同一条。
1265async fn adopt_attribute(
1266 state: &AppState,
1267 user: &utopia_core::models::User,
1268 kb_id: Uuid,
1269 req: &AdoptReq,
1270) -> ApiResult<Json<serde_json::Value>> {
1271 let spec = AttributeAdoption {
1272 key: req.key.trim(),
1273 label: req.label.trim(),
1274 description: req.description.as_deref().unwrap_or("").trim(),
1275 datatype: req.datatype.as_deref().unwrap_or("text"),
1276 unit: req.unit.as_deref().map(str::trim).filter(|s| !s.is_empty()),
1277 forms: &req.forms,
1278 existing: req.existing,
1279 };
1280 let done = adopt_attribute_core(state, kb_id, &spec).await?;
1281 let _ = utopia_store::audit::record(
1282 &state.pool,
1283 Some(kb_id),
1284 user.id,
1285 "ontology.attribute_adopted",
1286 "relation_type",
1287 Some(done.attribute_id),
1288 json!({ "key": spec.key, "forms": req.forms, "existing": req.existing,
1289 "remapped": done.remapped, "unconvertible": done.unconvertible }),
1290 )
1291 .await;
1292 // unconvertible 要回给调用方:改写了 3 条、丢下 2 条,界面得说得出后半句
1293 Ok(Json(json!({
1294 "id": done.attribute_id, "batch": done.batch_id,
1295 "remapped": done.remapped, "unconvertible": done.unconvertible
1296 })))
1297}
1298
1299/// 一次属性采纳要的全部输入。
1300pub(crate) struct AttributeAdoption<'a> {
1301 pub key: &'a str,
1302 pub label: &'a str,
1303 pub description: &'a str,
1304 pub datatype: &'a str,
1305 pub unit: Option<&'a str>,
1306 pub forms: &'a [String],
1307 /// true = key 指的是已有属性,只改写、不新建
1308 pub existing: bool,
1309}
1310
1311pub(crate) struct AttributeAdopted {
1312 pub attribute_id: Uuid,
1313 pub batch_id: Uuid,
1314 pub remapped: u32,
1315 /// 值换不动那个 datatype、因而**没有**被改写的条数。
1316 /// 必须往上传:改写了 3 条、丢下 2 条,只报前半句就是报喜不报忧
1317 pub unconvertible: usize,
1318}
1319
1320/// 建(或指向已有的)属性,并把等着它的字面值事实改挂过去。人工与自动共用。
1321pub(crate) async fn adopt_attribute_core(
1322 state: &AppState,
1323 kb_id: Uuid,
1324 spec: &AttributeAdoption<'_>,
1325) -> Result<AttributeAdopted, AppError> {
1326 // 先把待改写的事实取出来:它既定 domain,也定值换不换得动
1327 let facts = utopia_store::graph::value_facts_for_forms(&state.pool, kb_id, spec.forms).await?;
1328 let attribute_id = if spec.existing {
1329 utopia_store::ontology::relation_type_id_by_key(&state.pool, kb_id, spec.key)
1330 .await?
1331 .ok_or_else(|| {
1332 AppError::invalid("unknown_relation_key", "no relation type with that key")
1333 })?
1334 } else {
1335 // **domain 从数据里取。** 属性必须声明能挂在哪些类下,猜错的代价是硬的:
1336 // 主语类型对不上就整条丢弃。这些事实的主语现在是什么类是事实,不是判断
1337 let mut domains: Vec<Uuid> = facts.iter().map(|(_, type_id, _)| *type_id).collect();
1338 domains.sort_unstable();
1339 domains.dedup();
1340 if domains.is_empty() {
1341 return Err(AppError::invalid(
1342 "no_facts_for_forms",
1343 "nothing is waiting on those wordings",
1344 ));
1345 }
1346 utopia_store::ontology::create_relation_type(
1347 &state.pool,
1348 kb_id,
1349 spec.key,
1350 spec.label,
1351 "state",
1352 // 建议方不替时态引擎做决定:functional 会驱动它自动闭合旧值,
1353 // 而其余公理会驱动推理机——两者都该由人显式声明
1354 Default::default(),
1355 spec.description,
1356 "attribute",
1357 &domains,
1358 &[],
1359 Some(spec.datatype),
1360 spec.unit,
1361 )
1362 .await?
1363 };
1364
1365 // 换算按**库里那一条**的 datatype,不按请求——指向已有属性时请求里根本
1366 // 没有 datatype,而即便有,也该听本体的
1367 let datatype = utopia_store::ontology::relation_type_datatype(&state.pool, attribute_id)
1368 .await?
1369 .unwrap_or_else(|| "text".to_string());
1370 let mut rewrites: Vec<(Uuid, serde_json::Value)> = Vec::new();
1371 let mut unconvertible = 0usize;
1372 for (fact_id, _, object_value) in &facts {
1373 // 抽取写进去的形状是 {"value": …},取里面那一层来换算
1374 let raw = object_value.get("value").unwrap_or(object_value);
1375 match utopia_extract::normalize_attr_value(&datatype, raw) {
1376 Some(v) => rewrites.push((*fact_id, json!({ "value": v }))),
1377 // 换不动的**不改写**:宁可让它继续没有谓词,等下一次,
1378 // 也不把一个换不动的值硬塞进类型化的属性里
1379 None => unconvertible += 1,
1380 }
1381 }
1382 // 属性那一路没有签名可判(宾语是字面值),`left_off` 恒为 0
1383 let utopia_store::graph::Adopted {
1384 batch_id,
1385 moved: remapped,
1386 ..
1387 } = utopia_store::graph::adopt_value_facts(&state.pool, kb_id, attribute_id, &rewrites).await?;
1388 for form in spec.forms {
1389 let _ =
1390 utopia_store::ontology::clear_miss(&state.pool, kb_id, "attribute_type", form).await;
1391 }
1392 Ok(AttributeAdopted {
1393 attribute_id,
1394 batch_id,
1395 remapped,
1396 unconvertible,
1397 })
1398}
1399
1400/// 映射到**已有属性**:不建东西,只把这些说法的字面值事实挂过去。
1401pub(crate) async fn adopt_attribute_existing(
1402 state: &AppState,
1403 kb_id: Uuid,
1404 key: &str,
1405 forms: &[String],
1406) -> Result<(Uuid, u32), AppError> {
1407 let done = adopt_attribute_core(
1408 state,
1409 kb_id,
1410 &AttributeAdoption {
1411 key,
1412 label: "",
1413 description: "",
1414 datatype: "text",
1415 unit: None,
1416 forms,
1417 existing: true,
1418 },
1419 )
1420 .await?;
1421 Ok((done.batch_id, done.remapped))
1422}
1423
1424/// 自动扩本体那条路的入口。参数摊开而不是传 `AdoptReq`——那个结构是 HTTP
1425/// 请求体,自动路径没有请求。
1426#[allow(clippy::too_many_arguments)]
1427pub(crate) async fn adopt_attribute_auto(
1428 state: &AppState,
1429 kb_id: Uuid,
1430 key: &str,
1431 label: &str,
1432 description: &str,
1433 datatype: &str,
1434 unit: Option<&str>,
1435 forms: &[String],
1436) -> Result<(Uuid, u32), AppError> {
1437 let done = adopt_attribute_core(
1438 state,
1439 kb_id,
1440 &AttributeAdoption {
1441 key,
1442 label,
1443 description,
1444 datatype,
1445 unit,
1446 forms,
1447 existing: false,
1448 },
1449 )
1450 .await?;
1451 if done.unconvertible > 0 {
1452 tracing::info!(
1453 %kb_id, key, dropped = done.unconvertible,
1454 "有值换不动这个 datatype,那些事实继续没有谓词"
1455 );
1456 }
1457 Ok((done.batch_id, done.remapped))
1458}
1459
1460/// 类型消解的**只算不写**那一步:每个待精化实体的画像与候选类。
1461///
1462/// 跟本体导入同一个模式:先看计划,再决定落不落。在这里它还多一层用处——
1463/// 检索找不着的时候,回执里带着"我们拿什么去找的",第一眼就知道该改画像
1464/// 还是该改类的描述。
1465pub async fn type_resolution_preview(
1466 State(state): State<AppState>,
1467 AuthUser(user): AuthUser,
1468 Path(kb_id): Path<Uuid>,
1469) -> ApiResult<Json<serde_json::Value>> {
1470 require_kb(&state, &user, kb_id, Role::Editor).await?;
1471 let items = crate::type_resolution::preview(&state, kb_id).await?;
1472 Ok(Json(json!({ "items": items })))
1473}
1474
1475/// 跑一遍类型消解并落库:检索候选 → 裁决 → 三档处置。
1476///
1477/// 与 preview 分开是本仓库既有的形状(本体导入也是先看计划再落库)。这里还多
1478/// 一层理由:改类**不进时间轴**,所以它不像事实改写那样在实体历史里自己显形,
1479/// 先看一眼再动是唯一能看见它的时机。
1480pub async fn type_resolution_apply(
1481 State(state): State<AppState>,
1482 AuthUser(user): AuthUser,
1483 Path(kb_id): Path<Uuid>,
1484) -> ApiResult<Json<serde_json::Value>> {
1485 require_kb(&state, &user, kb_id, Role::Editor).await?;
1486 let outcome = crate::type_resolution::resolve(&state, kb_id).await?;
1487 let _ = utopia_store::audit::record(
1488 &state.pool,
1489 Some(kb_id),
1490 user.id,
1491 "ontology.types_resolved",
1492 "knowledge_base",
1493 Some(kb_id),
1494 json!({ "retyped": outcome.retyped, "for_review": outcome.for_review.len(),
1495 "left_alone": outcome.left_alone.len(), "batch": outcome.batch }),
1496 )
1497 .await;
1498 Ok(Json(json!(outcome)))
1499}
1500
1501/// 撤销一次类型消解:把那一批实体放回原来的类。
1502pub async fn type_resolution_undo(
1503 State(state): State<AppState>,
1504 AuthUser(user): AuthUser,
1505 Path((kb_id, batch_id)): Path<(Uuid, Uuid)>,
1506) -> ApiResult<Json<serde_json::Value>> {
1507 require_kb(&state, &user, kb_id, Role::Editor).await?;
1508 let reverted = utopia_store::resolution::unadopt_types(&state.pool, kb_id, batch_id).await?;
1509 let _ = utopia_store::audit::record(
1510 &state.pool,
1511 Some(kb_id),
1512 user.id,
1513 "ontology.types_resolution_reverted",
1514 "knowledge_base",
1515 Some(kb_id),
1516 json!({ "batch": batch_id, "reverted": reverted }),
1517 )
1518 .await;
1519 Ok(Json(json!({ "reverted": reverted })))
1520}
1521
1522#[derive(Deserialize)]
1523pub struct ApproveRefinementReq {
1524 pub from_type_id: Uuid,
1525 pub to_type_id: Uuid,
1526 /// 这一次要一并改掉的实体。**认可的是类对,改的是实体**——
1527 /// 两件事分开,所以调用方可以只认可规则而暂不动任何实体
1528 #[serde(default)]
1529 pub entity_ids: Vec<Uuid>,
1530}
1531
1532/// 认可一个"粗类 → 细类"的配对,并把随请求带来的实体改过去。
1533///
1534/// 待人工那一档由"跨没跨分类轴"触发,而实测那条判据测的往往是**种子类跟导入
1535/// 词汇表连没连上**,不是风险——schema.org 的 Place 另起 key,于是每个城市都
1536/// 要问一遍。配对认可一次就不再问:那是类与类之间的判断,实体只是碰巧撞上它。
1537pub async fn approve_refinement(
1538 State(state): State<AppState>,
1539 AuthUser(user): AuthUser,
1540 Path(kb_id): Path<Uuid>,
1541 Json(req): Json<ApproveRefinementReq>,
1542) -> ApiResult<Json<serde_json::Value>> {
1543 require_kb(&state, &user, kb_id, Role::Editor).await?;
1544 utopia_store::resolution::approve_refinement(
1545 &state.pool,
1546 kb_id,
1547 req.from_type_id,
1548 req.to_type_id,
1549 user.id,
1550 )
1551 .await?;
1552 let picks: Vec<(Uuid, Uuid)> = req
1553 .entity_ids
1554 .iter()
1555 .map(|id| (*id, req.to_type_id))
1556 .collect();
1557 let (batch, moved) = if picks.is_empty() {
1558 (None, 0)
1559 } else {
1560 let (b, n) =
1561 utopia_store::resolution::retype_entities(&state.pool, kb_id, &picks, Some(user.id))
1562 .await?;
1563 (Some(b), n)
1564 };
1565 let _ = utopia_store::audit::record(
1566 &state.pool,
1567 Some(kb_id),
1568 user.id,
1569 "ontology.refinement_approved",
1570 "entity_type",
1571 Some(req.to_type_id),
1572 json!({ "from": req.from_type_id, "to": req.to_type_id, "moved": moved }),
1573 )
1574 .await;
1575 Ok(Json(json!({ "moved": moved, "batch": batch })))
1576}
1577
1578#[cfg(test)]
1579mod tests {
1580 use super::{normalize_name, resolve_map_targets};
1581 use serde_json::json;
1582 use std::collections::{HashMap, HashSet};
1583
1584 #[test]
1585 fn names_align_across_spellings() {
1586 // 导进来的本体里 label 常常只是 key 的驼峰写法,两者必须归到一起
1587 assert_eq!(
1588 normalize_name("acquiredFrom"),
1589 normalize_name("acquired_from")
1590 );
1591 assert_eq!(
1592 normalize_name("Acquired From"),
1593 normalize_name("acquired_from")
1594 );
1595 // 不同的名字仍然不同——这一步只对齐写法,不做同义判断
1596 assert_ne!(normalize_name("acquired_from"), normalize_name("acquires"));
1597 // 中文标签原样保留(去不掉也不该去)
1598 assert_eq!(normalize_name("员工数"), "员工数");
1599 }
1600
1601 #[test]
1602 fn a_map_target_outside_the_candidates_is_dropped() {
1603 let by_name: HashMap<String, String> = [
1604 ("acquiredfrom".to_string(), "acquired_from".to_string()),
1605 ("员工数".to_string(), "headcount".to_string()),
1606 ]
1607 .into_iter()
1608 .collect();
1609 let mut p = json!({"map_to": [
1610 // 抄的是标签而不是 key —— 实测里模型就是这么干的,要能对回去
1611 {"key": "acquiredFrom", "forms": ["acquired from"]},
1612 // 按中文标签抄的,同样对得回去
1613 {"key": "员工数", "forms": ["员工总数"]},
1614 // 候选表里没有:界面上那个按钮会承诺一件做不到的事,所以整条丢掉
1615 {"key": "invented_key", "forms": ["whatever"]},
1616 // 连 key 都没有
1617 {"forms": ["x"]},
1618 ]});
1619 resolve_map_targets(&mut p, &by_name, &HashMap::new());
1620 let items = p["map_to"].as_array().unwrap();
1621 assert_eq!(items.len(), 2);
1622 assert_eq!(items[0]["key"], "acquired_from");
1623 assert_eq!(items[1]["key"], "headcount");
1624 }
1625
1626 #[test]
1627 fn proposals_without_a_map_to_section_are_left_alone() {
1628 let mut p = json!({"entity_types": [], "relation_types": []});
1629 resolve_map_targets(&mut p, &HashMap::new(), &HashMap::new());
1630 assert!(p.get("map_to").is_none());
1631 }
1632
1633 #[test]
1634 fn a_wording_that_carries_a_value_cannot_also_become_a_relation() {
1635 // 实测过的形状:模型把同一个 founded_in 既提成关系又提成属性。
1636 // 两条都采纳的话同一批事实被抢两次,谁先跑谁赢
1637 let value_only: HashSet<&str> = ["founded_in", "registered_capital"].into_iter().collect();
1638 let entity_only: HashSet<&str> = ["acquires"].into_iter().collect();
1639 let mut p = json!({
1640 "relation_types": [
1641 {"key": "founded", "forms": ["founded_in", "founding date"]},
1642 {"key": "acquires", "forms": ["acquires"]}
1643 ],
1644 "attribute_types": [
1645 {"key": "founding_year", "forms": ["founded_in"]},
1646 {"key": "registered_capital", "forms": ["registered_capital"]}
1647 ]
1648 });
1649 super::keep_forms(&mut p, "relation_types", &entity_only, &value_only);
1650 super::keep_forms(&mut p, "attribute_types", &value_only, &entity_only);
1651
1652 let rels = p["relation_types"].as_array().unwrap();
1653 // founded 只剩 "founding date"——那个说法两边都不认识,不该替模型否决
1654 assert_eq!(rels.len(), 2);
1655 assert_eq!(rels[0]["forms"].as_array().unwrap().len(), 1);
1656 assert_eq!(rels[0]["forms"][0], "founding date");
1657 assert_eq!(rels[1]["key"], "acquires");
1658 // 属性那边一条不动
1659 assert_eq!(p["attribute_types"].as_array().unwrap().len(), 2);
1660 }
1661
1662 #[test]
1663 fn a_proposal_left_with_no_wordings_is_dropped() {
1664 // forms 被剔光 = 它承诺的"改写 N 条"已经是零,留着只会让人点一下什么也没发生
1665 let value_only: HashSet<&str> = ["founded_in"].into_iter().collect();
1666 let mut p = json!({"relation_types": [{"key": "founded", "forms": ["founded_in"]}]});
1667 super::keep_forms(&mut p, "relation_types", &HashSet::new(), &value_only);
1668 assert!(p["relation_types"].as_array().unwrap().is_empty());
1669 }
1670
1671 #[test]
1672 fn a_type_proposal_without_wordings_is_left_alone() {
1673 // 没有 forms 的提案只是"加一个类型",不改写任何事实,与归档无关
1674 let mut p = json!({"entity_types": [{"key": "platform", "label": "Platform"}]});
1675 super::keep_forms(&mut p, "entity_types", &HashSet::new(), &HashSet::new());
1676 assert_eq!(p["entity_types"].as_array().unwrap().len(), 1);
1677 }
1678}