|
| 1 | +import re |
| 2 | +from collections import defaultdict |
| 3 | +from dataclasses import dataclass |
| 4 | +from typing import Dict, List, Tuple |
| 5 | + |
| 6 | +from graphgen.bases import BaseGraphStorage, BaseKGBuilder, BaseLLMClient, Chunk |
| 7 | +from graphgen.templates import KG_EXTRACTION_PROMPT |
| 8 | +from graphgen.utils import ( |
| 9 | + detect_if_chinese, |
| 10 | + handle_single_entity_extraction, |
| 11 | + handle_single_relationship_extraction, |
| 12 | + logger, |
| 13 | + pack_history_conversations, |
| 14 | + split_string_by_multi_markers, |
| 15 | +) |
| 16 | + |
| 17 | + |
| 18 | +@dataclass |
| 19 | +class LightRAGKGBuilder(BaseKGBuilder): |
| 20 | + llm_client: BaseLLMClient = None |
| 21 | + max_loop: int = 3 |
| 22 | + |
| 23 | + async def extract( |
| 24 | + self, chunk: Chunk |
| 25 | + ) -> Tuple[Dict[str, List[dict]], Dict[Tuple[str, str], List[dict]]]: |
| 26 | + """ |
| 27 | + Extract entities and relationships from a single chunk using the LLM client. |
| 28 | + :param chunk |
| 29 | + :return: (nodes_data, edges_data) |
| 30 | + """ |
| 31 | + chunk_id = chunk.id |
| 32 | + content = chunk.content |
| 33 | + |
| 34 | + # step 1: language_detection |
| 35 | + language = "Chinese" if detect_if_chinese(content) else "English" |
| 36 | + KG_EXTRACTION_PROMPT["FORMAT"]["language"] = language |
| 37 | + |
| 38 | + hint_prompt = KG_EXTRACTION_PROMPT[language]["TEMPLATE"].format( |
| 39 | + **KG_EXTRACTION_PROMPT["FORMAT"], input_text=content |
| 40 | + ) |
| 41 | + |
| 42 | + # step 2: initial glean |
| 43 | + final_result = await self.llm_client.generate_answer(hint_prompt) |
| 44 | + logger.debug("First extraction result: %s", final_result) |
| 45 | + |
| 46 | + # step3: iterative refinement |
| 47 | + history = pack_history_conversations(hint_prompt, final_result) |
| 48 | + for loop_idx in range(self.max_loop): |
| 49 | + if_loop_result = await self.llm_client.generate_answer( |
| 50 | + text=KG_EXTRACTION_PROMPT[language]["IF_LOOP"], history=history |
| 51 | + ) |
| 52 | + if_loop_result = if_loop_result.strip().strip('"').strip("'").lower() |
| 53 | + if if_loop_result != "yes": |
| 54 | + break |
| 55 | + |
| 56 | + glean_result = await self.llm_client.generate_answer( |
| 57 | + text=KG_EXTRACTION_PROMPT[language]["CONTINUE"], history=history |
| 58 | + ) |
| 59 | + logger.debug("Loop %s glean: %s", loop_idx + 1, glean_result) |
| 60 | + |
| 61 | + history += pack_history_conversations( |
| 62 | + KG_EXTRACTION_PROMPT[language]["CONTINUE"], glean_result |
| 63 | + ) |
| 64 | + final_result += glean_result |
| 65 | + |
| 66 | + # step 4: parse the final result |
| 67 | + records = split_string_by_multi_markers( |
| 68 | + final_result, |
| 69 | + [ |
| 70 | + KG_EXTRACTION_PROMPT["FORMAT"]["record_delimiter"], |
| 71 | + KG_EXTRACTION_PROMPT["FORMAT"]["completion_delimiter"], |
| 72 | + ], |
| 73 | + ) |
| 74 | + |
| 75 | + nodes = defaultdict(list) |
| 76 | + edges = defaultdict(list) |
| 77 | + |
| 78 | + for record in records: |
| 79 | + match = re.search(r"\((.*)\)", record) |
| 80 | + if not match: |
| 81 | + continue |
| 82 | + inner = match.group(1) |
| 83 | + |
| 84 | + attributes = split_string_by_multi_markers( |
| 85 | + inner, [KG_EXTRACTION_PROMPT["FORMAT"]["tuple_delimiter"]] |
| 86 | + ) |
| 87 | + |
| 88 | + entity = await handle_single_entity_extraction(attributes, chunk_id) |
| 89 | + if entity is not None: |
| 90 | + nodes[entity["entity_name"]].append(entity) |
| 91 | + continue |
| 92 | + |
| 93 | + relation = await handle_single_relationship_extraction(attributes, chunk_id) |
| 94 | + if relation is not None: |
| 95 | + key = (relation["src_id"], relation["tgt_id"]) |
| 96 | + edges[key].append(relation) |
| 97 | + |
| 98 | + return dict(nodes), dict(edges) |
| 99 | + |
| 100 | + async def merge_nodes( |
| 101 | + self, |
| 102 | + entity_name: str, |
| 103 | + node_data: Dict[str, List[dict]], |
| 104 | + kg_instance: BaseGraphStorage, |
| 105 | + ) -> BaseGraphStorage: |
| 106 | + pass |
| 107 | + |
| 108 | + async def merge_edges( |
| 109 | + self, |
| 110 | + edges_data: Dict[Tuple[str, str], List[dict]], |
| 111 | + kg_instance: BaseGraphStorage, |
| 112 | + ) -> BaseGraphStorage: |
| 113 | + pass |
| 114 | + |
| 115 | + # async def process_single_node(entity_name: str, node_data: list[dict]): |
| 116 | + # entity_types = [] |
| 117 | + # source_ids = [] |
| 118 | + # descriptions = [] |
| 119 | + # |
| 120 | + # node = await kg_instance.get_node(entity_name) |
| 121 | + # if node is not None: |
| 122 | + # entity_types.append(node["entity_type"]) |
| 123 | + # source_ids.extend( |
| 124 | + # split_string_by_multi_markers(node["source_id"], ["<SEP>"]) |
| 125 | + # ) |
| 126 | + # descriptions.append(node["description"]) |
| 127 | + # |
| 128 | + # # 统计当前节点数据和已有节点数据的entity_type出现次数,取出现次数最多的entity_type |
| 129 | + # entity_type = sorted( |
| 130 | + # Counter([dp["entity_type"] for dp in node_data] + entity_types).items(), |
| 131 | + # key=lambda x: x[1], |
| 132 | + # reverse=True, |
| 133 | + # )[0][0] |
| 134 | + # |
| 135 | + # description = "<SEP>".join( |
| 136 | + # sorted(set([dp["description"] for dp in node_data] + descriptions)) |
| 137 | + # ) |
| 138 | + # description = await _handle_kg_summary( |
| 139 | + # entity_name, description, llm_client, tokenizer_instance |
| 140 | + # ) |
| 141 | + # |
| 142 | + # source_id = "<SEP>".join( |
| 143 | + # set([dp["source_id"] for dp in node_data] + source_ids) |
| 144 | + # ) |
| 145 | + # |
| 146 | + # node_data = { |
| 147 | + # "entity_type": entity_type, |
| 148 | + # "description": description, |
| 149 | + # "source_id": source_id, |
| 150 | + # } |
| 151 | + # await kg_instance.upsert_node(entity_name, node_data=node_data) |
| 152 | + # node_data["entity_name"] = entity_name |
| 153 | + # return node_data |
0 commit comments