|
| 1 | +# Copyright (c) "Neo4j" |
| 2 | +# Neo4j Sweden AB [https://neo4j.com] |
| 3 | +# # |
| 4 | +# Licensed under the Apache License, Version 2.0 (the "License"); |
| 5 | +# you may not use this file except in compliance with the License. |
| 6 | +# You may obtain a copy of the License at |
| 7 | +# # |
| 8 | +# https://www.apache.org/licenses/LICENSE-2.0 |
| 9 | +# # |
| 10 | +# Unless required by applicable law or agreed to in writing, software |
| 11 | +# distributed under the License is distributed on an "AS IS" BASIS, |
| 12 | +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
| 13 | +# See the License for the specific language governing permissions and |
| 14 | +# limitations under the License. |
| 15 | +# Copyright (c) "Neo4j" |
| 16 | +# Neo4j Sweden AB [https://neo4j.com] |
| 17 | +# # |
| 18 | +# Licensed under the Apache License, Version 2.0 (the "License"); |
| 19 | +# you may not use this file except in compliance with the License. |
| 20 | +# You may obtain a copy of the License at |
| 21 | +# # |
| 22 | +# https://www.apache.org/licenses/LICENSE-2.0 |
| 23 | +# # |
| 24 | +# Unless required by applicable law or agreed to in writing, software |
| 25 | +# distributed under the License is distributed on an "AS IS" BASIS, |
| 26 | +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
| 27 | +# See the License for the specific language governing permissions and |
| 28 | +# limitations under the License. |
| 29 | +from __future__ import annotations |
| 30 | + |
| 31 | +from typing import Any, Dict, List, Literal, Tuple |
| 32 | + |
| 33 | +from neo4j_genai.exceptions import SchemaValidationError |
| 34 | +from neo4j_genai.pipeline import Component, DataModel |
| 35 | +from pydantic import BaseModel, ValidationError, model_validator, validate_call |
| 36 | + |
| 37 | + |
| 38 | +class SchemaProperty(BaseModel): |
| 39 | + name: str |
| 40 | + # See https://neo4j.com/docs/cypher-manual/current/values-and-types/property-structural-constructed/#property-types |
| 41 | + type: Literal[ |
| 42 | + "BOOLEAN", |
| 43 | + "DATE", |
| 44 | + "DURATION", |
| 45 | + "FLOAT", |
| 46 | + "INTEGER", |
| 47 | + "LIST", |
| 48 | + "LOCAL_DATETIME", |
| 49 | + "LOCAL_TIME", |
| 50 | + "POINT", |
| 51 | + "STRING", |
| 52 | + "ZONED_DATETIME", |
| 53 | + "ZONED_TIME", |
| 54 | + ] |
| 55 | + description: str = "" |
| 56 | + |
| 57 | + |
| 58 | +class SchemaEntity(BaseModel): |
| 59 | + """ |
| 60 | + Represents a possible node in the graph. |
| 61 | + """ |
| 62 | + |
| 63 | + label: str |
| 64 | + description: str = "" |
| 65 | + properties: List[SchemaProperty] = [] |
| 66 | + |
| 67 | + |
| 68 | +class SchemaRelation(BaseModel): |
| 69 | + """ |
| 70 | + Represents a possible relationship between nodes in the graph. |
| 71 | + """ |
| 72 | + |
| 73 | + label: str |
| 74 | + description: str = "" |
| 75 | + properties: List[SchemaProperty] = [] |
| 76 | + |
| 77 | + |
| 78 | +class SchemaConfig(DataModel): |
| 79 | + """ |
| 80 | + Represents possible relationships between entities and relations in the graph. |
| 81 | + """ |
| 82 | + |
| 83 | + entities: Dict[str, Dict[str, Any]] |
| 84 | + relations: Dict[str, Dict[str, Any]] |
| 85 | + potential_schema: List[Tuple[str, str, str]] |
| 86 | + |
| 87 | + @model_validator(mode="before") |
| 88 | + def check_schema(cls, data: Dict[str, Any]) -> Dict[str, Any]: |
| 89 | + entities = data.get("entities", {}).keys() |
| 90 | + relations = data.get("relations", {}).keys() |
| 91 | + potential_schema = data.get("potential_schema", []) |
| 92 | + |
| 93 | + for entity1, relation, entity2 in potential_schema: |
| 94 | + if entity1 not in entities: |
| 95 | + raise SchemaValidationError( |
| 96 | + f"Entity '{entity1}' is not defined in the provided entities." |
| 97 | + ) |
| 98 | + if relation not in relations: |
| 99 | + raise SchemaValidationError( |
| 100 | + f"Relation '{relation}' is not defined in the provided relations." |
| 101 | + ) |
| 102 | + if entity2 not in entities: |
| 103 | + raise SchemaValidationError( |
| 104 | + f"Entity '{entity1}' is not defined in the provided entities." |
| 105 | + ) |
| 106 | + |
| 107 | + return data |
| 108 | + |
| 109 | + |
| 110 | +class SchemaBuilder(Component): |
| 111 | + """ |
| 112 | + A builder class for constructing SchemaConfig objects from given entities, |
| 113 | + relations, and their interrelationships defined in a potential schema. |
| 114 | + """ |
| 115 | + |
| 116 | + @staticmethod |
| 117 | + def create_schema_model( |
| 118 | + entities: List[SchemaEntity], |
| 119 | + relations: List[SchemaRelation], |
| 120 | + potential_schema: List[Tuple[str, str, str]], |
| 121 | + ) -> SchemaConfig: |
| 122 | + """ |
| 123 | + Creates a SchemaConfig object from Lists of Entity and Relation objects |
| 124 | + and a Dictionary defining potential relationships. |
| 125 | +
|
| 126 | + Args: |
| 127 | + entities (List[SchemaEntity]): List of Entity objects. |
| 128 | + relations (List[SchemaRelation]): List of Relation objects. |
| 129 | + potential_schema (Dict[str, List[str]]): Dictionary mapping entity names to Lists of relation names. |
| 130 | +
|
| 131 | + Returns: |
| 132 | + SchemaConfig: A configured schema object. |
| 133 | + """ |
| 134 | + entity_dict = {entity.label: entity.dict() for entity in entities} |
| 135 | + relation_dict = {relation.label: relation.dict() for relation in relations} |
| 136 | + |
| 137 | + try: |
| 138 | + return SchemaConfig( |
| 139 | + entities=entity_dict, |
| 140 | + relations=relation_dict, |
| 141 | + potential_schema=potential_schema, |
| 142 | + ) |
| 143 | + except (ValidationError, SchemaValidationError) as e: |
| 144 | + raise SchemaValidationError(e) |
| 145 | + |
| 146 | + @validate_call |
| 147 | + async def run( |
| 148 | + self, |
| 149 | + entities: List[SchemaEntity], |
| 150 | + relations: List[SchemaRelation], |
| 151 | + potential_schema: List[Tuple[str, str, str]], |
| 152 | + ) -> SchemaConfig: |
| 153 | + """ |
| 154 | + Asynchronously constructs and returns a SchemaConfig object. |
| 155 | +
|
| 156 | + Args: |
| 157 | + entities (List[SchemaEntity]): List of Entity objects. |
| 158 | + relations (List[SchemaRelation]): List of Relation objects. |
| 159 | + potential_schema (Dict[str, List[str]]): Dictionary mapping entity names to Lists of relation names. |
| 160 | +
|
| 161 | + Returns: |
| 162 | + SchemaConfig: A configured schema object, constructed asynchronously. |
| 163 | + """ |
| 164 | + return self.create_schema_model(entities, relations, potential_schema) |
0 commit comments