1use crate::error::Result;
4
5pub struct KnowledgeBaseExample;
9
10impl KnowledgeBaseExample {
11 #[allow(dead_code)]
13 pub async fn knowledge_storage() -> Result<()> {
14 use crate::knowledge_base::{KnowledgeBase, KnowledgeDomain, KnowledgeEntry};
15
16 println!("=== Knowledge Base Example ===");
17 println!();
18
19 let mut kb = KnowledgeBase::new();
20
21 let entry1 = KnowledgeEntry {
23 id: "sol-basics".to_string(),
24 domain: KnowledgeDomain::Blockchain,
25 title: "Solidity Smart Contracts".to_string(),
26 content: "Solidity is a statically-typed language for Ethereum...".to_string(),
27 tags: vec![
28 "solidity".to_string(),
29 "ethereum".to_string(),
30 "smart contracts".to_string(),
31 ],
32 source: Some("https://docs.soliditylang.org".to_string()),
33 confidence: 0.95,
34 created_at: chrono::Utc::now(),
35 updated_at: chrono::Utc::now(),
36 };
37
38 let _ = kb.add_entry(entry1);
39
40 println!("Knowledge base created:");
41 println!(" Domains: Programming, Blockchain, Security, etc.");
42 println!(" Entries: Indexed by tags");
43 println!(" Search: Fast tag and relevance-based");
44 println!();
45 println!("Example entry:");
46 println!(" Title: Solidity Smart Contracts");
47 println!(" Domain: Blockchain");
48 println!(" Tags: solidity, ethereum, smart contracts");
49
50 Ok(())
51 }
52
53 #[allow(dead_code)]
55 pub async fn keyword_search() -> Result<()> {
56 use crate::knowledge_base::{KnowledgeBase, KnowledgeDomain, KnowledgeEntry};
57
58 println!("=== Keyword-Based Search ===");
59 println!();
60
61 let mut kb = KnowledgeBase::new();
62
63 let entry = KnowledgeEntry {
65 id: "rust-ownership".to_string(),
66 domain: KnowledgeDomain::Programming,
67 title: "Rust Ownership System".to_string(),
68 content: "Rust's ownership system ensures memory safety...".to_string(),
69 tags: vec![
70 "rust".to_string(),
71 "ownership".to_string(),
72 "memory safety".to_string(),
73 ],
74 source: Some("https://doc.rust-lang.org/book/".to_string()),
75 confidence: 0.98,
76 created_at: chrono::Utc::now(),
77 updated_at: chrono::Utc::now(),
78 };
79
80 let _ = kb.add_entry(entry);
81
82 let results = kb.search("rust ownership");
84
85 println!("Search: 'rust ownership'");
86 println!("Found {} results", results.len());
87 for entry in results {
88 println!(" * {}", entry.title);
89 }
90
91 Ok(())
92 }
93
94 #[allow(dead_code)]
96 pub async fn ai_integration(api_key: &str) -> Result<()> {
97 use crate::ai_evaluator::AiEvaluator;
98 use crate::knowledge_base::KnowledgeBase;
99 use crate::llm::LlmClientBuilder;
100
101 println!("=== AI Evaluator + Knowledge Base ===");
102 println!();
103
104 let _kb = KnowledgeBase::new();
105 let llm = LlmClientBuilder::new()
106 .openai_api_key(api_key)
107 .build()
108 .expect("Failed to build LLM client");
109
110 let _evaluator = AiEvaluator::new(llm);
111
112 println!("Integration workflow:");
113 println!(" 1. Search knowledge base for relevant info");
114 println!(" 2. Include in evaluation context");
115 println!(" 3. AI provides domain-aware feedback");
116 println!();
117 println!("Example:");
118 println!(" Code: Solidity smart contract");
119 println!(" KB: Retrieve Solidity best practices");
120 println!(" AI: Evaluate against known patterns");
121 println!(" Result: More accurate, context-aware review");
122
123 Ok(())
124 }
125
126 #[allow(dead_code)]
128 pub async fn persistence() -> Result<()> {
129 use crate::knowledge_base::KnowledgeBase;
130
131 println!("=== Knowledge Base Persistence ===");
132 println!();
133
134 let kb = KnowledgeBase::new();
135
136 kb.save_to_file("/tmp/knowledge_base.json")?;
138 println!("Saved to /tmp/knowledge_base.json");
139
140 let _loaded_kb = KnowledgeBase::load_from_file("/tmp/knowledge_base.json")?;
142 println!("Loaded from /tmp/knowledge_base.json");
143 println!();
144 println!("Benefits:");
145 println!(" * Preserve domain knowledge");
146 println!(" * Share across team");
147 println!(" * Version control");
148 println!(" * Backup and restore");
149
150 Ok(())
151 }
152
153 #[allow(dead_code)]
155 pub async fn multi_domain() -> Result<()> {
156 use crate::knowledge_base::KnowledgeBase;
157
158 println!("=== Multi-Domain Knowledge Base ===");
159 println!();
160
161 let _kb = KnowledgeBase::new();
162
163 println!("Supported domains:");
164 println!(" * Programming (Rust, Python, JavaScript, etc.)");
165 println!(" * Blockchain (Ethereum, Bitcoin, Solana, etc.)");
166 println!(" * Security (OWASP, CVEs, best practices)");
167 println!(" * MachineLearning (models, algorithms, frameworks)");
168 println!(" * DevOps (CI/CD, containers, cloud)");
169 println!(" * General (miscellaneous knowledge)");
170 println!();
171 println!("Query by domain:");
172 println!(" let blockchain = kb.get_by_domain(KnowledgeDomain::Blockchain);");
173 println!(" let security = kb.get_by_domain(KnowledgeDomain::Security);");
174
175 Ok(())
176 }
177}
178
179pub struct PerformanceProfilingExample;
184
185impl PerformanceProfilingExample {
186 pub async fn basic_profiling() -> Result<()> {
188 use crate::profiling::{OperationMetrics, PerformanceProfiler};
189 use std::time::Duration;
190
191 println!("=== Basic Performance Profiling ===");
192 println!();
193
194 let profiler = PerformanceProfiler::new();
195
196 println!("Recording operations...");
198 for i in 0..5 {
199 let metrics = OperationMetrics::new(
200 "code_evaluation".to_string(),
201 Duration::from_millis(100 + i * 50),
202 true,
203 )
204 .with_tokens(1500)
205 .with_cost(0.002);
206
207 profiler.record(metrics);
208 }
209
210 if let Some(stats) = profiler.get_stats("code_evaluation") {
212 println!("Code Evaluation Statistics:");
213 println!(" Total operations: {}", stats.total_count);
214 println!(" Success rate: {:.1}%", stats.success_rate * 100.0);
215 println!(" Avg duration: {:.2}ms", stats.avg_duration.as_millis());
216 println!(" Min duration: {:.2}ms", stats.min_duration.as_millis());
217 println!(" Max duration: {:.2}ms", stats.max_duration.as_millis());
218 println!(" Total tokens: {}", stats.total_tokens);
219 println!(" Total cost: ${:.4}", stats.total_cost);
220 }
221
222 Ok(())
223 }
224
225 pub async fn scoped_profiling() -> Result<()> {
227 use crate::profiling::{PerformanceProfiler, ScopedProfiler};
228 use std::sync::Arc;
229
230 println!("=== Scoped Profiling ===");
231 println!();
232
233 let profiler = Arc::new(PerformanceProfiler::new());
234
235 println!("Profiling code evaluation...");
236 {
237 let _scope = ScopedProfiler::new("code_evaluation".to_string(), profiler.clone());
238 tokio::time::sleep(std::time::Duration::from_millis(150)).await;
240 }
242
243 println!("Profiling fraud detection...");
244 {
245 let _scope = ScopedProfiler::new("fraud_detection".to_string(), profiler.clone());
246 tokio::time::sleep(std::time::Duration::from_millis(200)).await;
247 }
248
249 let report = profiler.generate_report();
251 println!();
252 println!("Performance Report:");
253 println!(" Total operations: {}", report.total_operations);
254 println!(" Total cost: ${:.4}", report.total_cost);
255 println!(" Total tokens: {}", report.total_tokens);
256 println!(" Operations by type: {}", report.operation_stats.len());
257
258 Ok(())
259 }
260
261 pub async fn comparative_analysis() -> Result<()> {
263 use crate::profiling::{OperationMetrics, PerformanceProfiler};
264 use std::time::Duration;
265
266 println!("=== Comparative Performance Analysis ===");
267 println!();
268
269 let profiler = PerformanceProfiler::new();
270
271 println!("Recording GPT-4 operations...");
273 for _ in 0..10 {
274 let metrics =
275 OperationMetrics::new("gpt-4".to_string(), Duration::from_millis(200), true)
276 .with_tokens(2000)
277 .with_cost(0.04);
278 profiler.record(metrics);
279 }
280
281 println!("Recording Claude operations...");
283 for _ in 0..10 {
284 let metrics =
285 OperationMetrics::new("claude".to_string(), Duration::from_millis(180), true)
286 .with_tokens(1800)
287 .with_cost(0.036);
288 profiler.record(metrics);
289 }
290
291 println!("Recording Gemini operations...");
293 for _ in 0..10 {
294 let metrics =
295 OperationMetrics::new("gemini".to_string(), Duration::from_millis(150), true)
296 .with_tokens(1900)
297 .with_cost(0.019);
298 profiler.record(metrics);
299 }
300
301 println!();
302 println!("Performance Comparison:");
303 println!("+---------+----------+----------+------------+----------+");
304 println!("| Model | Avg Time | Tokens | Total Cost | Success |");
305 println!("+---------+----------+----------+------------+----------+");
306
307 for model in ["gpt-4", "claude", "gemini"] {
308 if let Some(stats) = profiler.get_stats(model) {
309 println!(
310 "| {:<7} | {:>6}ms | {:>8} | ${:>9.4} | {:>7.1}% |",
311 model,
312 stats.avg_duration.as_millis(),
313 stats.total_tokens,
314 stats.total_cost,
315 stats.success_rate * 100.0
316 );
317 }
318 }
319 println!("+---------+----------+----------+------------+----------+");
320
321 println!();
322 println!("Winner: Gemini (fastest + cheapest)");
323
324 Ok(())
325 }
326
327 pub async fn cost_optimization() -> Result<()> {
329 use crate::profiling::{OperationMetrics, PerformanceProfiler};
330 use std::time::Duration;
331
332 println!("=== Cost Optimization Tracking ===");
333 println!();
334
335 let profiler = PerformanceProfiler::new();
336
337 println!("Tracking costs over 24 hours simulation...");
339
340 for _ in 0..100 {
342 let metrics =
343 OperationMetrics::new("evaluation".to_string(), Duration::from_millis(200), true)
344 .with_tokens(2000)
345 .with_cost(0.04);
346 profiler.record(metrics);
347 }
348
349 let report_before = profiler.generate_report();
350 println!("Before optimization:");
351 println!(" Total cost: ${:.2}", report_before.total_cost);
352 println!(
353 " Avg cost/op: ${:.4}",
354 report_before.total_cost / report_before.total_operations as f64
355 );
356
357 for _ in 0..100 {
359 let metrics = OperationMetrics::new(
360 "evaluation_optimized".to_string(),
361 Duration::from_millis(150),
362 true,
363 )
364 .with_tokens(1800)
365 .with_cost(0.018); profiler.record(metrics);
367 }
368
369 println!();
370 println!("After optimization:");
371 if let Some(stats) = profiler.get_stats("evaluation_optimized") {
372 let avg_cost = if stats.total_count > 0 {
373 stats.total_cost / stats.total_count as f64
374 } else {
375 0.0
376 };
377 println!(" Total cost: ${:.2}", stats.total_cost);
378 println!(" Avg cost/op: ${avg_cost:.4}");
379 println!(" Cost savings: 55%");
380 println!(" Monthly projection: ${:.2}", stats.total_cost * 15.0); }
382
383 println!();
384 println!("Optimization strategies applied:");
385 println!(" * Switched to cheaper model for simple tasks");
386 println!(" * Implemented response caching");
387 println!(" * Batched similar requests");
388
389 Ok(())
390 }
391
392 pub async fn realtime_monitoring() -> Result<()> {
394 use crate::profiling::{OperationMetrics, PerformanceProfiler};
395 use std::time::Duration;
396
397 println!("=== Real-time Performance Monitoring ===");
398 println!();
399
400 let mut profiler = PerformanceProfiler::new();
401 profiler.enable();
402
403 println!("Processing operations...");
404 for i in 0..5 {
405 let success = i < 4; let metrics = OperationMetrics::new(
407 "api_call".to_string(),
408 Duration::from_millis(100 + i * 30),
409 success,
410 )
411 .with_tokens((1000 + i * 200) as u32)
412 .with_cost(0.02 + i as f64 * 0.005);
413
414 if success {
415 profiler.record(metrics);
416 } else {
417 let metrics = metrics.with_error("Rate limit exceeded".to_string());
418 profiler.record(metrics);
419 }
420
421 if let Some(stats) = profiler.get_stats("api_call") {
423 println!(
424 "[{}] Requests: {} | Success: {:.1}% | Avg latency: {}ms | Cost: ${:.4}",
425 i + 1,
426 stats.total_count,
427 stats.success_rate * 100.0,
428 stats.avg_duration.as_millis(),
429 stats.total_cost
430 );
431 }
432 }
433
434 println!();
435 println!("Monitoring alerts:");
436 if let Some(stats) = profiler.get_stats("api_call") {
437 if stats.success_rate < 0.95 {
438 println!(" Warning: Success rate below 95%");
439 }
440 if stats.avg_duration.as_millis() > 150 {
441 println!(" Warning: Average latency above threshold");
442 }
443 }
444
445 Ok(())
446 }
447}
448
449pub struct ModelVersionManagementExample;
454
455impl ModelVersionManagementExample {
456 pub async fn basic_version_tracking() -> Result<()> {
458 use crate::model_version::{ModelMetrics, ModelRegistry, ModelVersion};
459
460 println!("=== Basic Model Version Tracking ===");
461 println!();
462
463 let mut registry = ModelRegistry::new();
464
465 println!("Registering model versions...");
467
468 let gpt4_v1 = ModelVersion::new("gpt-4-turbo", "20240301", "GPT-4 Turbo March 2024");
469 registry.register_version(gpt4_v1)?;
470
471 let gpt4_v2 = ModelVersion::new(
472 "gpt-4-turbo",
473 "20240601",
474 "GPT-4 Turbo June 2024 - Improved reasoning",
475 );
476 registry.register_version(gpt4_v2)?;
477
478 println!("Registered versions:");
479 for version in registry.get_model_versions("gpt-4-turbo") {
480 println!(" * {} ({})", version.version, version.description);
481 }
482
483 println!();
485 println!("Recording performance metrics...");
486 let metrics_v1 = ModelMetrics::new(94.5, 1500, 0.04);
487 registry.update_metrics("gpt-4-turbo", "20240301", metrics_v1)?;
488
489 let metrics_v2 = ModelMetrics::new(96.2, 1400, 0.042);
490 registry.update_metrics("gpt-4-turbo", "20240601", metrics_v2)?;
491
492 println!("Metrics updated successfully");
493
494 Ok(())
495 }
496
497 pub async fn version_comparison() -> Result<()> {
499 use crate::model_version::{ModelMetrics, ModelRegistry, ModelVersion};
500
501 println!("=== Model Version Comparison ===");
502 println!();
503
504 let mut registry = ModelRegistry::new();
505
506 let claude_opus =
508 ModelVersion::new("claude-3-opus", "20240229", "Claude 3 Opus - Most capable");
509 registry.register_version(claude_opus)?;
510
511 let claude_sonnet = ModelVersion::new(
512 "claude-3-5-sonnet",
513 "20241022",
514 "Claude 3.5 Sonnet - Balanced",
515 );
516 registry.register_version(claude_sonnet)?;
517
518 let claude_haiku =
519 ModelVersion::new("claude-3-haiku", "20240307", "Claude 3 Haiku - Fastest");
520 registry.register_version(claude_haiku)?;
521
522 registry.update_metrics(
524 "claude-3-opus",
525 "20240229",
526 ModelMetrics::new(97.8, 2000, 0.075),
527 )?;
528
529 registry.update_metrics(
530 "claude-3-5-sonnet",
531 "20241022",
532 ModelMetrics::new(96.5, 1800, 0.045),
533 )?;
534
535 registry.update_metrics(
536 "claude-3-haiku",
537 "20240307",
538 ModelMetrics::new(93.2, 1200, 0.0125),
539 )?;
540
541 println!("Claude Model Comparison:");
543 println!("+------------------+----------+--------+----------+-------------+");
544 println!("| Model | Accuracy | Tokens | Avg Cost | Cost/Acc |");
545 println!("+------------------+----------+--------+----------+-------------+");
546
547 for (model, version) in [
548 ("claude-3-opus", "20240229"),
549 ("claude-3-5-sonnet", "20241022"),
550 ("claude-3-haiku", "20240307"),
551 ] {
552 if let Some(v) = registry.get_version(model, version) {
553 println!(
554 "| {:<16} | {:>7.1}% | {:>6} | ${:>7.4} | {:>11.2} |",
555 model,
556 v.metrics.accuracy,
557 v.metrics.avg_tokens,
558 v.metrics.avg_cost,
559 v.metrics.cost_effectiveness()
560 );
561 }
562 }
563 println!("+------------------+----------+--------+----------+-------------+");
564
565 println!();
566 println!("Recommendations:");
567 println!(" * For maximum accuracy: claude-3-opus (97.8%)");
568 println!(" * For best value: claude-3-5-sonnet (2144 cost-effectiveness)");
569 println!(" * For lowest cost: claude-3-haiku ($0.0125/request)");
570
571 Ok(())
572 }
573
574 pub async fn performance_tracking() -> Result<()> {
576 use crate::model_version::{ModelMetrics, ModelRegistry, ModelVersion};
577
578 println!("=== Model Performance Over Time ===");
579 println!();
580
581 let mut registry = ModelRegistry::new();
582
583 let gpt4 = ModelVersion::new("gpt-4-turbo", "20240801", "GPT-4 Turbo August 2024");
584 registry.register_version(gpt4)?;
585
586 println!("Tracking performance over time...");
587 println!();
588
589 let mut metrics = ModelMetrics::new(95.0, 1500, 0.04);
591
592 for _ in 0..100 {
594 metrics.record_request(1500, 0.04, 200.0, true);
595 }
596 println!(
597 "Week 1: Accuracy={:.1}%, Requests={}, Cost=${:.2}",
598 metrics.accuracy,
599 metrics.total_requests,
600 metrics.avg_cost * metrics.total_requests as f64
601 );
602
603 for i in 0..100 {
605 let success = i % 10 != 0; metrics.record_request(1500, 0.04, 220.0, success);
607 }
608 println!(
609 "Week 2: Accuracy={:.1}%, Requests={}, Errors={}",
610 metrics.accuracy, metrics.total_requests, metrics.total_errors
611 );
612
613 for _ in 0..100 {
615 metrics.record_request(1400, 0.038, 180.0, true);
616 }
617 println!(
618 "Week 3: Accuracy={:.1}%, Avg Latency={:.1}ms, Cost=${:.4}",
619 metrics.accuracy, metrics.avg_latency_ms, metrics.avg_cost
620 );
621
622 registry.update_metrics("gpt-4-turbo", "20240801", metrics)?;
623
624 println!();
625 println!("Analysis:");
626 if let Some(v) = registry.get_version("gpt-4-turbo", "20240801") {
627 println!(" Total requests: {}", v.metrics.total_requests);
628 println!(" Error rate: {:.2}%", v.metrics.error_rate());
629 println!(" Average latency: {:.1}ms", v.metrics.avg_latency_ms);
630 println!(
631 " Cost effectiveness: {:.2}",
632 v.metrics.cost_effectiveness()
633 );
634 }
635
636 Ok(())
637 }
638
639 pub async fn ab_testing() -> Result<()> {
641 use crate::model_version::{ModelMetrics, ModelRegistry, ModelVersion};
642
643 println!("=== A/B Testing Model Versions ===");
644 println!();
645
646 let mut registry = ModelRegistry::new();
647
648 let version_a = ModelVersion::new("custom-model", "v1.0", "Baseline model");
650 registry.register_version(version_a)?;
651
652 let version_b = ModelVersion::new(
653 "custom-model",
654 "v1.1",
655 "Optimized model with new training data",
656 );
657 registry.register_version(version_b)?;
658
659 println!("A/B Test: custom-model v1.0 vs v1.1");
660 println!();
661
662 let mut metrics_a = ModelMetrics::new(94.0, 1600, 0.035);
664 let mut metrics_b = ModelMetrics::new(95.5, 1550, 0.034);
665
666 println!("Running A/B test with 1000 requests...");
667 for _ in 0..500 {
668 metrics_a.record_request(1600, 0.035, 195.0, true);
669 metrics_b.record_request(1550, 0.034, 185.0, true);
670 }
671
672 registry.update_metrics("custom-model", "v1.0", metrics_a)?;
673 registry.update_metrics("custom-model", "v1.1", metrics_b)?;
674
675 println!();
676 println!("A/B Test Results:");
677 println!("+-----------+----------+----------+----------+------------+");
678 println!("| Version | Accuracy | Latency | Avg Cost | Recommend |");
679 println!("+-----------+----------+----------+----------+------------+");
680
681 if let Some(v1) = registry.get_version("custom-model", "v1.0") {
682 println!(
683 "| v1.0 (A) | {:>7.1}% | {:>6.0}ms | ${:>6.4} | |",
684 v1.metrics.accuracy, v1.metrics.avg_latency_ms, v1.metrics.avg_cost
685 );
686 }
687 if let Some(v2) = registry.get_version("custom-model", "v1.1") {
688 println!(
689 "| v1.1 (B) | {:>7.1}% | {:>6.0}ms | ${:>6.4} | Winner |",
690 v2.metrics.accuracy, v2.metrics.avg_latency_ms, v2.metrics.avg_cost
691 );
692 }
693 println!("+-----------+----------+----------+----------+------------+");
694
695 println!();
696 println!("Decision: Promote v1.1 to production");
697 println!("Improvements:");
698 println!(" * +1.5% accuracy improvement");
699 println!(" * -10ms latency reduction");
700 println!(" * -2.9% cost reduction");
701
702 registry.set_active_version("custom-model", "v1.1")?;
704 println!();
705 println!("v1.1 is now the active version");
706
707 Ok(())
708 }
709
710 pub async fn deprecation_workflow() -> Result<()> {
712 use crate::model_version::{ModelRegistry, ModelVersion};
713
714 println!("=== Model Deprecation Workflow ===");
715 println!();
716
717 let mut registry = ModelRegistry::new();
718
719 let old_version = ModelVersion::new("gpt-3.5-turbo", "0301", "GPT-3.5 Turbo - March 2023");
721 registry.register_version(old_version)?;
722
723 let new_version = ModelVersion::new("gpt-4-turbo", "20240401", "GPT-4 Turbo - April 2024");
724 registry.register_version(new_version)?;
725
726 println!("Models registered:");
727 println!(" * gpt-3.5-turbo (0301) - Old version");
728 println!(" * gpt-4-turbo (20240401) - New version");
729
730 println!();
732 println!("Deprecating gpt-3.5-turbo...");
733 registry.deprecate_version("gpt-3.5-turbo", "0301")?;
734
735 println!("Model marked as deprecated");
736 println!();
737 println!("Migration path:");
738 println!(" 1. Update applications to use gpt-4-turbo");
739 println!(" 2. Monitor performance metrics");
740 println!(" 3. Gradual traffic shift (0% -> 100%)");
741 println!(" 4. Remove deprecated model after 90 days");
742
743 registry.set_active_version("gpt-4-turbo", "20240401")?;
745
746 println!();
747 println!("Active models:");
748 if let Some(active) = registry.get_active_version("gpt-4-turbo") {
749 println!(" * {} - {}", active.version, active.description);
750 }
751
752 println!();
753 println!("Deprecated models:");
754 println!(" gpt-3.5-turbo (0301) - Deprecated");
755
756 Ok(())
757 }
758}