kaccy-ai
AI services for Kaccy Protocol - Comprehensive LLM-powered evaluation, verification, fraud detection, and automation.
Overview
The kaccy-ai crate provides advanced AI capabilities for the Kaccy Protocol, including:
- Code & Content Evaluation - Quality scoring using multiple LLM providers
- Commitment Verification - Automated evidence validation (GitHub, social media, documents)
- Fraud Detection - Sybil attack detection, wash trading, image manipulation, reputation gaming
- Plagiarism Detection - Code and text similarity detection with semantic analysis
- Image Similarity - Perceptual hashing for duplicate detection and fraud prevention
- AI Oracle - Multi-model consensus for automated decision-making with continuous learning
- Token-Gated AI Access - Tiered AI features based on token holdings
- Cost Optimization - Smart model routing, caching, batching, and request deduplication
- Local LLM Support - Privacy-focused deployment with Ollama for zero-cost execution
Features
Multi-Provider LLM Integration
Supports multiple LLM providers with automatic fallback:
- OpenAI (GPT-4 Turbo, GPT-4o, GPT-3.5 Turbo)
- Anthropic (Claude 3 Opus, Claude 3 Sonnet, Claude 3 Haiku)
- Google Gemini (Gemini 1.5 Pro, Gemini 1.5 Flash, Gemini 2.0 Flash)
- DeepSeek (Chat, Coder, Reasoner) - Cost-effective models optimized for code
- Ollama (Llama, Mistral, CodeLlama, etc.) - Privacy-focused local LLM execution
Core Capabilities
1. Code Evaluation
use ;
use ;
let openai = with_default_model;
let llm_client = new;
let evaluator = with_config;
let result = evaluator.evaluate_code.await?;
println!;
2. Commitment Verification
use ;
let verifier = new;
let request = VerificationRequest ;
let result = verifier.verify_evidence.await?;
println!;
3. Fraud Detection
use ;
let fraud_service = new;
let input = FraudAnalysisInput ;
let report = fraud_service.analyze.await?;
println!;
4. AI Oracle (Multi-Model Consensus)
use ;
let mut oracle = new;
oracle.add_model; // Higher weight
oracle.add_model;
oracle.add_model;
let decision = oracle.verify_with_consensus.await?;
println!;
5. Batch Processing
use ;
use Arc;
let batch_config = BatchConfig ;
let batch_evaluator = new;
let codes = vec!;
let results = batch_evaluator.evaluate_batch.await?;
println!;
6. Plagiarism Detection
use ;
let config = PlagiarismConfig ;
let detector = new;
// Detect code plagiarism
let result = detector.detect_code_plagiarism.await?;
println!;
println!;
// Detect text plagiarism with semantic analysis
let result = detector.detect_text_plagiarism.await?;
println!;
println!;
7. Image Similarity Detection
use ;
// Create detector with perceptual hashing
let detector = new;
// Hash and compare images
let hash1 = detector.hash_image?;
let hash2 = detector.hash_image?;
let score = detector.compare_hashes;
if score.is_similar
// Build deduplication database
let mut db = new;
db.add_image?;
db.add_image?;
let duplicates = db.find_duplicates;
println!;
Advanced Features
Cost Optimization
Model Router
Automatically routes requests to cost-effective models based on task complexity:
use ;
let router = new;
// Simple tasks → Gemini Flash (cheapest)
let result = router.route_and_execute.await?;
// Complex tasks → GPT-4 Turbo or Claude Opus (most capable)
let result = router.route_and_execute.await?;
LLM Cache
use ;
let cache_config = LlmCacheConfig ;
let cached_client = new;
Request Batching
use BatchProcessor;
let batch_processor = new;
Resilience & Reliability
Circuit Breaker
use ;
let circuit_breaker = new;
let result = circuit_breaker.call.await?;
Retry with Exponential Backoff
use ;
let retry_config = RetryConfig ;
let executor = new;
let result = executor.execute.await?;
Rate Limiting
use ;
let rate_limiter = new;
rate_limiter.acquire.await;
let result = llm_client.chat.await?;
Token-Gated AI Access
Create tiered AI access based on token holdings:
use ;
use dec;
let mut access_manager = new;
let holder = TokenHolder ;
// Check access to features
if access_manager.check_access?
// Get feature quota
let quota = access_manager.get_feature_quota?;
println!;
Access Tiers:
- Free (0-999 tokens): Basic features, limited quotas
- Bronze (1k-10k): Increased quotas, fraud detection
- Silver (10k-100k): Batch processing, custom agents (up to 3)
- Gold (100k-1M): Priority support, advanced features, custom agents (up to 10)
- Platinum (1M+): Unlimited access, dedicated support, custom agents (unlimited)
Knowledge Base
Store and retrieve domain-specific knowledge:
use ;
let mut kb = new;
kb.add_entry;
let results = kb.search?;
Reputation Prediction
Predict future commitment success based on historical data:
use ;
let predictor = new;
let history = IssuerHistory ;
let prediction = predictor.predict_commitment_success.await?;
println!;
GitHub Integration
Comprehensive GitHub verification:
use ;
let github_client = new;
let github_verifier = new;
// Verify commit
let commit_result = github_verifier.verify_commit.await?;
// Verify release
let release_result = github_verifier.verify_release.await?;
// Verify PR/Issue closure
let pr_result = github_verifier.verify_pr.await?;
Document Analysis
Parse and analyze documents (PDF, Markdown, HTML):
use ;
// Parse PDF
let pdf_parser = new;
let = pdf_parser.parse_file?;
// Analyze document quality
let quality_analyzer = new;
let quality = quality_analyzer.analyze?;
println!;
Social Media Verification
Verify social media posts (Twitter/X, YouTube, LinkedIn):
use ;
let parser = new;
let details = parser.parse_url?;
let verifier = new;
let result = verifier.verify_post.await?;
Configuration Presets
Use pre-configured settings for different environments:
use ;
// Development: Fast feedback, lower costs
let dev_config = evaluator_config;
let dev_oracle = oracle_config;
// Production: High reliability, quality
let prod_config = evaluator_config;
let prod_circuit = circuit_breaker_config;
// High Volume: Maximum throughput
let hv_batch = batch_config;
let hv_cache = cache_config;
// Cost Optimized: Minimal cost
let cost_routing = routing_config;
Service Hub
Use the high-level service hub for simplified configuration:
use ;
let service = new
.with_openai
.with_anthropic
.with_gemini
.with_github
.enable_oracle
.enable_access_control
.build?;
// Use all services through a single hub
let evaluator = service.evaluator?;
let verifier = service.verifier?;
let fraud_detector = service.fraud_detector?;
let oracle = service.oracle?;
Environment Variables
# LLM Provider API Keys
OPENAI_API_KEY=sk-...
ANTHROPIC_API_KEY=sk-ant-...
GEMINI_API_KEY=...
# Model Selection
OPENAI_MODEL=gpt-4-turbo # Default: gpt-4-turbo
ANTHROPIC_MODEL=claude-3-opus-20240229 # Default: claude-3-opus-20240229
GEMINI_MODEL=gemini-1.5-pro # Default: gemini-1.5-pro
# GitHub Integration
GITHUB_TOKEN=ghp_...
# Optional Configuration
AI_MAX_TOKENS=2000 # Default: 2000
AI_TEMPERATURE=0.7 # Default: 0.7
Performance & Observability
Metrics Collection
use MetricsCollector;
let mut metrics = new;
// Metrics are automatically collected during operations
let snapshot = metrics.snapshot;
println!;
println!;
println!;
Performance Profiling
use PerformanceProfiler;
let mut profiler = new;
let report = profiler.generate_report;
println!;
Testing
# Run unit tests
# Run with nextest
# Run doc tests
# Check for warnings
# Generate documentation
Examples
See the examples module for comprehensive usage examples:
BasicCodeEvaluationExample- Simple code evaluationBatchProcessingExample- Batch processing with error handlingOracleConsensusExample- Multi-model consensusFraudDetectionExample- Comprehensive fraud detectionGeminiIntegrationExample- Gemini provider usageCompleteServiceExample- Full service hub setupIntegrationExample- Real-world integration patterns
Architecture
kaccy-ai/
├── src/
│ ├── lib.rs # Public API exports
│ ├── access_control.rs # Token-gated AI access
│ ├── ai_evaluator.rs # Core AI evaluator
│ ├── batch.rs # Batch processing utilities
│ ├── document.rs # Document parsing and analysis
│ ├── error.rs # Error types
│ ├── evaluator.rs # Quality evaluation trait
│ ├── evidence.rs # Evidence parsing
│ ├── examples.rs # Usage examples
│ ├── fraud.rs # Fraud detection
│ ├── github.rs # GitHub integration
│ ├── knowledge_base.rs # Knowledge storage
│ ├── model_version.rs # Model versioning
│ ├── ocr.rs # OCR and image analysis
│ ├── oracle.rs # AI oracle with consensus
│ ├── presets.rs # Configuration presets
│ ├── profiling.rs # Performance profiling
│ ├── reputation_predictor.rs # Reputation prediction
│ ├── service.rs # Service hub
│ ├── social.rs # Social media verification
│ ├── token_analyzer.rs # Token analysis
│ ├── transcript.rs # Video transcript analysis
│ ├── utils.rs # Utility functions
│ ├── verifier.rs # Commitment verifier
│ └── llm/
│ ├── mod.rs # LLM client abstraction
│ ├── openai.rs # OpenAI provider
│ ├── anthropic.rs # Anthropic provider
│ ├── gemini.rs # Google Gemini provider
│ ├── types.rs # Common types
│ ├── cache.rs # Response caching
│ ├── circuit_breaker.rs # Circuit breaker pattern
│ ├── cost_optimizer.rs # Cost optimization
│ ├── metrics.rs # Metrics collection
│ ├── observability.rs # Logging and tracing
│ ├── rate_limiter.rs # Rate limiting
│ ├── retry.rs # Retry logic
│ └── streaming.rs # Streaming support
└── Cargo.toml
Cost Management
Estimated costs per operation (using GPT-4 Turbo as baseline):
| Operation | Tokens | Cost |
|---|---|---|
| Code Evaluation | ~1,500 | $0.015 |
| Content Evaluation | ~1,200 | $0.012 |
| Commitment Verification | ~2,000 | $0.020 |
| Fraud Detection | ~2,500 | $0.025 |
| Oracle (3 models) | ~6,000 | $0.060 |
Cost Optimization Strategies:
- Use Gemini Flash for simple tasks ($0.000075/1k tokens - 200x cheaper)
- Enable caching for repeated requests (50-90% cost reduction)
- Use batch processing to reduce overhead
- Route by complexity (simple → cheap, complex → powerful)
Safety & Security
- Rate Limiting: Prevents API cost overruns
- Circuit Breakers: Protects against cascading failures
- Human-in-the-Loop: Escalates uncertain cases
- Audit Logging: Comprehensive decision tracking
- Input Validation: Prevents injection attacks
- Quota Management: Per-tier usage limits
Dependencies
Core dependencies:
tokio- Async runtimereqwest- HTTP clientserde/serde_json- Serializationasync-trait- Async traitsthiserror- Error handlingtracing- Logging and observability
Specialized:
lopdf- PDF parsingimage- Image processingregex- Pattern matchingrust_decimal- Precise decimal math
License
MIT OR Apache-2.0