Skip to content

Commit 9f69084

Browse files
authored
Removes | char from type hints to be compatible with Python 3.9 (neo4j#387)
* Removes | char from type hints to be compatible with Python 3.9 * Replaced Union types with Optional * Missed one
1 parent 8e01bad commit 9f69084

File tree

12 files changed

+54
-59
lines changed

12 files changed

+54
-59
lines changed

src/neo4j_graphrag/experimental/components/entity_relation_extractor.py

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -187,7 +187,7 @@ class LLMEntityRelationExtractor(EntityRelationExtractor):
187187
def __init__(
188188
self,
189189
llm: LLMInterface,
190-
prompt_template: ERExtractionTemplate | str = ERExtractionTemplate(),
190+
prompt_template: Union[ERExtractionTemplate, str] = ERExtractionTemplate(),
191191
create_lexical_graph: bool = True,
192192
on_error: OnError = OnError.RAISE,
193193
max_concurrency: int = 5,
@@ -291,7 +291,7 @@ async def run(
291291
chunks: TextChunks,
292292
document_info: Optional[DocumentInfo] = None,
293293
lexical_graph_config: Optional[LexicalGraphConfig] = None,
294-
schema: Union[GraphSchema, None] = None,
294+
schema: Optional[GraphSchema] = None,
295295
examples: str = "",
296296
**kwargs: Any,
297297
) -> Neo4jGraph:

src/neo4j_graphrag/experimental/pipeline/component.py

Lines changed: 4 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -15,12 +15,12 @@
1515
from __future__ import annotations
1616

1717
import inspect
18-
from typing import Any, get_type_hints
18+
from typing import Any, Union, get_type_hints
1919

2020
from pydantic import BaseModel
2121

22-
from neo4j_graphrag.experimental.pipeline.types.context import RunContext
2322
from neo4j_graphrag.experimental.pipeline.exceptions import PipelineDefinitionError
23+
from neo4j_graphrag.experimental.pipeline.types.context import RunContext
2424
from neo4j_graphrag.utils.validation import issubclass_safe
2525

2626

@@ -80,8 +80,8 @@ class Component(metaclass=ComponentMeta):
8080
# these variables are filled by the metaclass
8181
# added here for the type checker
8282
# DO NOT CHANGE
83-
component_inputs: dict[str, dict[str, str | bool]]
84-
component_outputs: dict[str, dict[str, str | bool | type]]
83+
component_inputs: dict[str, dict[str, Union[str, bool]]]
84+
component_outputs: dict[str, dict[str, Union[str, bool, type]]]
8585

8686
async def run(self, *args: Any, **kwargs: Any) -> DataModel:
8787
"""Run the component and return its result.

src/neo4j_graphrag/experimental/pipeline/config/base.py

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -17,7 +17,7 @@
1717
from __future__ import annotations
1818

1919
import logging
20-
from typing import Any
20+
from typing import Any, Optional
2121

2222
from pydantic import BaseModel, PrivateAttr
2323

@@ -58,5 +58,5 @@ def resolve_params(self, params: dict[str, ParamConfig]) -> dict[str, Any]:
5858
for param_name, param in params.items()
5959
}
6060

61-
def parse(self, resolved_data: dict[str, Any] | None = None) -> Any:
61+
def parse(self, resolved_data: Optional[dict[str, Any]] = None) -> Any:
6262
raise NotImplementedError()

src/neo4j_graphrag/experimental/pipeline/config/object_config.py

Lines changed: 8 additions & 17 deletions
Original file line numberDiff line numberDiff line change
@@ -31,15 +31,7 @@
3131

3232
import importlib
3333
import logging
34-
from typing import (
35-
Any,
36-
ClassVar,
37-
Generic,
38-
Optional,
39-
TypeVar,
40-
Union,
41-
cast,
42-
)
34+
from typing import Any, ClassVar, Generic, Optional, TypeVar, Union, cast
4335

4436
import neo4j
4537
from pydantic import (
@@ -58,7 +50,6 @@
5850
from neo4j_graphrag.llm import LLMInterface
5951
from neo4j_graphrag.utils.validation import issubclass_safe
6052

61-
6253
logger = logging.getLogger(__name__)
6354

6455

@@ -73,7 +64,7 @@ class ObjectConfig(AbstractConfig, Generic[T]):
7364
and its constructor parameters.
7465
"""
7566

76-
class_: str | None = Field(default=None, validate_default=True)
67+
class_: Optional[str] = Field(default=None, validate_default=True)
7768
"""Path to class to be instantiated."""
7869
params_: dict[str, ParamConfig] = {}
7970
"""Initialization parameters."""
@@ -128,7 +119,7 @@ def _get_class(cls, class_path: str, optional_module: Optional[str] = None) -> t
128119
raise ValueError(f"Could not find {class_name} in {module_name}")
129120
return cast(type, klass)
130121

131-
def parse(self, resolved_data: dict[str, Any] | None = None) -> T:
122+
def parse(self, resolved_data: Optional[dict[str, Any]] = None) -> T:
132123
"""Import `class_`, resolve `params_` and instantiate object."""
133124
self._global_data = resolved_data or {}
134125
logger.debug(f"OBJECT_CONFIG: parsing {self} using {resolved_data}")
@@ -162,7 +153,7 @@ def validate_class(cls, class_: Any) -> str:
162153
# not used
163154
return "not used"
164155

165-
def parse(self, resolved_data: dict[str, Any] | None = None) -> neo4j.Driver:
156+
def parse(self, resolved_data: Optional[dict[str, Any]] = None) -> neo4j.Driver:
166157
params = self.resolve_params(self.params_)
167158
# we know these params are there because of the required params validator
168159
uri = params.pop("uri")
@@ -185,7 +176,7 @@ class Neo4jDriverType(RootModel): # type: ignore[type-arg]
185176

186177
model_config = ConfigDict(arbitrary_types_allowed=True)
187178

188-
def parse(self, resolved_data: dict[str, Any] | None = None) -> neo4j.Driver:
179+
def parse(self, resolved_data: Optional[dict[str, Any]] = None) -> neo4j.Driver:
189180
if isinstance(self.root, neo4j.Driver):
190181
return self.root
191182
# self.root is a Neo4jDriverConfig object
@@ -212,7 +203,7 @@ class LLMType(RootModel): # type: ignore[type-arg]
212203

213204
model_config = ConfigDict(arbitrary_types_allowed=True)
214205

215-
def parse(self, resolved_data: dict[str, Any] | None = None) -> LLMInterface:
206+
def parse(self, resolved_data: Optional[dict[str, Any]] = None) -> LLMInterface:
216207
if isinstance(self.root, LLMInterface):
217208
return self.root
218209
return self.root.parse(resolved_data)
@@ -238,7 +229,7 @@ class EmbedderType(RootModel): # type: ignore[type-arg]
238229

239230
model_config = ConfigDict(arbitrary_types_allowed=True)
240231

241-
def parse(self, resolved_data: dict[str, Any] | None = None) -> Embedder:
232+
def parse(self, resolved_data: Optional[dict[str, Any]] = None) -> Embedder:
242233
if isinstance(self.root, Embedder):
243234
return self.root
244235
return self.root.parse(resolved_data)
@@ -266,7 +257,7 @@ class ComponentType(RootModel): # type: ignore[type-arg]
266257

267258
model_config = ConfigDict(arbitrary_types_allowed=True)
268259

269-
def parse(self, resolved_data: dict[str, Any] | None = None) -> Component:
260+
def parse(self, resolved_data: Optional[dict[str, Any]] = None) -> Component:
270261
if isinstance(self.root, Component):
271262
return self.root
272263
return self.root.parse(resolved_data)

src/neo4j_graphrag/experimental/pipeline/config/runner.py

Lines changed: 9 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -24,6 +24,7 @@
2424
from typing import (
2525
Annotated,
2626
Any,
27+
Optional,
2728
Union,
2829
)
2930

@@ -37,7 +38,6 @@
3738
from typing_extensions import Self
3839

3940
from neo4j_graphrag.experimental.pipeline import Pipeline
40-
from neo4j_graphrag.utils.file_handler import FileHandler
4141
from neo4j_graphrag.experimental.pipeline.config.pipeline_config import (
4242
AbstractPipelineConfig,
4343
PipelineConfig,
@@ -48,6 +48,7 @@
4848
from neo4j_graphrag.experimental.pipeline.config.types import PipelineType
4949
from neo4j_graphrag.experimental.pipeline.pipeline import PipelineResult
5050
from neo4j_graphrag.experimental.pipeline.types.definitions import PipelineDefinition
51+
from neo4j_graphrag.utils.file_handler import FileHandler
5152
from neo4j_graphrag.utils.logging import prettify
5253

5354
logger = logging.getLogger(__name__)
@@ -70,7 +71,9 @@ class PipelineConfigWrapper(BaseModel):
7071
Annotated[SimpleKGPipelineConfig, Tag(PipelineType.SIMPLE_KG_PIPELINE)],
7172
] = Field(discriminator=Discriminator(_get_discriminator_value))
7273

73-
def parse(self, resolved_data: dict[str, Any] | None = None) -> PipelineDefinition:
74+
def parse(
75+
self, resolved_data: Optional[dict[str, Any]] = None
76+
) -> PipelineDefinition:
7477
logger.debug("PIPELINE_CONFIG: start parsing config...")
7578
return self.config.parse(resolved_data)
7679

@@ -90,7 +93,7 @@ class PipelineRunner:
9093
def __init__(
9194
self,
9295
pipeline_definition: PipelineDefinition,
93-
config: AbstractPipelineConfig | None = None,
96+
config: Optional[AbstractPipelineConfig] = None,
9497
do_cleaning: bool = False,
9598
) -> None:
9699
self.config = config
@@ -100,7 +103,9 @@ def __init__(
100103

101104
@classmethod
102105
def from_config(
103-
cls, config: AbstractPipelineConfig | dict[str, Any], do_cleaning: bool = False
106+
cls,
107+
config: Union[AbstractPipelineConfig, dict[str, Any]],
108+
do_cleaning: bool = False,
104109
) -> Self:
105110
wrapper = PipelineConfigWrapper.model_validate({"config": config})
106111
logger.debug(

src/neo4j_graphrag/experimental/pipeline/orchestrator.py

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -19,15 +19,15 @@
1919
import uuid
2020
import warnings
2121
from functools import partial
22-
from typing import TYPE_CHECKING, Any, AsyncGenerator
22+
from typing import TYPE_CHECKING, Any, AsyncGenerator, Optional
2323

24-
from neo4j_graphrag.experimental.pipeline.types.context import RunContext
2524
from neo4j_graphrag.experimental.pipeline.exceptions import (
2625
PipelineDefinitionError,
2726
PipelineMissingDependencyError,
2827
PipelineStatusUpdateError,
2928
)
3029
from neo4j_graphrag.experimental.pipeline.notification import EventNotifier
30+
from neo4j_graphrag.experimental.pipeline.types.context import RunContext
3131
from neo4j_graphrag.experimental.pipeline.types.orchestration import (
3232
RunResult,
3333
RunStatus,
@@ -235,7 +235,7 @@ async def get_component_inputs(
235235
return component_inputs
236236

237237
async def add_result_for_component(
238-
self, name: str, result: dict[str, Any] | None, is_final: bool = False
238+
self, name: str, result: Optional[dict[str, Any]], is_final: bool = False
239239
) -> None:
240240
"""This is where we save the results in the result store and, optionally,
241241
in the final result store.

src/neo4j_graphrag/experimental/pipeline/pipeline.py

Lines changed: 10 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -14,12 +14,12 @@
1414
# limitations under the License.
1515
from __future__ import annotations
1616

17+
import asyncio
1718
import logging
1819
import warnings
1920
from collections import defaultdict
2021
from timeit import default_timer
21-
from typing import Any, Optional, AsyncGenerator
22-
import asyncio
22+
from typing import Any, AsyncGenerator, Optional
2323

2424
from neo4j_graphrag.utils.logging import prettify
2525

@@ -36,27 +36,26 @@
3636
from neo4j_graphrag.experimental.pipeline.exceptions import (
3737
PipelineDefinitionError,
3838
)
39+
from neo4j_graphrag.experimental.pipeline.notification import (
40+
Event,
41+
EventCallbackProtocol,
42+
EventType,
43+
PipelineEvent,
44+
)
3945
from neo4j_graphrag.experimental.pipeline.orchestrator import Orchestrator
4046
from neo4j_graphrag.experimental.pipeline.pipeline_graph import (
4147
PipelineEdge,
4248
PipelineGraph,
4349
PipelineNode,
4450
)
4551
from neo4j_graphrag.experimental.pipeline.stores import InMemoryStore, ResultStore
52+
from neo4j_graphrag.experimental.pipeline.types.context import RunContext
4653
from neo4j_graphrag.experimental.pipeline.types.definitions import (
4754
ComponentDefinition,
4855
ConnectionDefinition,
4956
PipelineDefinition,
5057
)
5158
from neo4j_graphrag.experimental.pipeline.types.orchestration import RunResult
52-
from neo4j_graphrag.experimental.pipeline.types.context import RunContext
53-
from neo4j_graphrag.experimental.pipeline.notification import (
54-
EventCallbackProtocol,
55-
Event,
56-
PipelineEvent,
57-
EventType,
58-
)
59-
6059

6160
logger = logging.getLogger(__name__)
6261

@@ -79,7 +78,7 @@ def __init__(self, name: str, component: Component):
7978

8079
async def execute(
8180
self, context: RunContext, inputs: dict[str, Any]
82-
) -> RunResult | None:
81+
) -> Optional[RunResult]:
8382
"""Execute the task
8483
8584
Returns:

src/neo4j_graphrag/experimental/pipeline/pipeline_graph.py

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -18,7 +18,7 @@
1818

1919
from __future__ import annotations
2020

21-
from typing import Any, Generic, Optional, TypeVar
21+
from typing import Any, Generic, Optional, TypeVar, Union
2222

2323

2424
class PipelineNode:
@@ -124,7 +124,7 @@ def previous_edges(self, node: str) -> list[GenericEdgeType]:
124124
res.append(edge)
125125
return res
126126

127-
def __contains__(self, node: GenericNodeType | str) -> bool:
127+
def __contains__(self, node: Union[GenericNodeType, str]) -> bool:
128128
if isinstance(node, str):
129129
return node in self._nodes
130130
return node.name in self._nodes

src/neo4j_graphrag/generation/graphrag.py

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -88,8 +88,8 @@ def search(
8888
message_history: Optional[Union[List[LLMMessage], MessageHistory]] = None,
8989
examples: str = "",
9090
retriever_config: Optional[dict[str, Any]] = None,
91-
return_context: bool | None = None,
92-
response_fallback: str | None = None,
91+
return_context: Optional[bool] = None,
92+
response_fallback: Optional[str] = None,
9393
) -> RagResultModel:
9494
"""
9595
.. warning::

src/neo4j_graphrag/generation/types.py

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -14,7 +14,7 @@
1414
# limitations under the License.
1515
from __future__ import annotations
1616

17-
from typing import Any, Union
17+
from typing import Any, Optional
1818

1919
from pydantic import BaseModel, ConfigDict, field_validator
2020

@@ -43,11 +43,11 @@ class RagSearchModel(BaseModel):
4343
examples: str = ""
4444
retriever_config: dict[str, Any] = {}
4545
return_context: bool = False
46-
response_fallback: str | None = None
46+
response_fallback: Optional[str] = None
4747

4848

4949
class RagResultModel(BaseModel):
5050
answer: str
51-
retriever_result: Union[RetrieverResult, None] = None
51+
retriever_result: Optional[RetrieverResult] = None
5252

5353
model_config = ConfigDict(arbitrary_types_allowed=True)

0 commit comments

Comments
 (0)