1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341
| from dataclasses import dataclass from typing import List, Dict, Optional, Tuple from enum import Enum import re
class QuestionType(Enum): ENTITY_QUERY = "entity_query" RELATION_QUERY = "relation_query" MULTI_HOP = "multi_hop" AGGREGATION = "aggregation" COMPARISON = "comparison" OPEN_DOMAIN = "open_domain" HYBRID = "hybrid"
@dataclass class QAResult: answer: str source: str confidence: float query: Optional[str] = None supporting_data: Optional[Dict] = None
class KnowledgeGraphQA: """完整的知识图谱问答系统""" def __init__(self, kg_client, embedding_model, llm): self.kg_client = kg_client self.embedding_model = embedding_model self.llm = llm self.entity_linker = EntityLinker() self.relation_extractor = RelationExtractor() self.semantic_parser = SemanticParser() self.query_executor = QueryExecutor(kg_client) self.answer_generator = AnswerGenerator(llm) def answer(self, question: str) -> QAResult: """主问答流程""" processed = self._preprocess(question) entities = self.entity_linker.link(processed['text']) relations = self.relation_extractor.extract(processed['text']) question_type = self._classify_question(question, entities, relations) if question_type in [QuestionType.ENTITY_QUERY, QuestionType.RELATION_QUERY, QuestionType.MULTI_HOP, QuestionType.AGGREGATION]: return self._handle_structured_query( question, entities, relations, question_type ) elif question_type == QuestionType.COMPARISON: return self._handle_comparison(question, entities, relations) else: return self._handle_open_domain(question) def _preprocess(self, question: str) -> Dict: """问题预处理""" return { 'text': question.strip(), 'original': question, 'tokens': question.split() } def _classify_question( self, question: str, entities: List, relations: List ) -> QuestionType: """问题分类""" question_lower = question.lower() if question.count("的") >= 2: return QuestionType.MULTI_HOP if any(kw in question_lower for kw in ["多少", "几个", "计数", "总数"]): return QuestionType.AGGREGATION if any(kw in question_lower for kw in ["比较", "哪个更大", "哪个小", "差异"]): return QuestionType.COMPARISON if entities and relations: return QuestionType.RELATION_QUERY if entities and not relations: return QuestionType.ENTITY_QUERY return QuestionType.OPEN_DOMAIN def _handle_structured_query( self, question: str, entities: List, relations: List, question_type: QuestionType ) -> QAResult: """处理结构化查询""" query = self.semantic_parser.parse( question, entities, relations, question_type ) if not query: return QAResult( answer="无法解析该问题", source="kg", confidence=0.0 ) results = self.query_executor.execute(query) answer = self.answer_generator.generate_from_kg( question, results, question_type ) return QAResult( answer=answer, source="knowledge_graph", confidence=0.95, query=str(query), supporting_data={"entities": entities, "relations": relations} ) def _handle_comparison( self, question: str, entities: List, relations: List ) -> QAResult: """处理比较类问题""" comparison_entities = self._extract_comparison_entities(question) comparison_data = {} for entity in comparison_entities: query = self._build_simple_query(entity, relations[0] if relations else None) results = self.query_executor.execute(query) if results: comparison_data[entity] = results[0] answer = self.answer_generator.generate_comparison( question, comparison_data ) return QAResult( answer=answer, source="hybrid", confidence=0.85, supporting_data=comparison_data ) def _handle_open_domain(self, question: str) -> QAResult: """处理开放域问题(委托给RAG)""" return QAResult( answer="该问题适合使用检索增强方式回答", source="rag_required", confidence=0.0 )
class EntityLinker: """实体链接""" def __init__(self): self.entity_dict = { "张三": "http://example.org/张三", "李四": "http://example.org/李四", "华为": "http://example.org/华为", "阿里巴巴": "http://example.org/阿里巴巴", } def link(self, text: str) -> List[Dict]: """将文本中的实体mention映射到图谱实体""" entities = [] for mention, uri in self.entity_dict.items(): if mention in text: entities.append({ "mention": mention, "uri": uri, "type": self._infer_type(uri) }) return entities def _infer_type(self, uri: str) -> str: if "公司" in uri or uri in ["华为", "阿里巴巴"]: return "Company" elif "人" in uri or uri in ["张三", "李四"]: return "Person" return "Unknown"
class RelationExtractor: """关系提取""" def __init__(self): self.relation_patterns = { r"(.*)的老板": "boss", r"(.*)的(.*)的老板": "boss", r"(.*)的(.*)": "related_to", r"有多少": "count", } def extract(self, text: str) -> List[str]: relations = [] for pattern, relation in self.relation_patterns.items(): if re.search(pattern, text): relations.append(relation) return list(set(relations))
class SemanticParser: """语义解析器""" def parse( self, question: str, entities: List, relations: List, question_type: QuestionType ) -> Optional[str]: """将问题解析为 SPARQL""" if not entities: return None entity_uri = entities[0]['uri'] entity_name = entities[0]['mention'] if question_type == QuestionType.MULTI_HOP: hops = question.count("的") if hops == 2: return f""" PREFIX ex: <http://example.org/> SELECT ?final WHERE {{ ex:{entity_name} ex:boss ?v1 . ?v1 ex:boss ?final . }} """ elif question_type == QuestionType.RELATION_QUERY: relation = relations[0] if relations else None if relation == "boss": return f""" PREFIX ex: <http://example.org/> SELECT ?boss WHERE {{ ex:{entity_name} ex:boss ?boss . }} """ elif question_type == QuestionType.AGGREGATION: return f""" PREFIX ex: <http://example.org/> SELECT COUNT(?item) WHERE {{ ex:{entity_name} ex:员工 ?item . }} """ return None
class QueryExecutor: """查询执行器""" def __init__(self, kg_client): self.kg_client = kg_client def execute(self, sparql: str) -> List[Dict]: """执行 SPARQL 查询""" try: return self.kg_client.execute(sparql) except Exception as e: print(f"Query execution error: {e}") return []
class AnswerGenerator: """答案生成器""" def __init__(self, llm): self.llm = llm def generate_from_kg( self, question: str, results: List[Dict], question_type: QuestionType ) -> str: """从图谱结果生成答案""" if not results: return "抱歉,未能找到相关信息。" if question_type == QuestionType.ENTITY_QUERY: return f"答案是:{results[0].get('target', '未知')}" elif question_type == QuestionType.MULTI_HOP: return f"经过推理,答案是:{results[0].get('final', '未知')}" elif question_type == QuestionType.AGGREGATION: return f"共有 {results[0].get('result', 0)} 个结果。" return f"找到 {len(results)} 个相关结果" def generate_comparison( self, question: str, data: Dict ) -> str: """生成比较答案""" if not data: return "无法获取比较数据" parts = [] for entity, value in data.items(): parts.append(f"{entity}: {value}") return ";".join(parts)
|