Validate an extraction JSON dict against the graphify schema. Returns a list of error strings - empty list means valid.
(data: dict)
| 8 | |
| 9 | |
| 10 | def validate_extraction(data: dict) -> list[str]: |
| 11 | """ |
| 12 | Validate an extraction JSON dict against the graphify schema. |
| 13 | Returns a list of error strings - empty list means valid. |
| 14 | """ |
| 15 | if not isinstance(data, dict): |
| 16 | return ["Extraction must be a JSON object"] |
| 17 | |
| 18 | errors: list[str] = [] |
| 19 | |
| 20 | # Collected during the node pass so the edge pass can reuse it. Only |
| 21 | # hashable ids land here; a non-hashable id (e.g. a list emitted by a |
| 22 | # malformed LLM extraction) is reported as an error rather than crashing |
| 23 | # the validator on set construction. |
| 24 | node_ids: set[str] = set() |
| 25 | |
| 26 | # Nodes |
| 27 | if "nodes" not in data: |
| 28 | errors.append("Missing required key 'nodes'") |
| 29 | elif not isinstance(data["nodes"], list): |
| 30 | errors.append("'nodes' must be a list") |
| 31 | else: |
| 32 | for i, node in enumerate(data["nodes"]): |
| 33 | if not isinstance(node, dict): |
| 34 | errors.append(f"Node {i} must be an object") |
| 35 | continue |
| 36 | for field in REQUIRED_NODE_FIELDS: |
| 37 | if field not in node: |
| 38 | errors.append(f"Node {i} (id={node.get('id', '?')!r}) missing required field '{field}'") |
| 39 | if "id" in node: |
| 40 | try: |
| 41 | hash(node["id"]) |
| 42 | except TypeError: |
| 43 | errors.append( |
| 44 | f"Node {i} has non-hashable id {node['id']!r} - id must be a string" |
| 45 | ) |
| 46 | else: |
| 47 | if isinstance(node["id"], str): |
| 48 | node_ids.add(node["id"]) |
| 49 | else: |
| 50 | errors.append(f"Node {i} id must be a string") |
| 51 | for field in ("label", "source_file"): |
| 52 | if field in node and not isinstance(node[field], str): |
| 53 | errors.append(f"Node {i} {field} must be a string") |
| 54 | if "file_type" in node and ( |
| 55 | not isinstance(node["file_type"], str) or node["file_type"] not in VALID_FILE_TYPES |
| 56 | ): |
| 57 | errors.append( |
| 58 | f"Node {i} (id={node.get('id', '?')!r}) has invalid file_type " |
| 59 | f"'{node['file_type']}' - must be one of {sorted(VALID_FILE_TYPES)}" |
| 60 | ) |
| 61 | |
| 62 | # Edges - accept "links" (NetworkX <= 3.1) as fallback for "edges" |
| 63 | edge_list = data.get("edges") if "edges" in data else data.get("links") |
| 64 | if edge_list is None: |
| 65 | errors.append("Missing required key 'edges'") |
| 66 | elif not isinstance(edge_list, list): |
| 67 | errors.append("'edges' must be a list") |