-
Notifications
You must be signed in to change notification settings - Fork 4
Expand file tree
/
Copy pathknowledge_graph_integration.rs
More file actions
346 lines (280 loc) Β· 12.9 KB
/
Copy pathknowledge_graph_integration.rs
File metadata and controls
346 lines (280 loc) Β· 12.9 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
//! Knowledge Graph Integration Example
//!
//! This example demonstrates the knowledge graph intelligence features:
//! - Context enrichment from knowledge graph
//! - Semantic relationship discovery
//! - Query-specific context injection
//! - Multi-layered context assembly
use terraphim_config::Role;
use terraphim_multi_agent::{
test_utils::create_test_role, CommandInput, CommandType, MultiAgentResult, TerraphimAgent,
};
use terraphim_persistence::DeviceStorage;
/// Create a role configured for knowledge graph demonstration
fn create_knowledge_graph_role() -> Role {
let mut role = create_test_role();
role.name = "KnowledgeGraphAgent".into();
role.shortname = Some("kg_agent".to_string());
// Add knowledge domain configuration
role.extra.insert(
"knowledge_domain".to_string(),
serde_json::json!("rust_programming"),
);
role.extra.insert(
"specializations".to_string(),
serde_json::json!(["memory_management", "async_programming", "type_system"]),
);
role.extra
.insert("context_enrichment".to_string(), serde_json::json!(true));
// Configure for knowledge graph integration
role.extra
.insert("llm_provider".to_string(), serde_json::json!("ollama"));
role.extra
.insert("ollama_model".to_string(), serde_json::json!("gemma3:270m"));
role.extra
.insert("llm_temperature".to_string(), serde_json::json!(0.6)); // Balanced for knowledge work
role
}
/// Example 1: Basic Knowledge Graph Context Enrichment
async fn example_context_enrichment() -> MultiAgentResult<()> {
println!("π§ Example 1: Knowledge Graph Context Enrichment");
println!("===============================================");
// Initialize storage
let persistence = DeviceStorage::arc_memory_only()
.await
.map_err(|e| terraphim_multi_agent::MultiAgentError::PersistenceError(e.to_string()))?;
// Create knowledge graph enabled agent
let role = create_knowledge_graph_role();
let agent = TerraphimAgent::new(role, persistence, None).await?;
agent.initialize().await?;
println!(
"β
Created knowledge graph agent: {}",
agent.role_config.name
);
// Test queries that should trigger knowledge graph enrichment
let queries = vec![
"How does Rust handle memory management?",
"What are async functions in Rust?",
"Explain Rust's type system",
"How to handle errors in Rust?",
];
for query in queries {
println!("\nπ Query: {}", query);
// This will internally call get_enriched_context_for_query()
let input = CommandInput::new(query.to_string(), CommandType::Answer);
let output = agent.process_command(input).await?;
println!("π Response: {}", output.text);
// Check if context was enriched
let context = agent.context.read().await;
println!("π Context items: {}", context.items.len());
println!("π― Context tokens: {}", context.current_tokens);
}
Ok(())
}
/// Example 2: Semantic Relationship Discovery
async fn example_semantic_relationships() -> MultiAgentResult<()> {
println!("\nπΈοΈ Example 2: Semantic Relationship Discovery");
println!("===============================================");
// Initialize storage and agent
let persistence = DeviceStorage::arc_memory_only()
.await
.map_err(|e| terraphim_multi_agent::MultiAgentError::PersistenceError(e.to_string()))?;
let role = create_knowledge_graph_role();
let agent = TerraphimAgent::new(role, persistence, None).await?;
agent.initialize().await?;
// Queries designed to test semantic relationships
let relationship_queries = vec![
(
"ownership",
"How does Rust ownership relate to memory safety?",
),
(
"borrowing",
"What's the relationship between borrowing and lifetimes?",
),
("async await", "How do async/await relate to Rust futures?"),
("traits generics", "How do traits work with generic types?"),
];
for (concept, query) in relationship_queries {
println!("\nπ― Concept: {} | Query: {}", concept, query);
let input = CommandInput::new(query.to_string(), CommandType::Analyze);
let output = agent.process_command(input).await?;
println!("π Analysis: {}", output.text);
// The agent internally uses:
// - rolegraph.find_matching_node_ids(query)
// - rolegraph.is_all_terms_connected_by_path(query)
// - rolegraph.query_graph(query, Some(3), None)
println!(" β
Knowledge graph relationships analyzed");
}
Ok(())
}
/// Example 3: Multi-layered Context Assembly
async fn example_multilayer_context() -> MultiAgentResult<()> {
println!("\nποΈ Example 3: Multi-layered Context Assembly");
println!("==============================================");
// Initialize storage and agent
let persistence = DeviceStorage::arc_memory_only()
.await
.map_err(|e| terraphim_multi_agent::MultiAgentError::PersistenceError(e.to_string()))?;
let mut role = create_knowledge_graph_role();
// Add haystack configuration to demonstrate multi-layered context
role.haystacks.push(terraphim_config::Haystack {
read_only: true,
atomic_server_secret: None,
extra_parameters: std::collections::HashMap::new(),
location: "./rust_docs".to_string(),
service: terraphim_config::ServiceType::Ripgrep,
fetch_content: false,
});
let agent = TerraphimAgent::new(role, persistence, None).await?;
agent.initialize().await?;
// Add some context to agent memory first (simulate previous interactions)
{
let mut context = agent.context.write().await;
context.add_item(terraphim_multi_agent::ContextItem::new(
terraphim_multi_agent::ContextItemType::Memory,
"Previous discussion about Rust memory management principles".to_string(),
25,
0.8,
))?;
context.add_item(terraphim_multi_agent::ContextItem::new(
terraphim_multi_agent::ContextItemType::Memory,
"User is learning about advanced Rust concepts".to_string(),
20,
0.7,
))?;
}
println!("π Added memory context for demonstration");
// Query that will trigger multi-layered context assembly
let complex_query = "How can I optimize memory allocation in async Rust applications?";
println!("π Complex Query: {}", complex_query);
println!("\nποΈ Multi-layered context will include:");
println!(" 1. Knowledge graph nodes matching the query terms");
println!(" 2. Semantic connectivity analysis");
println!(" 3. Related concepts from graph traversal");
println!(" 4. Relevant items from agent memory");
println!(" 5. Available haystack search sources");
let input = CommandInput::new(complex_query.to_string(), CommandType::Analyze);
let output = agent.process_command(input).await?;
println!("\nπ Comprehensive Analysis:");
println!("{}", output.text);
// Show final context state
let context = agent.context.read().await;
println!("\nπ Final Context Statistics:");
println!(" Total items: {}", context.items.len());
println!(" Total tokens: {}", context.current_tokens);
println!(
" Token utilization: {:.1}%",
(context.current_tokens as f32 / context.max_tokens as f32) * 100.0
);
Ok(())
}
/// Example 4: Context-Aware Command Comparison
async fn example_context_aware_commands() -> MultiAgentResult<()> {
println!("\nποΈ Example 4: Context-Aware Command Comparison");
println!("===============================================");
// Initialize storage and agent
let persistence = DeviceStorage::arc_memory_only()
.await
.map_err(|e| terraphim_multi_agent::MultiAgentError::PersistenceError(e.to_string()))?;
let role = create_knowledge_graph_role();
let agent = TerraphimAgent::new(role, persistence, None).await?;
agent.initialize().await?;
let base_query = "Rust async programming patterns";
println!("π― Base Query: {}", base_query);
println!("\nπ Testing all command types with knowledge graph enrichment:");
// Test each command type with the same query to show different behaviors
let command_types = vec![
(CommandType::Generate, "Creative generation with context"),
(CommandType::Answer, "Knowledge-based Q&A with enrichment"),
(
CommandType::Analyze,
"Structured analysis with graph insights",
),
(CommandType::Create, "Innovation with related concepts"),
(
CommandType::Review,
"Balanced review with comprehensive context",
),
];
for (command_type, description) in command_types {
println!("\nπΈ {} ({:?})", description, command_type);
let input = CommandInput::new(base_query.to_string(), command_type);
let start = std::time::Instant::now();
let output = agent.process_command(input).await?;
let duration = start.elapsed();
println!(" β±οΈ Processing time: {:?}", duration);
println!(" π Response: {}", output.text);
// Each command type uses the same get_enriched_context_for_query() but processes it differently
// based on temperature and system prompt variations
}
println!("\nβ
All command types successfully used knowledge graph enrichment!");
Ok(())
}
/// Example 5: Knowledge Graph Performance Analysis
async fn example_performance_analysis() -> MultiAgentResult<()> {
println!("\nβ‘ Example 5: Knowledge Graph Performance Analysis");
println!("=================================================");
// Initialize storage and agent
let persistence = DeviceStorage::arc_memory_only()
.await
.map_err(|e| terraphim_multi_agent::MultiAgentError::PersistenceError(e.to_string()))?;
let role = create_knowledge_graph_role();
let agent = TerraphimAgent::new(role, persistence, None).await?;
agent.initialize().await?;
// Test performance with different query complexities
let test_queries = vec![
("Simple", "Rust"),
("Medium", "Rust memory management"),
(
"Complex",
"How does Rust's ownership system interact with async programming patterns?",
),
(
"Very Complex",
"What are the performance implications of different async runtime configurations in Rust applications with heavy concurrent workloads?",
),
];
println!("π Performance Analysis of Knowledge Graph Enrichment:");
for (complexity, query) in test_queries {
println!("\nπ {} Query: {}", complexity, query);
let input = CommandInput::new(query.to_string(), CommandType::Answer);
// Measure context enrichment performance
let start = std::time::Instant::now();
let output = agent.process_command(input).await?;
let total_duration = start.elapsed();
// Get tracking information
let _token_tracker = agent.token_tracker.read().await;
let context = agent.context.read().await;
println!(" β±οΈ Total time: {:?}", total_duration);
println!(" π§ Context items: {}", context.items.len());
println!(" π« Context tokens: {}", context.current_tokens);
println!(" π Response length: {} chars", output.text.len());
// Calculate enrichment efficiency
let efficiency = output.text.len() as f32 / total_duration.as_millis() as f32;
println!(" π Efficiency: {:.2} chars/ms", efficiency);
}
println!("\nβ
Knowledge graph performance analysis completed!");
println!("π― The system efficiently handles queries of all complexity levels!");
Ok(())
}
#[tokio::main]
async fn main() -> Result<(), Box<dyn std::error::Error>> {
println!("π§ Terraphim Knowledge Graph Integration Examples");
println!("=================================================\n");
// Run all knowledge graph examples
example_context_enrichment().await?;
example_semantic_relationships().await?;
example_multilayer_context().await?;
example_context_aware_commands().await?;
example_performance_analysis().await?;
println!("\nβ
All knowledge graph examples completed successfully!");
println!("π Knowledge graph integration is working perfectly!");
println!("\nπ Key Features Demonstrated:");
println!(" β’ Smart context enrichment with get_enriched_context_for_query()");
println!(" β’ RoleGraph integration with semantic analysis");
println!(" β’ Multi-layered context assembly (graph + memory + haystacks)");
println!(" β’ Context-aware command processing with different temperatures");
println!(" β’ Performance optimization with efficient knowledge retrieval");
Ok(())
}