"""Graph construction with LLM extraction, concept clustering and optional Neo4j sync.""" from __future__ import annotations import hashlib import json import os import re from pathlib import Path from typing import Any import networkx as nx from ingest import load_documents from llm import llm_call RELATIONS = { "is_a", "part_of", "uses", "teaches", "requires", "depends_on", "implements", "applies_to", "subfield_of", "contains", "defined_by", "related_to", } def _normalise(value: str) -> str: return " ".join(value.strip().split()).title() def _json_response(text: str) -> dict[str, Any]: cleaned = re.sub(r"^```(?:json)?\s*|```\s*$", "", text.strip(), flags=re.MULTILINE).strip() decoder = json.JSONDecoder() for match in re.finditer(r"\{", cleaned): try: value, _ = decoder.raw_decode(cleaned, match.start()) except json.JSONDecodeError: continue if isinstance(value, dict) and ("entities" in value or "relations" in value): return value raise ValueError("The LLM did not return a JSON object") def extract_entities_and_relations(text: str) -> dict[str, list[dict[str, str]]]: prompt = f"""Extract a high-quality educational knowledge graph from this text. Return only JSON with entities and relations. Resolve aliases to canonical names, include subjects, skills, named entities and prerequisites, and avoid generic words. Allowed relations: {sorted(RELATIONS)} Schema: {{"entities":[{{"name":"...","type":"concept"}}], "relations":[{{"source":"...","target":"...","relation":"requires"}}]}} Text: {text[:8000]}""" data = _json_response(llm_call([{"role": "user", "content": prompt}])) entities: dict[str, dict[str, str]] = {} for item in data.get("entities", []): if isinstance(item, dict) and item.get("name"): name = _normalise(str(item["name"])) entities[name] = {"name": name, "type": str(item.get("type", "concept"))} relations = [] for item in data.get("relations", []): if not isinstance(item, dict): continue source, target = _normalise(str(item.get("source", ""))), _normalise(str(item.get("target", ""))) relation = str(item.get("relation", "related_to")).lower().strip() if source != target and source in entities and target in entities and relation in RELATIONS: relations.append({"source": source, "target": target, "relation": relation}) connected = {x for r in relations for x in (r["source"], r["target"])} return {"entities": [e for name, e in entities.items() if name in connected], "relations": relations} def get_cached_extraction(chunk: str, cache_dir: str = "cache") -> dict[str, list[dict[str, str]]]: Path(cache_dir).mkdir(exist_ok=True) path = Path(cache_dir) / f"{hashlib.sha256(chunk.encode()).hexdigest()}.json" if path.exists(): return json.loads(path.read_text(encoding="utf-8")) result = extract_entities_and_relations(chunk) path.write_text(json.dumps(result, ensure_ascii=False, indent=2), encoding="utf-8") return result def chunk_text(text: str, chunk_size: int = 8000, overlap: int = 300) -> list[str]: text = text.replace("\r", " ") chunks, current = [], "" for paragraph in text.split("\n"): paragraph = paragraph.strip() if len(paragraph) < 40: continue if len(current) + len(paragraph) <= chunk_size: current += paragraph + "\n" else: chunks.append(current) current = current[-overlap:] + "\n" + paragraph + "\n" if current: chunks.append(current) return chunks def cluster_concepts(graph: nx.Graph, resolution: float = 1.0) -> list[set[str]]: """Cluster named entities using graph community structure and label nodes.""" undirected = graph.to_undirected() if not undirected.nodes: return [] try: communities = list(nx.community.louvain_communities(undirected, resolution=resolution, seed=42)) except (AttributeError, nx.NetworkXError): communities = list(nx.community.greedy_modularity_communities(undirected)) for index, community in enumerate(communities, start=1): for node in community: graph.nodes[node]["cluster"] = f"concept_{index}" return communities def build_graph_from_documents(folder: str = "documents") -> nx.DiGraph: graph = nx.DiGraph() for document in load_documents(folder): for chunk in chunk_text(document["content"]): extraction = get_cached_extraction(chunk) for entity in extraction["entities"]: graph.add_node(entity["name"], type=entity["type"], source_doc=document["filename"]) for relation in extraction["relations"]: graph.add_edge(relation["source"], relation["target"], relation=relation["relation"], source_doc=document["filename"]) cluster_concepts(graph) return graph def save_graph(graph: nx.DiGraph, path: str = "graph/kg.graphml") -> None: Path(path).parent.mkdir(parents=True, exist_ok=True) nx.write_graphml(graph, path) def load_graph(path: str = "graph/kg.graphml") -> nx.DiGraph: return nx.read_graphml(path) def sync_graph_to_neo4j(graph: nx.DiGraph) -> int: """Sync to Neo4j when NEO4J_URI/USER/PASSWORD are configured; return edge count.""" from neo4j import GraphDatabase uri = os.environ["NEO4J_URI"] user = os.environ.get("NEO4J_USER", "neo4j") password = os.environ["NEO4J_PASSWORD"] database = os.environ.get("NEO4J_DATABASE", "neo4j") driver = GraphDatabase.driver(uri, auth=(user, password)) try: with driver.session(database=database) as session: for node, data in graph.nodes(data=True): session.run("MERGE (n:Concept {name:$name}) SET n.type=$type, n.cluster=$cluster", name=node, type=data.get("type", "concept"), cluster=data.get("cluster")) for source, target, data in graph.edges(data=True): session.run("""MATCH (a:Concept {name:$source}), (b:Concept {name:$target}) MERGE (a)-[r:RELATED {relation:$relation}]->(b) SET r.source_doc=$source_doc""", source=source, target=target, relation=data.get("relation", "related_to"), source_doc=data.get("source_doc")) finally: driver.close() return graph.number_of_edges()