comprehensive_demo/
comprehensive_demo.rs

1use std::time::Duration;
2
3use chrono::Utc;
4use llm_brain::{LLMBrain, Result};
5use serde_json::json;
6use tokio::time::sleep;
7
8/// Demonstrate storing and retrieving different memory types
9async fn demonstrate_memory_types(llm_brain: &LLMBrain) -> Result<()> {
10    println!("\n=== Demonstrating Memory Types ===");
11
12    // Create semantic memory - a Tesla car entity
13    println!("\nAdding semantic memory (Tesla Model 3)...");
14    let car_data = json!({
15        "name": "Tesla_Model_3",
16        "column": "Semantic",
17        "properties": {
18            "color": "red",
19            "year": "2023",
20            "mileage": "1000 miles",
21            "features": ["autopilot capabilities", "glass roof"],
22            "type": "electric vehicle"
23        },
24        "relationships": {
25            "type_of": ["Vehicle"],
26            "location": "garage"
27        }
28    });
29
30    let car_content = "The Tesla Model 3 is a red electric vehicle from 2023 with 1000 miles. \
31                      It features autopilot capabilities and a glass roof. It is parked in the garage.";
32
33    let car_id = llm_brain
34        .add_memory(car_content.to_owned(), car_data)
35        .await?;
36    println!("Added car memory with ID: {car_id}");
37
38    // Create episodic memory - buying the car
39    println!("\nAdding episodic memory (Buying the car)...");
40    let purchase_data = json!({
41        "name": "Tesla_Purchase",
42        "column": "Episodic",
43        "timestamp": Utc::now().to_rfc3339(),
44        "properties": {
45            "action": "Bought a new car",
46            "location": "Tesla Dealership",
47            "participants": ["Me", "Tesla Sales Representative"],
48            "emotion": "excited"
49        },
50        "relationships": {
51            "related_to": ["Tesla_Model_3"]
52        }
53    });
54
55    let purchase_content = "I bought a new Tesla Model 3 today at the Tesla Dealership. \
56                           The sales representative was very helpful. I was very excited about getting my new car.";
57
58    let purchase_id = llm_brain
59        .add_memory(purchase_content.to_owned(), purchase_data)
60        .await?;
61    println!("Added purchase memory with ID: {purchase_id}");
62
63    // Create procedural memory - charging the car
64    println!("\nAdding procedural memory (Charging the car)...");
65    let charging_data = json!({
66        "name": "Charge_Tesla",
67        "column": "Procedural",
68        "properties": {
69            "steps": [
70                "Park near charging station",
71                "Open charging port on car",
72                "Connect charging cable",
73                "Initiate charging via app or car interface",
74                "Wait for sufficient charge",
75                "Disconnect charging cable",
76                "Close charging port"
77            ],
78            "required_tools": ["Charging cable", "Tesla app"],
79            "estimated_time": "30-60 minutes",
80            "frequency": "weekly"
81        },
82        "relationships": {
83            "applies_to": ["Tesla_Model_3"]
84        }
85    });
86
87    let charging_content = "To charge a Tesla Model 3: First, park near a charging station. \
88                          Open the charging port on the car and connect the charging cable. \
89                          Then initiate charging via the app or car interface. Wait for 30-60 minutes \
90                          until there is sufficient charge. Finally, disconnect the charging cable \
91                          and close the charging port. This procedure should be performed weekly \
92                          and requires a charging cable and the Tesla app.";
93
94    let charging_id = llm_brain
95        .add_memory(charging_content.to_owned(), charging_data)
96        .await?;
97    println!("Added charging memory with ID: {charging_id}");
98
99    // Allow time for embeddings to be processed
100    sleep(Duration::from_millis(200)).await;
101
102    Ok(())
103}
104
105/// Demonstrate querying and memory recall capabilities
106async fn demonstrate_memory_recall(llm_brain: &LLMBrain) -> Result<()> {
107    println!("\n=== Demonstrating Memory Recall ===");
108
109    // Query for Tesla car
110    println!("\nQuerying for Tesla Model 3 information:");
111    let tesla_query = "What do I know about my Tesla Model 3?";
112    let tesla_results = llm_brain.recall(tesla_query, 3).await?;
113
114    for (i, (memory, score)) in tesla_results.iter().enumerate() {
115        println!("\nResult {}: Score {:.4}", i + 1, score);
116        println!("Content: {}", memory.content);
117        println!(
118            "Metadata: {}",
119            serde_json::to_string_pretty(&memory.metadata)?
120        );
121    }
122
123    // Query for car purchase experience
124    println!("\nQuerying for car purchase experience:");
125    let purchase_query = "When did I buy my Tesla?";
126    let purchase_results = llm_brain.recall(purchase_query, 2).await?;
127
128    for (i, (memory, score)) in purchase_results.iter().enumerate() {
129        println!("\nResult {}: Score {:.4}", i + 1, score);
130        println!("Content: {}", memory.content);
131        println!(
132            "Metadata: {}",
133            serde_json::to_string_pretty(&memory.metadata)?
134        );
135    }
136
137    // Query for charging instructions
138    println!("\nQuerying for charging instructions:");
139    let charging_query = "How do I charge my car?";
140    let charging_results = llm_brain.recall(charging_query, 2).await?;
141
142    for (i, (memory, score)) in charging_results.iter().enumerate() {
143        println!("\nResult {}: Score {:.4}", i + 1, score);
144        println!("Content: {}", memory.content);
145        println!(
146            "Metadata: {}",
147            serde_json::to_string_pretty(&memory.metadata)?
148        );
149    }
150
151    Ok(())
152}
153
154/// Demonstrate adding a memory and then finding it by similarity
155async fn demonstrate_memory_lookup(llm_brain: &LLMBrain) -> Result<()> {
156    println!("\n=== Demonstrating Memory Lookup ===");
157
158    // Add a new memory about a trip
159    println!("\nAdding memory about a road trip...");
160    let trip_data = json!({
161        "name": "Road_Trip_Tahoe",
162        "column": "Episodic",
163        "timestamp": Utc::now().to_rfc3339(),
164        "properties": {
165            "action": "Road trip to Lake Tahoe",
166            "location": "Lake Tahoe",
167            "participants": ["Me", "Family"],
168            "duration": "3 days",
169            "transportation": "Tesla Model 3",
170            "highlights": ["Beautiful scenery", "Hiking", "Swimming"]
171        }
172    });
173
174    let trip_content = "Last weekend, we took our Tesla Model 3 on a road trip to Lake Tahoe. \
175                       The drive was smooth and we enjoyed the beautiful scenery. \
176                       We spent 3 days there with the family, hiking and swimming in the lake. \
177                       The car performed excellently on the mountain roads.";
178
179    let trip_id = llm_brain
180        .add_memory(trip_content.to_owned(), trip_data)
181        .await?;
182    println!("Added trip memory with ID: {trip_id}");
183
184    // Allow time for embeddings to be processed
185    sleep(Duration::from_millis(200)).await;
186
187    // Now try to find this memory with various related queries
188    let queries = [
189        "Did we go on any trips with our Tesla?",
190        "What activities did we do at Lake Tahoe?",
191        "How did the Tesla perform on our road trip?",
192    ];
193
194    for (i, query) in queries.iter().enumerate() {
195        println!("\nQuery {}: \"{}\"", i + 1, query);
196        let results = llm_brain.recall(query, 1).await?;
197
198        if !results.is_empty() {
199            let (memory, score) = &results[0];
200            println!("Found memory (score: {score:.4}):");
201            println!("Content: {}", memory.content);
202        } else {
203            println!("No relevant memories found.");
204        }
205    }
206
207    // Direct lookup by ID
208    println!("\nDirect lookup by ID:");
209    if let Some(memory) = llm_brain
210        .get_memory_by_id_string(&trip_id.to_string())
211        .await?
212    {
213        println!("Successfully retrieved memory");
214        println!("Content: {}", memory.content);
215    } else {
216        println!("Failed to retrieve memory by ID");
217    }
218
219    Ok(())
220}
221
222#[tokio::main]
223async fn main() -> Result<()> {
224    // Initialize LLMBrain instance
225    println!("Initializing LLMBrain...");
226    let llm_brain = LLMBrain::launch().await?;
227
228    // Demonstrate different memory types
229    demonstrate_memory_types(&llm_brain).await?;
230
231    // Demonstrate memory recall
232    demonstrate_memory_recall(&llm_brain).await?;
233
234    // Demonstrate memory lookup
235    demonstrate_memory_lookup(&llm_brain).await?;
236
237    println!("\nComprehensive demonstration completed successfully!");
238    Ok(())
239}