World's first open-source enterprise world model.
Rust agent-memorybitemporalgraphragknowledge-baseknowledge-graphllmontologypgvectorpostgresqlragrustself-hostedsemantic-searchtemporal-knowledge-graphworld-model
An imported vocabulary can claim a class the seeds already named (#78)
WaylandYang2334e624de2b
diff --git a/crates/utopia-server/src/api/mod.rs b/crates/utopia-server/src/api/mod.rsindex 875fc8af..cf85c765 100644--- a/crates/utopia-server/src/api/mod.rs+++ b/crates/utopia-server/src/api/mod.rs@@ -120,6 +120,10 @@ pub fn router(state: AppState, cfg: &AppConfig) -> Router {get(documents_routes::extraction_drops),).route("/kbs/{id}/ontology", get(ontology_routes::get))+ .route(+ "/kbs/{id}/ontology/type-resolution/preview",+ post(ontology_routes::type_resolution_preview),+ ).route("/kbs/{id}/ontology/entity-types",post(ontology_routes::create_entity_type),diff --git a/crates/utopia-server/src/api/ontology_routes.rs b/crates/utopia-server/src/api/ontology_routes.rsindex 302e3c8b..03c8bf4d 100644--- a/crates/utopia-server/src/api/ontology_routes.rs+++ b/crates/utopia-server/src/api/ontology_routes.rs@@ -1239,6 +1239,21 @@ pub(crate) async fn adopt_attribute_auto(Ok((done.batch_id, done.remapped))}+/// 类型消解的**只算不写**那一步:每个待精化实体的画像与候选类。+///+/// 跟本体导入同一个模式:先看计划,再决定落不落。在这里它还多一层用处——+/// 检索找不着的时候,回执里带着"我们拿什么去找的",第一眼就知道该改画像+/// 还是该改类的描述。+pub async fn type_resolution_preview(+ State(state): State<AppState>,+ AuthUser(user): AuthUser,+ Path(kb_id): Path<Uuid>,+) -> ApiResult<Json<serde_json::Value>> {+ require_kb(&state, &user, kb_id, Role::Editor).await?;+ let items = crate::type_resolution::preview(&state, kb_id).await?;+ Ok(Json(json!({ "items": items })))+}+#[cfg(test)]mod tests {use super::{normalize_name, resolve_map_targets};diff --git a/crates/utopia-server/src/main.rs b/crates/utopia-server/src/main.rsindex d94a7b08..00167f15 100644--- a/crates/utopia-server/src/main.rs+++ b/crates/utopia-server/src/main.rs@@ -16,6 +16,7 @@ mod pipeline;mod query_engine;mod retrieval;mod state;+mod type_resolution;use state::AppState;use std::sync::Arc;@@ -135,6 +136,18 @@ async fn main() -> anyhow::Result<()> {.ok_or_else(|| anyhow::anyhow!("payload 缺少 kb_id"))?;bootstrap_ontology::bootstrap_ontology(&st, kb_id).await}+ // 本体向量索引:**后台建,不卡请求**。+ // 一份 965 类的本体首次要嵌 2600 行,六到八分钟;放在+ // 交互请求里就是导入完之后第一个用到检索的人干等+ "embed_ontology" => {+ let kb_id: Uuid = job+ .payload+ .get("kb_id")+ .and_then(|v| v.as_str())+ .and_then(|s| s.parse().ok())+ .ok_or_else(|| anyhow::anyhow!("payload 缺少 kb_id"))?;+ ontology_index::refresh(&st, kb_id).await.map(|_| ())+ }"adjudicate_entities" => {let kb_id: Uuid = job.payloaddiff --git a/crates/utopia-server/src/owl_import.rs b/crates/utopia-server/src/owl_import.rsindex 980b6a19..e8efecda 100644--- a/crates/utopia-server/src/owl_import.rs+++ b/crates/utopia-server/src/owl_import.rs@@ -208,11 +208,20 @@ pub async fn plan(} else if e_by_iri.contains_key(c.iri.as_str()) {(Disposition::Update, None)} else if let Some(existing) = e_by_key.get(c.key.as_str()) {- // key 撞了但 IRI 不同:这是两个不同的东西争一个短标签。- // 不自动加后缀——那会让重导入认不出自己上次建的是哪个- // 占位者可能是手工建的(没有 IRI)——那就返回 None,- // 由界面决定怎么措辞。服务端不产出展示文案- (Disposition::KeyTaken, existing.iri.clone())+ match existing.iri.as_deref() {+ // **占位者没有 IRI:认领它。**+ //+ // 没有 IRI 意味着这个类是本地起的名字(种子本体、或者手工建的),+ // 不是另一个词汇表的同名词。导入说的是"这个 IRI 就是那个类",+ // 而这一步不做,整棵树就是断的:schema.org 的 Organization+ // 撞上内置的 organization 被跳过,于是 Corporation 的父类指向+ // 一个没建出来的东西——内置那几个基类一个子类都挂不上,+ // 类型精化无从谈起。+ None => (Disposition::Update, None),+ // 已经有一个**不同的** IRI:两个词汇表争同一个短标签,+ // 这是真冲突。不自动加后缀——那会让重导入认不出自己上次建的是哪个+ Some(_) => (Disposition::KeyTaken, existing.iri.clone()),+ }} else {(Disposition::Create, None)};@@ -338,15 +347,29 @@ pub async fn apply(created_classes += 1;}Disposition::Update => {- if let Some(id) = utopia_store::ontology::update_type_from_import(+ // 两种 Update:这个 IRI 上次导过(按 IRI 找得到),+ // 或者它要认领一个同名的本地类(按 key 找,且那一行还没有 IRI)+ let updated = utopia_store::ontology::update_type_from_import(&state.pool,kb_id,&c.iri,&c.label,&c.description,)- .await?- {+ .await?;+ let id = match updated {+ Some(id) => Some(id),+ None => {+ utopia_store::ontology::adopt_iri_onto_key(+ &state.pool,+ kb_id,+ &c.key,+ &c.iri,+ )+ .await?+ }+ };+ if let Some(id) = id {id_of.insert(c.iri.clone(), id);updated_classes += 1;}@@ -517,6 +540,16 @@ pub async fn apply(summary,).await;+ // 本体刚变过,向量都是陈的。**排任务而不是就地跑**:这一趟要嵌几千行,+ // 放在导入请求里,用户点完确认要多等六到八分钟。排不上也不要紧——+ // 索引是自愈的,下一个用到检索的人会补上+ let _ = utopia_store::jobs::enqueue(+ &state.pool,+ "embed_ontology",+ serde_json::json!({ "kb_id": kb_id }),+ )+ .await;+Ok((import_id, plan))}diff --git a/crates/utopia-server/src/type_resolution.rs b/crates/utopia-server/src/type_resolution.rsnew file mode 100644index 00000000..d2249d12--- /dev/null+++ b/crates/utopia-server/src/type_resolution.rs@@ -0,0 +1,140 @@+//! 类型消解:把挂在倾倒场类下的实体,精化到本体里具体的类。+//!+//! **为什么能事后做,而谓词不能**(0001 的那个不对称):类型是挂在节点上的+//! 注解,可以等证据攒够了再贴;谓词就是事实本身,`(NVIDIA, ?, Mellanox)`+//! 根本不是一条事实。所以谓词走"先记原词、后映射",类型走"先粗后精"。+//!+//! 消解手里的东西跟抽取当场完全不同:+//!+//! 1. **`proposed_type`**——抽取时模型自己报的类型名,词表里没有才留下来。+//! 最强的一条,因为任务从"读懂这是什么"变成了"本体里哪个类叫这个意思"。+//! 2. **实体画像**——它参与的全部谓词,跨文档累积。+//! 3. **证据引文**——同一批句子,但聚在一起,且不必跟几十个别的实体抢注意力。+//!+//! 粗类的后代**排在前面**,但不是唯一能选的——两套本体的分类轴常常不重合+//! (schema.org 把软件挂在 CreativeWork 下,而抽取给的粗类是 product)。+//! 该说不的是裁决那一步,它看得到描述也看得到粗类。++use crate::{ontology_index, AppState};+use utopia_core::AppResult;+use uuid::Uuid;++/// 倾倒场类的 key。挂在它下面的实体是"没判出来",不是"判成了这个"。+const DUMPING_GROUND: &str = "concept";+/// 一轮看多少个实体。够一次人工过目,也够看出检索准不准。+const BATCH: i64 = 60;+/// 每个实体检索几个候选。给裁决看的,不是让它在一堆勉强相关里硬挑一个。+const CANDIDATES: i64 = 8;++/// 一个实体的消解建议(preview 用,不写库)。+#[derive(Debug, serde::Serialize)]+pub struct TypeSuggestion {+ pub entity_id: Uuid,+ pub name: String,+ pub coarse: String,+ pub proposed_type: Option<String>,+ pub fact_count: i64,+ /// 送去检索的那段字。**回给调用方**——检索找不着的时候,+ /// 第一个要看的就是"我们拿什么去找的"+ pub profile: String,+ pub candidates: Vec<utopia_core::models::TypeCandidate>,+}++/// 只算不写:每个待消解实体的画像与候选。+///+/// 独立成一步是有意的——在花力气建裁决之前,先回答"检索到底找不找得到"。+/// 找不到的话,裁决做得再好也没有用。+pub async fn preview(state: &AppState, kb_id: Uuid) -> AppResult<Vec<TypeSuggestion>> {+ let _ = ontology_index::refresh(state, kb_id).await;+ let subjects = utopia_store::resolution::entities_for_type_resolution(+ &state.pool,+ kb_id,+ DUMPING_GROUND,+ BATCH,+ )+ .await?;+ if subjects.is_empty() {+ return Ok(Vec::new());+ }+ let profiles: Vec<String> = subjects.iter().map(profile_of).collect();+ let per_entity = ontology_index::nearest_for_each(+ state,+ kb_id,+ &profiles,+ // 多取一些再按祖先过滤:过滤在检索之后,所以要留出被滤掉的余量+ CANDIDATES * 4,+ ontology_index::Target::Class,+ )+ .await+ .unwrap_or_default();++ let mut out = Vec::with_capacity(subjects.len());+ for (i, s) in subjects.iter().enumerate() {+ // 粗类的后代**排前面,但不是唯一能选的**。+ //+ // 起初这里是硬闸门(只许往后代走),实测 17 个实体里挡掉 4 个正确答案:+ // schema.org 把 SoftwareApplication 与 Periodical 都挂在 CreativeWork 下,+ // 而抽取给的粗类是 product / organization——两套分类的轴根本不重合,+ // 硬拦就是把正确答案永久锁在门外。跟 part_of 那次同一条教训:+ // **签名是导向,不是闸门**;系统性丢数据比偶尔判错贵得多。+ //+ // 该说不的是裁决那一步:它看得到描述、看得到粗类,能说出"这不是"。+ let descendants: std::collections::HashSet<_> =+ utopia_store::resolution::descendants_of(&state.pool, kb_id, s.coarse_id)+ .await?+ .into_iter()+ .collect();+ let mut ranked: Vec<_> = per_entity+ .get(i)+ .cloned()+ .unwrap_or_default()+ .into_iter()+ .filter(|c| c.id != s.coarse_id)+ .collect();+ // 稳定排序:后代提前,同一档内保持检索给的距离序+ ranked.sort_by_key(|c| !descendants.contains(&c.id));+ let candidates: Vec<_> = ranked.into_iter().take(CANDIDATES as usize).collect();+ out.push(TypeSuggestion {+ entity_id: s.id,+ name: s.canonical_name.clone(),+ coarse: s.coarse_key.clone(),+ proposed_type: s.proposed_type.clone(),+ fact_count: s.fact_count,+ profile: profiles[i].clone(),+ candidates,+ });+ }+ Ok(out)+}++/// 实体画像:送去做向量检索的那段字。+///+/// **模型自己报的类型名放最前面。** 它是最强的信号,而检索匹配的是类的+/// `label + description`——一个类名对一段类定义,比一串谓词对一段类定义近得多。+///+/// 名字、别名其次;谓词与引文垫后当语境。+fn profile_of(s: &utopia_store::resolution::TypeCandidateSubject) -> String {+ let mut parts: Vec<String> = Vec::new();+ if let Some(p) = s+ .proposed_type+ .as_deref()+ .map(str::trim)+ .filter(|x| !x.is_empty())+ {+ parts.push(p.to_string());+ }+ parts.push(s.canonical_name.clone());+ if !s.aliases.is_empty() {+ parts.push(s.aliases.join(", "));+ }+ if !s.roles.is_empty() {+ parts.push(s.roles.join(" "));+ }+ // 引文垫后当语境,且只有两句:它们是关于这个实体的句子没错,但也带着+ // 一堆跟类型无关的东西(时间、数字、别的实体),放多了会把画像的重心+ // 从"这是什么"拖到"这段文字讲了什么"。查询侧已经保证只取主语位的+ for q in s.quotes.iter().take(2) {+ parts.push(q.chars().take(120).collect());+ }+ parts.join(". ")+}diff --git a/crates/utopia-store/src/ontology.rs b/crates/utopia-store/src/ontology.rsindex 7d54a7aa..8b23c0fe 100644--- a/crates/utopia-store/src/ontology.rs+++ b/crates/utopia-store/src/ontology.rs@@ -986,3 +986,31 @@ pub async fn relation_type_datatype(pool: &PgPool, id: Uuid) -> AppResult<Option.await?;Ok(row.and_then(|(d,)| d))}++/// 把一个 IRI 认到已有的**本地**类上(原本没有 IRI 的那种)。+///+/// **只写 IRI,不动 label 与 description。** 认领要解决的是"这棵树是断的",+/// 不是"用词汇表的说法覆盖用户的说法":种子类的描述是照着抽取调过的、+/// 且跟库的语言走,而 schema.org 的描述是英文样板。覆盖它等于悄悄换掉+/// 抽取提示词里最承重的那一句。+///+/// 只在 `iri IS NULL` 时写,所以重复导入是幂等的,也绝不会抢走另一个+/// 词汇表已经认领的类。+pub async fn adopt_iri_onto_key(+ pool: &PgPool,+ kb_id: Uuid,+ key: &str,+ iri: &str,+) -> AppResult<Option<Uuid>> {+ let row: Option<(Uuid,)> = sqlx::query_as(+ "UPDATE entity_types SET iri = $3+ WHERE kb_id = $1 AND key = $2 AND iri IS NULL+ RETURNING id",+ )+ .bind(kb_id)+ .bind(key)+ .bind(iri)+ .fetch_optional(pool)+ .await?;+ Ok(row.map(|(id,)| id))+}diff --git a/crates/utopia-store/src/resolution.rs b/crates/utopia-store/src/resolution.rsindex 04f58f40..ec9c1834 100644--- a/crates/utopia-store/src/resolution.rs+++ b/crates/utopia-store/src/resolution.rs@@ -1671,3 +1671,107 @@ mod tests {assert!(cosine(&[0.0, 0.0], &[1.0, 1.0]).is_none());}}++/// 一个等着精化类型的实体,连同用来判断它是什么的全部材料。+#[derive(Debug, Clone, sqlx::FromRow)]+pub struct TypeCandidateSubject {+ pub id: Uuid,+ pub canonical_name: String,+ pub aliases: Vec<String>,+ /// 现在挂着的粗类。**它是地板**:精化只往它的后代走,够不着就原地不动+ pub coarse_key: String,+ pub coarse_id: Uuid,+ /// 抽取时模型自己报的类型名。词表里没有才会留在这儿——+ /// 也正因如此它是最强的信号:不是"读懂这是什么",是"本体里哪个类叫这个"+ pub proposed_type: Option<String>,+ /// 它参与的谓词,连着对方的名字(`produces 深蓝`、`leads by 张伟`)。+ /// **跨文档累积**,这正是抽取当场没有的东西+ pub roles: Vec<String>,+ /// 证据引文,最多几句。抽取看的是同一批句子,但那一次要同时做实体识别、+ /// 关系判断、时态解析、JSON 格式化,还要跟几十个别的实体抢注意力+ /// 证据引文,**只取它当主语的那些**。宾语位的引文讲的是主语:+ /// 「上海浦东新区」是 located_in 的宾语,引文却是"星云科技(上海)+ /// 有限公司是一家注册于上海浦东新区的股份有限公司",整句重心在+ /// "股份有限公司"上——实测那一版检索给出的候选全是 corporation 一类+ pub quotes: Vec<String>,+ pub fact_count: i64,+}++/// 值得送去精化类型的实体:挂在倾倒场类下的,或者模型报过一个词表外类型的。+///+/// 类型化得已经很具体的实体不动——重判一次只有下降风险,没有上升空间。+pub async fn entities_for_type_resolution(+ pool: &PgPool,+ kb_id: Uuid,+ dumping_ground: &str,+ limit: i64,+) -> AppResult<Vec<TypeCandidateSubject>> {+ Ok(sqlx::query_as(+ "SELECT e.id, e.canonical_name, e.aliases, t.key AS coarse_key, t.id AS coarse_id,+ e.proposed_type,+ -- 对方写**名字**,不写它的类型 key。+ -- 写 key 是自毁:查询里出现 organization / product / event 这些词,+ -- 而检索的目标正是这些类自己,于是候选就是画像里那几个词。+ -- 实测「张伟」的画像是 leads→organization … works_at→organization,+ -- 回来的候选是 corporation、organization、business_entity_type——+ -- 检索到的是画像自己,不是这个人是什么+ ARRAY(+ SELECT DISTINCT rt.key || CASE WHEN f.subject_id = e.id THEN ' ' ELSE ' by ' END+ || coalesce(oe.canonical_name, 'a value')+ FROM facts f+ JOIN relation_types rt ON rt.id = f.predicate_id+ LEFT JOIN entities oe ON oe.id = CASE WHEN f.subject_id = e.id+ THEN f.object_id ELSE f.subject_id END+ WHERE f.kb_id = $1 AND f.invalidated_at IS NULL+ AND (f.subject_id = e.id OR f.object_id = e.id)+ LIMIT 12+ ) AS roles,+ ARRAY(+ SELECT DISTINCT ev.quote FROM fact_evidence ev+ JOIN facts f2 ON f2.id = ev.fact_id+ WHERE f2.kb_id = $1 AND f2.invalidated_at IS NULL+ AND f2.subject_id = e.id+ AND ev.quote IS NOT NULL+ LIMIT 3+ ) AS quotes,+ (SELECT count(*) FROM facts f3+ WHERE f3.kb_id = $1 AND f3.invalidated_at IS NULL+ AND (f3.subject_id = e.id OR f3.object_id = e.id)) AS fact_count+ FROM entities e+ JOIN entity_types t ON t.id = e.type_id+ WHERE e.kb_id = $1 AND e.merged_into IS NULL+ -- 值得看的三种:挂在倾倒场下的、模型报过词表外类型的、+ -- **以及粗类本身还有子类的**。第三种是主力:抽取只认基类之后,+ -- organization 下面挂着 167 个更具体的类,那才是导进来的本体+ -- 唯一的用武之地。只看前两种就把它整个漏掉了+ AND (t.key = $2 OR e.proposed_type IS NOT NULL+ OR EXISTS (SELECT 1 FROM entity_type_parents p WHERE p.parent_id = t.id))+ ORDER BY fact_count DESC, e.created_at+ LIMIT $3",+ )+ .bind(kb_id)+ .bind(dumping_ground)+ .bind(limit)+ .fetch_all(pool)+ .await?)+}++/// 某个类的全部后代(含自身)。精化只能往粗类的后代走。+///+/// **递归而不是一层**:本体是 DAG,`software_application ⊂ creative_work ⊂ thing`,+/// 只查一层就把绝大多数正确答案挡在门外了。+pub async fn descendants_of(pool: &PgPool, kb_id: Uuid, root: Uuid) -> AppResult<Vec<Uuid>> {+ let rows: Vec<(Uuid,)> = sqlx::query_as(+ "WITH RECURSIVE d(id) AS (+ SELECT $2::uuid+ UNION+ SELECT p.child_id FROM entity_type_parents p JOIN d ON d.id = p.parent_id+ )+ SELECT d.id FROM d JOIN entity_types t ON t.id = d.id WHERE t.kb_id = $1",+ )+ .bind(kb_id)+ .bind(root)+ .fetch_all(pool)+ .await?;+ Ok(rows.into_iter().map(|(id,)| id).collect())+}