MCPcopy Create free account
hub / github.com/KnowledgeXLab/LeanRAG / Triple

Class Triple

CommonKG/triple.py:10–140  ·  view source on GitHub ↗

Source from the content-addressed store, hash-verified

8
9
10class Triple:
11 def __init__(self, head, relation, tail):
12 self.head = head.strip().replace("<", "").replace(">", "")
13 self.relation = relation.strip().replace("<", "").replace(">", "")
14 self.tail = tail.strip().replace("<", "").replace(">", "")
15
16 # 可以使用str(Triple)方法来返回三元组,等同于__str__
17 def __str__(self):
18 return f"<{self.head}>\t<{self.relation}>\t<{self.tail}>"
19 @classmethod
20 def triple_json_format(self, triple, doc_name="", source_id=""):
21 return {"triple": triple, "doc_name": doc_name, "source_id": source_id}
22
23 @classmethod
24 def get_example(self, entity, ref_kg_path):
25 open_kg = []
26 if entity:
27 with open(ref_kg_path, "r", encoding="utf-8") as kgfile:
28 for line in kgfile:
29 try:
30 triple = Triple(*line.strip().split("\t"))
31 if triple.head.lower() == entity.lower():
32 open_kg.append(str(triple))
33 except:
34 pass
35
36 if open_kg != []:
37 logger.info(f"Load open kg triple for {entity} nums: {len(open_kg)}.")
38 else:
39 open_kg = [
40 "<Bacterial sulfate>\t<is a type of>\t<sulfur compound\n",
41 "<Diabetes>\t<first line treatment>\t<Metformin>\n",
42 "<Insulin>\t<drug type>\t<Long-acting analog>\n",
43 ]
44 # logger.info(f"use default triples.")
45 return open_kg
46
47 ## 对llm生成的三元组进行处理,并给出分析结果
48 @classmethod
49 def get_triple(self, entities, res, head_mode="acc"):
50 """从大模型的回答中获得三元组,并分析异常情况"""
51
52 # 保存LLM输出得到的所有三元组,形式为"xx | xx | xx"
53 output_triples = set()
54 error_triples = set()
55 try:
56 for item in res.split("\n"):
57 item = re.sub(r"^\d+\.\s*", "", item, flags=re.MULTILINE)
58 if len(item) > 0:
59 subs = item.split("|")
60 # error format tripple,格式错误, 不符合"xx | xx | xx"
61 if len(subs) < 3 or len(subs) > 3:
62 continue
63 # 获取head, ralation, tail, 创建三元组实例,并添加到output_triples
64 output_triples.add(Triple(*subs))
65 except Exception as e: # 捕获所有异常
66 print("llm输出内容无法接解析成三元组:", e) # 输出错误信息:
67

Callers 2

get_exampleMethod · 0.85
get_tripleMethod · 0.85

Calls

no outgoing calls

Tested by

no test coverage detected