Skip to main content

kaccy_ai/examples/
basic.rs

1//! Basic usage examples: code evaluation, batch processing, oracle consensus,
2//! complete service setup, fraud detection, and integration patterns.
3
4use std::sync::Arc;
5
6use rust_decimal::Decimal;
7use uuid::Uuid;
8
9use crate::access_control::{AccessControlManager, AccessTier, AiFeature, TokenHolder};
10use crate::ai_evaluator::{AiEvaluator, AiFraudDetector, EvaluatorConfig};
11use crate::batch::{BatchCodeEvaluator, BatchConfig};
12use crate::error::Result;
13use crate::evaluator::QualityEvaluator;
14use crate::llm::{LlmClient, OpenAiClient};
15use crate::oracle::AiOracle;
16use crate::presets::{AccessTierPresets, ProductionPreset};
17use crate::service::{AiServiceBuilder, AiServiceHub};
18
19/// Example: Basic code evaluation workflow
20///
21/// Demonstrates how to:
22/// - Set up an LLM client
23/// - Create an evaluator
24/// - Evaluate code quality
25pub struct BasicCodeEvaluationExample;
26
27impl BasicCodeEvaluationExample {
28    /// Run the basic code evaluation example
29    ///
30    /// # Example
31    /// ```no_run
32    /// use kaccy_ai::examples::BasicCodeEvaluationExample;
33    ///
34    /// # #[tokio::main]
35    /// # async fn main() -> Result<(), Box<dyn std::error::Error>> {
36    /// BasicCodeEvaluationExample::run("your-api-key").await?;
37    /// # Ok(())
38    /// # }
39    /// ```
40    pub async fn run(api_key: &str) -> Result<()> {
41        // 1. Create an OpenAI client
42        let openai = OpenAiClient::with_default_model(api_key);
43        let llm_client = LlmClient::new(Box::new(openai));
44
45        // 2. Create an evaluator with default config
46        let evaluator = AiEvaluator::with_config(llm_client, EvaluatorConfig::default());
47
48        // 3. Evaluate some code
49        let code = r"
50            fn factorial(n: u64) -> u64 {
51                if n == 0 { 1 } else { n * factorial(n - 1) }
52            }
53        ";
54
55        let result = evaluator.evaluate_code(code, "rust").await?;
56
57        println!("Quality Score: {}", result.quality_score);
58        println!("Complexity Score: {}", result.complexity_score);
59        println!("Originality Score: {}", result.originality_score);
60        println!("Feedback: {}", result.feedback);
61
62        Ok(())
63    }
64}
65
66/// Example: Batch processing workflow
67///
68/// Demonstrates how to:
69/// - Set up batch processing
70/// - Process multiple code samples efficiently
71/// - Handle errors in batch operations
72pub struct BatchProcessingExample;
73
74impl BatchProcessingExample {
75    /// Run the batch processing example
76    #[allow(dead_code)]
77    pub async fn run(api_key: &str) -> Result<()> {
78        // 1. Create the evaluator
79        let openai = OpenAiClient::with_default_model(api_key);
80        let llm_client = LlmClient::new(Box::new(openai));
81        let evaluator = Arc::new(AiEvaluator::with_config(
82            llm_client,
83            EvaluatorConfig::default(),
84        ));
85
86        // 2. Create batch processor with production settings
87        let batch_config = ProductionPreset::batch_config();
88        let batch_evaluator = BatchCodeEvaluator::new(evaluator, batch_config);
89
90        // 3. Prepare multiple code samples
91        let codes = vec![
92            (
93                "fn add(a: i32, b: i32) -> i32 { a + b }".to_string(),
94                "rust".to_string(),
95            ),
96            (
97                "function add(a, b) { return a + b; }".to_string(),
98                "javascript".to_string(),
99            ),
100            (
101                "def add(a, b): return a + b".to_string(),
102                "python".to_string(),
103            ),
104        ];
105
106        // 4. Process in batch
107        let result = batch_evaluator.evaluate_batch(codes).await?;
108
109        println!("Total processed: {}", result.total);
110        println!("Successes: {}", result.success_count());
111        println!("Failures: {}", result.failure_count());
112        println!("Success rate: {:.2}%", result.success_rate() * 100.0);
113
114        Ok(())
115    }
116}
117
118/// Example: AI Oracle with multi-model consensus
119///
120/// Demonstrates how to:
121/// - Set up an AI Oracle
122/// - Use multi-model consensus
123/// - Learn from human feedback
124pub struct OracleConsensusExample;
125
126impl OracleConsensusExample {
127    /// Run the oracle consensus example
128    #[allow(dead_code)]
129    pub async fn run(_api_key: &str) -> Result<()> {
130        // 1. Create oracle with production config
131        let oracle_config = ProductionPreset::oracle_config();
132        let mut oracle = AiOracle::new(oracle_config);
133
134        // 2. Add models via config (models are managed through the config)
135        // In production, you would configure multiple LLM providers through the oracle config
136
137        // 3. Make a decision with consensus
138        let request = crate::ai_evaluator::VerificationRequest {
139            commitment_title: "Deploy smart contract".to_string(),
140            commitment_description: Some("Deploy audited smart contract to mainnet".to_string()),
141            deadline: "2024-12-31".to_string(),
142            evidence_url: "https://etherscan.io/address/0x123...".to_string(),
143            evidence_description: Some("Contract deployed with verified source code".to_string()),
144        };
145        let decision = oracle.verify_with_consensus(&request).await?;
146
147        println!("Consensus Decision: {}", decision.approved);
148        println!("Confidence: {}", decision.confidence);
149        println!("Reasoning: {}", decision.reasoning);
150
151        // 4. Learn from human feedback (if decision was wrong)
152        let human_decision = true; // Assume human verified this was correct
153        oracle.record_feedback(
154            "commitment-123".to_string(),
155            decision.approved,
156            decision.confidence,
157            human_decision,
158        );
159
160        Ok(())
161    }
162}
163
164/// Example: Complete service setup with access control
165///
166/// Demonstrates how to:
167/// - Set up the full AI service hub
168/// - Configure access control
169/// - Use tiered access
170pub struct CompleteServiceExample;
171
172impl CompleteServiceExample {
173    /// Run the complete service example
174    #[allow(dead_code)]
175    pub async fn run(api_key: &str) -> Result<()> {
176        // 1. Create LLM client
177        let openai = OpenAiClient::with_default_model(api_key);
178        let llm_client = Arc::new(LlmClient::new(Box::new(openai)));
179
180        // 2. Build service with all features
181        let mut service = AiServiceBuilder::new(llm_client)
182            .evaluator_config(ProductionPreset::evaluator_config())
183            .with_oracle(ProductionPreset::oracle_config())
184            .with_access_control()
185            .build();
186
187        // 3. Set up access control with tiers
188        let mut access_control = AccessControlManager::new();
189        access_control.update_tier_config(AccessTierPresets::silver_tier());
190
191        // 4. Create a token holder
192        let holder = TokenHolder {
193            user_id: Uuid::new_v4(),
194            token_id: Uuid::new_v4(),
195            balance: Decimal::new(1000, 0),
196            tier: AccessTier::Silver,
197        };
198
199        // 5. Check and use features
200        if let Some(Ok(true)) = service.can_access_feature(&holder, AiFeature::CodeEvaluation) {
201            let evaluator = service.evaluator();
202            let code = "fn hello() { println!(\"Hello\"); }";
203            let result = evaluator.evaluate_code(code, "rust").await?;
204
205            // Record usage
206            service.record_usage(&holder, AiFeature::CodeEvaluation);
207
208            println!("Evaluation successful: {}", result.quality_score);
209        }
210
211        Ok(())
212    }
213}
214
215/// Example: Fraud detection workflow
216///
217/// Demonstrates how to:
218/// - Set up fraud detection
219/// - Analyze user behavior
220/// - Interpret risk scores
221pub struct FraudDetectionExample;
222
223impl FraudDetectionExample {
224    /// Run the fraud detection example
225    #[allow(dead_code)]
226    pub async fn run(api_key: &str) -> Result<()> {
227        // 1. Create fraud detector
228        let openai = OpenAiClient::with_default_model(api_key);
229        let llm_client = LlmClient::new(Box::new(openai));
230        let fraud_detector = AiFraudDetector::new(llm_client);
231
232        // 2. Prepare fraud check request
233        let request = crate::ai_evaluator::FraudCheckRequest {
234            content_type: "Task completion claim".to_string(),
235            content: "I have completed all 50 tasks! Here's proof: [screenshot]".to_string(),
236            commitments_made: 50,
237            commitments_fulfilled: 2, // Suspicious: claimed 50 but only fulfilled 2 before
238            avg_quality_score: Some(85.0),
239        };
240
241        // 3. Check for fraud
242        let result = fraud_detector.check_fraud(&request).await?;
243
244        println!("Risk Level: {:?}", result.risk_level);
245        println!("Risk Score: {}", result.risk_score);
246        println!("Suspicious Indicators:");
247        for indicator in &result.indicators {
248            println!("  - {indicator}");
249        }
250        println!("Recommendation: {}", result.recommendation);
251
252        Ok(())
253    }
254}
255
256/// Example: Integration with external systems
257///
258/// Demonstrates how to:
259/// - Integrate AI services with your application
260/// - Handle errors gracefully
261/// - Implement caching and optimization
262pub struct IntegrationExample;
263
264impl IntegrationExample {
265    /// Example integration with a web service
266    #[allow(dead_code)]
267    pub async fn web_service_integration(api_key: &str) -> Result<()> {
268        // 1. Create service hub (singleton in your app)
269        let openai = OpenAiClient::with_default_model(api_key);
270        let llm_client = Arc::new(LlmClient::new(Box::new(openai)));
271        let service = AiServiceHub::new(llm_client);
272
273        // 2. Use in request handlers
274        let code_to_evaluate = "fn main() {}";
275        let evaluator = service.evaluator();
276
277        match evaluator.evaluate_code(code_to_evaluate, "rust").await {
278            Ok(result) => {
279                println!("✓ Evaluation successful");
280                println!("Quality: {}/100", result.quality_score);
281            }
282            Err(e) => {
283                eprintln!("✗ Evaluation failed: {e}");
284                // Handle error (return HTTP 500, log, etc.)
285            }
286        }
287
288        Ok(())
289    }
290
291    /// Example batch processing for background jobs
292    #[allow(dead_code)]
293    pub async fn background_job_processing(api_key: &str) -> Result<()> {
294        // 1. Set up batch processor
295        let openai = OpenAiClient::with_default_model(api_key);
296        let llm_client = LlmClient::new(Box::new(openai));
297        let evaluator = Arc::new(AiEvaluator::with_config(
298            llm_client,
299            ProductionPreset::evaluator_config(),
300        ));
301
302        // 2. Use high-volume settings for background jobs
303        let batch_config = BatchConfig::with_concurrency(20).with_continue_on_error(true);
304
305        let batch_evaluator = BatchCodeEvaluator::new(evaluator, batch_config);
306
307        // 3. Process queued items
308        let queued_codes = vec![
309            // ... fetch from database/queue
310        ];
311
312        let results = batch_evaluator.evaluate_batch(queued_codes).await?;
313
314        println!("Processed {} items", results.total);
315        println!("Success rate: {:.1}%", results.success_rate() * 100.0);
316
317        Ok(())
318    }
319}