Model-config web apps: describe the app in configuration instead of writing code. Built on Polars and DuckDB.
ai_services.py · 9.0 KB · 286 lines
| 1 | #!/usr/bin/env python3 |
| 2 | """ |
| 3 | Demo: AI Black Box Services for DBBasic |
| 4 | Shows how natural language becomes running endpoints |
| 5 | """ |
| 6 | |
| 7 | from fastapi import FastAPI, Request, HTTPException |
| 8 | from typing import Dict, Any |
| 9 | import random |
| 10 | import json |
| 11 | from datetime import datetime |
| 12 | |
| 13 | app = FastAPI(title="DBBasic AI Black Box Services") |
| 14 | |
| 15 | # Simulate AI-generated services |
| 16 | # In production, these would be generated by LLMs from descriptions |
| 17 | |
| 18 | @app.post("/ai/calculate_order_total") |
| 19 | async def calculate_order_total(request: Request): |
| 20 | """ |
| 21 | AI Service: Calculate tax based on customer location |
| 22 | Generated from: "Calculate tax based on customer location and add to subtotal for total" |
| 23 | """ |
| 24 | data = await request.json() |
| 25 | |
| 26 | subtotal = data.get('subtotal', 0) |
| 27 | location = data.get('customer_location', {}) |
| 28 | state = location.get('state', 'CA') |
| 29 | |
| 30 | # Tax rates (AI would fetch real-time rates) |
| 31 | tax_rates = { |
| 32 | 'CA': 0.0725, |
| 33 | 'NY': 0.08, |
| 34 | 'TX': 0.0625, |
| 35 | 'FL': 0.06, |
| 36 | 'WA': 0.065 |
| 37 | } |
| 38 | |
| 39 | rate = tax_rates.get(state, 0.07) |
| 40 | tax = subtotal * rate |
| 41 | total = subtotal + tax |
| 42 | |
| 43 | return { |
| 44 | 'success': True, |
| 45 | 'service': 'calculate_order_total', |
| 46 | 'generated_by': 'AI from description', |
| 47 | 'data': { |
| 48 | 'subtotal': subtotal, |
| 49 | 'tax': round(tax, 2), |
| 50 | 'total': round(total, 2), |
| 51 | 'tax_rate': rate, |
| 52 | 'state': state |
| 53 | } |
| 54 | } |
| 55 | |
| 56 | @app.post("/ai/send_order_confirmation") |
| 57 | async def send_order_confirmation(request: Request): |
| 58 | """ |
| 59 | AI Service: Send order confirmation email |
| 60 | Generated from: "Send a nice order confirmation email with order details and tracking link" |
| 61 | """ |
| 62 | data = await request.json() |
| 63 | |
| 64 | customer_email = data.get('customer_email') |
| 65 | order_id = data.get('order_id') |
| 66 | items = data.get('items', []) |
| 67 | |
| 68 | # AI generates the email content |
| 69 | tracking_number = f"TRK{random.randint(100000, 999999)}" |
| 70 | |
| 71 | email_content = f""" |
| 72 | Order Confirmation #{order_id} |
| 73 | |
| 74 | Thank you for your order! |
| 75 | |
| 76 | Items: |
| 77 | {chr(10).join([f"- {item.get('name', 'Item')} x{item.get('quantity', 1)}" for item in items])} |
| 78 | |
| 79 | Track your order: https://track.example.com/{tracking_number} |
| 80 | |
| 81 | We'll notify you when it ships! |
| 82 | """ |
| 83 | |
| 84 | return { |
| 85 | 'success': True, |
| 86 | 'service': 'send_order_confirmation', |
| 87 | 'generated_by': 'AI from description', |
| 88 | 'data': { |
| 89 | 'email_sent': True, |
| 90 | 'to': customer_email, |
| 91 | 'subject': f'Order #{order_id} Confirmation', |
| 92 | 'tracking_number': tracking_number, |
| 93 | 'message_id': f'msg_{random.randint(100000, 999999)}' |
| 94 | } |
| 95 | } |
| 96 | |
| 97 | @app.post("/ai/recalculate_customer_segment") |
| 98 | async def recalculate_customer_segment(request: Request): |
| 99 | """ |
| 100 | AI Service: Customer segmentation |
| 101 | Generated from: "Segment customer as bronze/silver/gold/platinum based on lifetime value and order frequency" |
| 102 | """ |
| 103 | data = await request.json() |
| 104 | |
| 105 | lifetime_value = data.get('lifetime_value', 0) |
| 106 | order_count = data.get('order_count', 0) |
| 107 | |
| 108 | # AI determines segmentation logic |
| 109 | if lifetime_value > 10000 or order_count > 50: |
| 110 | segment = 'platinum' |
| 111 | benefits = ['Free shipping', '20% discount', 'Priority support', 'Early access'] |
| 112 | elif lifetime_value > 5000 or order_count > 25: |
| 113 | segment = 'gold' |
| 114 | benefits = ['Free shipping', '15% discount', 'Priority support'] |
| 115 | elif lifetime_value > 1000 or order_count > 10: |
| 116 | segment = 'silver' |
| 117 | benefits = ['Free shipping on orders over $50', '10% discount'] |
| 118 | else: |
| 119 | segment = 'bronze' |
| 120 | benefits = ['5% discount on first order'] |
| 121 | |
| 122 | return { |
| 123 | 'success': True, |
| 124 | 'service': 'recalculate_customer_segment', |
| 125 | 'generated_by': 'AI from description', |
| 126 | 'data': { |
| 127 | 'segment': segment, |
| 128 | 'benefits': benefits, |
| 129 | 'lifetime_value': lifetime_value, |
| 130 | 'order_count': order_count |
| 131 | } |
| 132 | } |
| 133 | |
| 134 | @app.post("/ai/detect_fraud") |
| 135 | async def detect_fraud(request: Request): |
| 136 | """ |
| 137 | AI Service: Fraud detection |
| 138 | Generated from: "Score order for fraud risk using customer history and patterns" |
| 139 | """ |
| 140 | data = await request.json() |
| 141 | |
| 142 | # AI analyzes patterns |
| 143 | order_amount = data.get('total', 0) |
| 144 | is_new_customer = data.get('is_new_customer', False) |
| 145 | shipping_matches_billing = data.get('shipping_matches_billing', True) |
| 146 | |
| 147 | # AI-generated fraud scoring logic |
| 148 | risk_score = 0 |
| 149 | reasons = [] |
| 150 | |
| 151 | if order_amount > 1000: |
| 152 | risk_score += 20 |
| 153 | reasons.append('High order amount') |
| 154 | |
| 155 | if is_new_customer: |
| 156 | risk_score += 15 |
| 157 | reasons.append('New customer') |
| 158 | |
| 159 | if not shipping_matches_billing: |
| 160 | risk_score += 25 |
| 161 | reasons.append('Different shipping address') |
| 162 | |
| 163 | # Random factor to simulate ML model |
| 164 | risk_score += random.randint(-10, 20) |
| 165 | risk_score = max(0, min(100, risk_score)) |
| 166 | |
| 167 | risk_level = 'low' if risk_score < 30 else 'medium' if risk_score < 60 else 'high' |
| 168 | |
| 169 | return { |
| 170 | 'success': True, |
| 171 | 'service': 'detect_fraud', |
| 172 | 'generated_by': 'AI from description', |
| 173 | 'data': { |
| 174 | 'risk_score': risk_score, |
| 175 | 'risk_level': risk_level, |
| 176 | 'reasons': reasons, |
| 177 | 'recommend_review': risk_score > 60, |
| 178 | 'recommend_block': risk_score > 80 |
| 179 | } |
| 180 | } |
| 181 | |
| 182 | @app.post("/ai/optimize_prices") |
| 183 | async def optimize_prices(request: Request): |
| 184 | """ |
| 185 | AI Service: Dynamic pricing |
| 186 | Generated from: "Adjust prices based on competitor pricing, demand, and margin targets" |
| 187 | """ |
| 188 | data = await request.json() |
| 189 | |
| 190 | current_price = data.get('current_price', 100) |
| 191 | cost = data.get('cost', 50) |
| 192 | competitor_price = data.get('competitor_price', current_price) |
| 193 | demand_level = data.get('demand_level', 'normal') # low, normal, high |
| 194 | |
| 195 | # AI determines optimal price |
| 196 | margin_target = 0.3 # 30% margin |
| 197 | min_price = cost * (1 + margin_target) |
| 198 | |
| 199 | # Demand multiplier |
| 200 | demand_multipliers = { |
| 201 | 'low': 0.9, |
| 202 | 'normal': 1.0, |
| 203 | 'high': 1.1 |
| 204 | } |
| 205 | |
| 206 | # AI calculates optimal price |
| 207 | optimal_price = competitor_price * demand_multipliers[demand_level] |
| 208 | optimal_price = max(min_price, optimal_price) |
| 209 | |
| 210 | # Add some randomness to simulate market dynamics |
| 211 | optimal_price *= (0.95 + random.random() * 0.1) |
| 212 | |
| 213 | return { |
| 214 | 'success': True, |
| 215 | 'service': 'optimize_prices', |
| 216 | 'generated_by': 'AI from description', |
| 217 | 'data': { |
| 218 | 'current_price': current_price, |
| 219 | 'optimal_price': round(optimal_price, 2), |
| 220 | 'expected_margin': round((optimal_price - cost) / optimal_price, 2), |
| 221 | 'price_change': round(optimal_price - current_price, 2), |
| 222 | 'reasoning': f'Based on {demand_level} demand and competitor at ${competitor_price}' |
| 223 | } |
| 224 | } |
| 225 | |
| 226 | @app.get("/ai/services") |
| 227 | async def list_services(): |
| 228 | """List all AI-generated services""" |
| 229 | return { |
| 230 | 'services': [ |
| 231 | { |
| 232 | 'name': 'calculate_order_total', |
| 233 | 'endpoint': '/ai/calculate_order_total', |
| 234 | 'description': 'Calculate tax based on customer location and add to subtotal' |
| 235 | }, |
| 236 | { |
| 237 | 'name': 'send_order_confirmation', |
| 238 | 'endpoint': '/ai/send_order_confirmation', |
| 239 | 'description': 'Send order confirmation email with tracking' |
| 240 | }, |
| 241 | { |
| 242 | 'name': 'recalculate_customer_segment', |
| 243 | 'endpoint': '/ai/recalculate_customer_segment', |
| 244 | 'description': 'Segment customers based on value and frequency' |
| 245 | }, |
| 246 | { |
| 247 | 'name': 'detect_fraud', |
| 248 | 'endpoint': '/ai/detect_fraud', |
| 249 | 'description': 'Score orders for fraud risk' |
| 250 | }, |
| 251 | { |
| 252 | 'name': 'optimize_prices', |
| 253 | 'endpoint': '/ai/optimize_prices', |
| 254 | 'description': 'Dynamic pricing optimization' |
| 255 | } |
| 256 | ], |
| 257 | 'note': 'All services auto-generated from natural language descriptions' |
| 258 | } |
| 259 | |
| 260 | @app.get("/") |
| 261 | async def root(): |
| 262 | return { |
| 263 | 'title': 'DBBasic AI Black Box Services', |
| 264 | 'message': 'These services were generated from natural language descriptions', |
| 265 | 'endpoints': [ |
| 266 | 'GET /ai/services - List all services', |
| 267 | 'POST /ai/calculate_order_total - Calculate order totals', |
| 268 | 'POST /ai/send_order_confirmation - Send emails', |
| 269 | 'POST /ai/recalculate_customer_segment - Customer segmentation', |
| 270 | 'POST /ai/detect_fraud - Fraud detection', |
| 271 | 'POST /ai/optimize_prices - Price optimization' |
| 272 | ], |
| 273 | 'philosophy': 'Config defines structure. AI implements logic. No code written.' |
| 274 | } |
| 275 | |
| 276 | if __name__ == "__main__": |
| 277 | import uvicorn |
| 278 | print("=" * 60) |
| 279 | print("DBBasic AI Black Box Services") |
| 280 | print("=" * 60) |
| 281 | print("Services generated from natural language descriptions") |
| 282 | print("No code was written - AI created these from config") |
| 283 | print("-" * 60) |
| 284 | print("Starting server on http://localhost:8002") |
| 285 | print("-" * 60) |
| 286 | uvicorn.run(app, host="0.0.0.0", port=8002) |