| 1 | //! utopia-extract: LLM 抽取(实体/关系/时间归一化)。 |
| 2 | //! 提示词注入本体类型与文档元时间;输出严格 JSON;证据引句强制(无引句降置信度)。 |
| 3 | |
| 4 | use chrono::{DateTime, NaiveDate, TimeZone, Utc}; |
| 5 | use serde::Deserialize; |
| 6 | use utopia_llm::ChatMessage; |
| 7 | |
| 8 | #[derive(Debug, Deserialize)] |
| 9 | pub struct Extraction { |
| 10 | #[serde(default)] |
| 11 | pub entities: Vec<ExtractedEntity>, |
| 12 | #[serde(default)] |
| 13 | pub facts: Vec<ExtractedFact>, |
| 14 | } |
| 15 | |
| 16 | #[derive(Debug, Deserialize)] |
| 17 | pub struct ExtractedEntity { |
| 18 | pub name: String, |
| 19 | #[serde(rename = "type")] |
| 20 | pub type_key: String, |
| 21 | /// 模型自己的说法:它认为这最具体是个什么。**不校验、不入本体**。 |
| 22 | /// |
| 23 | /// 存在的理由是清单里总有个"差不多"的:本体有 product,模型觉得够用就选了, |
| 24 | /// 心里那个"向量数据库软件"就此丢失。实测 17 个实体的 proposed_type |
| 25 | /// 全是空的,正是这个原因——而事后消解最需要的恰是这个名字: |
| 26 | /// 短名字对短标签,比拿一段中文散文去匹配 "A software application." 近得多。 |
| 27 | #[serde(default)] |
| 28 | pub specific_type: Option<String>, |
| 29 | } |
| 30 | |
| 31 | #[derive(Debug, Deserialize)] |
| 32 | pub struct ExtractedFact { |
| 33 | pub subject: String, |
| 34 | pub predicate: String, |
| 35 | /// 关系事实的宾语实体名;属性事实为空 |
| 36 | #[serde(default)] |
| 37 | pub object: Option<String>, |
| 38 | /// 属性事实的字面值(谓词是 attribute 时) |
| 39 | #[serde(default)] |
| 40 | pub value: Option<serde_json::Value>, |
| 41 | #[serde(default)] |
| 42 | pub valid_from: Option<String>, |
| 43 | #[serde(default)] |
| 44 | pub valid_to: Option<String>, |
| 45 | #[serde(default)] |
| 46 | pub confidence: Option<f32>, |
| 47 | #[serde(default)] |
| 48 | pub quote: Option<String>, |
| 49 | } |
| 50 | |
| 51 | /// 提示词里的一条关系。 |
| 52 | /// |
| 53 | /// 比类多一样东西:**类型签名**。它是给模型的签名,不是闸门——在模型落笔那一刻 |
| 54 | /// 减少"Alice works_at 西雅图",而不是等错了再拦。事后校验面对的是既成事实 |
| 55 | ///(丢掉可惜、留着是脏数据),签名是在写出来之前掰正。本体写错时模型看到原文 |
| 56 | /// 说了别的仍可覆盖;硬闸门会系统性丢数据,`part_of` 烧我们的正是那种方式。 |
| 57 | pub struct PromptRelation { |
| 58 | pub key: String, |
| 59 | pub label: String, |
| 60 | pub description: String, |
| 61 | /// 形如 `person|organization → vendor`,`*` 表示那一侧不限。空串 = 两侧都不限。 |
| 62 | /// **一律用 key**:模型要输出的就是 key,中文库里 person 的 label 是"人物", |
| 63 | /// 写进签名等于教它输出一个不存在的类型(docs/decisions/0004) |
| 64 | pub signature: String, |
| 65 | } |
| 66 | |
| 67 | /// 构造抽取提示词。`types` 为 (key, label, description) 三元组; |
| 68 | /// description 非空时按行列出——本体里的语义指引直接决定抽取质量。 |
| 69 | /// `attributes` 为调用方预排版的属性行("person.salary (number, CNY): 月薪"); |
| 70 | /// 为空时提示词一字不变——没定义属性的库零成本。 |
| 71 | pub fn build_messages( |
| 72 | types: &[(String, String, String)], |
| 73 | relations: &[PromptRelation], |
| 74 | attributes: &[String], |
| 75 | doc_time: Option<&str>, |
| 76 | filename: &str, |
| 77 | // 本文档前面几块已经认下的 (类型 key, 实体名),按首次出现排序。 |
| 78 | // 第一块为空——那时还没有"前面" |
| 79 | known: &[(String, String)], |
| 80 | chunk_text: &str, |
| 81 | ) -> Vec<ChatMessage> { |
| 82 | // **有描述时不送 label**。label 是给人看的显示名,而且它跟界面无关、 |
| 83 | // 跟这个库的语料语言走——中文库里 person 的 label 是"人物"。 |
| 84 | // `- person (人物): 有名有姓的具体的人…` 里那个"人物"相对 key 近乎零信息量, |
| 85 | // 却让提示词在语料语言与标识符之间来回跳。描述为空时才拿它兜底: |
| 86 | // 光一个 key 太单薄。见 docs/decisions/0004 |
| 87 | let fmt_list = |items: &[(String, String, String)]| { |
| 88 | items |
| 89 | .iter() |
| 90 | .map(|(k, l, d)| { |
| 91 | let d = d.trim(); |
| 92 | if d.is_empty() { |
| 93 | format!("- {k} ({l})") |
| 94 | } else { |
| 95 | format!("- {k}: {d}") |
| 96 | } |
| 97 | }) |
| 98 | .collect::<Vec<_>>() |
| 99 | .join("\n") |
| 100 | }; |
| 101 | let type_list = fmt_list(types); |
| 102 | // 关系行:有签名时括号里放签名,没有才退回 label。 |
| 103 | // `- works_at (person → organization): 一个人受雇于某个组织。` |
| 104 | let rel_list = relations |
| 105 | .iter() |
| 106 | .map(|r| { |
| 107 | let d = r.description.trim(); |
| 108 | let paren = if !r.signature.is_empty() { |
| 109 | r.signature.clone() |
| 110 | } else if d.is_empty() { |
| 111 | r.label.clone() |
| 112 | } else { |
| 113 | String::new() |
| 114 | }; |
| 115 | match (paren.is_empty(), d.is_empty()) { |
| 116 | (false, false) => format!("- {} ({paren}): {d}", r.key), |
| 117 | (false, true) => format!("- {} ({paren})", r.key), |
| 118 | (true, false) => format!("- {}: {d}", r.key), |
| 119 | (true, true) => format!("- {}", r.key), |
| 120 | } |
| 121 | }) |
| 122 | .collect::<Vec<_>>() |
| 123 | .join("\n"); |
| 124 | // 记号只在真有签名时解释一次;没有签名的库,提示词一字不变。 |
| 125 | // 说明用英文——提示词的**指令语言**是英文,只有 description 跟语料走 |
| 126 | let sig_note = if relations.iter().any(|r| !r.signature.is_empty()) { |
| 127 | ". A parenthesis after the key is the type signature, subject then object; \ |
| 128 | \"|\" means or, \"*\" means unconstrained. It is a hint, not a rule — \ |
| 129 | when the text says otherwise, write what the text says" |
| 130 | } else { |
| 131 | "" |
| 132 | }; |
| 133 | let time_ctx = doc_time |
| 134 | .map(|t| { |
| 135 | format!( |
| 136 | "Document date: {t}. Resolve relative time expressions (e.g. \"last year\", \ |
| 137 | \"this March\") to absolute dates using it as the reference." |
| 138 | ) |
| 139 | }) |
| 140 | .unwrap_or_else(|| { |
| 141 | "Document date unknown — only output dates explicitly written in the text.".into() |
| 142 | }); |
| 143 | |
| 144 | // 属性段按需注入:清单 + 输出说明 + 取值规则。没定义属性时完全不出现 |
| 145 | let attr_section = if attributes.is_empty() { |
| 146 | String::new() |
| 147 | } else { |
| 148 | format!( |
| 149 | "\nAttributes (literal-valued fields, listed as class.attribute_key; as \"predicate\" \ |
| 150 | use the attribute_key alone — e.g. \"salary\", not \"person.salary\" — with a \ |
| 151 | \"value\" instead of \"object\"):\n{}\n", |
| 152 | attributes.join("\n") |
| 153 | ) |
| 154 | }; |
| 155 | let attr_rules = if attributes.is_empty() { |
| 156 | String::new() |
| 157 | } else { |
| 158 | "\n10. Attribute facts carry \"value\" (no \"object\"): number = plain number without \ |
| 159 | thousands separators or unit symbols; date = \"YYYY[-MM[-DD]]\"; bool = true/false; \ |
| 160 | text = a short string. Only attach an attribute to a subject of its listed class. \ |
| 161 | valid_from = when this value took effect, if the text says so." |
| 162 | .to_string() |
| 163 | }; |
| 164 | let system = format!( |
| 165 | "You are a knowledge-graph extraction engine. Extract entities and factual relations \ |
| 166 | from the given text. Output exactly one JSON object and nothing else.\n\ |
| 167 | \n\ |
| 168 | Entity types (prefer these keys):\n{type_list}\n\ |
| 169 | \n\ |
| 170 | Relation types (prefer these keys){sig_note}:\n{rel_list}\n\ |
| 171 | {attr_section}\ |
| 172 | \n\ |
| 173 | Output format:\n\ |
| 174 | {{\"entities\":[{{\"name\":\"entity name\",\"type\":\"type key\",\"specific_type\":\"what you would call it\"}}],\n\ |
| 175 | \"facts\":[{{\"subject\":\"subject entity name\",\"predicate\":\"relation key\",\"object\":\"object entity name\",\n\ |
| 176 | \"valid_from\":\"2023-01\",\"valid_to\":null,\"confidence\":0.9,\"quote\":\"verbatim supporting quote\"}}]}}\n\ |
| 177 | \n\ |
| 178 | Rules:\n\ |
| 179 | 1. Use the canonical full name as written in the text, in the text's original language; \ |
| 180 | list each entity once. Text introduces a full name and then shortens it — \ |
| 181 | \"星云科技上海研究院\" becomes \"上海研究院\", \"Nebula Technologies Inc.\" becomes \ |
| 182 | \"Nebula\" — and both forms mean one entity, listed once under the fuller form. \ |
| 183 | Two names are two entities only when the text is talking about two things.\n\ |
| 184 | 2. Every fact's subject/object must appear in entities.\n\ |
| 185 | 3. Dates must be \"YYYY\", \"YYYY-MM\", \"YYYY-MM-DD\", or null — never invent dates.\n\ |
| 186 | 3a. valid_to takes a third value: \"unknown\". Use it when the text says the relation \ |
| 187 | has ended but does not say when — \"former CEO of X\", \"stepped down\", \"left the \ |
| 188 | company\", \"no longer available\", \"until recently\". Use null only for something \ |
| 189 | still going on. These are not interchangeable: null asserts it still holds, and \ |
| 190 | writing null for a relation the text says is over makes us claim the opposite of \ |
| 191 | the source.\n\ |
| 192 | 4. {time_ctx}\n\ |
| 193 | 5. quote must be a contiguous excerpt from the source text; every fact needs one.\n\ |
| 194 | 6. confidence in 0~1: 0.9 explicitly stated, 0.7 inferred, 0.5 uncertain.\n\ |
| 195 | 7. If nothing can be extracted, output {{\"entities\":[],\"facts\":[]}}.\n\ |
| 196 | 8. If no listed relation fits, do not force the nearest one — write the predicate the \ |
| 197 | text itself uses, in snake_case (e.g. \"available_on\", \"runs_on\"). A relation \ |
| 198 | named after the text is worth more than a listed one that says something false.\n\ |
| 199 | 9. The same holds for entity types: if none of the listed types fits, write the type \ |
| 200 | the text implies, in snake_case (e.g. \"model\", \"technology\"). Do not fall back \ |
| 201 | to a broad listed type such as \"thing\" or \"creative_work\" merely because \ |
| 202 | nothing specific matched — that hides the gap instead of reporting it.\n\ |
| 203 | 10. specific_type is required on every entity and is never checked against the list. \ |
| 204 | Name the most specific kind the thing is, in the words you would use for it. Write \ |
| 205 | it even when \"type\" already fits, and make it narrower than \"type\" wherever the \ |
| 206 | text supports it — type \"product\", specific_type \"vector database software\". \ |
| 207 | Repeat the listed type only when the text genuinely says nothing more precise.\ |
| 208 | {attr_rules}" |
| 209 | ); |
| 210 | |
| 211 | // 已知实体紧挨着正文:服从性靠位置,理由见 known_block 的注释 |
| 212 | let user = format!( |
| 213 | "Source file: \"{filename}\"\n{}\nText:\n{chunk_text}", |
| 214 | known_block(known) |
| 215 | ); |
| 216 | |
| 217 | vec![ |
| 218 | ChatMessage { |
| 219 | role: "system".into(), |
| 220 | content: system, |
| 221 | }, |
| 222 | ChatMessage { |
| 223 | role: "user".into(), |
| 224 | content: user, |
| 225 | }, |
| 226 | ] |
| 227 | } |
| 228 | |
| 229 | /// 已在本文档中出现过的实体,放进提示词的字符预算。 |
| 230 | /// |
| 231 | /// 超出就截断(保留先出现的)。中文商业文本先出全称、主角先出场,所以 |
| 232 | /// **首次出现顺序天然偏向那些后面会被简称的名字**。 |
| 233 | const KNOWN_BUDGET_CHARS: usize = 1200; |
| 234 | |
| 235 | /// 把「本文档已经认下的实体」排版成提示词里的一段。空则返回空串。 |
| 236 | /// |
| 237 | /// **为什么在正文之前、指令贴着清单**:抽象规则打不过挨着它的具体块——本体建议 |
| 238 | /// 那次,语言要求就输给了紧随其后的英文 JSON 骨架,挪到骨架之后并点名它才生效。 |
| 239 | /// 服从性靠位置,所以指令挨着它管的数据放,两者一起挨着正文。 |
| 240 | /// |
| 241 | /// **顺带一条与放哪条消息无关的规矩:逐块变化的内容一律放最后。** 前缀缓存匹配的是 |
| 242 | /// token 前缀,而消息按 system→user 拼接,所以「system 末尾」与「user 开头」几乎等价; |
| 243 | /// 真正会打碎缓存的是把它塞在**中间**(本体之后、规则之前),那会把规则挤出前缀。 |
| 244 | /// 缓存本身不归我们管——供应商开不开、报不报都由它,本部署实测 `cached=0`—— |
| 245 | /// 我们只负责别把它弄碎。自部署 vLLM 默认开着自动前缀缓存,那省的是算力不是钱。 |
| 246 | fn known_block(known: &[(String, String)]) -> String { |
| 247 | if known.is_empty() { |
| 248 | return String::new(); |
| 249 | } |
| 250 | // 按类型分组:更紧凑,而且顺带压住跨块类型漂移 |
| 251 | //(同一个"沧海"在一块里是 product、另一块里是 project) |
| 252 | let mut by_type: Vec<(&str, Vec<&str>)> = Vec::new(); |
| 253 | let mut used = 0usize; |
| 254 | for (type_key, name) in known { |
| 255 | used += name.chars().count() + 2; |
| 256 | if used > KNOWN_BUDGET_CHARS { |
| 257 | break; |
| 258 | } |
| 259 | match by_type.iter_mut().find(|(k, _)| *k == type_key.as_str()) { |
| 260 | Some((_, names)) => names.push(name), |
| 261 | None => by_type.push((type_key, vec![name])), |
| 262 | } |
| 263 | } |
| 264 | if by_type.is_empty() { |
| 265 | return String::new(); |
| 266 | } |
| 267 | let lines = by_type |
| 268 | .iter() |
| 269 | .map(|(k, names)| format!(" {k}: {}", names.join(", "))) |
| 270 | .collect::<Vec<_>>() |
| 271 | .join("\n"); |
| 272 | format!( |
| 273 | "\nAlready recorded from earlier parts of this same document:\n{lines}\n\ |
| 274 | \n\ |
| 275 | If something in the text below refers to one of these, write that exact string as \ |
| 276 | the name, and give it that same type — documents abbreviate after first mention \ |
| 277 | (\"星云科技上海研究院\" later becomes \"上海研究院\"), and the shortened form must \ |
| 278 | not become a second entity. If it is a different thing, name it as the text does; \ |
| 279 | do not force it onto this list.\n" |
| 280 | ) |
| 281 | } |
| 282 | |
| 283 | /// 从 LLM 回复中稳健地取出 JSON 块(容忍代码围栏与前后废话)。 |
| 284 | pub fn json_block(raw: &str) -> anyhow::Result<String> { |
| 285 | let text = raw.trim(); |
| 286 | let cleaned = text |
| 287 | .strip_prefix("```json") |
| 288 | .or_else(|| text.strip_prefix("```")) |
| 289 | .map(|s| s.trim_end_matches("```")) |
| 290 | .unwrap_or(text); |
| 291 | let start = cleaned.find('{'); |
| 292 | let end = cleaned.rfind('}'); |
| 293 | match (start, end) { |
| 294 | (Some(s), Some(e)) if e > s => Ok(cleaned[s..=e].to_string()), |
| 295 | _ => anyhow::bail!("No JSON found in LLM reply"), |
| 296 | } |
| 297 | } |
| 298 | |
| 299 | pub fn parse_response(raw: &str) -> anyhow::Result<Extraction> { |
| 300 | let json_str = json_block(raw)?; |
| 301 | let extraction: Extraction = serde_json::from_str(&json_str) |
| 302 | .map_err(|e| anyhow::anyhow!("Failed to parse extraction JSON: {e}"))?; |
| 303 | Ok(extraction) |
| 304 | } |
| 305 | |
| 306 | // --------------------------------------------------------------------------- |
| 307 | // 实体消解裁决(攒批:一次调用裁多对,LLM 只处理 embedding 分不出的灰区) |
| 308 | // --------------------------------------------------------------------------- |
| 309 | |
| 310 | /// 待裁决的一侧:名字 + 类型 + 事实摘要行。 |
| 311 | pub struct AdjudicationSide { |
| 312 | pub name: String, |
| 313 | pub type_label: String, |
| 314 | pub facts: Vec<String>, |
| 315 | } |
| 316 | |
| 317 | pub struct AdjudicationPair { |
| 318 | pub left: AdjudicationSide, |
| 319 | pub right: AdjudicationSide, |
| 320 | } |
| 321 | |
| 322 | #[derive(Debug, Deserialize)] |
| 323 | pub struct AdjudicationVerdict { |
| 324 | pub i: usize, |
| 325 | pub verdict: String, |
| 326 | #[serde(default)] |
| 327 | pub confidence: Option<f32>, |
| 328 | } |
| 329 | |
| 330 | #[derive(Debug, Deserialize)] |
| 331 | struct AdjudicationReply { |
| 332 | #[serde(default)] |
| 333 | verdicts: Vec<AdjudicationVerdict>, |
| 334 | } |
| 335 | |
| 336 | /// 构造攒批裁决提示词。保守偏置:证据不足答 unsure(宁分勿合,合并要证据)。 |
| 337 | pub fn build_adjudication_messages(pairs: &[AdjudicationPair]) -> Vec<ChatMessage> { |
| 338 | let system = "You are an entity-resolution adjudicator for a knowledge graph. \ |
| 339 | For each numbered pair, decide whether the two records refer to the SAME real-world \ |
| 340 | entity or are namesakes (different entities that share a name).\n\ |
| 341 | \n\ |
| 342 | Judge by the facts attached to each record: employer/affiliation, role, time ranges, \ |
| 343 | and connected entities. Identical names alone are NEVER sufficient evidence of sameness. \ |
| 344 | Contradictory affiliations in overlapping time periods indicate different entities \ |
| 345 | (but people do change jobs — non-overlapping periods can belong to one person).\n\ |
| 346 | \n\ |
| 347 | One name containing the other is a different case, and the rule above does not apply \ |
| 348 | to it: \"星云科技上海研究院\" against \"上海研究院\", \"Nebula Technologies Inc.\" \ |
| 349 | against \"Nebula\". Documents drop the qualifier after first mention, so the shorter \ |
| 350 | form is usually the longer one abbreviated — treat the containment as evidence FOR \ |
| 351 | sameness and let the facts settle it. Shared people, parent or location confirm one \ |
| 352 | entity; a different parent or conflicting leadership means the shorter name belongs \ |
| 353 | to something else.\n\ |
| 354 | Abbreviation removes a qualifier from the FRONT. It never adds a noun or a \ |
| 355 | prepositional phrase at the end, so those are different entities however much text \ |
| 356 | they share: \"the operator library for the Canghai Platform\" is not the Canghai \ |
| 357 | Platform, \"Qiming X7 programme\" is not the Qiming X7, and \"沧海平台项目\" is not \ |
| 358 | \"沧海平台\" — a project, a programme, a team or a component is its own record.\n\ |
| 359 | \n\ |
| 360 | Output exactly one JSON object and nothing else:\n\ |
| 361 | {\"verdicts\":[{\"i\":0,\"verdict\":\"same|different|unsure\",\"confidence\":0.9}]}\n\ |
| 362 | \n\ |
| 363 | Rules:\n\ |
| 364 | 1. One verdict per pair, using the pair's number as \"i\".\n\ |
| 365 | 2. confidence in 0~1.\n\ |
| 366 | 3. Be conservative: if the evidence is insufficient to decide, answer \"unsure\" — \ |
| 367 | a wrong merge is far more damaging than leaving two records separate." |
| 368 | .to_string(); |
| 369 | |
| 370 | let mut user = String::new(); |
| 371 | for (i, p) in pairs.iter().enumerate() { |
| 372 | let fmt = |s: &AdjudicationSide| { |
| 373 | let facts = if s.facts.is_empty() { |
| 374 | " (no recorded facts)".to_string() |
| 375 | } else { |
| 376 | s.facts |
| 377 | .iter() |
| 378 | .map(|f| format!(" - {f}")) |
| 379 | .collect::<Vec<_>>() |
| 380 | .join("\n") |
| 381 | }; |
| 382 | format!("\"{}\" ({})\n{}", s.name, s.type_label, facts) |
| 383 | }; |
| 384 | user.push_str(&format!( |
| 385 | "Pair {i}:\nRecord A: {}\nRecord B: {}\n\n", |
| 386 | fmt(&p.left), |
| 387 | fmt(&p.right) |
| 388 | )); |
| 389 | } |
| 390 | |
| 391 | vec![ |
| 392 | ChatMessage { |
| 393 | role: "system".into(), |
| 394 | content: system, |
| 395 | }, |
| 396 | ChatMessage { |
| 397 | role: "user".into(), |
| 398 | content: user, |
| 399 | }, |
| 400 | ] |
| 401 | } |
| 402 | |
| 403 | pub fn parse_adjudication(raw: &str) -> anyhow::Result<Vec<AdjudicationVerdict>> { |
| 404 | let json_str = json_block(raw)?; |
| 405 | let reply: AdjudicationReply = serde_json::from_str(&json_str) |
| 406 | .map_err(|e| anyhow::anyhow!("Failed to parse adjudication JSON: {e}"))?; |
| 407 | Ok(reply.verdicts) |
| 408 | } |
| 409 | |
| 410 | /// 属性值按 datatype 归一。失败返回 None——宁缺勿脏,调用方跳过并记日志。 |
| 411 | /// number 容忍千分位/空格;date 要求 YYYY[-MM[-DD]] 且保留原精度;bool 宽容 yes/no。 |
| 412 | pub fn normalize_attr_value(datatype: &str, raw: &serde_json::Value) -> Option<serde_json::Value> { |
| 413 | match datatype { |
| 414 | "number" => match raw { |
| 415 | serde_json::Value::Number(n) => Some(serde_json::Value::Number(n.clone())), |
| 416 | serde_json::Value::String(s) => { |
| 417 | let cleaned: String = s |
| 418 | .chars() |
| 419 | .filter(|c| !matches!(c, ',' | ' ' | '_')) |
| 420 | .collect(); |
| 421 | cleaned |
| 422 | .parse::<f64>() |
| 423 | .ok() |
| 424 | .filter(|f| f.is_finite()) |
| 425 | .and_then(serde_json::Number::from_f64) |
| 426 | .map(serde_json::Value::Number) |
| 427 | } |
| 428 | _ => None, |
| 429 | }, |
| 430 | "date" => { |
| 431 | let s = raw.as_str()?.trim(); |
| 432 | parse_time(s).map(|_| serde_json::Value::String(s.to_string())) |
| 433 | } |
| 434 | "bool" => match raw { |
| 435 | serde_json::Value::Bool(b) => Some(serde_json::Value::Bool(*b)), |
| 436 | serde_json::Value::String(s) => match s.trim().to_ascii_lowercase().as_str() { |
| 437 | "true" | "yes" | "是" => Some(serde_json::Value::Bool(true)), |
| 438 | "false" | "no" | "否" => Some(serde_json::Value::Bool(false)), |
| 439 | _ => None, |
| 440 | }, |
| 441 | _ => None, |
| 442 | }, |
| 443 | _ => { |
| 444 | let s = match raw { |
| 445 | serde_json::Value::String(s) => s.trim().to_string(), |
| 446 | serde_json::Value::Number(n) => n.to_string(), |
| 447 | _ => return None, |
| 448 | }; |
| 449 | (!s.is_empty()).then(|| serde_json::Value::String(s.chars().take(500).collect())) |
| 450 | } |
| 451 | } |
| 452 | } |
| 453 | |
| 454 | /// 解析时间字符串 → (UTC 时间, 精度)。支持 YYYY / YYYY-MM / YYYY-MM-DD。 |
| 455 | pub fn parse_time(s: &str) -> Option<(DateTime<Utc>, &'static str)> { |
| 456 | let s = s.trim(); |
| 457 | if s.is_empty() || s.eq_ignore_ascii_case("null") { |
| 458 | return None; |
| 459 | } |
| 460 | if let Ok(d) = NaiveDate::parse_from_str(s, "%Y-%m-%d") { |
| 461 | return Some((Utc.from_utc_datetime(&d.and_hms_opt(0, 0, 0)?), "day")); |
| 462 | } |
| 463 | if let Ok(d) = NaiveDate::parse_from_str(&format!("{s}-01"), "%Y-%m-%d") { |
| 464 | return Some((Utc.from_utc_datetime(&d.and_hms_opt(0, 0, 0)?), "month")); |
| 465 | } |
| 466 | if s.len() == 4 { |
| 467 | if let Ok(year) = s.parse::<i32>() { |
| 468 | let d = NaiveDate::from_ymd_opt(year, 1, 1)?; |
| 469 | return Some((Utc.from_utc_datetime(&d.and_hms_opt(0, 0, 0)?), "year")); |
| 470 | } |
| 471 | } |
| 472 | None |
| 473 | } |
| 474 | |
| 475 | #[cfg(test)] |
| 476 | mod prompt_shape_tests { |
| 477 | use super::*; |
| 478 | |
| 479 | fn rel(key: &str, description: &str, signature: &str) -> PromptRelation { |
| 480 | PromptRelation { |
| 481 | key: key.into(), |
| 482 | label: key.replace('_', " "), |
| 483 | description: description.into(), |
| 484 | signature: signature.into(), |
| 485 | } |
| 486 | } |
| 487 | |
| 488 | /// 签名进括号,而且**一律是 key**:中文库的 label 是"人物", |
| 489 | /// 写进提示词等于教模型输出一个不存在的类型。 |
| 490 | #[test] |
| 491 | fn a_signature_takes_the_parenthesis_and_uses_keys() { |
| 492 | let rels = vec![rel("works_at", "受雇于某个组织。", "person → organization")]; |
| 493 | let msgs = build_messages(&[], &rels, &[], None, "a.txt", &[], "text"); |
| 494 | assert!(msgs[0] |
| 495 | .content |
| 496 | .contains("- works_at (person → organization): 受雇于某个组织。")); |
| 497 | } |
| 498 | |
| 499 | /// 多值用 `|`,空的一侧用 `*` —— 都是 key 层面的记号,不是类型名 |
| 500 | #[test] |
| 501 | fn several_classes_join_with_a_pipe_and_an_empty_side_is_a_star() { |
| 502 | let rels = vec![rel("buys_from", "", "employee|team → *")]; |
| 503 | let msgs = build_messages(&[], &rels, &[], None, "a.txt", &[], "text"); |
| 504 | assert!(msgs[0].content.contains("- buys_from (employee|team → *)")); |
| 505 | } |
| 506 | |
| 507 | /// **没有签名的库,提示词一字不变**:记号说明也不出现。 |
| 508 | /// 大多数库不会声明 domain/range,不该为此付每块的 token |
| 509 | #[test] |
| 510 | fn a_base_without_signatures_pays_nothing() { |
| 511 | let rels = vec![rel("works_at", "受雇于某个组织。", "")]; |
| 512 | let msgs = build_messages(&[], &rels, &[], None, "a.txt", &[], "text"); |
| 513 | assert!(msgs[0].content.contains("- works_at: 受雇于某个组织。")); |
| 514 | assert!(!msgs[0].content.contains("type signature")); |
| 515 | assert!(!msgs[0].content.contains('→')); |
| 516 | } |
| 517 | |
| 518 | /// 签名是提示不是闸门。这句话必须在提示词里 —— 少了它, |
| 519 | /// 模型会把签名当硬规则,本体写错时就系统性丢数据(part_of 那种方式) |
| 520 | #[test] |
| 521 | fn the_prompt_says_the_signature_is_a_hint() { |
| 522 | let rels = vec![rel("works_at", "d", "person → organization")]; |
| 523 | let msgs = build_messages(&[], &rels, &[], None, "a.txt", &[], "text"); |
| 524 | assert!(msgs[0].content.contains("hint, not a rule")); |
| 525 | } |
| 526 | |
| 527 | /// 已知实体必须落在 **user** 消息里、紧挨着正文。 |
| 528 | /// |
| 529 | /// 理由是服从性不是缓存:抽象规则打不过挨着它的具体块。清单放进 system 的 |
| 530 | /// 规则区,就会隔着输出格式、十条规则、文件名,离它要管的正文最远。 |
| 531 | #[test] |
| 532 | fn known_entities_stay_out_of_the_system_message() { |
| 533 | // 用一个规则 1 的例子里没有的名字:规则 1 也提"星云科技上海研究院", |
| 534 | // 拿它断言等于测不出清单到底在哪条消息里 |
| 535 | let known = vec![( |
| 536 | "organization".to_string(), |
| 537 | "华瑞集团智能制造研究院".to_string(), |
| 538 | )]; |
| 539 | let msgs = build_messages(&[], &[], &[], None, "a.txt", &known, "text"); |
| 540 | assert_eq!(msgs[0].role, "system"); |
| 541 | assert!(!msgs[0].content.contains("Already recorded")); |
| 542 | assert!(!msgs[0].content.contains("华瑞集团智能制造研究院")); |
| 543 | assert!(msgs[1] |
| 544 | .content |
| 545 | .contains("organization: 华瑞集团智能制造研究院")); |
| 546 | } |
| 547 | |
| 548 | /// 第一块没有"前面",那一段应当完全不出现——成本为零,而不是一段空标题 |
| 549 | #[test] |
| 550 | fn the_first_chunk_carries_no_block() { |
| 551 | let msgs = build_messages(&[], &[], &[], None, "a.txt", &[], "text"); |
| 552 | assert!(!msgs[1].content.contains("Already recorded")); |
| 553 | } |
| 554 | |
| 555 | /// 反向护栏必须在:给了参照物就会有人硬套(`concept` 那次的教训) |
| 556 | #[test] |
| 557 | fn the_block_tells_the_model_not_to_force_a_match() { |
| 558 | let known = vec![("person".to_string(), "陈立".to_string())]; |
| 559 | let msgs = build_messages(&[], &[], &[], None, "a.txt", &known, "text"); |
| 560 | assert!(msgs[1].content.contains("do not force it onto this list")); |
| 561 | } |
| 562 | |
| 563 | /// 有描述就不送 label——中文库的 label 是中文,混进提示词只会让 |
| 564 | /// 标识符与语料语言来回跳,而它相对 key 近乎零信息量。 |
| 565 | #[test] |
| 566 | fn described_types_drop_the_label() { |
| 567 | let types = vec![ |
| 568 | ( |
| 569 | "person".into(), |
| 570 | "人物".into(), |
| 571 | "有名有姓的具体的人。".into(), |
| 572 | ), |
| 573 | ("event".into(), "事件".into(), String::new()), |
| 574 | ]; |
| 575 | let msgs = build_messages(&types, &[], &[], None, "a.txt", &[], "text"); |
| 576 | let prompt = format!("{:?}", msgs); |
| 577 | assert!(prompt.contains("- person: 有名有姓的具体的人。")); |
| 578 | assert!(!prompt.contains("person (人物)")); |
| 579 | // 描述为空时 label 仍是唯一的额外线索,留着 |
| 580 | assert!(prompt.contains("- event (事件)")); |
| 581 | } |
| 582 | } |
| 583 | |
| 584 | #[cfg(test)] |
| 585 | mod tests { |
| 586 | use super::*; |
| 587 | |
| 588 | #[test] |
| 589 | fn parse_time_precisions() { |
| 590 | assert_eq!(parse_time("2024").unwrap().1, "year"); |
| 591 | assert_eq!(parse_time("2024-07").unwrap().1, "month"); |
| 592 | assert_eq!(parse_time("2024-07-15").unwrap().1, "day"); |
| 593 | assert!(parse_time("null").is_none()); |
| 594 | assert!(parse_time("").is_none()); |
| 595 | assert!(parse_time("下个月").is_none()); |
| 596 | } |
| 597 | |
| 598 | #[test] |
| 599 | fn parse_adjudication_reply() { |
| 600 | let raw = "```json\n{\"verdicts\":[{\"i\":0,\"verdict\":\"same\",\"confidence\":0.92},{\"i\":1,\"verdict\":\"unsure\"}]}\n```"; |
| 601 | let v = parse_adjudication(raw).unwrap(); |
| 602 | assert_eq!(v.len(), 2); |
| 603 | assert_eq!(v[0].verdict, "same"); |
| 604 | assert_eq!(v[1].confidence, None); |
| 605 | } |
| 606 | |
| 607 | #[test] |
| 608 | fn normalize_attr_values() { |
| 609 | use serde_json::json; |
| 610 | assert_eq!( |
| 611 | normalize_attr_value("number", &json!("35,000")), |
| 612 | Some(json!(35000.0)) |
| 613 | ); |
| 614 | assert_eq!(normalize_attr_value("number", &json!(42)), Some(json!(42))); |
| 615 | assert_eq!(normalize_attr_value("number", &json!("about ten")), None); |
| 616 | assert_eq!( |
| 617 | normalize_attr_value("date", &json!("2024-07")), |
| 618 | Some(json!("2024-07")) |
| 619 | ); |
| 620 | assert_eq!(normalize_attr_value("date", &json!("下个月")), None); |
| 621 | assert_eq!( |
| 622 | normalize_attr_value("bool", &json!("yes")), |
| 623 | Some(json!(true)) |
| 624 | ); |
| 625 | assert_eq!( |
| 626 | normalize_attr_value("text", &json!(" CTO ")), |
| 627 | Some(json!("CTO")) |
| 628 | ); |
| 629 | assert_eq!(normalize_attr_value("text", &json!([1])), None); |
| 630 | } |
| 631 | |
| 632 | #[test] |
| 633 | fn parse_response_with_fence() { |
| 634 | let raw = "好的,结果如下:\n```json\n{\"entities\":[{\"name\":\"张三\",\"type\":\"person\"}],\"facts\":[]}\n```"; |
| 635 | let e = parse_response(raw).unwrap(); |
| 636 | assert_eq!(e.entities.len(), 1); |
| 637 | assert_eq!(e.entities[0].type_key, "person"); |
| 638 | } |
| 639 | |
| 640 | /// specific_type 在骨架里、也在规则里,且两处都说"永远要填"。 |
| 641 | /// |
| 642 | /// 只写进骨架是不够的:**规则与骨架冲突时骨架赢**(语言那条就栽过一次)。 |
| 643 | /// 这里两边一致,所以要一起钉住。 |
| 644 | #[test] |
| 645 | fn every_entity_is_asked_for_its_own_words() { |
| 646 | let msgs = build_messages(&[], &[], &[], None, "a.txt", &[], "text"); |
| 647 | let sys = &msgs[0].content; |
| 648 | assert!(sys.contains("\"specific_type\":\"what you would call it\"")); |
| 649 | assert!(sys.contains("required on every entity")); |
| 650 | // 关键的一句:不校验。校验它就等于又造了一个词表 |
| 651 | assert!(sys.contains("never checked against the list")); |
| 652 | // 与 type 的关系必须说清楚,否则模型会把粗类抄一遍 |
| 653 | assert!(sys.contains("narrower than")); |
| 654 | } |
| 655 | } |