2024-08-23 13:01:33 -07: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.
|
|
|
|
|
"""
|
|
|
|
|
|
2024-08-22 12:26:13 -07:00
|
|
|
import logging
|
2024-08-13 14:35:43 -04:00
|
|
|
from abc import ABC, abstractmethod
|
2024-12-09 10:36:04 -08:00
|
|
|
from datetime import datetime
|
2024-08-26 10:30:22 -04:00
|
|
|
from enum import Enum
|
2024-08-22 12:26:13 -07:00
|
|
|
from time import time
|
2025-03-05 15:27:03 -05:00
|
|
|
from typing import Any
|
2024-08-15 12:03:41 -04:00
|
|
|
from uuid import uuid4
|
2024-08-14 10:17:12 -04:00
|
|
|
|
|
|
|
|
from pydantic import BaseModel, Field
|
2024-12-02 11:17:37 -05:00
|
|
|
from typing_extensions import LiteralString
|
2024-08-13 14:35:43 -04:00
|
|
|
|
2025-06-13 12:06:57 -04:00
|
|
|
from graphiti_core.driver.driver import GraphDriver
|
2024-09-27 12:47:04 -04:00
|
|
|
from graphiti_core.embedder import EmbedderClient
|
2024-09-11 12:53:17 -04:00
|
|
|
from graphiti_core.errors import NodeNotFoundError
|
2025-06-13 12:06:57 -04:00
|
|
|
from graphiti_core.helpers import DEFAULT_DATABASE, parse_db_date
|
2024-10-21 12:33:32 -04:00
|
|
|
from graphiti_core.models.nodes.node_db_queries import (
|
|
|
|
|
COMMUNITY_NODE_SAVE,
|
|
|
|
|
ENTITY_NODE_SAVE,
|
|
|
|
|
EPISODIC_NODE_SAVE,
|
|
|
|
|
)
|
2024-12-09 10:36:04 -08:00
|
|
|
from graphiti_core.utils.datetime_utils import utc_now
|
2024-08-18 13:22:31 -04:00
|
|
|
|
2024-08-13 14:35:43 -04:00
|
|
|
logger = logging.getLogger(__name__)
|
|
|
|
|
|
2025-04-20 23:20:19 -04:00
|
|
|
ENTITY_NODE_RETURN: LiteralString = """
|
|
|
|
|
RETURN
|
|
|
|
|
n.uuid As uuid,
|
|
|
|
|
n.name AS name,
|
|
|
|
|
n.group_id AS group_id,
|
|
|
|
|
n.created_at AS created_at,
|
|
|
|
|
n.summary AS summary,
|
|
|
|
|
labels(n) AS labels,
|
2025-04-22 12:03:09 -04:00
|
|
|
properties(n) AS attributes
|
|
|
|
|
"""
|
2025-04-20 23:20:19 -04:00
|
|
|
|
2024-08-13 14:35:43 -04:00
|
|
|
|
2024-08-26 10:30:22 -04:00
|
|
|
class EpisodeType(Enum):
|
2024-08-26 13:11:50 -04:00
|
|
|
"""
|
|
|
|
|
Enumeration of different types of episodes that can be processed.
|
|
|
|
|
|
|
|
|
|
This enum defines the various sources or formats of episodes that the system
|
|
|
|
|
can handle. It's used to categorize and potentially handle different types
|
|
|
|
|
of input data differently.
|
|
|
|
|
|
|
|
|
|
Attributes:
|
|
|
|
|
-----------
|
|
|
|
|
message : str
|
|
|
|
|
Represents a standard message-type episode. The content for this type
|
|
|
|
|
should be formatted as "actor: content". For example, "user: Hello, how are you?"
|
|
|
|
|
or "assistant: I'm doing well, thank you for asking."
|
|
|
|
|
json : str
|
|
|
|
|
Represents an episode containing a JSON string object with structured data.
|
2024-08-26 15:51:13 -07:00
|
|
|
text : str
|
|
|
|
|
Represents a plain text episode.
|
2024-08-26 13:11:50 -04:00
|
|
|
"""
|
|
|
|
|
|
2024-08-26 10:30:22 -04:00
|
|
|
message = 'message'
|
|
|
|
|
json = 'json'
|
2024-08-26 15:51:13 -07:00
|
|
|
text = 'text'
|
2024-08-26 10:30:22 -04:00
|
|
|
|
|
|
|
|
@staticmethod
|
|
|
|
|
def from_str(episode_type: str):
|
|
|
|
|
if episode_type == 'message':
|
|
|
|
|
return EpisodeType.message
|
|
|
|
|
if episode_type == 'json':
|
|
|
|
|
return EpisodeType.json
|
2024-08-26 15:51:13 -07:00
|
|
|
if episode_type == 'text':
|
|
|
|
|
return EpisodeType.text
|
2024-08-26 10:30:22 -04:00
|
|
|
logger.error(f'Episode type: {episode_type} not implemented')
|
|
|
|
|
raise NotImplementedError
|
|
|
|
|
|
|
|
|
|
|
2024-08-13 14:35:43 -04:00
|
|
|
class Node(BaseModel, ABC):
|
2024-09-18 12:48:44 -04:00
|
|
|
uuid: str = Field(default_factory=lambda: str(uuid4()))
|
2024-08-26 20:00:28 -07:00
|
|
|
name: str = Field(description='name of the node')
|
2024-09-24 15:55:30 -04:00
|
|
|
group_id: str = Field(description='partition of the graph')
|
2024-08-23 14:18:45 -04:00
|
|
|
labels: list[str] = Field(default_factory=list)
|
2024-12-09 10:36:04 -08:00
|
|
|
created_at: datetime = Field(default_factory=lambda: utc_now())
|
2024-08-13 14:35:43 -04:00
|
|
|
|
2024-08-23 14:18:45 -04:00
|
|
|
@abstractmethod
|
2025-06-13 12:06:57 -04:00
|
|
|
async def save(self, driver: GraphDriver): ...
|
2024-08-13 14:35:43 -04:00
|
|
|
|
2025-06-13 12:06:57 -04:00
|
|
|
async def delete(self, driver: GraphDriver):
|
2024-09-11 12:06:35 -04:00
|
|
|
result = await driver.execute_query(
|
|
|
|
|
"""
|
2024-11-18 13:55:18 -05:00
|
|
|
MATCH (n:Entity|Episodic|Community {uuid: $uuid})
|
2024-09-11 12:06:35 -04:00
|
|
|
DETACH DELETE n
|
|
|
|
|
""",
|
|
|
|
|
uuid=self.uuid,
|
2024-10-22 10:01:56 -04:00
|
|
|
database_=DEFAULT_DATABASE,
|
2024-09-11 12:06:35 -04:00
|
|
|
)
|
|
|
|
|
|
2024-10-11 16:38:56 -04:00
|
|
|
logger.debug(f'Deleted Node: {self.uuid}')
|
2024-09-11 12:06:35 -04:00
|
|
|
|
|
|
|
|
return result
|
2024-08-27 16:18:01 -04:00
|
|
|
|
2024-08-23 14:18:45 -04:00
|
|
|
def __hash__(self):
|
|
|
|
|
return hash(self.uuid)
|
2024-08-16 09:29:57 -04:00
|
|
|
|
2024-08-23 14:18:45 -04:00
|
|
|
def __eq__(self, other):
|
|
|
|
|
if isinstance(other, Node):
|
|
|
|
|
return self.uuid == other.uuid
|
|
|
|
|
return False
|
2024-08-16 09:29:57 -04:00
|
|
|
|
2024-11-18 13:55:18 -05:00
|
|
|
@classmethod
|
2025-06-13 12:06:57 -04:00
|
|
|
async def delete_by_group_id(cls, driver: GraphDriver, group_id: str):
|
2024-11-18 13:55:18 -05:00
|
|
|
await driver.execute_query(
|
|
|
|
|
"""
|
|
|
|
|
MATCH (n:Entity|Episodic|Community {group_id: $group_id})
|
|
|
|
|
DETACH DELETE n
|
|
|
|
|
""",
|
|
|
|
|
group_id=group_id,
|
|
|
|
|
database_=DEFAULT_DATABASE,
|
|
|
|
|
)
|
|
|
|
|
|
|
|
|
|
return 'SUCCESS'
|
|
|
|
|
|
2024-08-27 16:18:01 -04:00
|
|
|
@classmethod
|
2025-06-13 12:06:57 -04:00
|
|
|
async def get_by_uuid(cls, driver: GraphDriver, uuid: str): ...
|
2024-08-27 16:18:01 -04:00
|
|
|
|
2024-09-11 12:06:35 -04:00
|
|
|
@classmethod
|
2025-06-13 12:06:57 -04:00
|
|
|
async def get_by_uuids(cls, driver: GraphDriver, uuids: list[str]): ...
|
2024-09-11 12:06:35 -04:00
|
|
|
|
2024-08-13 14:35:43 -04:00
|
|
|
|
|
|
|
|
class EpisodicNode(Node):
|
2024-08-26 10:30:22 -04:00
|
|
|
source: EpisodeType = Field(description='source type')
|
2024-08-23 14:18:45 -04:00
|
|
|
source_description: str = Field(description='description of the data source')
|
|
|
|
|
content: str = Field(description='raw episode data')
|
|
|
|
|
valid_at: datetime = Field(
|
|
|
|
|
description='datetime of when the original document was created',
|
|
|
|
|
)
|
|
|
|
|
entity_edges: list[str] = Field(
|
|
|
|
|
description='list of entity edges referenced in this episode',
|
|
|
|
|
default_factory=list,
|
|
|
|
|
)
|
|
|
|
|
|
2025-06-13 12:06:57 -04:00
|
|
|
async def save(self, driver: GraphDriver):
|
2024-08-23 14:18:45 -04:00
|
|
|
result = await driver.execute_query(
|
2024-10-21 12:33:32 -04:00
|
|
|
EPISODIC_NODE_SAVE,
|
2024-08-23 14:18:45 -04:00
|
|
|
uuid=self.uuid,
|
|
|
|
|
name=self.name,
|
2024-09-06 12:33:42 -04:00
|
|
|
group_id=self.group_id,
|
2024-08-23 14:18:45 -04:00
|
|
|
source_description=self.source_description,
|
|
|
|
|
content=self.content,
|
|
|
|
|
entity_edges=self.entity_edges,
|
|
|
|
|
created_at=self.created_at,
|
|
|
|
|
valid_at=self.valid_at,
|
2024-08-26 10:30:22 -04:00
|
|
|
source=self.source.value,
|
2024-10-22 10:01:56 -04:00
|
|
|
database_=DEFAULT_DATABASE,
|
2024-08-23 14:18:45 -04:00
|
|
|
)
|
2024-08-14 10:17:12 -04:00
|
|
|
|
2025-06-13 12:06:57 -04:00
|
|
|
logger.debug(f'Saved Node to Graph: {self.uuid}')
|
2024-08-13 14:35:43 -04:00
|
|
|
|
2024-08-23 14:18:45 -04:00
|
|
|
return result
|
2024-08-13 14:35:43 -04:00
|
|
|
|
2024-09-11 12:06:35 -04:00
|
|
|
@classmethod
|
2025-06-13 12:06:57 -04:00
|
|
|
async def get_by_uuid(cls, driver: GraphDriver, uuid: str):
|
2024-09-11 12:06:35 -04:00
|
|
|
records, _, _ = await driver.execute_query(
|
2024-08-27 16:18:01 -04:00
|
|
|
"""
|
2024-09-11 12:06:35 -04:00
|
|
|
MATCH (e:Episodic {uuid: $uuid})
|
|
|
|
|
RETURN e.content AS content,
|
|
|
|
|
e.created_at AS created_at,
|
|
|
|
|
e.valid_at AS valid_at,
|
|
|
|
|
e.uuid AS uuid,
|
|
|
|
|
e.name AS name,
|
2024-09-11 12:53:17 -04:00
|
|
|
e.group_id AS group_id,
|
2024-09-11 12:06:35 -04:00
|
|
|
e.source_description AS source_description,
|
2025-02-05 15:17:08 -05:00
|
|
|
e.source AS source,
|
|
|
|
|
e.entity_edges AS entity_edges
|
2024-08-27 16:18:01 -04:00
|
|
|
""",
|
2024-09-11 12:06:35 -04:00
|
|
|
uuid=uuid,
|
2024-10-22 10:01:56 -04:00
|
|
|
database_=DEFAULT_DATABASE,
|
2024-11-18 13:55:18 -05:00
|
|
|
routing_='r',
|
2024-08-27 16:18:01 -04:00
|
|
|
)
|
|
|
|
|
|
2024-09-11 12:06:35 -04:00
|
|
|
episodes = [get_episodic_node_from_record(record) for record in records]
|
2024-08-27 16:18:01 -04:00
|
|
|
|
2024-09-11 12:53:17 -04:00
|
|
|
if len(episodes) == 0:
|
|
|
|
|
raise NodeNotFoundError(uuid)
|
|
|
|
|
|
2024-09-11 12:06:35 -04:00
|
|
|
return episodes[0]
|
2024-08-27 16:18:01 -04:00
|
|
|
|
|
|
|
|
@classmethod
|
2025-06-13 12:06:57 -04:00
|
|
|
async def get_by_uuids(cls, driver: GraphDriver, uuids: list[str]):
|
2024-08-27 16:18:01 -04:00
|
|
|
records, _, _ = await driver.execute_query(
|
|
|
|
|
"""
|
2024-09-11 12:06:35 -04:00
|
|
|
MATCH (e:Episodic) WHERE e.uuid IN $uuids
|
2024-09-18 15:44:28 -04:00
|
|
|
RETURN DISTINCT
|
|
|
|
|
e.content AS content,
|
2024-09-06 12:33:42 -04:00
|
|
|
e.created_at AS created_at,
|
|
|
|
|
e.valid_at AS valid_at,
|
|
|
|
|
e.uuid AS uuid,
|
|
|
|
|
e.name AS name,
|
2024-09-17 12:19:20 -04:00
|
|
|
e.group_id AS group_id,
|
2024-09-06 12:33:42 -04:00
|
|
|
e.source_description AS source_description,
|
2025-02-05 15:17:08 -05:00
|
|
|
e.source AS source,
|
|
|
|
|
e.entity_edges AS entity_edges
|
2024-08-27 16:18:01 -04:00
|
|
|
""",
|
2024-09-11 12:06:35 -04:00
|
|
|
uuids=uuids,
|
2024-10-22 10:01:56 -04:00
|
|
|
database_=DEFAULT_DATABASE,
|
2024-11-18 13:55:18 -05:00
|
|
|
routing_='r',
|
2024-08-27 16:18:01 -04:00
|
|
|
)
|
|
|
|
|
|
2024-09-06 12:33:42 -04:00
|
|
|
episodes = [get_episodic_node_from_record(record) for record in records]
|
2024-08-27 16:18:01 -04:00
|
|
|
|
2024-09-19 16:16:40 -04:00
|
|
|
return episodes
|
|
|
|
|
|
|
|
|
|
@classmethod
|
2024-12-02 11:17:37 -05:00
|
|
|
async def get_by_group_ids(
|
|
|
|
|
cls,
|
2025-06-13 12:06:57 -04:00
|
|
|
driver: GraphDriver,
|
2024-12-02 11:17:37 -05:00
|
|
|
group_ids: list[str],
|
2024-12-06 12:46:50 -05:00
|
|
|
limit: int | None = None,
|
2025-04-08 17:59:40 -04:00
|
|
|
uuid_cursor: str | None = None,
|
2024-12-02 11:17:37 -05:00
|
|
|
):
|
2025-04-08 17:59:40 -04:00
|
|
|
cursor_query: LiteralString = 'AND e.uuid < $uuid' if uuid_cursor else ''
|
2024-12-06 12:46:50 -05:00
|
|
|
limit_query: LiteralString = 'LIMIT $limit' if limit is not None else ''
|
2024-12-02 11:17:37 -05:00
|
|
|
|
2024-09-19 16:16:40 -04:00
|
|
|
records, _, _ = await driver.execute_query(
|
|
|
|
|
"""
|
|
|
|
|
MATCH (e:Episodic) WHERE e.group_id IN $group_ids
|
2024-12-02 11:17:37 -05:00
|
|
|
"""
|
|
|
|
|
+ cursor_query
|
|
|
|
|
+ """
|
2024-09-19 16:16:40 -04:00
|
|
|
RETURN DISTINCT
|
|
|
|
|
e.content AS content,
|
|
|
|
|
e.created_at AS created_at,
|
|
|
|
|
e.valid_at AS valid_at,
|
|
|
|
|
e.uuid AS uuid,
|
|
|
|
|
e.name AS name,
|
|
|
|
|
e.group_id AS group_id,
|
|
|
|
|
e.source_description AS source_description,
|
2025-02-05 15:17:08 -05:00
|
|
|
e.source AS source,
|
|
|
|
|
e.entity_edges AS entity_edges
|
2025-04-08 17:59:40 -04:00
|
|
|
ORDER BY e.uuid DESC
|
2024-12-06 12:46:50 -05:00
|
|
|
"""
|
|
|
|
|
+ limit_query,
|
2024-09-19 16:16:40 -04:00
|
|
|
group_ids=group_ids,
|
2025-04-08 17:59:40 -04:00
|
|
|
uuid=uuid_cursor,
|
2024-12-02 11:17:37 -05:00
|
|
|
limit=limit,
|
2024-10-22 10:01:56 -04:00
|
|
|
database_=DEFAULT_DATABASE,
|
2024-11-18 13:55:18 -05:00
|
|
|
routing_='r',
|
2024-09-19 16:16:40 -04:00
|
|
|
)
|
2025-04-15 12:37:23 -04:00
|
|
|
|
|
|
|
|
episodes = [get_episodic_node_from_record(record) for record in records]
|
|
|
|
|
|
|
|
|
|
return episodes
|
|
|
|
|
|
2025-04-22 12:03:09 -04:00
|
|
|
@classmethod
|
2025-06-13 12:06:57 -04:00
|
|
|
async def get_by_entity_node_uuid(cls, driver: GraphDriver, entity_node_uuid: str):
|
2025-04-22 12:03:09 -04:00
|
|
|
records, _, _ = await driver.execute_query(
|
|
|
|
|
"""
|
|
|
|
|
MATCH (e:Episodic)-[r:MENTIONS]->(n:Entity {uuid: $entity_node_uuid})
|
|
|
|
|
RETURN DISTINCT
|
|
|
|
|
e.content AS content,
|
|
|
|
|
e.created_at AS created_at,
|
|
|
|
|
e.valid_at AS valid_at,
|
|
|
|
|
e.uuid AS uuid,
|
|
|
|
|
e.name AS name,
|
|
|
|
|
e.group_id AS group_id,
|
|
|
|
|
e.source_description AS source_description,
|
|
|
|
|
e.source AS source,
|
|
|
|
|
e.entity_edges AS entity_edges
|
|
|
|
|
""",
|
|
|
|
|
entity_node_uuid=entity_node_uuid,
|
|
|
|
|
database_=DEFAULT_DATABASE,
|
|
|
|
|
routing_='r',
|
|
|
|
|
)
|
|
|
|
|
|
|
|
|
|
episodes = [get_episodic_node_from_record(record) for record in records]
|
|
|
|
|
|
|
|
|
|
return episodes
|
|
|
|
|
|
2024-08-13 14:35:43 -04:00
|
|
|
|
2024-08-15 11:04:57 -04:00
|
|
|
class EntityNode(Node):
|
2024-08-23 14:18:45 -04:00
|
|
|
name_embedding: list[float] | None = Field(default=None, description='embedding of the name')
|
|
|
|
|
summary: str = Field(description='regional summary of surrounding edges', default_factory=str)
|
2025-02-13 12:17:52 -05:00
|
|
|
attributes: dict[str, Any] = Field(
|
|
|
|
|
default={}, description='Additional attributes of the node. Dependent on node labels'
|
|
|
|
|
)
|
2024-08-22 13:06:42 -07:00
|
|
|
|
2024-09-27 12:47:04 -04:00
|
|
|
async def generate_name_embedding(self, embedder: EmbedderClient):
|
2024-08-23 14:18:45 -04:00
|
|
|
start = time()
|
|
|
|
|
text = self.name.replace('\n', ' ')
|
2024-10-29 11:03:31 -04:00
|
|
|
self.name_embedding = await embedder.create(input_data=[text])
|
2024-08-23 14:18:45 -04:00
|
|
|
end = time()
|
2024-10-11 16:38:56 -04:00
|
|
|
logger.debug(f'embedded {text} in {end - start} ms')
|
2024-08-22 13:06:42 -07:00
|
|
|
|
2024-09-27 12:47:04 -04:00
|
|
|
return self.name_embedding
|
2024-08-22 13:06:42 -07:00
|
|
|
|
2025-06-13 12:06:57 -04:00
|
|
|
async def load_name_embedding(self, driver: GraphDriver):
|
2025-05-07 20:08:30 -04:00
|
|
|
query: LiteralString = """
|
|
|
|
|
MATCH (n:Entity {uuid: $uuid})
|
|
|
|
|
RETURN n.name_embedding AS name_embedding
|
|
|
|
|
"""
|
|
|
|
|
records, _, _ = await driver.execute_query(
|
|
|
|
|
query, uuid=self.uuid, database_=DEFAULT_DATABASE, routing_='r'
|
|
|
|
|
)
|
|
|
|
|
|
|
|
|
|
if len(records) == 0:
|
|
|
|
|
raise NodeNotFoundError(self.uuid)
|
|
|
|
|
|
|
|
|
|
self.name_embedding = records[0]['name_embedding']
|
|
|
|
|
|
2025-06-13 12:06:57 -04:00
|
|
|
async def save(self, driver: GraphDriver):
|
2025-02-13 12:17:52 -05:00
|
|
|
entity_data: dict[str, Any] = {
|
|
|
|
|
'uuid': self.uuid,
|
|
|
|
|
'name': self.name,
|
|
|
|
|
'name_embedding': self.name_embedding,
|
|
|
|
|
'group_id': self.group_id,
|
|
|
|
|
'summary': self.summary,
|
|
|
|
|
'created_at': self.created_at,
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
entity_data.update(self.attributes or {})
|
|
|
|
|
|
2024-08-23 14:18:45 -04:00
|
|
|
result = await driver.execute_query(
|
2024-10-21 12:33:32 -04:00
|
|
|
ENTITY_NODE_SAVE,
|
2025-02-13 12:17:52 -05:00
|
|
|
labels=self.labels + ['Entity'],
|
|
|
|
|
entity_data=entity_data,
|
2024-10-22 10:01:56 -04:00
|
|
|
database_=DEFAULT_DATABASE,
|
2024-08-23 14:18:45 -04:00
|
|
|
)
|
2024-08-13 14:35:43 -04:00
|
|
|
|
2025-06-13 12:06:57 -04:00
|
|
|
logger.debug(f'Saved Node to Graph: {self.uuid}')
|
2024-08-13 14:35:43 -04:00
|
|
|
|
2024-08-23 14:18:45 -04:00
|
|
|
return result
|
2024-08-27 16:18:01 -04:00
|
|
|
|
2024-09-11 12:06:35 -04:00
|
|
|
@classmethod
|
2025-06-13 12:06:57 -04:00
|
|
|
async def get_by_uuid(cls, driver: GraphDriver, uuid: str):
|
2025-04-20 23:20:19 -04:00
|
|
|
query = (
|
2024-08-27 16:18:01 -04:00
|
|
|
"""
|
2025-06-13 14:12:09 -04:00
|
|
|
MATCH (n:Entity {uuid: $uuid})
|
|
|
|
|
"""
|
2025-04-20 23:20:19 -04:00
|
|
|
+ ENTITY_NODE_RETURN
|
|
|
|
|
)
|
|
|
|
|
records, _, _ = await driver.execute_query(
|
|
|
|
|
query,
|
2024-09-11 12:06:35 -04:00
|
|
|
uuid=uuid,
|
2024-10-22 10:01:56 -04:00
|
|
|
database_=DEFAULT_DATABASE,
|
2024-11-18 13:55:18 -05:00
|
|
|
routing_='r',
|
2024-09-11 12:06:35 -04:00
|
|
|
)
|
|
|
|
|
|
|
|
|
|
nodes = [get_entity_node_from_record(record) for record in records]
|
|
|
|
|
|
2024-10-14 21:54:33 -04:00
|
|
|
if len(nodes) == 0:
|
|
|
|
|
raise NodeNotFoundError(uuid)
|
|
|
|
|
|
2024-09-11 12:06:35 -04:00
|
|
|
return nodes[0]
|
|
|
|
|
|
|
|
|
|
@classmethod
|
2025-06-13 12:06:57 -04:00
|
|
|
async def get_by_uuids(cls, driver: GraphDriver, uuids: list[str]):
|
2024-09-11 12:06:35 -04:00
|
|
|
records, _, _ = await driver.execute_query(
|
|
|
|
|
"""
|
|
|
|
|
MATCH (n:Entity) WHERE n.uuid IN $uuids
|
2025-04-20 23:20:19 -04:00
|
|
|
"""
|
|
|
|
|
+ ENTITY_NODE_RETURN,
|
2024-09-11 12:06:35 -04:00
|
|
|
uuids=uuids,
|
2024-10-22 10:01:56 -04:00
|
|
|
database_=DEFAULT_DATABASE,
|
2024-11-18 13:55:18 -05:00
|
|
|
routing_='r',
|
2024-09-11 12:06:35 -04:00
|
|
|
)
|
|
|
|
|
|
|
|
|
|
nodes = [get_entity_node_from_record(record) for record in records]
|
|
|
|
|
|
2024-09-19 16:16:40 -04:00
|
|
|
return nodes
|
|
|
|
|
|
|
|
|
|
@classmethod
|
2024-12-02 11:17:37 -05:00
|
|
|
async def get_by_group_ids(
|
|
|
|
|
cls,
|
2025-06-13 12:06:57 -04:00
|
|
|
driver: GraphDriver,
|
2024-12-02 11:17:37 -05:00
|
|
|
group_ids: list[str],
|
2024-12-06 12:46:50 -05:00
|
|
|
limit: int | None = None,
|
2025-04-08 17:59:40 -04:00
|
|
|
uuid_cursor: str | None = None,
|
2024-12-02 11:17:37 -05:00
|
|
|
):
|
2025-04-08 17:59:40 -04:00
|
|
|
cursor_query: LiteralString = 'AND n.uuid < $uuid' if uuid_cursor else ''
|
2024-12-06 12:46:50 -05:00
|
|
|
limit_query: LiteralString = 'LIMIT $limit' if limit is not None else ''
|
2024-12-02 11:17:37 -05:00
|
|
|
|
2024-09-19 16:16:40 -04:00
|
|
|
records, _, _ = await driver.execute_query(
|
|
|
|
|
"""
|
|
|
|
|
MATCH (n:Entity) WHERE n.group_id IN $group_ids
|
2024-12-02 11:17:37 -05:00
|
|
|
"""
|
|
|
|
|
+ cursor_query
|
2025-04-20 23:20:19 -04:00
|
|
|
+ ENTITY_NODE_RETURN
|
2024-12-02 11:17:37 -05:00
|
|
|
+ """
|
2025-04-08 17:59:40 -04:00
|
|
|
ORDER BY n.uuid DESC
|
2024-12-06 12:46:50 -05:00
|
|
|
"""
|
|
|
|
|
+ limit_query,
|
2024-09-19 16:16:40 -04:00
|
|
|
group_ids=group_ids,
|
2025-04-08 17:59:40 -04:00
|
|
|
uuid=uuid_cursor,
|
2024-12-02 11:17:37 -05:00
|
|
|
limit=limit,
|
2024-10-22 10:01:56 -04:00
|
|
|
database_=DEFAULT_DATABASE,
|
2024-11-18 13:55:18 -05:00
|
|
|
routing_='r',
|
2024-09-19 16:16:40 -04:00
|
|
|
)
|
|
|
|
|
|
|
|
|
|
nodes = [get_entity_node_from_record(record) for record in records]
|
2024-09-11 12:06:35 -04:00
|
|
|
|
|
|
|
|
return nodes
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
class CommunityNode(Node):
|
|
|
|
|
name_embedding: list[float] | None = Field(default=None, description='embedding of the name')
|
|
|
|
|
summary: str = Field(description='region summary of member nodes', default_factory=str)
|
|
|
|
|
|
2025-06-13 12:06:57 -04:00
|
|
|
async def save(self, driver: GraphDriver):
|
2024-09-11 12:06:35 -04:00
|
|
|
result = await driver.execute_query(
|
2024-10-21 12:33:32 -04:00
|
|
|
COMMUNITY_NODE_SAVE,
|
2024-08-27 16:18:01 -04:00
|
|
|
uuid=self.uuid,
|
2024-09-11 12:06:35 -04:00
|
|
|
name=self.name,
|
|
|
|
|
group_id=self.group_id,
|
|
|
|
|
summary=self.summary,
|
|
|
|
|
name_embedding=self.name_embedding,
|
|
|
|
|
created_at=self.created_at,
|
2024-10-22 10:01:56 -04:00
|
|
|
database_=DEFAULT_DATABASE,
|
2024-08-27 16:18:01 -04:00
|
|
|
)
|
|
|
|
|
|
2025-06-13 12:06:57 -04:00
|
|
|
logger.debug(f'Saved Node to Graph: {self.uuid}')
|
2024-08-27 16:18:01 -04:00
|
|
|
|
|
|
|
|
return result
|
|
|
|
|
|
2024-09-27 12:47:04 -04:00
|
|
|
async def generate_name_embedding(self, embedder: EmbedderClient):
|
2024-09-11 12:06:35 -04:00
|
|
|
start = time()
|
|
|
|
|
text = self.name.replace('\n', ' ')
|
2024-10-29 11:03:31 -04:00
|
|
|
self.name_embedding = await embedder.create(input_data=[text])
|
2024-09-11 12:06:35 -04:00
|
|
|
end = time()
|
2024-10-11 16:38:56 -04:00
|
|
|
logger.debug(f'embedded {text} in {end - start} ms')
|
2024-09-11 12:06:35 -04:00
|
|
|
|
2024-09-27 12:47:04 -04:00
|
|
|
return self.name_embedding
|
2024-09-11 12:06:35 -04:00
|
|
|
|
2025-06-13 12:06:57 -04:00
|
|
|
async def load_name_embedding(self, driver: GraphDriver):
|
2025-05-07 20:08:30 -04:00
|
|
|
query: LiteralString = """
|
|
|
|
|
MATCH (c:Community {uuid: $uuid})
|
|
|
|
|
RETURN c.name_embedding AS name_embedding
|
|
|
|
|
"""
|
|
|
|
|
records, _, _ = await driver.execute_query(
|
|
|
|
|
query, uuid=self.uuid, database_=DEFAULT_DATABASE, routing_='r'
|
|
|
|
|
)
|
|
|
|
|
|
|
|
|
|
if len(records) == 0:
|
|
|
|
|
raise NodeNotFoundError(self.uuid)
|
|
|
|
|
|
|
|
|
|
self.name_embedding = records[0]['name_embedding']
|
|
|
|
|
|
2024-08-27 16:18:01 -04:00
|
|
|
@classmethod
|
2025-06-13 12:06:57 -04:00
|
|
|
async def get_by_uuid(cls, driver: GraphDriver, uuid: str):
|
2024-08-27 16:18:01 -04:00
|
|
|
records, _, _ = await driver.execute_query(
|
|
|
|
|
"""
|
2024-09-11 12:06:35 -04:00
|
|
|
MATCH (n:Community {uuid: $uuid})
|
2024-08-27 16:18:01 -04:00
|
|
|
RETURN
|
|
|
|
|
n.uuid As uuid,
|
2024-09-05 14:09:19 -04:00
|
|
|
n.name AS name,
|
2024-09-17 12:19:20 -04:00
|
|
|
n.group_id AS group_id,
|
2024-08-27 16:18:01 -04:00
|
|
|
n.created_at AS created_at,
|
|
|
|
|
n.summary AS summary
|
|
|
|
|
""",
|
|
|
|
|
uuid=uuid,
|
2024-10-22 10:01:56 -04:00
|
|
|
database_=DEFAULT_DATABASE,
|
2024-11-18 13:55:18 -05:00
|
|
|
routing_='r',
|
2024-08-27 16:18:01 -04:00
|
|
|
)
|
|
|
|
|
|
2024-09-11 12:06:35 -04:00
|
|
|
nodes = [get_community_node_from_record(record) for record in records]
|
2024-08-27 16:18:01 -04:00
|
|
|
|
2024-10-14 21:54:33 -04:00
|
|
|
if len(nodes) == 0:
|
|
|
|
|
raise NodeNotFoundError(uuid)
|
|
|
|
|
|
2024-08-27 16:18:01 -04:00
|
|
|
return nodes[0]
|
2024-09-05 14:09:19 -04:00
|
|
|
|
2024-09-11 12:06:35 -04:00
|
|
|
@classmethod
|
2025-06-13 12:06:57 -04:00
|
|
|
async def get_by_uuids(cls, driver: GraphDriver, uuids: list[str]):
|
2024-09-11 12:06:35 -04:00
|
|
|
records, _, _ = await driver.execute_query(
|
|
|
|
|
"""
|
|
|
|
|
MATCH (n:Community) WHERE n.uuid IN $uuids
|
|
|
|
|
RETURN
|
|
|
|
|
n.uuid As uuid,
|
|
|
|
|
n.name AS name,
|
2024-09-17 12:19:20 -04:00
|
|
|
n.group_id AS group_id,
|
2024-09-11 12:06:35 -04:00
|
|
|
n.created_at AS created_at,
|
|
|
|
|
n.summary AS summary
|
|
|
|
|
""",
|
|
|
|
|
uuids=uuids,
|
2024-10-22 10:01:56 -04:00
|
|
|
database_=DEFAULT_DATABASE,
|
2024-11-18 13:55:18 -05:00
|
|
|
routing_='r',
|
2024-09-11 12:06:35 -04:00
|
|
|
)
|
|
|
|
|
|
2024-09-19 16:16:40 -04:00
|
|
|
communities = [get_community_node_from_record(record) for record in records]
|
2024-09-11 12:06:35 -04:00
|
|
|
|
2024-09-19 16:16:40 -04:00
|
|
|
return communities
|
2024-09-11 12:06:35 -04:00
|
|
|
|
2024-09-19 16:16:40 -04:00
|
|
|
@classmethod
|
2024-12-02 11:17:37 -05:00
|
|
|
async def get_by_group_ids(
|
|
|
|
|
cls,
|
2025-06-13 12:06:57 -04:00
|
|
|
driver: GraphDriver,
|
2024-12-02 11:17:37 -05:00
|
|
|
group_ids: list[str],
|
2024-12-06 12:46:50 -05:00
|
|
|
limit: int | None = None,
|
2025-04-08 17:59:40 -04:00
|
|
|
uuid_cursor: str | None = None,
|
2024-12-02 11:17:37 -05:00
|
|
|
):
|
2025-04-08 17:59:40 -04:00
|
|
|
cursor_query: LiteralString = 'AND n.uuid < $uuid' if uuid_cursor else ''
|
2024-12-06 12:46:50 -05:00
|
|
|
limit_query: LiteralString = 'LIMIT $limit' if limit is not None else ''
|
2024-12-02 11:17:37 -05:00
|
|
|
|
2024-09-19 16:16:40 -04:00
|
|
|
records, _, _ = await driver.execute_query(
|
|
|
|
|
"""
|
|
|
|
|
MATCH (n:Community) WHERE n.group_id IN $group_ids
|
2024-12-02 11:17:37 -05:00
|
|
|
"""
|
|
|
|
|
+ cursor_query
|
|
|
|
|
+ """
|
2024-09-19 16:16:40 -04:00
|
|
|
RETURN
|
|
|
|
|
n.uuid As uuid,
|
|
|
|
|
n.name AS name,
|
|
|
|
|
n.group_id AS group_id,
|
|
|
|
|
n.created_at AS created_at,
|
|
|
|
|
n.summary AS summary
|
2025-04-08 17:59:40 -04:00
|
|
|
ORDER BY n.uuid DESC
|
2024-12-06 12:46:50 -05:00
|
|
|
"""
|
|
|
|
|
+ limit_query,
|
2024-09-19 16:16:40 -04:00
|
|
|
group_ids=group_ids,
|
2025-04-08 17:59:40 -04:00
|
|
|
uuid=uuid_cursor,
|
2024-12-02 11:17:37 -05:00
|
|
|
limit=limit,
|
2024-10-22 10:01:56 -04:00
|
|
|
database_=DEFAULT_DATABASE,
|
2024-11-18 13:55:18 -05:00
|
|
|
routing_='r',
|
2024-09-19 16:16:40 -04:00
|
|
|
)
|
|
|
|
|
|
|
|
|
|
communities = [get_community_node_from_record(record) for record in records]
|
|
|
|
|
|
|
|
|
|
return communities
|
2024-09-11 12:06:35 -04:00
|
|
|
|
2024-09-05 14:09:19 -04:00
|
|
|
|
|
|
|
|
# Node helpers
|
2024-09-06 12:33:42 -04:00
|
|
|
def get_episodic_node_from_record(record: Any) -> EpisodicNode:
|
|
|
|
|
return EpisodicNode(
|
|
|
|
|
content=record['content'],
|
2025-06-13 14:12:09 -04:00
|
|
|
created_at=parse_db_date(record['created_at']), # type: ignore
|
|
|
|
|
valid_at=parse_db_date(record['valid_at']), # type: ignore
|
2024-09-06 12:33:42 -04:00
|
|
|
uuid=record['uuid'],
|
|
|
|
|
group_id=record['group_id'],
|
|
|
|
|
source=EpisodeType.from_str(record['source']),
|
|
|
|
|
name=record['name'],
|
|
|
|
|
source_description=record['source_description'],
|
2025-02-05 15:17:08 -05:00
|
|
|
entity_edges=record['entity_edges'],
|
2024-09-06 12:33:42 -04:00
|
|
|
)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
def get_entity_node_from_record(record: Any) -> EntityNode:
|
2025-02-25 15:55:06 -05:00
|
|
|
entity_node = EntityNode(
|
2024-09-06 12:33:42 -04:00
|
|
|
uuid=record['uuid'],
|
|
|
|
|
name=record['name'],
|
|
|
|
|
group_id=record['group_id'],
|
2025-02-13 12:17:52 -05:00
|
|
|
labels=record['labels'],
|
2025-06-13 14:12:09 -04:00
|
|
|
created_at=parse_db_date(record['created_at']), # type: ignore
|
2024-09-06 12:33:42 -04:00
|
|
|
summary=record['summary'],
|
2025-02-13 12:17:52 -05:00
|
|
|
attributes=record['attributes'],
|
2024-09-06 12:33:42 -04:00
|
|
|
)
|
2024-09-11 12:06:35 -04:00
|
|
|
|
2025-04-16 10:32:03 -04:00
|
|
|
entity_node.attributes.pop('uuid', None)
|
|
|
|
|
entity_node.attributes.pop('name', None)
|
|
|
|
|
entity_node.attributes.pop('group_id', None)
|
|
|
|
|
entity_node.attributes.pop('name_embedding', None)
|
|
|
|
|
entity_node.attributes.pop('summary', None)
|
|
|
|
|
entity_node.attributes.pop('created_at', None)
|
2025-02-25 15:55:06 -05:00
|
|
|
|
|
|
|
|
return entity_node
|
|
|
|
|
|
2024-09-11 12:06:35 -04:00
|
|
|
|
|
|
|
|
def get_community_node_from_record(record: Any) -> CommunityNode:
|
|
|
|
|
return CommunityNode(
|
|
|
|
|
uuid=record['uuid'],
|
|
|
|
|
name=record['name'],
|
|
|
|
|
group_id=record['group_id'],
|
|
|
|
|
name_embedding=record['name_embedding'],
|
2025-06-13 14:12:09 -04:00
|
|
|
created_at=parse_db_date(record['created_at']), # type: ignore
|
2024-09-11 12:06:35 -04:00
|
|
|
summary=record['summary'],
|
|
|
|
|
)
|
2025-04-26 22:09:12 -04:00
|
|
|
|
|
|
|
|
|
|
|
|
|
async def create_entity_node_embeddings(embedder: EmbedderClient, nodes: list[EntityNode]):
|
2025-06-26 20:54:43 -07:00
|
|
|
if not nodes: # Handle empty list case
|
|
|
|
|
return
|
2025-04-26 22:09:12 -04:00
|
|
|
name_embeddings = await embedder.create_batch([node.name for node in nodes])
|
|
|
|
|
for node, name_embedding in zip(nodes, name_embeddings, strict=True):
|
|
|
|
|
node.name_embedding = name_embedding
|