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
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
//! Core engine for the memory graph
mod async_memory_graph;
pub use async_memory_graph::AsyncMemoryGraph;
use crate::error::{Error, Result};
use crate::storage::{SledBackend, StorageBackend};
use crate::types::{
AgentNode, Config, ConversationSession, Edge, EdgeType, Node, NodeId, PromptMetadata,
PromptNode, PromptTemplate, ResponseMetadata, ResponseNode, SessionId, TemplateId, TokenUsage,
ToolInvocation,
};
use parking_lot::RwLock;
use std::collections::HashMap;
use std::sync::Arc;
/// Main interface for interacting with the memory graph
///
/// `MemoryGraph` provides a thread-safe, high-level API for managing conversation
/// sessions, prompts, responses, and their relationships in a graph structure.
///
/// # Examples
///
/// ```no_run
/// use llm_memory_graph::{MemoryGraph, Config};
///
/// # fn main() -> Result<(), Box<dyn std::error::Error>> {
/// let config = Config::new("./data/my_graph.db");
/// let graph = MemoryGraph::open(config)?;
///
/// let session = graph.create_session()?;
/// let prompt_id = graph.add_prompt(session.id, "What is Rust?".to_string(), None)?;
/// # Ok(())
/// # }
/// ```
pub struct MemoryGraph {
backend: Arc<dyn StorageBackend>,
sessions: Arc<RwLock<HashMap<SessionId, ConversationSession>>>,
}
impl MemoryGraph {
/// Open or create a memory graph with the given configuration
///
/// This will create the database directory if it doesn't exist and initialize
/// all necessary storage trees.
///
/// # Errors
///
/// Returns an error if:
/// - The database path is invalid or inaccessible
/// - Storage initialization fails
/// - Existing data is corrupted
///
/// # Examples
///
/// ```no_run
/// use llm_memory_graph::{MemoryGraph, Config};
///
/// # fn main() -> Result<(), Box<dyn std::error::Error>> {
/// let config = Config::new("./data/graph.db");
/// let graph = MemoryGraph::open(config)?;
/// # Ok(())
/// # }
/// ```
pub fn open(config: Config) -> Result<Self> {
let backend = SledBackend::open(&config.path)?;
Ok(Self {
backend: Arc::new(backend),
sessions: Arc::new(RwLock::new(HashMap::new())),
})
}
/// Create a new conversation session
///
/// Sessions are used to group related prompts and responses together.
/// Each session has a unique ID and can store custom metadata.
///
/// # Errors
///
/// Returns an error if the session cannot be persisted to storage.
///
/// # Examples
///
/// ```no_run
/// # use llm_memory_graph::{MemoryGraph, Config};
/// # fn main() -> Result<(), Box<dyn std::error::Error>> {
/// # let graph = MemoryGraph::open(Config::default())?;
/// let session = graph.create_session()?;
/// println!("Created session: {}", session.id);
/// # Ok(())
/// # }
/// ```
pub fn create_session(&self) -> Result<ConversationSession> {
let session = ConversationSession::new();
self.backend.store_node(&Node::Session(session.clone()))?;
// Cache the session
self.sessions.write().insert(session.id, session.clone());
Ok(session)
}
/// Create a session with custom metadata
///
/// # Errors
///
/// Returns an error if the session cannot be persisted to storage.
///
/// # Examples
///
/// ```no_run
/// # use llm_memory_graph::{MemoryGraph, Config};
/// # use std::collections::HashMap;
/// # fn main() -> Result<(), Box<dyn std::error::Error>> {
/// # let graph = MemoryGraph::open(Config::default())?;
/// let mut metadata = HashMap::new();
/// metadata.insert("user_id".to_string(), "123".to_string());
/// let session = graph.create_session_with_metadata(metadata)?;
/// # Ok(())
/// # }
/// ```
pub fn create_session_with_metadata(
&self,
metadata: HashMap<String, String>,
) -> Result<ConversationSession> {
let session = ConversationSession::with_metadata(metadata);
self.backend.store_node(&Node::Session(session.clone()))?;
// Cache the session
self.sessions.write().insert(session.id, session.clone());
Ok(session)
}
/// Get a session by ID
///
/// This will first check the in-memory cache, then fall back to storage.
///
/// # Errors
///
/// Returns an error if:
/// - The session doesn't exist
/// - Storage retrieval fails
///
/// # Examples
///
/// ```no_run
/// # use llm_memory_graph::{MemoryGraph, Config};
/// # fn main() -> Result<(), Box<dyn std::error::Error>> {
/// # let graph = MemoryGraph::open(Config::default())?;
/// # let created_session = graph.create_session()?;
/// let session = graph.get_session(created_session.id)?;
/// # Ok(())
/// # }
/// ```
pub fn get_session(&self, session_id: SessionId) -> Result<ConversationSession> {
// Check cache first
if let Some(session) = self.sessions.read().get(&session_id) {
return Ok(session.clone());
}
// Fall back to storage
let nodes = self.backend.get_session_nodes(&session_id)?;
for node in nodes {
if let Node::Session(session) = node {
if session.id == session_id {
// Update cache
self.sessions.write().insert(session_id, session.clone());
return Ok(session);
}
}
}
Err(Error::SessionNotFound(session_id.to_string()))
}
/// Add a prompt to a session
///
/// This creates a new prompt node and automatically creates edges linking it
/// to the session and to the previous prompt if one exists.
///
/// # Errors
///
/// Returns an error if:
/// - The session doesn't exist
/// - Storage operations fail
///
/// # Examples
///
/// ```no_run
/// # use llm_memory_graph::{MemoryGraph, Config};
/// # fn main() -> Result<(), Box<dyn std::error::Error>> {
/// # let graph = MemoryGraph::open(Config::default())?;
/// # let session = graph.create_session()?;
/// let prompt_id = graph.add_prompt(
/// session.id,
/// "Explain quantum entanglement".to_string(),
/// None,
/// )?;
/// # Ok(())
/// # }
/// ```
pub fn add_prompt(
&self,
session_id: SessionId,
content: String,
metadata: Option<PromptMetadata>,
) -> Result<NodeId> {
// Verify session exists
self.get_session(session_id)?;
let prompt = if let Some(meta) = metadata {
PromptNode::with_metadata(session_id, content, meta)
} else {
PromptNode::new(session_id, content)
};
let prompt_id = prompt.id;
self.backend.store_node(&Node::Prompt(prompt.clone()))?;
// Create edge from prompt to session
let session_nodes = self.backend.get_session_nodes(&session_id)?;
if let Some(session_node) = session_nodes.iter().find(|n| matches!(n, Node::Session(_))) {
let edge = Edge::new(prompt_id, session_node.id(), EdgeType::PartOf);
self.backend.store_edge(&edge)?;
}
// Find the previous prompt in this session and create a Follows edge
let session_prompts: Vec<_> = session_nodes
.into_iter()
.filter_map(|n| {
if let Node::Prompt(p) = n {
Some(p)
} else {
None
}
})
.collect();
if !session_prompts.is_empty() {
// Get the most recent prompt (excluding the one we just added)
let mut previous_prompts: Vec<_> = session_prompts
.into_iter()
.filter(|p| p.id != prompt_id)
.collect();
previous_prompts.sort_by(|a, b| b.timestamp.cmp(&a.timestamp));
if let Some(prev_prompt) = previous_prompts.first() {
let edge = Edge::new(prompt_id, prev_prompt.id, EdgeType::Follows);
self.backend.store_edge(&edge)?;
}
}
Ok(prompt_id)
}
/// Add a response to a prompt
///
/// This creates a response node and a RespondsTo edge linking it to the prompt.
///
/// # Errors
///
/// Returns an error if:
/// - The prompt doesn't exist
/// - Storage operations fail
///
/// # Examples
///
/// ```no_run
/// # use llm_memory_graph::{MemoryGraph, Config, TokenUsage};
/// # fn main() -> Result<(), Box<dyn std::error::Error>> {
/// # let graph = MemoryGraph::open(Config::default())?;
/// # let session = graph.create_session()?;
/// # let prompt_id = graph.add_prompt(session.id, "Test".to_string(), None)?;
/// let usage = TokenUsage::new(10, 20);
/// let response_id = graph.add_response(
/// prompt_id,
/// "Quantum entanglement is...".to_string(),
/// usage,
/// None,
/// )?;
/// # Ok(())
/// # }
/// ```
pub fn add_response(
&self,
prompt_id: NodeId,
content: String,
usage: TokenUsage,
metadata: Option<ResponseMetadata>,
) -> Result<NodeId> {
// Verify prompt exists
self.get_node(prompt_id)?;
let response = if let Some(meta) = metadata {
ResponseNode::with_metadata(prompt_id, content, usage, meta)
} else {
ResponseNode::new(prompt_id, content, usage)
};
let response_id = response.id;
self.backend.store_node(&Node::Response(response.clone()))?;
// Create edge from response to prompt
let edge = Edge::new(response_id, prompt_id, EdgeType::RespondsTo);
self.backend.store_edge(&edge)?;
Ok(response_id)
}
/// Add a tool invocation node to the graph
///
/// This creates a tool invocation record and automatically creates an INVOKES edge
/// from the response to the tool invocation.
///
/// # Arguments
///
/// * `tool` - The tool invocation to add
///
/// # Returns
///
/// The node ID of the created tool invocation
///
/// # Example
///
/// ```no_run
/// # use llm_memory_graph::*;
/// # fn main() -> Result<()> {
/// # let graph = MemoryGraph::open(Config::default())?;
/// # let session = graph.create_session()?;
/// # let prompt_id = graph.add_prompt(session.id, "Test".to_string(), None)?;
/// # let response_id = graph.add_response(prompt_id, "Response".to_string(), TokenUsage::new(10, 20), None)?;
/// let params = serde_json::json!({"operation": "add", "a": 2, "b": 3});
/// let tool = ToolInvocation::new(response_id, "calculator".to_string(), params);
/// let tool_id = graph.add_tool_invocation(tool)?;
/// # Ok(())
/// # }
/// ```
pub fn add_tool_invocation(&self, tool: ToolInvocation) -> Result<NodeId> {
let tool_id = tool.id;
let response_id = tool.response_id;
// Store the tool invocation node
self.backend.store_node(&Node::ToolInvocation(tool))?;
// Create INVOKES edge from response to tool
let edge = Edge::new(response_id, tool_id, EdgeType::Invokes);
self.backend.store_edge(&edge)?;
Ok(tool_id)
}
/// Update an existing tool invocation with results
///
/// This method updates a tool invocation's status, result, and duration after execution.
///
/// # Arguments
///
/// * `tool_id` - The ID of the tool invocation to update
/// * `success` - Whether the tool execution was successful
/// * `result_or_error` - Either the result (if successful) or error message (if failed)
/// * `duration_ms` - Execution duration in milliseconds
///
/// # Example
///
/// ```no_run
/// # use llm_memory_graph::*;
/// # fn main() -> Result<()> {
/// # let graph = MemoryGraph::open(Config::default())?;
/// # let session = graph.create_session()?;
/// # let prompt_id = graph.add_prompt(session.id, "Test".to_string(), None)?;
/// # let response_id = graph.add_response(prompt_id, "Response".to_string(), TokenUsage::new(10, 20), None)?;
/// # let params = serde_json::json!({"operation": "add", "a": 2, "b": 3});
/// # let tool = ToolInvocation::new(response_id, "calculator".to_string(), params);
/// # let tool_id = graph.add_tool_invocation(tool)?;
/// // Mark tool invocation as successful
/// let result = serde_json::json!({"result": 5});
/// graph.update_tool_invocation(tool_id, true, serde_json::to_string(&result)?, 150)?;
/// # Ok(())
/// # }
/// ```
pub fn update_tool_invocation(
&self,
tool_id: NodeId,
success: bool,
result_or_error: String,
duration_ms: u64,
) -> Result<()> {
// Get the tool invocation node
let node = self
.backend
.get_node(&tool_id)?
.ok_or_else(|| Error::NodeNotFound(tool_id.to_string()))?;
if let Node::ToolInvocation(mut tool) = node {
if success {
let result: serde_json::Value = serde_json::from_str(&result_or_error)?;
tool.mark_success(result, duration_ms);
} else {
tool.mark_failed(result_or_error, duration_ms);
}
// Update the node in storage
self.backend.store_node(&Node::ToolInvocation(tool))?;
Ok(())
} else {
Err(Error::InvalidNodeType {
expected: "ToolInvocation".to_string(),
actual: format!("{:?}", node.node_type()),
})
}
}
/// Get all tool invocations for a specific response
///
/// # Arguments
///
/// * `response_id` - The response node ID
///
/// # Returns
///
/// A vector of tool invocation nodes
///
/// # Example
///
/// ```no_run
/// # use llm_memory_graph::*;
/// # fn main() -> Result<()> {
/// # let graph = MemoryGraph::open(Config::default())?;
/// # let session = graph.create_session()?;
/// # let prompt_id = graph.add_prompt(session.id, "Test".to_string(), None)?;
/// # let response_id = graph.add_response(prompt_id, "Response".to_string(), TokenUsage::new(10, 20), None)?;
/// let tools = graph.get_response_tools(response_id)?;
/// println!("Response invoked {} tools", tools.len());
/// # Ok(())
/// # }
/// ```
pub fn get_response_tools(&self, response_id: NodeId) -> Result<Vec<ToolInvocation>> {
let edges = self.backend.get_outgoing_edges(&response_id)?;
let mut tools = Vec::new();
for edge in edges {
if edge.edge_type == EdgeType::Invokes {
if let Some(Node::ToolInvocation(tool)) = self.backend.get_node(&edge.to)? {
tools.push(tool);
}
}
}
Ok(tools)
}
/// Create and register an agent in the graph
///
/// # Errors
///
/// Returns an error if storage fails
///
/// # Examples
///
/// ```no_run
/// # use llm_memory_graph::{MemoryGraph, Config, AgentNode};
/// # fn main() -> Result<(), Box<dyn std::error::Error>> {
/// # let graph = MemoryGraph::open(Config::default())?;
/// let agent = AgentNode::new(
/// "Researcher".to_string(),
/// "research".to_string(),
/// vec!["web_search".to_string(), "summarize".to_string()],
/// );
/// let agent_id = graph.add_agent(agent)?;
/// # Ok(())
/// # }
/// ```
pub fn add_agent(&self, agent: AgentNode) -> Result<NodeId> {
let node_id = agent.node_id;
self.backend.store_node(&Node::Agent(agent))?;
Ok(node_id)
}
/// Update an existing agent's data
///
/// # Errors
///
/// Returns an error if:
/// - The agent doesn't exist
/// - Storage update fails
///
/// # Examples
///
/// ```no_run
/// # use llm_memory_graph::{MemoryGraph, Config, AgentNode};
/// # fn main() -> Result<(), Box<dyn std::error::Error>> {
/// # let graph = MemoryGraph::open(Config::default())?;
/// # let agent = AgentNode::new("Test".to_string(), "test".to_string(), vec![]);
/// # let node_id = graph.add_agent(agent)?;
/// let node = graph.get_node(node_id)?;
/// if let llm_memory_graph::types::Node::Agent(mut agent) = node {
/// agent.update_metrics(true, 250, 150);
/// graph.update_agent(agent)?;
/// }
/// # Ok(())
/// # }
/// ```
pub fn update_agent(&self, agent: AgentNode) -> Result<()> {
self.backend.store_node(&Node::Agent(agent))?;
Ok(())
}
/// Assign an agent to handle a prompt
///
/// Creates a HandledBy edge from the prompt to the agent.
///
/// # Errors
///
/// Returns an error if storage fails
///
/// # Examples
///
/// ```no_run
/// # use llm_memory_graph::{MemoryGraph, Config, AgentNode};
/// # fn main() -> Result<(), Box<dyn std::error::Error>> {
/// # let graph = MemoryGraph::open(Config::default())?;
/// # let session = graph.create_session()?;
/// # let prompt_id = graph.add_prompt(session.id, "Test".to_string(), None)?;
/// # let agent = AgentNode::new("Test".to_string(), "test".to_string(), vec![]);
/// # let agent_node_id = graph.add_agent(agent)?;
/// graph.assign_agent_to_prompt(prompt_id, agent_node_id)?;
/// # Ok(())
/// # }
/// ```
pub fn assign_agent_to_prompt(&self, prompt_id: NodeId, agent_node_id: NodeId) -> Result<()> {
let edge = Edge::new(prompt_id, agent_node_id, EdgeType::HandledBy);
self.backend.store_edge(&edge)?;
Ok(())
}
/// Create a transfer from a response to an agent
///
/// Creates a TransfersTo edge indicating agent handoff.
///
/// # Errors
///
/// Returns an error if storage fails
///
/// # Examples
///
/// ```no_run
/// # use llm_memory_graph::{MemoryGraph, Config, AgentNode, TokenUsage};
/// # fn main() -> Result<(), Box<dyn std::error::Error>> {
/// # let graph = MemoryGraph::open(Config::default())?;
/// # let session = graph.create_session()?;
/// # let prompt_id = graph.add_prompt(session.id, "Test".to_string(), None)?;
/// # let response_id = graph.add_response(prompt_id, "Test".to_string(), TokenUsage::new(10, 10), None)?;
/// # let agent = AgentNode::new("Test".to_string(), "test".to_string(), vec![]);
/// # let agent_node_id = graph.add_agent(agent)?;
/// graph.transfer_to_agent(response_id, agent_node_id)?;
/// # Ok(())
/// # }
/// ```
pub fn transfer_to_agent(&self, response_id: NodeId, agent_node_id: NodeId) -> Result<()> {
let edge = Edge::new(response_id, agent_node_id, EdgeType::TransfersTo);
self.backend.store_edge(&edge)?;
Ok(())
}
/// Get the agent assigned to handle a prompt
///
/// # Errors
///
/// Returns an error if:
/// - No agent is assigned
/// - Storage retrieval fails
///
/// # Examples
///
/// ```no_run
/// # use llm_memory_graph::{MemoryGraph, Config, AgentNode};
/// # fn main() -> Result<(), Box<dyn std::error::Error>> {
/// # let graph = MemoryGraph::open(Config::default())?;
/// # let session = graph.create_session()?;
/// # let prompt_id = graph.add_prompt(session.id, "Test".to_string(), None)?;
/// # let agent = AgentNode::new("Test".to_string(), "test".to_string(), vec![]);
/// # let agent_id = graph.add_agent(agent)?;
/// # graph.assign_agent_to_prompt(prompt_id, agent_id)?;
/// let agent = graph.get_prompt_agent(prompt_id)?;
/// println!("Handled by: {}", agent.name);
/// # Ok(())
/// # }
/// ```
pub fn get_prompt_agent(&self, prompt_id: NodeId) -> Result<AgentNode> {
let edges = self.backend.get_outgoing_edges(&prompt_id)?;
for edge in edges {
if edge.edge_type == EdgeType::HandledBy {
if let Some(Node::Agent(agent)) = self.backend.get_node(&edge.to)? {
return Ok(agent);
}
}
}
Err(Error::TraversalError(
"No agent assigned to this prompt".to_string(),
))
}
/// Get all agents a response was transferred to
///
/// # Errors
///
/// Returns an error if storage retrieval fails
///
/// # Examples
///
/// ```no_run
/// # use llm_memory_graph::{MemoryGraph, Config, AgentNode, TokenUsage};
/// # fn main() -> Result<(), Box<dyn std::error::Error>> {
/// # let graph = MemoryGraph::open(Config::default())?;
/// # let session = graph.create_session()?;
/// # let prompt_id = graph.add_prompt(session.id, "Test".to_string(), None)?;
/// # let response_id = graph.add_response(prompt_id, "Test".to_string(), TokenUsage::new(10, 10), None)?;
/// let agents = graph.get_agent_handoffs(response_id)?;
/// for agent in agents {
/// println!("Transferred to: {}", agent.name);
/// }
/// # Ok(())
/// # }
/// ```
pub fn get_agent_handoffs(&self, response_id: NodeId) -> Result<Vec<AgentNode>> {
let edges = self.backend.get_outgoing_edges(&response_id)?;
let mut agents = Vec::new();
for edge in edges {
if edge.edge_type == EdgeType::TransfersTo {
if let Some(Node::Agent(agent)) = self.backend.get_node(&edge.to)? {
agents.push(agent);
}
}
}
Ok(agents)
}
/// Get a node by its ID
///
/// # Errors
///
/// Returns an error if:
/// - The node doesn't exist
/// - Storage retrieval fails
///
/// # Examples
///
/// ```no_run
/// # use llm_memory_graph::{MemoryGraph, Config};
/// # fn main() -> Result<(), Box<dyn std::error::Error>> {
/// # let graph = MemoryGraph::open(Config::default())?;
/// # let session = graph.create_session()?;
/// # let prompt_id = graph.add_prompt(session.id, "Test".to_string(), None)?;
/// let node = graph.get_node(prompt_id)?;
/// # Ok(())
/// # }
/// ```
pub fn get_node(&self, node_id: NodeId) -> Result<Node> {
self.backend
.get_node(&node_id)?
.ok_or_else(|| Error::NodeNotFound(node_id.to_string()))
}
/// Add a custom edge between two nodes
///
/// # Errors
///
/// Returns an error if storage operations fail.
///
/// # Examples
///
/// ```no_run
/// # use llm_memory_graph::{MemoryGraph, Config, EdgeType};
/// # fn main() -> Result<(), Box<dyn std::error::Error>> {
/// # let graph = MemoryGraph::open(Config::default())?;
/// # let session = graph.create_session()?;
/// # let prompt1 = graph.add_prompt(session.id, "Test1".to_string(), None)?;
/// # let prompt2 = graph.add_prompt(session.id, "Test2".to_string(), None)?;
/// graph.add_edge(prompt1, prompt2, EdgeType::Follows)?;
/// # Ok(())
/// # }
/// ```
pub fn add_edge(&self, from: NodeId, to: NodeId, edge_type: EdgeType) -> Result<()> {
let edge = Edge::new(from, to, edge_type);
self.backend.store_edge(&edge)?;
Ok(())
}
/// Get all edges originating from a node
///
/// # Errors
///
/// Returns an error if storage retrieval fails.
///
/// # Examples
///
/// ```no_run
/// # use llm_memory_graph::{MemoryGraph, Config};
/// # fn main() -> Result<(), Box<dyn std::error::Error>> {
/// # let graph = MemoryGraph::open(Config::default())?;
/// # let session = graph.create_session()?;
/// # let prompt_id = graph.add_prompt(session.id, "Test".to_string(), None)?;
/// let edges = graph.get_outgoing_edges(prompt_id)?;
/// # Ok(())
/// # }
/// ```
pub fn get_outgoing_edges(&self, node_id: NodeId) -> Result<Vec<Edge>> {
self.backend.get_outgoing_edges(&node_id)
}
/// Get all edges pointing to a node
///
/// # Errors
///
/// Returns an error if storage retrieval fails.
///
/// # Examples
///
/// ```no_run
/// # use llm_memory_graph::{MemoryGraph, Config};
/// # fn main() -> Result<(), Box<dyn std::error::Error>> {
/// # let graph = MemoryGraph::open(Config::default())?;
/// # let session = graph.create_session()?;
/// # let prompt_id = graph.add_prompt(session.id, "Test".to_string(), None)?;
/// let edges = graph.get_incoming_edges(prompt_id)?;
/// # Ok(())
/// # }
/// ```
pub fn get_incoming_edges(&self, node_id: NodeId) -> Result<Vec<Edge>> {
self.backend.get_incoming_edges(&node_id)
}
/// Get all nodes in a session
///
/// # Errors
///
/// Returns an error if storage retrieval fails.
///
/// # Examples
///
/// ```no_run
/// # use llm_memory_graph::{MemoryGraph, Config};
/// # fn main() -> Result<(), Box<dyn std::error::Error>> {
/// # let graph = MemoryGraph::open(Config::default())?;
/// # let session = graph.create_session()?;
/// let nodes = graph.get_session_nodes(session.id)?;
/// # Ok(())
/// # }
/// ```
pub fn get_session_nodes(&self, session_id: SessionId) -> Result<Vec<Node>> {
self.backend.get_session_nodes(&session_id)
}
/// Flush all pending writes to disk
///
/// # Errors
///
/// Returns an error if the flush operation fails.
///
/// # Examples
///
/// ```no_run
/// # use llm_memory_graph::{MemoryGraph, Config};
/// # fn main() -> Result<(), Box<dyn std::error::Error>> {
/// # let graph = MemoryGraph::open(Config::default())?;
/// graph.flush()?;
/// # Ok(())
/// # }
/// ```
pub fn flush(&self) -> Result<()> {
self.backend.flush()
}
/// Get storage statistics
///
/// Returns information about node count, edge count, storage size, etc.
///
/// # Errors
///
/// Returns an error if statistics cannot be retrieved.
///
/// # Examples
///
/// ```no_run
/// # use llm_memory_graph::{MemoryGraph, Config};
/// # fn main() -> Result<(), Box<dyn std::error::Error>> {
/// # let graph = MemoryGraph::open(Config::default())?;
/// let stats = graph.stats()?;
/// println!("Nodes: {}, Edges: {}", stats.node_count, stats.edge_count);
/// # Ok(())
/// # }
/// ```
pub fn stats(&self) -> Result<crate::storage::StorageStats> {
self.backend.stats()
}
// ===== Template Management Methods =====
/// Create and store a new prompt template
///
/// Templates are versioned prompt structures that can be instantiated with variables.
///
/// # Errors
///
/// Returns an error if storage fails.
///
/// # Examples
///
/// ```no_run
/// # use llm_memory_graph::{MemoryGraph, Config, PromptTemplate, VariableSpec};
/// # fn main() -> Result<(), Box<dyn std::error::Error>> {
/// # let graph = MemoryGraph::open(Config::default())?;
/// let variables = vec![
/// VariableSpec::new(
/// "user_input".to_string(),
/// "String".to_string(),
/// true,
/// "User's question".to_string(),
/// ),
/// ];
/// let template = PromptTemplate::new(
/// "Question Answering".to_string(),
/// "Answer this question: {{user_input}}".to_string(),
/// variables,
/// );
/// let template_id = graph.create_template(template)?;
/// # Ok(())
/// # }
/// ```
pub fn create_template(&self, template: PromptTemplate) -> Result<TemplateId> {
let template_id = template.id;
self.backend.store_node(&Node::Template(template))?;
Ok(template_id)
}
/// Get a template by its ID
///
/// # Errors
///
/// Returns an error if:
/// - The template doesn't exist
/// - Storage retrieval fails
///
/// # Examples
///
/// ```no_run
/// # use llm_memory_graph::{MemoryGraph, Config, PromptTemplate, VariableSpec};
/// # fn main() -> Result<(), Box<dyn std::error::Error>> {
/// # let graph = MemoryGraph::open(Config::default())?;
/// # let template = PromptTemplate::new("Test".to_string(), "{{x}}".to_string(), vec![]);
/// # let template_id = graph.create_template(template)?;
/// let template = graph.get_template(template_id)?;
/// # Ok(())
/// # }
/// ```
pub fn get_template(&self, _template_id: TemplateId) -> Result<PromptTemplate> {
// Templates store template_id as their primary ID, but we need the node_id
// We'll need to search for it - for now, let's try a direct approach
// In practice, we might want to add a template index to the storage backend
// For now, search all nodes (this is inefficient - TODO: add template index)
let stats = self.backend.stats()?;
for _ in 0..stats.node_count {
// This is a placeholder - we need a way to iterate all nodes
// or maintain a template index
}
Err(Error::NodeNotFound(
"Template lookup by TemplateId not yet fully implemented - use get_template_by_node_id instead".to_string()
))
}
/// Get a template by its node ID
///
/// # Errors
///
/// Returns an error if:
/// - The node doesn't exist or is not a template
/// - Storage retrieval fails
///
/// # Examples
///
/// ```no_run
/// # use llm_memory_graph::{MemoryGraph, Config, PromptTemplate};
/// # fn main() -> Result<(), Box<dyn std::error::Error>> {
/// # let graph = MemoryGraph::open(Config::default())?;
/// # let template = PromptTemplate::new("Test".to_string(), "{{x}}".to_string(), vec![]);
/// # let node_id = template.node_id;
/// # graph.create_template(template)?;
/// let template = graph.get_template_by_node_id(node_id)?;
/// # Ok(())
/// # }
/// ```
pub fn get_template_by_node_id(&self, node_id: NodeId) -> Result<PromptTemplate> {
let node = self
.backend
.get_node(&node_id)?
.ok_or_else(|| Error::NodeNotFound(format!("Node {} not found", node_id)))?;
match node {
Node::Template(template) => Ok(template),
_ => Err(Error::ValidationError(format!(
"Node {} is not a template",
node_id
))),
}
}
/// Update an existing template
///
/// This will store the updated template data. Note that the template's
/// version should be bumped appropriately before calling this method.
///
/// # Errors
///
/// Returns an error if storage update fails.
///
/// # Examples
///
/// ```no_run
/// # use llm_memory_graph::{MemoryGraph, Config, PromptTemplate, VersionLevel};
/// # fn main() -> Result<(), Box<dyn std::error::Error>> {
/// # let graph = MemoryGraph::open(Config::default())?;
/// # let template = PromptTemplate::new("Test".to_string(), "{{x}}".to_string(), vec![]);
/// # let node_id = template.node_id;
/// # graph.create_template(template)?;
/// let mut template = graph.get_template_by_node_id(node_id)?;
/// template.record_usage();
/// template.bump_version(VersionLevel::Patch);
/// graph.update_template(template)?;
/// # Ok(())
/// # }
/// ```
pub fn update_template(&self, template: PromptTemplate) -> Result<()> {
self.backend.store_node(&Node::Template(template))?;
Ok(())
}
/// Link a prompt to the template it was instantiated from
///
/// Creates an Instantiates edge from the prompt to the template.
///
/// # Errors
///
/// Returns an error if storage fails.
///
/// # Examples
///
/// ```no_run
/// # use llm_memory_graph::{MemoryGraph, Config, PromptTemplate, VariableSpec};
/// # use std::collections::HashMap;
/// # fn main() -> Result<(), Box<dyn std::error::Error>> {
/// # let graph = MemoryGraph::open(Config::default())?;
/// # let session = graph.create_session()?;
/// # let template = PromptTemplate::new("Test".to_string(), "Hello {{name}}".to_string(), vec![]);
/// # let template_node_id = template.node_id;
/// # graph.create_template(template.clone())?;
/// let mut values = HashMap::new();
/// values.insert("name".to_string(), "World".to_string());
/// let prompt_text = template.instantiate(&values)?;
/// let prompt_id = graph.add_prompt(session.id, prompt_text, None)?;
/// graph.link_prompt_to_template(prompt_id, template_node_id)?;
/// # Ok(())
/// # }
/// ```
pub fn link_prompt_to_template(
&self,
prompt_id: NodeId,
template_node_id: NodeId,
) -> Result<()> {
let edge = Edge::new(prompt_id, template_node_id, EdgeType::Instantiates);
self.backend.store_edge(&edge)?;
Ok(())
}
/// Create a new template that inherits from a parent template
///
/// This creates the new template and automatically establishes an Inherits edge.
///
/// # Errors
///
/// Returns an error if storage fails.
///
/// # Examples
///
/// ```no_run
/// # use llm_memory_graph::{MemoryGraph, Config, PromptTemplate, VariableSpec};
/// # fn main() -> Result<(), Box<dyn std::error::Error>> {
/// # let graph = MemoryGraph::open(Config::default())?;
/// # let parent = PromptTemplate::new("Parent".to_string(), "Base: {{x}}".to_string(), vec![]);
/// # let parent_id = parent.id;
/// # let parent_node_id = parent.node_id;
/// # graph.create_template(parent)?;
/// let child = PromptTemplate::from_parent(
/// parent_id,
/// "Child Template".to_string(),
/// "Extended: {{x}} with {{y}}".to_string(),
/// vec![],
/// );
/// let child_id = graph.create_template_from_parent(child, parent_node_id)?;
/// # Ok(())
/// # }
/// ```
pub fn create_template_from_parent(
&self,
template: PromptTemplate,
parent_node_id: NodeId,
) -> Result<TemplateId> {
let template_id = template.id;
let template_node_id = template.node_id;
// Store the new template
self.backend.store_node(&Node::Template(template))?;
// Create Inherits edge from child to parent
let edge = Edge::new(template_node_id, parent_node_id, EdgeType::Inherits);
self.backend.store_edge(&edge)?;
Ok(template_id)
}
}
#[cfg(test)]
mod tests {
use super::*;
use tempfile::tempdir;
#[test]
fn test_create_graph() {
let dir = tempdir().unwrap();
let config = Config::new(dir.path());
let graph = MemoryGraph::open(config).unwrap();
let stats = graph.stats().unwrap();
assert_eq!(stats.node_count, 0);
}
#[test]
fn test_create_session() {
let dir = tempdir().unwrap();
let config = Config::new(dir.path());
let graph = MemoryGraph::open(config).unwrap();
let session = graph.create_session().unwrap();
let retrieved = graph.get_session(session.id).unwrap();
assert_eq!(session.id, retrieved.id);
}
#[test]
fn test_add_prompt() {
let dir = tempdir().unwrap();
let config = Config::new(dir.path());
let graph = MemoryGraph::open(config).unwrap();
let session = graph.create_session().unwrap();
let prompt_id = graph
.add_prompt(session.id, "Test prompt".to_string(), None)
.unwrap();
let node = graph.get_node(prompt_id).unwrap();
assert!(matches!(node, Node::Prompt(_)));
}
#[test]
fn test_add_response() {
let dir = tempdir().unwrap();
let config = Config::new(dir.path());
let graph = MemoryGraph::open(config).unwrap();
let session = graph.create_session().unwrap();
let prompt_id = graph
.add_prompt(session.id, "Test prompt".to_string(), None)
.unwrap();
let usage = TokenUsage::new(10, 20);
let response_id = graph
.add_response(prompt_id, "Test response".to_string(), usage, None)
.unwrap();
let node = graph.get_node(response_id).unwrap();
assert!(matches!(node, Node::Response(_)));
}
#[test]
fn test_conversation_chain() {
let dir = tempdir().unwrap();
let config = Config::new(dir.path());
let graph = MemoryGraph::open(config).unwrap();
let session = graph.create_session().unwrap();
// Add first prompt
let prompt1 = graph
.add_prompt(session.id, "First prompt".to_string(), None)
.unwrap();
let usage1 = TokenUsage::new(5, 10);
let _response1 = graph
.add_response(prompt1, "First response".to_string(), usage1, None)
.unwrap();
// Add second prompt
let prompt2 = graph
.add_prompt(session.id, "Second prompt".to_string(), None)
.unwrap();
let usage2 = TokenUsage::new(6, 12);
let _response2 = graph
.add_response(prompt2, "Second response".to_string(), usage2, None)
.unwrap();
// Verify session has all nodes
let nodes = graph.get_session_nodes(session.id).unwrap();
assert!(nodes.len() >= 4); // session + 2 prompts + 2 responses
// Verify edges exist
let outgoing = graph.get_outgoing_edges(prompt2).unwrap();
assert!(!outgoing.is_empty());
}
#[test]
fn test_session_not_found() {
let dir = tempdir().unwrap();
let config = Config::new(dir.path());
let graph = MemoryGraph::open(config).unwrap();
let fake_session = SessionId::new();
let result = graph.get_session(fake_session);
assert!(result.is_err());
assert!(matches!(result.unwrap_err(), Error::SessionNotFound(_)));
}
#[test]
fn test_node_not_found() {
let dir = tempdir().unwrap();
let config = Config::new(dir.path());
let graph = MemoryGraph::open(config).unwrap();
let fake_node = NodeId::new();
let result = graph.get_node(fake_node);
assert!(result.is_err());
assert!(matches!(result.unwrap_err(), Error::NodeNotFound(_)));
}
#[test]
fn test_session_with_metadata() {
let dir = tempdir().unwrap();
let config = Config::new(dir.path());
let graph = MemoryGraph::open(config).unwrap();
let mut metadata = HashMap::new();
metadata.insert("user".to_string(), "alice".to_string());
let session = graph.create_session_with_metadata(metadata).unwrap();
let retrieved = graph.get_session(session.id).unwrap();
assert_eq!(retrieved.metadata.get("user"), Some(&"alice".to_string()));
}
}