-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmain.py
More file actions
1782 lines (1553 loc) · 69 KB
/
Copy pathmain.py
File metadata and controls
1782 lines (1553 loc) · 69 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
"""
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
from time import time
from uuid import uuid4
from dotenv import load_dotenv
from pydantic import BaseModel
from typing_extensions import LiteralString
from cogram.cross_encoder.client import CrossEncoderClient
from cogram.cross_encoder.openai_reranker_client import OpenAIRerankerClient
from cogram.utils.decorators import handle_multiple_group_ids
from cogram.driver.driver import GraphDriver
from cogram.driver.neo4j_driver import Neo4jDriver
from cogram.core.edges import (
CommunityEdge,
Edge,
EntityEdge,
EpisodicEdge,
HasEpisodeEdge,
NextEpisodeEdge,
create_entity_edge_embeddings,
)
from cogram.embedder import EmbedderClient, OpenAIEmbedder
from cogram.core.errors import EdgeNotFoundError, NodeNotFoundError
from cogram.core.clients import GraphitiClients
from cogram.utils.helpers import (
get_default_group_id,
semaphore_gather,
validate_excluded_entity_types,
validate_group_id,
)
from cogram.llm_client import LLMClient, OpenAIClient
from cogram.namespaces import EdgeNamespace, NodeNamespace
from cogram.core.nodes import (
CommunityNode,
EntityNode,
EpisodeType,
EpisodicNode,
Node,
SagaNode,
create_entity_node_embeddings,
)
from cogram.prompts.lib import prompt_library
from cogram.prompts.summarize_sagas import SagaSummary
from cogram.search.search import SearchConfig, search
from cogram.search.search_config import DEFAULT_SEARCH_LIMIT, SearchResults
from cogram.search.search_config_recipes import (
COMBINED_HYBRID_SEARCH_CROSS_ENCODER,
EDGE_HYBRID_SEARCH_NODE_DISTANCE,
EDGE_HYBRID_SEARCH_RRF,
)
from cogram.search.search_filters import SearchFilters
from cogram.search.search_utils import (
RELEVANT_SCHEMA_LIMIT,
get_mentioned_nodes,
)
from cogram.telemetry import capture_event
from cogram.utils.tracer import Tracer, create_tracer
from cogram.utils.bulk_utils import (
RawEpisode,
add_nodes_and_edges_bulk,
dedupe_edges_bulk,
dedupe_nodes_bulk,
extract_nodes_and_edges_bulk,
resolve_edge_pointers,
retrieve_previous_episodes_bulk,
)
from cogram.utils.datetime_utils import utc_now
from cogram.utils.maintenance.community_operations import (
build_communities,
remove_communities,
update_community,
)
from cogram.utils.maintenance.edge_operations import (
build_episodic_edges,
extract_edges,
resolve_extracted_edge,
resolve_extracted_edges,
)
from cogram.utils.maintenance.graph_data_operations import (
EPISODE_WINDOW_LEN,
retrieve_episodes,
)
from cogram.utils.maintenance.node_operations import (
extract_attributes_from_nodes,
extract_nodes,
resolve_extracted_nodes,
)
from cogram.utils.ontology_utils.entity_types_utils import validate_entity_types
from cogram.utils.text_utils import MAX_SUMMARY_CHARS
logger = logging.getLogger(__name__)
load_dotenv()
class AddEpisodeResults(BaseModel):
episode: EpisodicNode
episodic_edges: list[EpisodicEdge]
nodes: list[EntityNode]
edges: list[EntityEdge]
communities: list[CommunityNode]
community_edges: list[CommunityEdge]
class AddBulkEpisodeResults(BaseModel):
episodes: list[EpisodicNode]
episodic_edges: list[EpisodicEdge]
nodes: list[EntityNode]
edges: list[EntityEdge]
communities: list[CommunityNode]
community_edges: list[CommunityEdge]
class AddTripletResults(BaseModel):
nodes: list[EntityNode]
edges: list[EntityEdge]
class Cogram:
"""Cogram: forked Graphiti with the intent layer, Engram cache, Redis active
memory, knot synthesis, and MCP server baked in.
The ``Graphiti`` name is preserved as an alias at module level for backward
compatibility — everything that previously imported ``Graphiti`` keeps working.
"""
def __init__(
self,
uri: str | None = None,
user: str | None = None,
password: str | None = None,
llm_client: LLMClient | None = None,
embedder: EmbedderClient | None = None,
cross_encoder: CrossEncoderClient | None = None,
store_raw_episode_content: bool = True,
graph_driver: GraphDriver | None = None,
max_coroutines: int | None = None,
tracer: Tracer | None = None,
trace_span_prefix: str = 'graphiti',
):
"""
Initialize a Graphiti instance.
This constructor sets up a connection to a graph database and initializes
the LLM client for natural language processing tasks.
Parameters
----------
uri : str
The URI of the Neo4j database.
user : str
The username for authenticating with the Neo4j database.
password : str
The password for authenticating with the Neo4j database.
llm_client : LLMClient | None, optional
An instance of LLMClient for natural language processing tasks.
If not provided, a default OpenAIClient will be initialized.
embedder : EmbedderClient | None, optional
An instance of EmbedderClient for embedding tasks.
If not provided, a default OpenAIEmbedder will be initialized.
cross_encoder : CrossEncoderClient | None, optional
An instance of CrossEncoderClient for reranking tasks.
If not provided, a default OpenAIRerankerClient will be initialized.
store_raw_episode_content : bool, optional
Whether to store the raw content of episodes. Defaults to True.
graph_driver : GraphDriver | None, optional
An instance of GraphDriver for database operations.
If not provided, a default Neo4jDriver will be initialized.
max_coroutines : int | None, optional
The maximum number of concurrent operations allowed. Overrides SEMAPHORE_LIMIT set in the environment.
If not set, the Graphiti default is used.
tracer : Tracer | None, optional
An OpenTelemetry tracer instance for distributed tracing. If not provided, tracing is disabled (no-op).
trace_span_prefix : str, optional
Prefix to prepend to all span names. Defaults to 'graphiti'.
Returns
-------
None
Notes
-----
This method establishes a connection to a graph database (Neo4j by default) using the provided
credentials. It also sets up the LLM client, either using the provided client
or by creating a default OpenAIClient.
The default database name is defined during the driver’s construction. If a different database name
is required, it should be specified in the URI or set separately after
initialization.
The OpenAI API key is expected to be set in the environment variables.
Make sure to set the OPENAI_API_KEY environment variable before initializing
Graphiti if you're using the default OpenAIClient.
"""
if graph_driver:
self.driver = graph_driver
else:
if uri is None:
raise ValueError('uri must be provided when graph_driver is None')
self.driver = Neo4jDriver(uri, user, password)
self.store_raw_episode_content = store_raw_episode_content
self.max_coroutines = max_coroutines
if llm_client:
self.llm_client = llm_client
else:
self.llm_client = OpenAIClient()
if embedder:
self.embedder = embedder
else:
self.embedder = OpenAIEmbedder()
if cross_encoder:
self.cross_encoder = cross_encoder
else:
self.cross_encoder = OpenAIRerankerClient()
# Initialize tracer
self.tracer = create_tracer(tracer, trace_span_prefix)
# Set tracer on clients
self.llm_client.set_tracer(self.tracer)
self.clients = GraphitiClients(
driver=self.driver,
llm_client=self.llm_client,
embedder=self.embedder,
cross_encoder=self.cross_encoder,
tracer=self.tracer,
)
# Initialize namespace API (graphiti.nodes.entity.save(), etc.)
self.nodes = NodeNamespace(self.driver, self.embedder)
self.edges = EdgeNamespace(self.driver, self.embedder)
# Capture telemetry event
self._capture_initialization_telemetry()
def _capture_initialization_telemetry(self):
"""Capture telemetry event for Graphiti initialization."""
try:
# Detect provider types from class names
llm_provider = self._get_provider_type(self.llm_client)
embedder_provider = self._get_provider_type(self.embedder)
reranker_provider = self._get_provider_type(self.cross_encoder)
database_provider = self._get_provider_type(self.driver)
properties = {
'llm_provider': llm_provider,
'embedder_provider': embedder_provider,
'reranker_provider': reranker_provider,
'database_provider': database_provider,
}
capture_event('graphiti_initialized', properties)
except Exception:
# Silently handle telemetry errors
pass
@property
def token_tracker(self):
"""Access the LLM client's token usage tracker.
Returns the TokenUsageTracker from the LLM client, which can be used to:
- Get token usage by prompt type: tracker.get_usage()
- Get total token usage: tracker.get_total_usage()
- Print a formatted summary: tracker.print_summary()
- Reset tracking: tracker.reset()
"""
return self.llm_client.token_tracker
def _get_provider_type(self, client) -> str:
"""Get provider type from client class name."""
if client is None:
return 'none'
class_name = client.__class__.__name__.lower()
# LLM providers
if 'openai' in class_name:
return 'openai'
elif 'azure' in class_name:
return 'azure'
elif 'anthropic' in class_name:
return 'anthropic'
elif 'crossencoder' in class_name:
return 'crossencoder'
elif 'gemini' in class_name:
return 'gemini'
elif 'groq' in class_name:
return 'groq'
# Database providers
elif 'neo4j' in class_name:
return 'neo4j'
elif 'falkor' in class_name:
return 'falkordb'
# Embedder providers
elif 'voyage' in class_name:
return 'voyage'
else:
return 'unknown'
async def close(self):
"""
Close the connection to the Neo4j database.
This method safely closes the driver connection to the Neo4j database.
It should be called when the Graphiti instance is no longer needed or
when the application is shutting down.
Parameters
----------
self
Returns
-------
None
Notes
-----
It's important to close the driver connection to release system resources
and ensure that all pending transactions are completed or rolled back.
This method should be called as part of a cleanup process, potentially
in a context manager or a shutdown hook.
Example:
graphiti = Graphiti(uri, user, password)
try:
# Use graphiti...
finally:
graphiti.close()
"""
await self.driver.close()
async def _get_or_create_saga(self, saga_name: str, group_id: str, now: datetime) -> SagaNode:
"""
Get an existing saga by name or create a new one.
Parameters
----------
saga_name : str
The name of the saga.
group_id : str
The group id for the saga.
now : datetime
The current timestamp for creation.
Returns
-------
SagaNode
The existing or newly created saga node.
"""
from cogram.utils.helpers import parse_db_date
records, _, _ = await self.driver.execute_query(
"""
MATCH (s:Saga {name: $name, group_id: $group_id})
RETURN s.uuid AS uuid, s.name AS name, s.group_id AS group_id, s.created_at AS created_at
""",
name=saga_name,
group_id=group_id,
routing_='r',
)
if records:
record = records[0]
return SagaNode(
uuid=record['uuid'],
name=record['name'],
group_id=record['group_id'],
created_at=parse_db_date(record['created_at']), # type: ignore
)
saga = SagaNode(name=saga_name, group_id=group_id, created_at=now)
await saga.save(self.driver)
return saga
async def _saga_get_previous_episode_uuid(
self, saga_uuid: str, current_episode_uuid: str
) -> str | None:
"""Find the most recent episode UUID in a saga, excluding the current one."""
if self.driver.graph_operations_interface:
try:
return await self.driver.graph_operations_interface.saga_get_previous_episode_uuid(
self.driver, saga_uuid, current_episode_uuid
)
except NotImplementedError:
pass
records, _, _ = await self.driver.execute_query(
"""
MATCH (s:Saga {uuid: $saga_uuid})-[:HAS_EPISODE]->(e:Episodic)
WHERE e.uuid <> $current_episode_uuid
RETURN e.uuid AS uuid
ORDER BY e.valid_at DESC, e.created_at DESC
LIMIT 1
""",
saga_uuid=saga_uuid,
current_episode_uuid=current_episode_uuid,
routing_='r',
)
if records:
return records[0]['uuid']
return None
async def _saga_get_episode_contents(
self,
saga_uuid: str,
since: datetime | None = None,
limit: int = 200,
) -> list[str] | None:
"""Retrieve episode contents for summarization, using IoC if available."""
if self.driver.graph_operations_interface:
try:
return await self.driver.graph_operations_interface.saga_get_episode_contents(
self.driver, saga_uuid, since=since, limit=limit
)
except NotImplementedError:
pass
return None
async def summarize_saga(self, saga_id: str) -> SagaNode:
"""Incrementally summarize a saga using only new episodes since the last summary.
If the saga has been summarized before (``last_summarized_at`` is set),
only episodes added after that timestamp are fetched. The existing
summary is provided to the LLM as context so no information is lost.
On the first call (no prior summary), all episodes are included.
Parameters
----------
saga_id : str
The UUID of the saga to summarize.
Returns
-------
SagaNode
The updated saga node with the new summary.
Raises
------
NodeNotFoundError
If the saga with the given UUID does not exist.
"""
saga = await SagaNode.get_by_uuid(self.driver, saga_id)
# Fetch only episodes added since the last summary (or all if never summarized).
max_episodes = 200
since = saga.last_summarized_at
# Try IoC interface first, fall back to raw Cypher
episode_contents = await self._saga_get_episode_contents(
saga_id, since=since, limit=max_episodes
)
if episode_contents is None:
if since is not None:
records, _, _ = await self.driver.execute_query(
"""
MATCH (s:Saga {uuid: $saga_uuid})-[:HAS_EPISODE]->(e:Episodic)
WHERE e.created_at > $since
RETURN e.content AS content
ORDER BY e.valid_at ASC, e.created_at ASC
LIMIT $limit
""",
saga_uuid=saga_id,
since=since,
limit=max_episodes,
routing_='r',
)
else:
records, _, _ = await self.driver.execute_query(
"""
MATCH (s:Saga {uuid: $saga_uuid})-[:HAS_EPISODE]->(e:Episodic)
RETURN e.content AS content
ORDER BY e.valid_at DESC, e.created_at DESC
LIMIT $limit
""",
saga_uuid=saga_id,
limit=max_episodes,
routing_='r',
)
# Reverse to chronological order for the prompt
records = list(reversed(records))
episode_contents = [r['content'] for r in records if r.get('content')]
if not episode_contents:
logger.info(f'No new episodes found for saga {saga_id}, skipping summary')
return saga
context = {
'saga_name': saga.name,
'existing_summary': saga.summary or '',
'episodes': episode_contents,
}
llm_response = await self.llm_client.generate_response(
prompt_library.summarize_sagas.summarize_saga(context),
response_model=SagaSummary,
prompt_name='summarize_sagas.summarize_saga',
)
summary = llm_response.get('summary', '')
if len(summary) > MAX_SUMMARY_CHARS:
summary = summary[:MAX_SUMMARY_CHARS]
saga.summary = summary
saga.last_summarized_at = utc_now()
await saga.save(self.driver)
logger.info(f'Updated summary for saga {saga_id}')
return saga
async def build_indices_and_constraints(self, delete_existing: bool = False):
"""
Build indices and constraints in the Neo4j database.
This method sets up the necessary indices and constraints in the Neo4j database
to optimize query performance and ensure data integrity for the knowledge graph.
Parameters
----------
self
delete_existing : bool, optional
Whether to clear existing indices before creating new ones.
Returns
-------
None
Notes
-----
This method should typically be called once during the initial setup of the
knowledge graph or when updating the database schema. It uses the
driver's `build_indices_and_constraints` method to perform
the actual database operations.
The specific indices and constraints created depend on the implementation
of the driver's `build_indices_and_constraints` method. Refer to the specific
driver documentation for details on the exact database schema modifications.
Caution: Running this method on a large existing database may take some time
and could impact database performance during execution.
"""
await self.driver.build_indices_and_constraints(delete_existing)
async def _extract_and_resolve_nodes(
self,
episode: EpisodicNode | list[EpisodicNode],
previous_episodes: list[EpisodicNode],
entity_types: dict[str, type[BaseModel]] | None,
excluded_entity_types: list[str] | None,
) -> tuple[
list[EntityNode], dict[str, str], list[tuple[EntityNode, EntityNode]], dict[str, list[int]]
]:
"""Extract nodes from episode(s) and resolve against existing graph."""
episodes = episode if isinstance(episode, list) else [episode]
primary_episode = episodes[0]
extracted_nodes, node_episode_index_map = await extract_nodes(
self.clients, episode, previous_episodes, entity_types, excluded_entity_types
)
nodes, uuid_map, duplicates = await resolve_extracted_nodes(
self.clients,
extracted_nodes,
primary_episode,
previous_episodes,
entity_types,
)
return nodes, uuid_map, duplicates, node_episode_index_map
async def _extract_and_resolve_edges(
self,
episode: EpisodicNode | list[EpisodicNode],
extracted_nodes: list[EntityNode],
previous_episodes: list[EpisodicNode],
edge_type_map: dict[tuple[str, str], list[str]],
group_id: str,
edge_types: dict[str, type[BaseModel]] | None,
nodes: list[EntityNode],
uuid_map: dict[str, str],
custom_extraction_instructions: str | None = None,
) -> tuple[list[EntityEdge], list[EntityEdge], list[EntityEdge]]:
"""Extract edges from episode(s) and resolve against existing graph.
Returns
-------
tuple[list[EntityEdge], list[EntityEdge], list[EntityEdge]]
A tuple of (resolved_edges, invalidated_edges, new_edges) where:
- resolved_edges: All edges after resolution
- invalidated_edges: Edges invalidated by new information
- new_edges: Only edges that are new to the graph (not duplicates)
"""
episodes = episode if isinstance(episode, list) else [episode]
primary_episode = episodes[0]
extracted_edges = await extract_edges(
self.clients,
episode,
extracted_nodes,
previous_episodes,
edge_type_map,
group_id,
edge_types,
custom_extraction_instructions,
)
edges = resolve_edge_pointers(extracted_edges, uuid_map)
resolved_edges, invalidated_edges, new_edges = await resolve_extracted_edges(
self.clients,
edges,
primary_episode,
nodes,
edge_types or {},
edge_type_map,
)
return resolved_edges, invalidated_edges, new_edges
async def _process_episode_data(
self,
episode: EpisodicNode | list[EpisodicNode],
nodes: list[EntityNode],
entity_edges: list[EntityEdge],
now: datetime,
group_id: str,
saga: str | SagaNode | None = None,
saga_previous_episode_uuid: str | None = None,
node_episode_index_map: dict[str, list[int]] | None = None,
) -> tuple[list[EpisodicEdge], EpisodicNode]:
"""Process and save episode data to the graph.
Parameters
----------
episode : EpisodicNode | list[EpisodicNode]
The episode(s) to process.
nodes : list[EntityNode]
The entity nodes extracted from the episode(s).
entity_edges : list[EntityEdge]
The entity edges extracted from the episode(s).
now : datetime
The current timestamp.
group_id : str
The group id for the episode.
saga : str | SagaNode | None
Optional. Either a saga name (str) or a SagaNode object to associate
this episode with. If a string is provided, the saga will be looked up
by name or created if it doesn't exist.
saga_previous_episode_uuid : str | None
Optional. UUID of the previous episode in the saga. If provided, skips
the database query to find the most recent episode. Useful for efficiently
adding multiple episodes to the same saga in sequence.
node_episode_index_map : dict[str, list[int]] | None
Optional mapping from node UUID to 0-indexed episode positions for
building episodic edges with correct attribution.
"""
episodes = episode if isinstance(episode, list) else [episode]
episode_uuids = [ep.uuid for ep in episodes]
episodic_edges = build_episodic_edges(nodes, episode_uuids, now, node_episode_index_map)
for ep in episodes:
ep.entity_edges = [edge.uuid for edge in entity_edges]
if not self.store_raw_episode_content:
ep.content = ''
await add_nodes_and_edges_bulk(
self.driver,
episodes,
episodic_edges,
nodes,
entity_edges,
self.embedder,
)
primary_episode = episodes[0]
# Handle saga association if provided
if saga is not None:
# Get or create saga node based on input type
if isinstance(saga, str):
saga_node = await self._get_or_create_saga(saga, group_id, now)
else:
saga_node = saga
# Use provided previous episode UUID or query for it
previous_episode_uuid: str | None = saga_previous_episode_uuid
if previous_episode_uuid is None:
previous_episode_uuid = await self._saga_get_previous_episode_uuid(
saga_node.uuid, primary_episode.uuid
)
# Create NEXT_EPISODE edge from the previous episode to the new one
if previous_episode_uuid is not None:
next_episode_edge = NextEpisodeEdge(
source_node_uuid=previous_episode_uuid,
target_node_uuid=primary_episode.uuid,
group_id=group_id,
created_at=now,
)
await next_episode_edge.save(self.driver)
# Create HAS_EPISODE edge from saga to the new episode
has_episode_edge = HasEpisodeEdge(
source_node_uuid=saga_node.uuid,
target_node_uuid=primary_episode.uuid,
group_id=group_id,
created_at=now,
)
await has_episode_edge.save(self.driver)
# Track first and last episode on the saga node
if saga_node.first_episode_uuid is None:
saga_node.first_episode_uuid = primary_episode.uuid
saga_node.last_episode_uuid = primary_episode.uuid
await saga_node.save(self.driver)
return episodic_edges, primary_episode
async def _extract_and_dedupe_nodes_bulk(
self,
episode_context: list[tuple[EpisodicNode, list[EpisodicNode]]],
edge_type_map: dict[tuple[str, str], list[str]],
edge_types: dict[str, type[BaseModel]] | None,
entity_types: dict[str, type[BaseModel]] | None,
excluded_entity_types: list[str] | None,
custom_extraction_instructions: str | None = None,
) -> tuple[
dict[str, list[EntityNode]],
dict[str, str],
list[list[EntityEdge]],
]:
"""Extract nodes and edges from all episodes and deduplicate."""
# Extract all nodes and edges for each episode
extracted_nodes_bulk, extracted_edges_bulk = await extract_nodes_and_edges_bulk(
self.clients,
episode_context,
edge_type_map=edge_type_map,
edge_types=edge_types,
entity_types=entity_types,
excluded_entity_types=excluded_entity_types,
custom_extraction_instructions=custom_extraction_instructions,
)
# Dedupe extracted nodes in memory
nodes_by_episode, uuid_map = await dedupe_nodes_bulk(
self.clients, extracted_nodes_bulk, episode_context, entity_types
)
return nodes_by_episode, uuid_map, extracted_edges_bulk
async def _resolve_nodes_and_edges_bulk(
self,
nodes_by_episode: dict[str, list[EntityNode]],
edges_by_episode: dict[str, list[EntityEdge]],
episode_context: list[tuple[EpisodicNode, list[EpisodicNode]]],
entity_types: dict[str, type[BaseModel]] | None,
edge_types: dict[str, type[BaseModel]] | None,
edge_type_map: dict[tuple[str, str], list[str]],
episodes: list[EpisodicNode],
) -> tuple[list[EntityNode], list[EntityEdge], list[EntityEdge], dict[str, str]]:
"""Resolve nodes and edges against the existing graph."""
nodes_by_uuid: dict[str, EntityNode] = {
node.uuid: node for nodes in nodes_by_episode.values() for node in nodes
}
# Get unique nodes per episode
nodes_by_episode_unique: dict[str, list[EntityNode]] = {}
nodes_uuid_set: set[str] = set()
for episode, _ in episode_context:
nodes_by_episode_unique[episode.uuid] = []
nodes = [nodes_by_uuid[node.uuid] for node in nodes_by_episode[episode.uuid]]
for node in nodes:
if node.uuid not in nodes_uuid_set:
nodes_by_episode_unique[episode.uuid].append(node)
nodes_uuid_set.add(node.uuid)
# Resolve nodes
node_results = await semaphore_gather(
*[
resolve_extracted_nodes(
self.clients,
nodes_by_episode_unique[episode.uuid],
episode,
previous_episodes,
entity_types,
)
for episode, previous_episodes in episode_context
]
)
resolved_nodes: list[EntityNode] = []
uuid_map: dict[str, str] = {}
for result in node_results:
resolved_nodes.extend(result[0])
uuid_map.update(result[1])
# Update nodes_by_uuid with resolved nodes
for resolved_node in resolved_nodes:
nodes_by_uuid[resolved_node.uuid] = resolved_node
# Update nodes_by_episode_unique with resolved pointers
for episode_uuid, nodes in nodes_by_episode_unique.items():
updated_nodes: list[EntityNode] = []
for node in nodes:
updated_node_uuid = uuid_map.get(node.uuid, node.uuid)
updated_node = nodes_by_uuid[updated_node_uuid]
updated_nodes.append(updated_node)
nodes_by_episode_unique[episode_uuid] = updated_nodes
# Extract attributes for resolved nodes
hydrated_nodes_results: list[list[EntityNode]] = await semaphore_gather(
*[
extract_attributes_from_nodes(
self.clients,
nodes_by_episode_unique[episode.uuid],
episode,
previous_episodes,
entity_types,
)
for episode, previous_episodes in episode_context
]
)
final_hydrated_nodes = [node for nodes in hydrated_nodes_results for node in nodes]
# Resolve edges with updated pointers
edges_by_episode_unique: dict[str, list[EntityEdge]] = {}
edges_uuid_set: set[str] = set()
for episode_uuid, edges in edges_by_episode.items():
edges_with_updated_pointers = resolve_edge_pointers(edges, uuid_map)
edges_by_episode_unique[episode_uuid] = []
for edge in edges_with_updated_pointers:
if edge.uuid not in edges_uuid_set:
edges_by_episode_unique[episode_uuid].append(edge)
edges_uuid_set.add(edge.uuid)
edge_results = await semaphore_gather(
*[
resolve_extracted_edges(
self.clients,
edges_by_episode_unique[episode.uuid],
episode,
final_hydrated_nodes,
edge_types or {},
edge_type_map,
)
for episode in episodes
]
)
resolved_edges: list[EntityEdge] = []
invalidated_edges: list[EntityEdge] = []
for result in edge_results:
resolved_edges.extend(result[0])
invalidated_edges.extend(result[1])
# result[2] is new_edges - not used in bulk flow since attributes
# are extracted before edge resolution
return final_hydrated_nodes, resolved_edges, invalidated_edges, uuid_map
@handle_multiple_group_ids
async def retrieve_episodes(
self,
reference_time: datetime,
last_n: int = EPISODE_WINDOW_LEN,
group_ids: list[str] | None = None,
source: EpisodeType | None = None,
driver: GraphDriver | None = None,
saga: str | None = None,
) -> list[EpisodicNode]:
"""
Retrieve the last n episodic nodes from the graph.
This method fetches a specified number of the most recent episodic nodes
from the graph, relative to the given reference time.
Parameters
----------
reference_time : datetime
The reference time to retrieve episodes before.
last_n : int, optional
The number of episodes to retrieve. Defaults to EPISODE_WINDOW_LEN.
group_ids : list[str | None], optional
The group ids to return data from.
source : EpisodeType | None, optional
Filter episodes by source type.
driver : GraphDriver | None, optional
The graph driver to use. If not provided, uses the default driver.
saga : str | None, optional
If provided, only retrieve episodes that belong to the saga with this name.
Returns
-------
list[EpisodicNode]
A list of the most recent EpisodicNode objects.
Notes
-----
The actual retrieval is performed by the `retrieve_episodes` function
from the `graphiti_core.utils` module, unless a saga is specified.
"""
if driver is None:
driver = self.clients.driver
if driver.graph_operations_interface:
try:
return await driver.graph_operations_interface.retrieve_episodes(
driver, reference_time, last_n, group_ids, source, saga
)
except NotImplementedError:
pass
return await retrieve_episodes(driver, reference_time, last_n, group_ids, source, saga)
async def add_episode(
self,
name: str,
episode_body: str,
source_description: str,
reference_time: datetime,
source: EpisodeType = EpisodeType.message,
group_id: str | None = None,
uuid: str | None = None,
update_communities: bool = False,
entity_types: dict[str, type[BaseModel]] | None = None,
excluded_entity_types: list[str] | None = None,
previous_episode_uuids: list[str] | None = None,
edge_types: dict[str, type[BaseModel]] | None = None,
edge_type_map: dict[tuple[str, str], list[str]] | None = None,
custom_extraction_instructions: str | None = None,
saga: str | SagaNode | None = None,
saga_previous_episode_uuid: str | None = None,
) -> AddEpisodeResults:
"""
Process an episode and update the graph.
This method extracts information from the episode, creates nodes and edges,
and updates the graph database accordingly.
Parameters
----------
name : str
The name of the episode.
episode_body : str
The content of the episode.
source_description : str
A description of the episode's source.
reference_time : datetime
The reference time for the episode.
source : EpisodeType, optional
The type of the episode. Defaults to EpisodeType.message.
group_id : str | None
An id for the graph partition the episode is a part of.
uuid : str | None
Optional uuid of the episode.
update_communities : bool
Optional. Whether to update communities with new node information
entity_types : dict[str, BaseModel] | None
Optional. Dictionary mapping entity type names to their Pydantic model definitions.
excluded_entity_types : list[str] | None
Optional. List of entity type names to exclude from the graph. Entities classified
into these types will not be added to the graph. Can include 'Entity' to exclude
the default entity type.
previous_episode_uuids : list[str] | None
Optional. list of episode uuids to use as the previous episodes. If this is not provided,
the most recent episodes by created_at date will be used.
custom_extraction_instructions : str | None
Optional. Custom extraction instructions string to be included in the extract entities and extract edges prompts.
This allows for additional instructions or context to guide the extraction process.
saga : str | SagaNode | None
Optional. Either a saga name (str) or a SagaNode object to associate this episode with.
If a string is provided and a saga with this name already exists in the group, the episode
will be added to it. Otherwise, a new saga will be created. Sagas are connected to episodes
via HAS_EPISODE edges, and consecutive episodes are linked via NEXT_EPISODE edges.
saga_previous_episode_uuid : str | None