graphiti-core 0.18.8__py3-none-any.whl → 0.19.0__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 graphiti-core might be problematic. Click here for more details.

Files changed (32) hide show
  1. graphiti_core/driver/driver.py +4 -0
  2. graphiti_core/driver/falkordb_driver.py +3 -14
  3. graphiti_core/driver/kuzu_driver.py +175 -0
  4. graphiti_core/driver/neptune_driver.py +301 -0
  5. graphiti_core/edges.py +155 -62
  6. graphiti_core/graph_queries.py +31 -2
  7. graphiti_core/graphiti.py +6 -1
  8. graphiti_core/helpers.py +8 -8
  9. graphiti_core/llm_client/config.py +1 -1
  10. graphiti_core/llm_client/openai_base_client.py +15 -5
  11. graphiti_core/llm_client/openai_client.py +16 -6
  12. graphiti_core/migrations/__init__.py +0 -0
  13. graphiti_core/migrations/neo4j_node_group_labels.py +114 -0
  14. graphiti_core/models/edges/edge_db_queries.py +205 -76
  15. graphiti_core/models/nodes/node_db_queries.py +253 -74
  16. graphiti_core/nodes.py +271 -98
  17. graphiti_core/prompts/extract_edges.py +1 -0
  18. graphiti_core/prompts/extract_nodes.py +1 -1
  19. graphiti_core/search/search.py +42 -12
  20. graphiti_core/search/search_config.py +4 -0
  21. graphiti_core/search/search_filters.py +35 -22
  22. graphiti_core/search/search_utils.py +1329 -392
  23. graphiti_core/utils/bulk_utils.py +50 -15
  24. graphiti_core/utils/datetime_utils.py +13 -0
  25. graphiti_core/utils/maintenance/community_operations.py +39 -32
  26. graphiti_core/utils/maintenance/edge_operations.py +47 -13
  27. graphiti_core/utils/maintenance/graph_data_operations.py +100 -15
  28. graphiti_core/utils/maintenance/node_operations.py +7 -3
  29. {graphiti_core-0.18.8.dist-info → graphiti_core-0.19.0.dist-info}/METADATA +87 -13
  30. {graphiti_core-0.18.8.dist-info → graphiti_core-0.19.0.dist-info}/RECORD +32 -28
  31. {graphiti_core-0.18.8.dist-info → graphiti_core-0.19.0.dist-info}/WHEEL +0 -0
  32. {graphiti_core-0.18.8.dist-info → graphiti_core-0.19.0.dist-info}/licenses/LICENSE +0 -0
@@ -27,9 +27,13 @@ logger = logging.getLogger(__name__)
27
27
  class GraphProvider(Enum):
28
28
  NEO4J = 'neo4j'
29
29
  FALKORDB = 'falkordb'
30
+ KUZU = 'kuzu'
31
+ NEPTUNE = 'neptune'
30
32
 
31
33
 
32
34
  class GraphDriverSession(ABC):
35
+ provider: GraphProvider
36
+
33
37
  async def __aenter__(self):
34
38
  return self
35
39
 
@@ -15,7 +15,6 @@ limitations under the License.
15
15
  """
16
16
 
17
17
  import logging
18
- from datetime import datetime
19
18
  from typing import TYPE_CHECKING, Any
20
19
 
21
20
  if TYPE_CHECKING:
@@ -33,11 +32,14 @@ else:
33
32
  ) from None
34
33
 
35
34
  from graphiti_core.driver.driver import GraphDriver, GraphDriverSession, GraphProvider
35
+ from graphiti_core.utils.datetime_utils import convert_datetimes_to_strings
36
36
 
37
37
  logger = logging.getLogger(__name__)
38
38
 
39
39
 
40
40
  class FalkorDriverSession(GraphDriverSession):
41
+ provider = GraphProvider.FALKORDB
42
+
41
43
  def __init__(self, graph: FalkorGraph):
42
44
  self.graph = graph
43
45
 
@@ -164,16 +166,3 @@ class FalkorDriver(GraphDriver):
164
166
  cloned = FalkorDriver(falkor_db=self.client, database=database)
165
167
 
166
168
  return cloned
167
-
168
-
169
- def convert_datetimes_to_strings(obj):
170
- if isinstance(obj, dict):
171
- return {k: convert_datetimes_to_strings(v) for k, v in obj.items()}
172
- elif isinstance(obj, list):
173
- return [convert_datetimes_to_strings(item) for item in obj]
174
- elif isinstance(obj, tuple):
175
- return tuple(convert_datetimes_to_strings(item) for item in obj)
176
- elif isinstance(obj, datetime):
177
- return obj.isoformat()
178
- else:
179
- return obj
@@ -0,0 +1,175 @@
1
+ """
2
+ Copyright 2024, Zep Software, Inc.
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
+ http://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
+ """
16
+
17
+ import logging
18
+ from typing import Any
19
+
20
+ import kuzu
21
+
22
+ from graphiti_core.driver.driver import GraphDriver, GraphDriverSession, GraphProvider
23
+
24
+ logger = logging.getLogger(__name__)
25
+
26
+ # Kuzu requires an explicit schema.
27
+ # As Kuzu currently does not support creating full text indexes on edge properties,
28
+ # we work around this by representing (n:Entity)-[:RELATES_TO]->(m:Entity) as
29
+ # (n)-[:RELATES_TO]->(e:RelatesToNode_)-[:RELATES_TO]->(m).
30
+ SCHEMA_QUERIES = """
31
+ CREATE NODE TABLE IF NOT EXISTS Episodic (
32
+ uuid STRING PRIMARY KEY,
33
+ name STRING,
34
+ group_id STRING,
35
+ created_at TIMESTAMP,
36
+ source STRING,
37
+ source_description STRING,
38
+ content STRING,
39
+ valid_at TIMESTAMP,
40
+ entity_edges STRING[]
41
+ );
42
+ CREATE NODE TABLE IF NOT EXISTS Entity (
43
+ uuid STRING PRIMARY KEY,
44
+ name STRING,
45
+ group_id STRING,
46
+ labels STRING[],
47
+ created_at TIMESTAMP,
48
+ name_embedding FLOAT[],
49
+ summary STRING,
50
+ attributes STRING
51
+ );
52
+ CREATE NODE TABLE IF NOT EXISTS Community (
53
+ uuid STRING PRIMARY KEY,
54
+ name STRING,
55
+ group_id STRING,
56
+ created_at TIMESTAMP,
57
+ name_embedding FLOAT[],
58
+ summary STRING
59
+ );
60
+ CREATE NODE TABLE IF NOT EXISTS RelatesToNode_ (
61
+ uuid STRING PRIMARY KEY,
62
+ group_id STRING,
63
+ created_at TIMESTAMP,
64
+ name STRING,
65
+ fact STRING,
66
+ fact_embedding FLOAT[],
67
+ episodes STRING[],
68
+ expired_at TIMESTAMP,
69
+ valid_at TIMESTAMP,
70
+ invalid_at TIMESTAMP,
71
+ attributes STRING
72
+ );
73
+ CREATE REL TABLE IF NOT EXISTS RELATES_TO(
74
+ FROM Entity TO RelatesToNode_,
75
+ FROM RelatesToNode_ TO Entity
76
+ );
77
+ CREATE REL TABLE IF NOT EXISTS MENTIONS(
78
+ FROM Episodic TO Entity,
79
+ uuid STRING PRIMARY KEY,
80
+ group_id STRING,
81
+ created_at TIMESTAMP
82
+ );
83
+ CREATE REL TABLE IF NOT EXISTS HAS_MEMBER(
84
+ FROM Community TO Entity,
85
+ FROM Community TO Community,
86
+ uuid STRING,
87
+ group_id STRING,
88
+ created_at TIMESTAMP
89
+ );
90
+ """
91
+
92
+
93
+ class KuzuDriver(GraphDriver):
94
+ provider: GraphProvider = GraphProvider.KUZU
95
+
96
+ def __init__(
97
+ self,
98
+ db: str = ':memory:',
99
+ max_concurrent_queries: int = 1,
100
+ ):
101
+ super().__init__()
102
+ self.db = kuzu.Database(db)
103
+
104
+ self.setup_schema()
105
+
106
+ self.client = kuzu.AsyncConnection(self.db, max_concurrent_queries=max_concurrent_queries)
107
+
108
+ async def execute_query(
109
+ self, cypher_query_: str, **kwargs: Any
110
+ ) -> tuple[list[dict[str, Any]] | list[list[dict[str, Any]]], None, None]:
111
+ params = {k: v for k, v in kwargs.items() if v is not None}
112
+ # Kuzu does not support these parameters.
113
+ params.pop('database_', None)
114
+ params.pop('routing_', None)
115
+
116
+ try:
117
+ results = await self.client.execute(cypher_query_, parameters=params)
118
+ except Exception as e:
119
+ params = {k: (v[:5] if isinstance(v, list) else v) for k, v in params.items()}
120
+ logger.error(f'Error executing Kuzu query: {e}\n{cypher_query_}\n{params}')
121
+ raise
122
+
123
+ if not results:
124
+ return [], None, None
125
+
126
+ if isinstance(results, list):
127
+ dict_results = [list(result.rows_as_dict()) for result in results]
128
+ else:
129
+ dict_results = list(results.rows_as_dict())
130
+ return dict_results, None, None # type: ignore
131
+
132
+ def session(self, _database: str | None = None) -> GraphDriverSession:
133
+ return KuzuDriverSession(self)
134
+
135
+ async def close(self):
136
+ # Do not explicity close the connection, instead rely on GC.
137
+ pass
138
+
139
+ def delete_all_indexes(self, database_: str):
140
+ pass
141
+
142
+ def setup_schema(self):
143
+ conn = kuzu.Connection(self.db)
144
+ conn.execute(SCHEMA_QUERIES)
145
+ conn.close()
146
+
147
+
148
+ class KuzuDriverSession(GraphDriverSession):
149
+ provider = GraphProvider.KUZU
150
+
151
+ def __init__(self, driver: KuzuDriver):
152
+ self.driver = driver
153
+
154
+ async def __aenter__(self):
155
+ return self
156
+
157
+ async def __aexit__(self, exc_type, exc, tb):
158
+ # No cleanup needed for Kuzu, but method must exist.
159
+ pass
160
+
161
+ async def close(self):
162
+ # Do not close the session here, as we're reusing the driver connection.
163
+ pass
164
+
165
+ async def execute_write(self, func, *args, **kwargs):
166
+ # Directly await the provided async function with `self` as the transaction/session
167
+ return await func(self, *args, **kwargs)
168
+
169
+ async def run(self, query: str | list, **kwargs: Any) -> Any:
170
+ if isinstance(query, list):
171
+ for cypher, params in query:
172
+ await self.driver.execute_query(cypher, **params)
173
+ else:
174
+ await self.driver.execute_query(query, **kwargs)
175
+ return None
@@ -0,0 +1,301 @@
1
+ """
2
+ Copyright 2024, Zep Software, Inc.
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
+ http://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
+ """
16
+
17
+ import asyncio
18
+ import datetime
19
+ import logging
20
+ from collections.abc import Coroutine
21
+ from typing import Any
22
+
23
+ import boto3
24
+ from langchain_aws.graphs import NeptuneAnalyticsGraph, NeptuneGraph
25
+ from opensearchpy import OpenSearch, Urllib3AWSV4SignerAuth, Urllib3HttpConnection, helpers
26
+
27
+ from graphiti_core.driver.driver import GraphDriver, GraphDriverSession, GraphProvider
28
+
29
+ logger = logging.getLogger(__name__)
30
+ DEFAULT_SIZE = 10
31
+
32
+ aoss_indices = [
33
+ {
34
+ 'index_name': 'node_name_and_summary',
35
+ 'body': {
36
+ 'mappings': {
37
+ 'properties': {
38
+ 'uuid': {'type': 'keyword'},
39
+ 'name': {'type': 'text'},
40
+ 'summary': {'type': 'text'},
41
+ 'group_id': {'type': 'text'},
42
+ }
43
+ }
44
+ },
45
+ 'query': {
46
+ 'query': {'multi_match': {'query': '', 'fields': ['name', 'summary', 'group_id']}},
47
+ 'size': DEFAULT_SIZE,
48
+ },
49
+ },
50
+ {
51
+ 'index_name': 'community_name',
52
+ 'body': {
53
+ 'mappings': {
54
+ 'properties': {
55
+ 'uuid': {'type': 'keyword'},
56
+ 'name': {'type': 'text'},
57
+ 'group_id': {'type': 'text'},
58
+ }
59
+ }
60
+ },
61
+ 'query': {
62
+ 'query': {'multi_match': {'query': '', 'fields': ['name', 'group_id']}},
63
+ 'size': DEFAULT_SIZE,
64
+ },
65
+ },
66
+ {
67
+ 'index_name': 'episode_content',
68
+ 'body': {
69
+ 'mappings': {
70
+ 'properties': {
71
+ 'uuid': {'type': 'keyword'},
72
+ 'content': {'type': 'text'},
73
+ 'source': {'type': 'text'},
74
+ 'source_description': {'type': 'text'},
75
+ 'group_id': {'type': 'text'},
76
+ }
77
+ }
78
+ },
79
+ 'query': {
80
+ 'query': {
81
+ 'multi_match': {
82
+ 'query': '',
83
+ 'fields': ['content', 'source', 'source_description', 'group_id'],
84
+ }
85
+ },
86
+ 'size': DEFAULT_SIZE,
87
+ },
88
+ },
89
+ {
90
+ 'index_name': 'edge_name_and_fact',
91
+ 'body': {
92
+ 'mappings': {
93
+ 'properties': {
94
+ 'uuid': {'type': 'keyword'},
95
+ 'name': {'type': 'text'},
96
+ 'fact': {'type': 'text'},
97
+ 'group_id': {'type': 'text'},
98
+ }
99
+ }
100
+ },
101
+ 'query': {
102
+ 'query': {'multi_match': {'query': '', 'fields': ['name', 'fact', 'group_id']}},
103
+ 'size': DEFAULT_SIZE,
104
+ },
105
+ },
106
+ ]
107
+
108
+
109
+ class NeptuneDriver(GraphDriver):
110
+ provider: GraphProvider = GraphProvider.NEPTUNE
111
+
112
+ def __init__(self, host: str, aoss_host: str, port: int = 8182, aoss_port: int = 443):
113
+ """This initializes a NeptuneDriver for use with Neptune as a backend
114
+
115
+ Args:
116
+ host (str): The Neptune Database or Neptune Analytics host
117
+ aoss_host (str): The OpenSearch host value
118
+ port (int, optional): The Neptune Database port, ignored for Neptune Analytics. Defaults to 8182.
119
+ aoss_port (int, optional): The OpenSearch port. Defaults to 443.
120
+ """
121
+ if not host:
122
+ raise ValueError('You must provide an endpoint to create a NeptuneDriver')
123
+
124
+ if host.startswith('neptune-db://'):
125
+ # This is a Neptune Database Cluster
126
+ endpoint = host.replace('neptune-db://', '')
127
+ self.client = NeptuneGraph(endpoint, port)
128
+ logger.debug('Creating Neptune Database session for %s', host)
129
+ elif host.startswith('neptune-graph://'):
130
+ # This is a Neptune Analytics Graph
131
+ graphId = host.replace('neptune-graph://', '')
132
+ self.client = NeptuneAnalyticsGraph(graphId)
133
+ logger.debug('Creating Neptune Graph session for %s', host)
134
+ else:
135
+ raise ValueError(
136
+ 'You must provide an endpoint to create a NeptuneDriver as either neptune-db://<endpoint> or neptune-graph://<graphid>'
137
+ )
138
+
139
+ if not aoss_host:
140
+ raise ValueError('You must provide an AOSS endpoint to create an OpenSearch driver.')
141
+
142
+ session = boto3.Session()
143
+ self.aoss_client = OpenSearch(
144
+ hosts=[{'host': aoss_host, 'port': aoss_port}],
145
+ http_auth=Urllib3AWSV4SignerAuth(
146
+ session.get_credentials(), session.region_name, 'aoss'
147
+ ),
148
+ use_ssl=True,
149
+ verify_certs=True,
150
+ connection_class=Urllib3HttpConnection,
151
+ pool_maxsize=20,
152
+ )
153
+
154
+ def _sanitize_parameters(self, query, params: dict):
155
+ if isinstance(query, list):
156
+ queries = []
157
+ for q in query:
158
+ queries.append(self._sanitize_parameters(q, params))
159
+ return queries
160
+ else:
161
+ for k, v in params.items():
162
+ if isinstance(v, datetime.datetime):
163
+ params[k] = v.isoformat()
164
+ elif isinstance(v, list):
165
+ # Handle lists that might contain datetime objects
166
+ for i, item in enumerate(v):
167
+ if isinstance(item, datetime.datetime):
168
+ v[i] = item.isoformat()
169
+ query = str(query).replace(f'${k}', f'datetime(${k})')
170
+ if isinstance(item, dict):
171
+ query = self._sanitize_parameters(query, v[i])
172
+
173
+ # If the list contains datetime objects, we need to wrap each element with datetime()
174
+ if any(isinstance(item, str) and 'T' in item for item in v):
175
+ # Create a new list expression with datetime() wrapped around each element
176
+ datetime_list = (
177
+ '['
178
+ + ', '.join(
179
+ f'datetime("{item}")'
180
+ if isinstance(item, str) and 'T' in item
181
+ else repr(item)
182
+ for item in v
183
+ )
184
+ + ']'
185
+ )
186
+ query = str(query).replace(f'${k}', datetime_list)
187
+ elif isinstance(v, dict):
188
+ query = self._sanitize_parameters(query, v)
189
+ return query
190
+
191
+ async def execute_query(
192
+ self, cypher_query_, **kwargs: Any
193
+ ) -> tuple[dict[str, Any], None, None]:
194
+ params = dict(kwargs)
195
+ if isinstance(cypher_query_, list):
196
+ for q in cypher_query_:
197
+ result, _, _ = self._run_query(q[0], q[1])
198
+ return result, None, None
199
+ else:
200
+ return self._run_query(cypher_query_, params)
201
+
202
+ def _run_query(self, cypher_query_, params):
203
+ cypher_query_ = str(self._sanitize_parameters(cypher_query_, params))
204
+ try:
205
+ result = self.client.query(cypher_query_, params=params)
206
+ except Exception as e:
207
+ logger.error('Query: %s', cypher_query_)
208
+ logger.error('Parameters: %s', params)
209
+ logger.error('Error executing query: %s', e)
210
+ raise e
211
+
212
+ return result, None, None
213
+
214
+ def session(self, database: str | None = None) -> GraphDriverSession:
215
+ return NeptuneDriverSession(driver=self)
216
+
217
+ async def close(self) -> None:
218
+ return self.client.client.close()
219
+
220
+ async def _delete_all_data(self) -> Any:
221
+ return await self.execute_query('MATCH (n) DETACH DELETE n')
222
+
223
+ def delete_all_indexes(self) -> Coroutine[Any, Any, Any]:
224
+ return self.delete_all_indexes_impl()
225
+
226
+ async def delete_all_indexes_impl(self) -> Coroutine[Any, Any, Any]:
227
+ # No matter what happens above, always return True
228
+ return self.delete_aoss_indices()
229
+
230
+ async def create_aoss_indices(self):
231
+ for index in aoss_indices:
232
+ index_name = index['index_name']
233
+ client = self.aoss_client
234
+ if not client.indices.exists(index=index_name):
235
+ client.indices.create(index=index_name, body=index['body'])
236
+ # Sleep for 1 minute to let the index creation complete
237
+ await asyncio.sleep(60)
238
+
239
+ async def delete_aoss_indices(self):
240
+ for index in aoss_indices:
241
+ index_name = index['index_name']
242
+ client = self.aoss_client
243
+ if client.indices.exists(index=index_name):
244
+ client.indices.delete(index=index_name)
245
+
246
+ def run_aoss_query(self, name: str, query_text: str, limit: int = 10) -> dict[str, Any]:
247
+ for index in aoss_indices:
248
+ if name.lower() == index['index_name']:
249
+ index['query']['query']['multi_match']['query'] = query_text
250
+ query = {'size': limit, 'query': index['query']}
251
+ resp = self.aoss_client.search(body=query['query'], index=index['index_name'])
252
+ return resp
253
+ return {}
254
+
255
+ def save_to_aoss(self, name: str, data: list[dict]) -> int:
256
+ for index in aoss_indices:
257
+ if name.lower() == index['index_name']:
258
+ to_index = []
259
+ for d in data:
260
+ item = {'_index': name}
261
+ for p in index['body']['mappings']['properties']:
262
+ item[p] = d[p]
263
+ to_index.append(item)
264
+ success, failed = helpers.bulk(self.aoss_client, to_index, stats_only=True)
265
+ if failed > 0:
266
+ return success
267
+ else:
268
+ return 0
269
+
270
+ return 0
271
+
272
+
273
+ class NeptuneDriverSession(GraphDriverSession):
274
+ provider = GraphProvider.NEPTUNE
275
+
276
+ def __init__(self, driver: NeptuneDriver): # type: ignore[reportUnknownArgumentType]
277
+ self.driver = driver
278
+
279
+ async def __aenter__(self):
280
+ return self
281
+
282
+ async def __aexit__(self, exc_type, exc, tb):
283
+ # No cleanup needed for Neptune, but method must exist
284
+ pass
285
+
286
+ async def close(self):
287
+ # No explicit close needed for Neptune, but method must exist
288
+ pass
289
+
290
+ async def execute_write(self, func, *args, **kwargs):
291
+ # Directly await the provided async function with `self` as the transaction/session
292
+ return await func(self, *args, **kwargs)
293
+
294
+ async def run(self, query: str | list, **kwargs: Any) -> Any:
295
+ if isinstance(query, list):
296
+ res = None
297
+ for q in query:
298
+ res = await self.driver.execute_query(q, **kwargs)
299
+ return res
300
+ else:
301
+ return await self.driver.execute_query(str(query), **kwargs)