camel-ai 0.1.1__py3-none-any.whl → 0.1.3__py3-none-any.whl
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Potentially problematic release.
This version of camel-ai might be problematic. Click here for more details.
- camel/__init__.py +1 -11
- camel/agents/__init__.py +5 -5
- camel/agents/chat_agent.py +124 -63
- camel/agents/critic_agent.py +28 -17
- camel/agents/deductive_reasoner_agent.py +235 -0
- camel/agents/embodied_agent.py +92 -40
- camel/agents/role_assignment_agent.py +27 -17
- camel/agents/task_agent.py +60 -34
- camel/agents/tool_agents/base.py +0 -1
- camel/agents/tool_agents/hugging_face_tool_agent.py +7 -4
- camel/configs.py +119 -7
- camel/embeddings/__init__.py +2 -0
- camel/embeddings/base.py +3 -2
- camel/embeddings/openai_embedding.py +3 -3
- camel/embeddings/sentence_transformers_embeddings.py +65 -0
- camel/functions/__init__.py +13 -3
- camel/functions/google_maps_function.py +335 -0
- camel/functions/math_functions.py +7 -7
- camel/functions/openai_function.py +344 -42
- camel/functions/search_functions.py +100 -35
- camel/functions/twitter_function.py +484 -0
- camel/functions/weather_functions.py +36 -23
- camel/generators.py +65 -46
- camel/human.py +17 -11
- camel/interpreters/__init__.py +25 -0
- camel/interpreters/base.py +49 -0
- camel/{utils/python_interpreter.py → interpreters/internal_python_interpreter.py} +129 -48
- camel/interpreters/interpreter_error.py +19 -0
- camel/interpreters/subprocess_interpreter.py +190 -0
- camel/loaders/__init__.py +22 -0
- camel/{functions/base_io_functions.py → loaders/base_io.py} +38 -35
- camel/{functions/unstructured_io_fuctions.py → loaders/unstructured_io.py} +199 -110
- camel/memories/__init__.py +17 -7
- camel/memories/agent_memories.py +156 -0
- camel/memories/base.py +97 -32
- camel/memories/blocks/__init__.py +21 -0
- camel/memories/{chat_history_memory.py → blocks/chat_history_block.py} +34 -34
- camel/memories/blocks/vectordb_block.py +101 -0
- camel/memories/context_creators/__init__.py +3 -2
- camel/memories/context_creators/score_based.py +32 -20
- camel/memories/records.py +6 -5
- camel/messages/__init__.py +2 -2
- camel/messages/base.py +99 -16
- camel/messages/func_message.py +7 -4
- camel/models/__init__.py +4 -2
- camel/models/anthropic_model.py +132 -0
- camel/models/base_model.py +3 -2
- camel/models/model_factory.py +10 -8
- camel/models/open_source_model.py +25 -13
- camel/models/openai_model.py +9 -10
- camel/models/stub_model.py +6 -5
- camel/prompts/__init__.py +7 -5
- camel/prompts/ai_society.py +21 -14
- camel/prompts/base.py +54 -47
- camel/prompts/code.py +22 -14
- camel/prompts/evaluation.py +8 -5
- camel/prompts/misalignment.py +26 -19
- camel/prompts/object_recognition.py +35 -0
- camel/prompts/prompt_templates.py +14 -8
- camel/prompts/role_description_prompt_template.py +16 -10
- camel/prompts/solution_extraction.py +9 -5
- camel/prompts/task_prompt_template.py +24 -21
- camel/prompts/translation.py +9 -5
- camel/responses/agent_responses.py +5 -2
- camel/retrievers/__init__.py +24 -0
- camel/retrievers/auto_retriever.py +319 -0
- camel/retrievers/base.py +64 -0
- camel/retrievers/bm25_retriever.py +149 -0
- camel/retrievers/vector_retriever.py +166 -0
- camel/societies/__init__.py +1 -1
- camel/societies/babyagi_playing.py +56 -32
- camel/societies/role_playing.py +188 -133
- camel/storages/__init__.py +18 -0
- camel/storages/graph_storages/__init__.py +23 -0
- camel/storages/graph_storages/base.py +82 -0
- camel/storages/graph_storages/graph_element.py +74 -0
- camel/storages/graph_storages/neo4j_graph.py +582 -0
- camel/storages/key_value_storages/base.py +1 -2
- camel/storages/key_value_storages/in_memory.py +1 -2
- camel/storages/key_value_storages/json.py +8 -13
- camel/storages/vectordb_storages/__init__.py +33 -0
- camel/storages/vectordb_storages/base.py +202 -0
- camel/storages/vectordb_storages/milvus.py +396 -0
- camel/storages/vectordb_storages/qdrant.py +371 -0
- camel/terminators/__init__.py +1 -1
- camel/terminators/base.py +2 -3
- camel/terminators/response_terminator.py +21 -12
- camel/terminators/token_limit_terminator.py +5 -3
- camel/types/__init__.py +12 -6
- camel/types/enums.py +86 -13
- camel/types/openai_types.py +10 -5
- camel/utils/__init__.py +18 -13
- camel/utils/commons.py +242 -81
- camel/utils/token_counting.py +135 -15
- {camel_ai-0.1.1.dist-info → camel_ai-0.1.3.dist-info}/METADATA +116 -74
- camel_ai-0.1.3.dist-info/RECORD +101 -0
- {camel_ai-0.1.1.dist-info → camel_ai-0.1.3.dist-info}/WHEEL +1 -1
- camel/memories/context_creators/base.py +0 -72
- camel_ai-0.1.1.dist-info/RECORD +0 -75
|
@@ -0,0 +1,74 @@
|
|
|
1
|
+
# =========== Copyright 2023 @ CAMEL-AI.org. All Rights Reserved. ===========
|
|
2
|
+
# Licensed under the Apache License, Version 2.0 (the “License”);
|
|
3
|
+
# you may not use this file except in compliance with the License.
|
|
4
|
+
# You may obtain a copy of the License at
|
|
5
|
+
#
|
|
6
|
+
# http://www.apache.org/licenses/LICENSE-2.0
|
|
7
|
+
#
|
|
8
|
+
# Unless required by applicable law or agreed to in writing, software
|
|
9
|
+
# distributed under the License is distributed on an “AS IS” BASIS,
|
|
10
|
+
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
|
11
|
+
# See the License for the specific language governing permissions and
|
|
12
|
+
# limitations under the License.
|
|
13
|
+
# =========== Copyright 2023 @ CAMEL-AI.org. All Rights Reserved. ===========
|
|
14
|
+
from __future__ import annotations
|
|
15
|
+
|
|
16
|
+
from dataclasses import dataclass, field
|
|
17
|
+
from typing import List, Union
|
|
18
|
+
|
|
19
|
+
from unstructured.documents.elements import Element
|
|
20
|
+
|
|
21
|
+
|
|
22
|
+
@dataclass
|
|
23
|
+
class Node:
|
|
24
|
+
r"""Represents a node in a graph with associated properties.
|
|
25
|
+
|
|
26
|
+
Attributes:
|
|
27
|
+
id (Union[str, int]): A unique identifier for the node.
|
|
28
|
+
type (str): The type of the relationship.
|
|
29
|
+
properties (dict): Additional properties and metadata associated with
|
|
30
|
+
the node.
|
|
31
|
+
"""
|
|
32
|
+
|
|
33
|
+
id: Union[str, int]
|
|
34
|
+
type: str = "Node"
|
|
35
|
+
properties: dict = field(default_factory=dict)
|
|
36
|
+
|
|
37
|
+
|
|
38
|
+
@dataclass
|
|
39
|
+
class Relationship:
|
|
40
|
+
r"""Represents a directed relationship between two nodes in a graph.
|
|
41
|
+
|
|
42
|
+
Attributes:
|
|
43
|
+
subj (Node): The subject/source node of the relationship.
|
|
44
|
+
obj (Node): The object/target node of the relationship.
|
|
45
|
+
type (str): The type of the relationship.
|
|
46
|
+
properties (dict): Additional properties associated with the
|
|
47
|
+
relationship.
|
|
48
|
+
"""
|
|
49
|
+
|
|
50
|
+
subj: Node
|
|
51
|
+
obj: Node
|
|
52
|
+
type: str = "Relationship"
|
|
53
|
+
properties: dict = field(default_factory=dict)
|
|
54
|
+
|
|
55
|
+
|
|
56
|
+
@dataclass
|
|
57
|
+
class GraphElement:
|
|
58
|
+
r"""A graph element with lists of nodes and relationships.
|
|
59
|
+
|
|
60
|
+
Attributes:
|
|
61
|
+
nodes (List[Node]): A list of nodes in the graph.
|
|
62
|
+
relationships (List[Relationship]): A list of relationships in the
|
|
63
|
+
graph.
|
|
64
|
+
source (Element): The element from which the graph information is
|
|
65
|
+
derived.
|
|
66
|
+
"""
|
|
67
|
+
|
|
68
|
+
# Allow arbitrary types for Element
|
|
69
|
+
class Config:
|
|
70
|
+
arbitrary_types_allowed = True
|
|
71
|
+
|
|
72
|
+
nodes: List[Node]
|
|
73
|
+
relationships: List[Relationship]
|
|
74
|
+
source: Element
|
|
@@ -0,0 +1,582 @@
|
|
|
1
|
+
# =========== Copyright 2023 @ CAMEL-AI.org. All Rights Reserved. ===========
|
|
2
|
+
# Licensed under the Apache License, Version 2.0 (the “License”);
|
|
3
|
+
# you may not use this file except in compliance with the License.
|
|
4
|
+
# You may obtain a copy of the License at
|
|
5
|
+
#
|
|
6
|
+
# http://www.apache.org/licenses/LICENSE-2.0
|
|
7
|
+
#
|
|
8
|
+
# Unless required by applicable law or agreed to in writing, software
|
|
9
|
+
# distributed under the License is distributed on an “AS IS” BASIS,
|
|
10
|
+
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
|
11
|
+
# See the License for the specific language governing permissions and
|
|
12
|
+
# limitations under the License.
|
|
13
|
+
# =========== Copyright 2023 @ CAMEL-AI.org. All Rights Reserved. ===========
|
|
14
|
+
import logging
|
|
15
|
+
from hashlib import md5
|
|
16
|
+
from typing import Any, Dict, List, Optional
|
|
17
|
+
|
|
18
|
+
from camel.storages.graph_storages import BaseGraphStorage, GraphElement
|
|
19
|
+
|
|
20
|
+
logger = logging.getLogger(__name__)
|
|
21
|
+
|
|
22
|
+
BASE_ENTITY_LABEL = "__Entity__"
|
|
23
|
+
EXCLUDED_LABELS = ["Excluded_Label_A", "Excluded_Label_B"]
|
|
24
|
+
EXCLUDED_RELS = ["Excluded_Rel_A"]
|
|
25
|
+
|
|
26
|
+
NODE_PROPERTY_QUERY = """
|
|
27
|
+
CALL apoc.meta.data()
|
|
28
|
+
YIELD label, other, elementType, type, property
|
|
29
|
+
WHERE NOT type = "RELATIONSHIP" AND elementType = "node"
|
|
30
|
+
AND NOT label IN $EXCLUDED_LABELS
|
|
31
|
+
WITH label AS nodeLabels, collect({property:property, type:type}) AS properties
|
|
32
|
+
RETURN {labels: nodeLabels, properties: properties} AS output
|
|
33
|
+
"""
|
|
34
|
+
|
|
35
|
+
REL_PROPERTY_QUERY = """
|
|
36
|
+
CALL apoc.meta.data()
|
|
37
|
+
YIELD label, other, elementType, type, property
|
|
38
|
+
WHERE NOT type = "RELATIONSHIP" AND elementType = "relationship"
|
|
39
|
+
AND NOT label IN $EXCLUDED_LABELS
|
|
40
|
+
WITH label AS nodeLabels, collect({property:property, type:type}) AS properties
|
|
41
|
+
RETURN {type: nodeLabels, properties: properties} AS output
|
|
42
|
+
"""
|
|
43
|
+
|
|
44
|
+
REL_QUERY = """
|
|
45
|
+
CALL apoc.meta.data()
|
|
46
|
+
YIELD label, other, elementType, type, property
|
|
47
|
+
WHERE type = "RELATIONSHIP" AND elementType = "node"
|
|
48
|
+
UNWIND other AS other_node
|
|
49
|
+
WITH * WHERE NOT label IN $EXCLUDED_LABELS
|
|
50
|
+
AND NOT other_node IN $EXCLUDED_LABELS
|
|
51
|
+
RETURN {start: label, type: property, end: toString(other_node)} AS output
|
|
52
|
+
"""
|
|
53
|
+
|
|
54
|
+
INCLUDE_DOCS_QUERY = (
|
|
55
|
+
"MERGE (d:Element {id:$element['element_id']}) "
|
|
56
|
+
"SET d.text = $element['text'] "
|
|
57
|
+
"SET d += $element['metadata'] "
|
|
58
|
+
"WITH d "
|
|
59
|
+
)
|
|
60
|
+
|
|
61
|
+
LIST_LIMIT = 128
|
|
62
|
+
|
|
63
|
+
|
|
64
|
+
class Neo4jGraph(BaseGraphStorage):
|
|
65
|
+
r"""Provides a connection to a Neo4j database for various graph operations.
|
|
66
|
+
|
|
67
|
+
The detailed information about Neo4j is available at:
|
|
68
|
+
`Neo4j https://neo4j.com/docs/getting-started`
|
|
69
|
+
|
|
70
|
+
This module refered to the work of Langchian and Llamaindex.
|
|
71
|
+
|
|
72
|
+
Args:
|
|
73
|
+
url (str): The URL of the Neo4j database server.
|
|
74
|
+
username (str): The username for database authentication.
|
|
75
|
+
password (str): The password for database authentication.
|
|
76
|
+
database (str): The name of the database to connect to. Defaults to
|
|
77
|
+
`neo4j`.
|
|
78
|
+
timeout (Optional[float]): The timeout for transactions in seconds.
|
|
79
|
+
Useful for terminating long-running queries. Defaults to `None`.
|
|
80
|
+
truncate (bool): A flag to indicate whether to remove lists with more
|
|
81
|
+
than `LIST_LIMIT` elements from results. Defaults to `False`.
|
|
82
|
+
"""
|
|
83
|
+
|
|
84
|
+
def __init__(
|
|
85
|
+
self,
|
|
86
|
+
url: str,
|
|
87
|
+
username: str,
|
|
88
|
+
password: str,
|
|
89
|
+
database: str = "neo4j",
|
|
90
|
+
timeout: Optional[float] = None,
|
|
91
|
+
truncate: bool = False,
|
|
92
|
+
) -> None:
|
|
93
|
+
r"""Create a new Neo4j graph instance."""
|
|
94
|
+
try:
|
|
95
|
+
import neo4j
|
|
96
|
+
except ImportError:
|
|
97
|
+
raise ValueError(
|
|
98
|
+
"Could not import neo4j python package. "
|
|
99
|
+
"Please install it with `pip install neo4j`."
|
|
100
|
+
)
|
|
101
|
+
|
|
102
|
+
self.driver = neo4j.GraphDatabase.driver(url, auth=(username, password))
|
|
103
|
+
self.database = database
|
|
104
|
+
self.timeout = timeout
|
|
105
|
+
self.truncate = truncate
|
|
106
|
+
self.schema: str = ""
|
|
107
|
+
self.structured_schema: Dict[str, Any] = {}
|
|
108
|
+
|
|
109
|
+
# Verify connection
|
|
110
|
+
try:
|
|
111
|
+
self.driver.verify_connectivity()
|
|
112
|
+
except neo4j.exceptions.ServiceUnavailable:
|
|
113
|
+
raise ValueError(
|
|
114
|
+
"Could not connect to Neo4j database. "
|
|
115
|
+
"Please ensure that the url is correct"
|
|
116
|
+
)
|
|
117
|
+
except neo4j.exceptions.AuthError:
|
|
118
|
+
raise ValueError(
|
|
119
|
+
"Could not connect to Neo4j database. "
|
|
120
|
+
"Please ensure that the username and password are correct"
|
|
121
|
+
)
|
|
122
|
+
# Set schema
|
|
123
|
+
try:
|
|
124
|
+
self.refresh_schema()
|
|
125
|
+
except neo4j.exceptions.ClientError:
|
|
126
|
+
raise ValueError(
|
|
127
|
+
"Could not use APOC procedures. "
|
|
128
|
+
"Please ensure the APOC plugin is installed in Neo4j and that "
|
|
129
|
+
"'apoc.meta.data()' is allowed in Neo4j configuration "
|
|
130
|
+
)
|
|
131
|
+
|
|
132
|
+
@property
|
|
133
|
+
def get_client(self) -> Any:
|
|
134
|
+
r"""Get the underlying graph storage client."""
|
|
135
|
+
return self.driver
|
|
136
|
+
|
|
137
|
+
@property
|
|
138
|
+
def get_schema(self, refresh: bool = False) -> str:
|
|
139
|
+
r"""Retrieve the schema of the Neo4jGraph store.
|
|
140
|
+
|
|
141
|
+
Args:
|
|
142
|
+
refresh (bool): A flag indicating whether to forcibly refresh the
|
|
143
|
+
schema from the Neo4jGraph store regardless of whether it is
|
|
144
|
+
already cached. Defaults to `False`.
|
|
145
|
+
|
|
146
|
+
Returns:
|
|
147
|
+
str: The schema of the Neo4jGraph store.
|
|
148
|
+
"""
|
|
149
|
+
if self.schema and not refresh:
|
|
150
|
+
return self.schema
|
|
151
|
+
self.refresh_schema()
|
|
152
|
+
logger.debug(f"get_schema() schema:\n{self.schema}")
|
|
153
|
+
return self.schema
|
|
154
|
+
|
|
155
|
+
@property
|
|
156
|
+
def get_structured_schema(self) -> Dict[str, Any]:
|
|
157
|
+
r"""Returns the structured schema of the graph
|
|
158
|
+
|
|
159
|
+
Returns:
|
|
160
|
+
Dict[str, Any]: The structured schema of the graph.
|
|
161
|
+
"""
|
|
162
|
+
return self.structured_schema
|
|
163
|
+
|
|
164
|
+
def _value_truncate(self, raw_value: Any) -> Any:
|
|
165
|
+
r"""Truncates the input raw value by removing entries that is
|
|
166
|
+
dictionary or list with values resembling embeddings and containing
|
|
167
|
+
more than `LIST_LIMIT` elements. This method aims to reduce unnecessary
|
|
168
|
+
computational cost and noise in scenarios where such detailed data
|
|
169
|
+
structures are not needed. If the input value is not dictionary or
|
|
170
|
+
list then give the raw value back.
|
|
171
|
+
|
|
172
|
+
Args:
|
|
173
|
+
raw_value (Any): The raw value to be truncated.
|
|
174
|
+
|
|
175
|
+
Returns:
|
|
176
|
+
Any: The truncated value, with embedding-like
|
|
177
|
+
dictionaries and oversized lists handled.
|
|
178
|
+
"""
|
|
179
|
+
if isinstance(raw_value, dict):
|
|
180
|
+
new_dict = {}
|
|
181
|
+
for key, value in raw_value.items():
|
|
182
|
+
if isinstance(value, dict):
|
|
183
|
+
truncated_value = self._value_truncate(value)
|
|
184
|
+
# Check if the truncated value is not None
|
|
185
|
+
if truncated_value is not None:
|
|
186
|
+
new_dict[key] = truncated_value
|
|
187
|
+
elif isinstance(value, list):
|
|
188
|
+
if len(value) < LIST_LIMIT:
|
|
189
|
+
truncated_value = self._value_truncate(value)
|
|
190
|
+
# Check if the truncated value is not None
|
|
191
|
+
if truncated_value is not None:
|
|
192
|
+
new_dict[key] = truncated_value
|
|
193
|
+
# Do not include the key if the list is oversized
|
|
194
|
+
else:
|
|
195
|
+
new_dict[key] = value
|
|
196
|
+
return new_dict
|
|
197
|
+
elif isinstance(raw_value, list):
|
|
198
|
+
if len(raw_value) < LIST_LIMIT:
|
|
199
|
+
return [
|
|
200
|
+
self._value_truncate(item)
|
|
201
|
+
for item in raw_value
|
|
202
|
+
if self._value_truncate(item) is not None
|
|
203
|
+
]
|
|
204
|
+
else:
|
|
205
|
+
return None
|
|
206
|
+
else:
|
|
207
|
+
return raw_value
|
|
208
|
+
|
|
209
|
+
def query(
|
|
210
|
+
self, query: str, params: Optional[Dict[str, Any]] = None
|
|
211
|
+
) -> List[Dict[str, Any]]:
|
|
212
|
+
r"""Executes a Neo4j Cypher declarative query in a database.
|
|
213
|
+
|
|
214
|
+
Args:
|
|
215
|
+
query (str): The Cypher query to be executed.
|
|
216
|
+
params (Optional[Dict[str, Any]]): A dictionary of parameters to
|
|
217
|
+
be used in the query. Defaults to `None`.
|
|
218
|
+
|
|
219
|
+
Returns:
|
|
220
|
+
List[Dict[str, Any]]: A list of dictionaries, each
|
|
221
|
+
dictionary represents a row of results from the Cypher query.
|
|
222
|
+
|
|
223
|
+
Raises:
|
|
224
|
+
ValueError: If the executed Cypher query syntax is invalid.
|
|
225
|
+
"""
|
|
226
|
+
from neo4j import Query
|
|
227
|
+
from neo4j.exceptions import CypherSyntaxError
|
|
228
|
+
|
|
229
|
+
if params is None:
|
|
230
|
+
params = {}
|
|
231
|
+
|
|
232
|
+
with self.driver.session(database=self.database) as session:
|
|
233
|
+
try:
|
|
234
|
+
data = session.run(
|
|
235
|
+
Query(text=query, timeout=self.timeout), params
|
|
236
|
+
)
|
|
237
|
+
json_data = [r.data() for r in data]
|
|
238
|
+
if self.truncate:
|
|
239
|
+
json_data = [self._value_truncate(el) for el in json_data]
|
|
240
|
+
return json_data
|
|
241
|
+
except CypherSyntaxError as e:
|
|
242
|
+
raise ValueError(
|
|
243
|
+
f"Generated Cypher Statement is not valid\n{e}"
|
|
244
|
+
)
|
|
245
|
+
|
|
246
|
+
def refresh_schema(self) -> None:
|
|
247
|
+
r"""Refreshes the Neo4j graph schema information by querying the
|
|
248
|
+
database for node properties, relationship properties, and
|
|
249
|
+
relationships.
|
|
250
|
+
"""
|
|
251
|
+
from neo4j.exceptions import ClientError
|
|
252
|
+
|
|
253
|
+
# Extract schema elements from the database
|
|
254
|
+
node_properties = [
|
|
255
|
+
el["output"]
|
|
256
|
+
for el in self.query(
|
|
257
|
+
NODE_PROPERTY_QUERY,
|
|
258
|
+
params={
|
|
259
|
+
"EXCLUDED_LABELS": [*EXCLUDED_LABELS, BASE_ENTITY_LABEL]
|
|
260
|
+
},
|
|
261
|
+
)
|
|
262
|
+
]
|
|
263
|
+
rel_properties = [
|
|
264
|
+
el["output"]
|
|
265
|
+
for el in self.query(
|
|
266
|
+
REL_PROPERTY_QUERY, params={"EXCLUDED_LABELS": EXCLUDED_RELS}
|
|
267
|
+
)
|
|
268
|
+
]
|
|
269
|
+
relationships = [
|
|
270
|
+
el["output"]
|
|
271
|
+
for el in self.query(
|
|
272
|
+
REL_QUERY,
|
|
273
|
+
params={
|
|
274
|
+
"EXCLUDED_LABELS": [*EXCLUDED_LABELS, BASE_ENTITY_LABEL]
|
|
275
|
+
},
|
|
276
|
+
)
|
|
277
|
+
]
|
|
278
|
+
|
|
279
|
+
# Get constraints & indexes
|
|
280
|
+
try:
|
|
281
|
+
constraint = self.query("SHOW CONSTRAINTS")
|
|
282
|
+
index = self.query("SHOW INDEXES YIELD *")
|
|
283
|
+
except (
|
|
284
|
+
ClientError
|
|
285
|
+
): # Read-only user might not have access to schema information
|
|
286
|
+
constraint = []
|
|
287
|
+
index = []
|
|
288
|
+
|
|
289
|
+
self.structured_schema = {
|
|
290
|
+
"node_props": {
|
|
291
|
+
el["labels"]: el["properties"] for el in node_properties
|
|
292
|
+
},
|
|
293
|
+
"rel_props": {
|
|
294
|
+
el["type"]: el["properties"] for el in rel_properties
|
|
295
|
+
},
|
|
296
|
+
"relationships": relationships,
|
|
297
|
+
"metadata": {"constraint": constraint, "index": index},
|
|
298
|
+
}
|
|
299
|
+
|
|
300
|
+
# Format node properties
|
|
301
|
+
formatted_node_props = []
|
|
302
|
+
for el in node_properties:
|
|
303
|
+
props_str = ", ".join(
|
|
304
|
+
[
|
|
305
|
+
f"{prop['property']}: {prop['type']}"
|
|
306
|
+
for prop in el["properties"]
|
|
307
|
+
]
|
|
308
|
+
)
|
|
309
|
+
formatted_node_props.append(f"{el['labels']} {{{props_str}}}")
|
|
310
|
+
|
|
311
|
+
# Format relationship properties
|
|
312
|
+
formatted_rel_props = []
|
|
313
|
+
for el in rel_properties:
|
|
314
|
+
props_str = ", ".join(
|
|
315
|
+
[
|
|
316
|
+
f"{prop['property']}: {prop['type']}"
|
|
317
|
+
for prop in el["properties"]
|
|
318
|
+
]
|
|
319
|
+
)
|
|
320
|
+
formatted_rel_props.append(f"{el['type']} {{{props_str}}}")
|
|
321
|
+
|
|
322
|
+
# Format relationships
|
|
323
|
+
formatted_rels = [
|
|
324
|
+
f"(:{el['start']})-[:{el['type']}]->(:{el['end']})"
|
|
325
|
+
for el in relationships
|
|
326
|
+
]
|
|
327
|
+
|
|
328
|
+
self.schema = "\n".join(
|
|
329
|
+
[
|
|
330
|
+
"Node properties are the following:",
|
|
331
|
+
", ".join(formatted_node_props),
|
|
332
|
+
"Relationship properties are the following:",
|
|
333
|
+
", ".join(formatted_rel_props),
|
|
334
|
+
"The relationships are the following:",
|
|
335
|
+
", ".join(formatted_rels),
|
|
336
|
+
]
|
|
337
|
+
)
|
|
338
|
+
|
|
339
|
+
def add_triplet(self, subj: str, obj: str, rel: str) -> None:
|
|
340
|
+
r"""Adds a relationship (triplet) between two entities in the database.
|
|
341
|
+
|
|
342
|
+
Args:
|
|
343
|
+
subj (str): The identifier for the subject entity.
|
|
344
|
+
obj (str): The identifier for the object entity.
|
|
345
|
+
rel (str): The relationship between the subject and object.
|
|
346
|
+
"""
|
|
347
|
+
query = """
|
|
348
|
+
MERGE (n1:`%s` {id:$subj})
|
|
349
|
+
MERGE (n2:`%s` {id:$obj})
|
|
350
|
+
MERGE (n1)-[:`%s`]->(n2)
|
|
351
|
+
"""
|
|
352
|
+
|
|
353
|
+
prepared_statement = query % (
|
|
354
|
+
BASE_ENTITY_LABEL.replace("_", ""),
|
|
355
|
+
BASE_ENTITY_LABEL.replace("_", ""),
|
|
356
|
+
rel.replace(" ", "_").upper(),
|
|
357
|
+
)
|
|
358
|
+
|
|
359
|
+
# Execute the query within a database session
|
|
360
|
+
with self.driver.session(database=self.database) as session:
|
|
361
|
+
session.run(prepared_statement, {"subj": subj, "obj": obj})
|
|
362
|
+
|
|
363
|
+
def _delete_rel(self, subj: str, obj: str, rel: str) -> None:
|
|
364
|
+
r"""Deletes a specific relationship between two nodes in the Neo4j
|
|
365
|
+
database.
|
|
366
|
+
|
|
367
|
+
Args:
|
|
368
|
+
subj (str): The identifier for the subject entity.
|
|
369
|
+
obj (str): The identifier for the object entity.
|
|
370
|
+
rel (str): The relationship between the subject and object to
|
|
371
|
+
delete.
|
|
372
|
+
"""
|
|
373
|
+
with self.driver.session(database=self.database) as session:
|
|
374
|
+
session.run(
|
|
375
|
+
(
|
|
376
|
+
"MATCH (n1:{})-[r:{}]->(n2:{}) WHERE n1.id = $subj AND n2.id"
|
|
377
|
+
" = $obj DELETE r"
|
|
378
|
+
).format(
|
|
379
|
+
BASE_ENTITY_LABEL.replace("_", ""),
|
|
380
|
+
rel,
|
|
381
|
+
BASE_ENTITY_LABEL.replace("_", ""),
|
|
382
|
+
),
|
|
383
|
+
{"subj": subj, "obj": obj},
|
|
384
|
+
)
|
|
385
|
+
|
|
386
|
+
def _delete_entity(self, entity: str) -> None:
|
|
387
|
+
r"""Deletes an entity from the Neo4j database based on its unique
|
|
388
|
+
identifier.
|
|
389
|
+
|
|
390
|
+
Args:
|
|
391
|
+
entity (str): The unique identifier of the entity to be deleted.
|
|
392
|
+
"""
|
|
393
|
+
with self.driver.session(database=self.database) as session:
|
|
394
|
+
session.run(
|
|
395
|
+
"MATCH (n:%s) WHERE n.id = $entity DELETE n"
|
|
396
|
+
% BASE_ENTITY_LABEL.replace("_", ""),
|
|
397
|
+
{"entity": entity},
|
|
398
|
+
)
|
|
399
|
+
|
|
400
|
+
def _check_edges(self, entity: str) -> bool:
|
|
401
|
+
r"""Checks if the given entity has any relationships in the graph
|
|
402
|
+
database.
|
|
403
|
+
|
|
404
|
+
Args:
|
|
405
|
+
entity (str): The unique identifier of the entity to check.
|
|
406
|
+
|
|
407
|
+
Returns:
|
|
408
|
+
bool: True if the entity has at least one edge (relationship),
|
|
409
|
+
False otherwise.
|
|
410
|
+
"""
|
|
411
|
+
with self.driver.session(database=self.database) as session:
|
|
412
|
+
is_exists_result = session.run(
|
|
413
|
+
"MATCH (n1:%s)--() WHERE n1.id = $entity RETURN count(*)"
|
|
414
|
+
% (BASE_ENTITY_LABEL.replace("_", "")),
|
|
415
|
+
{"entity": entity},
|
|
416
|
+
)
|
|
417
|
+
return bool(list(is_exists_result))
|
|
418
|
+
|
|
419
|
+
def delete_triplet(self, subj: str, obj: str, rel: str) -> None:
|
|
420
|
+
r"""Deletes a specific triplet from the graph, comprising a subject,
|
|
421
|
+
object and relationship.
|
|
422
|
+
|
|
423
|
+
Args:
|
|
424
|
+
subj (str): The identifier for the subject entity.
|
|
425
|
+
obj (str): The identifier for the object entity.
|
|
426
|
+
rel (str): The relationship between the subject and object.
|
|
427
|
+
"""
|
|
428
|
+
self._delete_rel(subj, obj, rel)
|
|
429
|
+
if not self._check_edges(subj):
|
|
430
|
+
self._delete_entity(subj)
|
|
431
|
+
if not self._check_edges(obj):
|
|
432
|
+
self._delete_entity(obj)
|
|
433
|
+
|
|
434
|
+
def _get_node_import_query(
|
|
435
|
+
self, base_entity_label: bool, include_source: bool
|
|
436
|
+
) -> str:
|
|
437
|
+
r"""Constructs a Cypher query string for importing nodes into a Neo4j
|
|
438
|
+
database.
|
|
439
|
+
|
|
440
|
+
Args:
|
|
441
|
+
base_entity_label (bool): Flag indicating whether to use a base
|
|
442
|
+
entity label in the MERGE operation.
|
|
443
|
+
include_source (bool): Flag indicating whether to include source
|
|
444
|
+
element information in the query.
|
|
445
|
+
|
|
446
|
+
Returns:
|
|
447
|
+
str: A Cypher query string tailored based on the provided flags.
|
|
448
|
+
"""
|
|
449
|
+
REL = 'MERGE (d)-[:MENTIONS]->(source) ' if include_source else ''
|
|
450
|
+
if base_entity_label:
|
|
451
|
+
return (
|
|
452
|
+
f"{INCLUDE_DOCS_QUERY if include_source else ''}"
|
|
453
|
+
"UNWIND $data AS row "
|
|
454
|
+
f"MERGE (source:`{BASE_ENTITY_LABEL}` {{id: row.id}}) "
|
|
455
|
+
"SET source += row.properties "
|
|
456
|
+
f"{REL}"
|
|
457
|
+
"WITH source, row "
|
|
458
|
+
"CALL apoc.create.addLabels( source, [row.type] ) YIELD node "
|
|
459
|
+
"RETURN distinct 'done' AS result"
|
|
460
|
+
)
|
|
461
|
+
else:
|
|
462
|
+
return (
|
|
463
|
+
f"{INCLUDE_DOCS_QUERY if include_source else ''}"
|
|
464
|
+
"UNWIND $data AS row "
|
|
465
|
+
"CALL apoc.merge.node([row.type], {id: row.id}, "
|
|
466
|
+
"row.properties, {}) YIELD node "
|
|
467
|
+
f"{'MERGE (d)-[:MENTIONS]->(node) ' if include_source else ''}"
|
|
468
|
+
"RETURN distinct 'done' AS result"
|
|
469
|
+
)
|
|
470
|
+
|
|
471
|
+
def _get_rel_import_query(self, base_entity_label: bool) -> str:
|
|
472
|
+
r"""Constructs a Cypher query string for importing relationship into a
|
|
473
|
+
Neo4j database.
|
|
474
|
+
|
|
475
|
+
Args:
|
|
476
|
+
base_entity_label (bool): Flag indicating whether to use a base
|
|
477
|
+
entity label in the MERGE operation.
|
|
478
|
+
|
|
479
|
+
Returns:
|
|
480
|
+
str: A Cypher query string tailored based on the provided flags.
|
|
481
|
+
"""
|
|
482
|
+
if base_entity_label:
|
|
483
|
+
return (
|
|
484
|
+
"UNWIND $data AS row "
|
|
485
|
+
f"MERGE (subj:`{BASE_ENTITY_LABEL}` {{id: row.subj}}) "
|
|
486
|
+
f"MERGE (obj:`{BASE_ENTITY_LABEL}` {{id: row.obj}}) "
|
|
487
|
+
"WITH subj, obj, row "
|
|
488
|
+
"CALL apoc.merge.relationship(subj, row.type, "
|
|
489
|
+
"{}, row.properties, obj) YIELD rel "
|
|
490
|
+
"RETURN distinct 'done'"
|
|
491
|
+
)
|
|
492
|
+
else:
|
|
493
|
+
return (
|
|
494
|
+
"UNWIND $data AS row "
|
|
495
|
+
"CALL apoc.merge.node([row.subj_label], {id: row.subj},"
|
|
496
|
+
"{}, {}) YIELD node as subj "
|
|
497
|
+
"CALL apoc.merge.node([row.obj_label], {id: row.obj},"
|
|
498
|
+
"{}, {}) YIELD node as obj "
|
|
499
|
+
"CALL apoc.merge.relationship(subj, row.type, "
|
|
500
|
+
"{}, row.properties, obj) YIELD rel "
|
|
501
|
+
"RETURN distinct 'done'"
|
|
502
|
+
)
|
|
503
|
+
|
|
504
|
+
def add_graph_elements(
|
|
505
|
+
self,
|
|
506
|
+
graph_elements: List[GraphElement],
|
|
507
|
+
include_source: bool = False,
|
|
508
|
+
base_entity_label: bool = False,
|
|
509
|
+
) -> None:
|
|
510
|
+
r"""Adds nodes and relationships from a list of GraphElement objects
|
|
511
|
+
to the graph storage.
|
|
512
|
+
|
|
513
|
+
Args:
|
|
514
|
+
graph_elements (List[GraphElement]): A list of GraphElement
|
|
515
|
+
objects that contain the nodes and relationships to be added
|
|
516
|
+
to the graph. Each GraphElement should encapsulate the
|
|
517
|
+
structure of part of the graph, including nodes,
|
|
518
|
+
relationships, and the source element information.
|
|
519
|
+
include_source (bool, optional): If True, stores the source
|
|
520
|
+
element and links it to nodes in the graph using the MENTIONS
|
|
521
|
+
relationship. This is useful for tracing back the origin of
|
|
522
|
+
data. Merges source elements based on the `id` property from
|
|
523
|
+
the source element metadata if available; otherwise it
|
|
524
|
+
calculates the MD5 hash of `page_content` for merging process.
|
|
525
|
+
Defaults to `False`.
|
|
526
|
+
base_entity_label (bool, optional): If True, each newly created
|
|
527
|
+
node gets a secondary `BASE_ENTITY_LABEL` label, which is
|
|
528
|
+
indexed and improves import speed and performance. Defaults to
|
|
529
|
+
`False`.
|
|
530
|
+
"""
|
|
531
|
+
if base_entity_label: # check if constraint already exists
|
|
532
|
+
constraint_exists = any(
|
|
533
|
+
el["labelsOrTypes"] == [BASE_ENTITY_LABEL]
|
|
534
|
+
and el["properties"] == ["id"]
|
|
535
|
+
for el in self.structured_schema.get("metadata", {}).get(
|
|
536
|
+
"constraint", []
|
|
537
|
+
)
|
|
538
|
+
)
|
|
539
|
+
if not constraint_exists:
|
|
540
|
+
# Create constraint
|
|
541
|
+
self.query(
|
|
542
|
+
"CREATE CONSTRAINT IF NOT EXISTS FOR"
|
|
543
|
+
f"(b:{BASE_ENTITY_LABEL}) "
|
|
544
|
+
"REQUIRE b.id IS UNIQUE;"
|
|
545
|
+
)
|
|
546
|
+
self.refresh_schema() # refresh constraint information
|
|
547
|
+
|
|
548
|
+
node_import_query = self._get_node_import_query(
|
|
549
|
+
base_entity_label, include_source
|
|
550
|
+
)
|
|
551
|
+
rel_import_query = self._get_rel_import_query(base_entity_label)
|
|
552
|
+
for element in graph_elements:
|
|
553
|
+
if not element.source.to_dict()['element_id']:
|
|
554
|
+
element.source.to_dict()['element_id'] = md5(
|
|
555
|
+
str(element).encode("utf-8")
|
|
556
|
+
).hexdigest()
|
|
557
|
+
|
|
558
|
+
# Import nodes
|
|
559
|
+
self.query(
|
|
560
|
+
node_import_query,
|
|
561
|
+
{
|
|
562
|
+
"data": [el.__dict__ for el in element.nodes],
|
|
563
|
+
"element": element.source.to_dict(),
|
|
564
|
+
},
|
|
565
|
+
)
|
|
566
|
+
# Import relationships
|
|
567
|
+
self.query(
|
|
568
|
+
rel_import_query,
|
|
569
|
+
{
|
|
570
|
+
"data": [
|
|
571
|
+
{
|
|
572
|
+
"subj": el.subj.id,
|
|
573
|
+
"subj_label": el.subj.type,
|
|
574
|
+
"obj": el.obj.id,
|
|
575
|
+
"obj_label": el.obj.type,
|
|
576
|
+
"type": el.type.replace(" ", "_").upper(),
|
|
577
|
+
"properties": el.properties,
|
|
578
|
+
}
|
|
579
|
+
for el in element.relationships
|
|
580
|
+
]
|
|
581
|
+
},
|
|
582
|
+
)
|
|
@@ -46,6 +46,5 @@ class InMemoryKeyValueStorage(BaseKeyValueStorage):
|
|
|
46
46
|
return deepcopy(self.memory_list)
|
|
47
47
|
|
|
48
48
|
def clear(self) -> None:
|
|
49
|
-
r"""Removes all records from the key-value storage system.
|
|
50
|
-
"""
|
|
49
|
+
r"""Removes all records from the key-value storage system."""
|
|
51
50
|
self.memory_list.clear()
|