Builds and manages a knowledge graph from document chunks.
| 142 | return splits, self.vector_store |
| 143 | |
| 144 | class KnowledgeGraph: |
| 145 | """Builds and manages a knowledge graph from document chunks.""" |
| 146 | |
| 147 | def __init__(self, edges_threshold: float = DEFAULT_EDGES_THRESHOLD): |
| 148 | self.graph = nx.Graph() |
| 149 | self.lemmatizer = WordNetLemmatizer() |
| 150 | self.concept_cache = {} |
| 151 | self.nlp = self._load_spacy_model() |
| 152 | self.edges_threshold = edges_threshold |
| 153 | self._all_embeddings = [] |
| 154 | |
| 155 | def _load_spacy_model(self): |
| 156 | """Load spaCy model, downloading if necessary.""" |
| 157 | try: |
| 158 | return spacy.load("en_core_web_sm") |
| 159 | except OSError: |
| 160 | logger.info("[GraphRAG] Downloading spaCy model...") |
| 161 | download("en_core_web_sm") |
| 162 | return spacy.load("en_core_web_sm") |
| 163 | |
| 164 | def build_graph(self, splits: List, llm, embedding_model) -> None: |
| 165 | """Build the knowledge graph from document splits.""" |
| 166 | self._add_nodes(splits) |
| 167 | embeddings = self._create_embeddings(splits, embedding_model) |
| 168 | self._all_embeddings = list(embeddings) |
| 169 | self._extract_concepts(splits, llm) |
| 170 | self._add_edges(embeddings) |
| 171 | |
| 172 | def _add_nodes(self, splits: List) -> None: |
| 173 | """Add nodes to the graph.""" |
| 174 | for i, split in enumerate(splits): |
| 175 | self.graph.add_node(i, content=split.page_content) |
| 176 | |
| 177 | def _create_embeddings(self, splits: List, embedding_model) -> np.ndarray: |
| 178 | """Create embeddings for document splits.""" |
| 179 | texts = [split.page_content for split in splits] |
| 180 | return embedding_model.embed_documents(texts) |
| 181 | |
| 182 | def _extract_concepts(self, splits: List, llm) -> None: |
| 183 | """Extract concepts from all splits using multi-threading.""" |
| 184 | max_workers = int(os.environ.get("GRAPH_RAG_MAX_WORKERS", str(DEFAULT_MAX_WORKERS))) |
| 185 | |
| 186 | with ThreadPoolExecutor(max_workers=max_workers) as executor: |
| 187 | future_to_node = { |
| 188 | executor.submit(self._extract_concepts_and_entities, split.page_content, llm): i |
| 189 | for i, split in enumerate(splits) |
| 190 | } |
| 191 | |
| 192 | for future in tqdm(as_completed(future_to_node), total=len(splits), |
| 193 | desc="Extracting concepts"): |
| 194 | node = future_to_node[future] |
| 195 | try: |
| 196 | concepts = future.result() |
| 197 | self.graph.nodes[node]['concepts'] = concepts |
| 198 | except Exception as e: |
| 199 | logger.warning(f"[GraphRAG] Concept extraction failed for node {node}: {e}") |
| 200 | self.graph.nodes[node]['concepts'] = [] |
| 201 |