2025-06-13 12:06:57 -04:00
|
|
|
"""
|
|
|
|
|
Copyright 2024, Zep Software, Inc.
|
|
|
|
|
|
|
|
|
|
Licensed under the Apache License, Version 2.0 (the "License");
|
|
|
|
|
you may not use this file except in compliance with the License.
|
|
|
|
|
You may obtain a copy of the License at
|
|
|
|
|
|
|
|
|
|
http://www.apache.org/licenses/LICENSE-2.0
|
|
|
|
|
|
|
|
|
|
Unless required by applicable law or agreed to in writing, software
|
|
|
|
|
distributed under the License is distributed on an "AS IS" BASIS,
|
|
|
|
|
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
|
|
|
|
See the License for the specific language governing permissions and
|
|
|
|
|
limitations under the License.
|
|
|
|
|
"""
|
|
|
|
|
|
|
|
|
|
import logging
|
|
|
|
|
from datetime import datetime
|
2025-07-05 08:57:07 -07:00
|
|
|
from typing import TYPE_CHECKING, Any
|
2025-06-13 12:06:57 -04:00
|
|
|
|
2025-07-05 08:57:07 -07:00
|
|
|
if TYPE_CHECKING:
|
|
|
|
|
from falkordb import Graph as FalkorGraph
|
|
|
|
|
from falkordb.asyncio import FalkorDB
|
|
|
|
|
else:
|
|
|
|
|
try:
|
|
|
|
|
from falkordb import Graph as FalkorGraph
|
|
|
|
|
from falkordb.asyncio import FalkorDB
|
|
|
|
|
except ImportError:
|
|
|
|
|
# If falkordb is not installed, raise an ImportError
|
|
|
|
|
raise ImportError(
|
|
|
|
|
'falkordb is required for FalkorDriver. '
|
|
|
|
|
'Install it with: pip install graphiti-core[falkordb]'
|
|
|
|
|
) from None
|
2025-06-13 12:06:57 -04:00
|
|
|
|
|
|
|
|
from graphiti_core.driver.driver import GraphDriver, GraphDriverSession
|
|
|
|
|
|
|
|
|
|
logger = logging.getLogger(__name__)
|
|
|
|
|
|
|
|
|
|
|
2025-06-13 14:12:09 -04:00
|
|
|
class FalkorDriverSession(GraphDriverSession):
|
2025-06-13 12:06:57 -04:00
|
|
|
def __init__(self, graph: FalkorGraph):
|
|
|
|
|
self.graph = graph
|
|
|
|
|
|
|
|
|
|
async def __aenter__(self):
|
|
|
|
|
return self
|
|
|
|
|
|
|
|
|
|
async def __aexit__(self, exc_type, exc, tb):
|
|
|
|
|
# No cleanup needed for Falkor, but method must exist
|
|
|
|
|
pass
|
|
|
|
|
|
|
|
|
|
async def close(self):
|
|
|
|
|
# No explicit close needed for FalkorDB, but method must exist
|
|
|
|
|
pass
|
|
|
|
|
|
|
|
|
|
async def execute_write(self, func, *args, **kwargs):
|
|
|
|
|
# Directly await the provided async function with `self` as the transaction/session
|
|
|
|
|
return await func(self, *args, **kwargs)
|
|
|
|
|
|
2025-06-13 14:12:09 -04:00
|
|
|
async def run(self, query: str | list, **kwargs: Any) -> Any:
|
2025-06-13 12:06:57 -04:00
|
|
|
# FalkorDB does not support argument for Label Set, so it's converted into an array of queries
|
2025-06-13 14:12:09 -04:00
|
|
|
if isinstance(query, list):
|
|
|
|
|
for cypher, params in query:
|
2025-06-13 12:06:57 -04:00
|
|
|
params = convert_datetimes_to_strings(params)
|
2025-06-30 12:04:21 -07:00
|
|
|
await self.graph.query(str(cypher), params) # type: ignore[reportUnknownArgumentType]
|
2025-06-13 12:06:57 -04:00
|
|
|
else:
|
|
|
|
|
params = dict(kwargs)
|
|
|
|
|
params = convert_datetimes_to_strings(params)
|
2025-06-30 12:04:21 -07:00
|
|
|
await self.graph.query(str(query), params) # type: ignore[reportUnknownArgumentType]
|
2025-06-13 12:06:57 -04:00
|
|
|
# Assuming `graph.query` is async (ideal); otherwise, wrap in executor
|
|
|
|
|
return None
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
class FalkorDriver(GraphDriver):
|
|
|
|
|
provider: str = 'falkordb'
|
|
|
|
|
|
|
|
|
|
def __init__(
|
|
|
|
|
self,
|
2025-06-30 18:01:44 +03:00
|
|
|
host: str = 'localhost',
|
2025-06-30 12:55:05 -07:00
|
|
|
port: int = 6379,
|
2025-06-30 18:01:44 +03:00
|
|
|
username: str | None = None,
|
|
|
|
|
password: str | None = None,
|
|
|
|
|
falkor_db: FalkorDB | None = None,
|
2025-07-10 14:25:39 -07:00
|
|
|
database: str = 'default_db',
|
2025-06-13 12:06:57 -04:00
|
|
|
):
|
2025-06-30 18:01:44 +03:00
|
|
|
"""
|
|
|
|
|
Initialize the FalkorDB driver.
|
2025-06-13 12:06:57 -04:00
|
|
|
|
2025-06-30 12:55:05 -07:00
|
|
|
FalkorDB is a multi-tenant graph database.
|
|
|
|
|
To connect, provide the host and port.
|
2025-06-30 18:01:44 +03:00
|
|
|
The default parameters assume a local (on-premises) FalkorDB instance.
|
|
|
|
|
"""
|
|
|
|
|
super().__init__()
|
|
|
|
|
if falkor_db is not None:
|
|
|
|
|
# If a FalkorDB instance is provided, use it directly
|
|
|
|
|
self.client = falkor_db
|
|
|
|
|
else:
|
|
|
|
|
self.client = FalkorDB(host=host, port=port, username=username, password=password)
|
2025-07-10 14:25:39 -07:00
|
|
|
self._database = database
|
2025-06-13 12:06:57 -04:00
|
|
|
|
2025-06-13 14:12:09 -04:00
|
|
|
def _get_graph(self, graph_name: str | None) -> FalkorGraph:
|
2025-07-10 14:25:39 -07:00
|
|
|
# FalkorDB requires a non-None database name for multi-tenant graphs; the default is "default_db"
|
2025-06-13 12:06:57 -04:00
|
|
|
if graph_name is None:
|
2025-07-10 14:25:39 -07:00
|
|
|
graph_name = self._database
|
2025-06-13 12:06:57 -04:00
|
|
|
return self.client.select_graph(graph_name)
|
|
|
|
|
|
|
|
|
|
async def execute_query(self, cypher_query_, **kwargs: Any):
|
2025-07-10 14:25:39 -07:00
|
|
|
graph_name = kwargs.pop('database_', self._database)
|
2025-06-13 12:06:57 -04:00
|
|
|
graph = self._get_graph(graph_name)
|
|
|
|
|
|
|
|
|
|
# Convert datetime objects to ISO strings (FalkorDB does not support datetime objects directly)
|
|
|
|
|
params = convert_datetimes_to_strings(dict(kwargs))
|
|
|
|
|
|
|
|
|
|
try:
|
2025-06-30 12:04:21 -07:00
|
|
|
result = await graph.query(cypher_query_, params) # type: ignore[reportUnknownArgumentType]
|
2025-06-13 12:06:57 -04:00
|
|
|
except Exception as e:
|
|
|
|
|
if 'already indexed' in str(e):
|
|
|
|
|
# check if index already exists
|
|
|
|
|
logger.info(f'Index already exists: {e}')
|
|
|
|
|
return None
|
|
|
|
|
logger.error(f'Error executing FalkorDB query: {e}')
|
|
|
|
|
raise
|
|
|
|
|
|
|
|
|
|
# Convert the result header to a list of strings
|
2025-06-30 18:01:44 +03:00
|
|
|
header = [h[1] for h in result.header]
|
2025-06-30 12:55:05 -07:00
|
|
|
|
2025-06-30 18:01:44 +03:00
|
|
|
# Convert FalkorDB's result format (list of lists) to the format expected by Graphiti (list of dicts)
|
|
|
|
|
records = []
|
|
|
|
|
for row in result.result_set:
|
|
|
|
|
record = {}
|
|
|
|
|
for i, field_name in enumerate(header):
|
|
|
|
|
if i < len(row):
|
|
|
|
|
record[field_name] = row[i]
|
|
|
|
|
else:
|
|
|
|
|
# If there are more fields in header than values in row, set to None
|
|
|
|
|
record[field_name] = None
|
|
|
|
|
records.append(record)
|
2025-06-30 12:55:05 -07:00
|
|
|
|
2025-06-30 18:01:44 +03:00
|
|
|
return records, header, None
|
2025-06-13 12:06:57 -04:00
|
|
|
|
2025-07-10 14:25:39 -07:00
|
|
|
def session(self, database: str | None = None) -> GraphDriverSession:
|
2025-06-13 14:12:09 -04:00
|
|
|
return FalkorDriverSession(self._get_graph(database))
|
2025-06-13 12:06:57 -04:00
|
|
|
|
|
|
|
|
async def close(self) -> None:
|
2025-06-30 18:01:44 +03:00
|
|
|
"""Close the driver connection."""
|
|
|
|
|
if hasattr(self.client, 'aclose'):
|
2025-06-30 12:55:05 -07:00
|
|
|
await self.client.aclose() # type: ignore[reportUnknownMemberType]
|
2025-06-30 18:01:44 +03:00
|
|
|
elif hasattr(self.client.connection, 'aclose'):
|
|
|
|
|
await self.client.connection.aclose()
|
|
|
|
|
elif hasattr(self.client.connection, 'close'):
|
|
|
|
|
await self.client.connection.close()
|
|
|
|
|
|
2025-07-10 14:25:39 -07:00
|
|
|
async def delete_all_indexes(self, database_: str | None = None) -> None:
|
|
|
|
|
database = database_ or self._database
|
2025-06-30 18:01:44 +03:00
|
|
|
await self.execute_query(
|
2025-06-13 12:06:57 -04:00
|
|
|
'CALL db.indexes() YIELD name DROP INDEX name',
|
2025-07-10 14:25:39 -07:00
|
|
|
database_=database,
|
2025-06-13 12:06:57 -04:00
|
|
|
)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
def convert_datetimes_to_strings(obj):
|
|
|
|
|
if isinstance(obj, dict):
|
|
|
|
|
return {k: convert_datetimes_to_strings(v) for k, v in obj.items()}
|
|
|
|
|
elif isinstance(obj, list):
|
|
|
|
|
return [convert_datetimes_to_strings(item) for item in obj]
|
|
|
|
|
elif isinstance(obj, tuple):
|
|
|
|
|
return tuple(convert_datetimes_to_strings(item) for item in obj)
|
|
|
|
|
elif isinstance(obj, datetime):
|
|
|
|
|
return obj.isoformat()
|
|
|
|
|
else:
|
|
|
|
|
return obj
|