BDR-AI commited on
Commit
0a977be
Β·
verified Β·
1 Parent(s): ef34340

Add unified API Gateway with authentication, rate limiting, and pricing tiers

Browse files
Files changed (1) hide show
  1. app.py +249 -0
app.py ADDED
@@ -0,0 +1,249 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import gradio as gr
2
+ import hashlib
3
+ import time
4
+ import json
5
+ from datetime import datetime
6
+ from collections import defaultdict
7
+ import os
8
+
9
+ # ============================================================================
10
+ # GCC INSURANCE INTELLIGENCE LAB - UNIFIED API GATEWAY
11
+ # ============================================================================
12
+ # Version: 1.0.0
13
+ # Features: Authentication, Rate Limiting, Pricing Tiers, Usage Tracking
14
+ # ============================================================================
15
+
16
+ # Pricing Tiers Configuration
17
+ PRICING_TIERS = {
18
+ "starter": {
19
+ "name": "Starter",
20
+ "price": 500,
21
+ "requests_per_month": 1000,
22
+ "rate_limit_per_minute": 10,
23
+ "features": ["claims_processing", "basic_fraud_detection"],
24
+ "support": "email"
25
+ },
26
+ "professional": {
27
+ "name": "Professional",
28
+ "price": 2000,
29
+ "requests_per_month": 10000,
30
+ "rate_limit_per_minute": 50,
31
+ "features": ["claims_processing", "fraud_detection", "underwriting", "document_rag"],
32
+ "support": "priority"
33
+ },
34
+ "enterprise": {
35
+ "name": "Enterprise",
36
+ "price": 5000,
37
+ "requests_per_month": 100000,
38
+ "rate_limit_per_minute": 200,
39
+ "features": ["all"],
40
+ "support": "dedicated"
41
+ }
42
+ }
43
+
44
+ # Demo API Keys (In production, use secure database)
45
+ API_KEYS = {
46
+ "demo-starter-key": {"tier": "starter", "org": "Demo Starter Org"},
47
+ "demo-pro-key": {"tier": "professional", "org": "Demo Professional Org"},
48
+ "demo-enterprise-key": {"tier": "enterprise", "org": "Demo Enterprise Org"}
49
+ }
50
+
51
+ # Usage tracking
52
+ usage_tracker = defaultdict(lambda: {"requests": 0, "last_reset": time.time()})
53
+ rate_limiter = defaultdict(list)
54
+
55
+ def validate_api_key(api_key):
56
+ """Validate API key and return tier info"""
57
+ if api_key in API_KEYS:
58
+ return True, API_KEYS[api_key]
59
+ return False, None
60
+
61
+ def check_rate_limit(api_key):
62
+ """Check if request is within rate limits"""
63
+ if api_key not in API_KEYS:
64
+ return False, "Invalid API key"
65
+
66
+ tier = API_KEYS[api_key]["tier"]
67
+ limit = PRICING_TIERS[tier]["rate_limit_per_minute"]
68
+
69
+ current_time = time.time()
70
+ minute_ago = current_time - 60
71
+
72
+ # Clean old requests
73
+ rate_limiter[api_key] = [t for t in rate_limiter[api_key] if t > minute_ago]
74
+
75
+ if len(rate_limiter[api_key]) >= limit:
76
+ return False, f"Rate limit exceeded ({limit}/min for {tier} tier)"
77
+
78
+ rate_limiter[api_key].append(current_time)
79
+ return True, "OK"
80
+
81
+ def process_claims(api_key, claim_data):
82
+ """Process insurance claim using AI"""
83
+ valid, info = validate_api_key(api_key)
84
+ if not valid:
85
+ return {"error": "Invalid API key", "status": 401}
86
+
87
+ allowed, msg = check_rate_limit(api_key)
88
+ if not allowed:
89
+ return {"error": msg, "status": 429}
90
+
91
+ # Simulate AI processing
92
+ result = {
93
+ "status": "success",
94
+ "claim_id": f"CLM-{hashlib.md5(claim_data.encode()).hexdigest()[:8].upper()}",
95
+ "processing_time": "0.45s",
96
+ "ai_assessment": {
97
+ "validity_score": 0.92,
98
+ "recommended_action": "APPROVE",
99
+ "confidence": 0.88,
100
+ "flags": []
101
+ },
102
+ "tier": info["tier"],
103
+ "organization": info["org"]
104
+ }
105
+ return result
106
+
107
+ def detect_fraud(api_key, transaction_data):
108
+ """Detect potential fraud in transaction"""
109
+ valid, info = validate_api_key(api_key)
110
+ if not valid:
111
+ return {"error": "Invalid API key", "status": 401}
112
+
113
+ tier = info["tier"]
114
+ if tier == "starter":
115
+ features = ["basic_fraud_detection"]
116
+ else:
117
+ features = ["advanced_fraud_detection", "pattern_analysis", "network_analysis"]
118
+
119
+ allowed, msg = check_rate_limit(api_key)
120
+ if not allowed:
121
+ return {"error": msg, "status": 429}
122
+
123
+ result = {
124
+ "status": "success",
125
+ "transaction_id": f"TXN-{hashlib.md5(transaction_data.encode()).hexdigest()[:8].upper()}",
126
+ "fraud_score": 0.15,
127
+ "risk_level": "LOW",
128
+ "features_used": features,
129
+ "recommendation": "PROCEED",
130
+ "tier": tier
131
+ }
132
+ return result
133
+
134
+ def assess_underwriting(api_key, policy_data):
135
+ """AI-powered underwriting risk assessment"""
136
+ valid, info = validate_api_key(api_key)
137
+ if not valid:
138
+ return {"error": "Invalid API key", "status": 401}
139
+
140
+ tier = info["tier"]
141
+ if tier == "starter":
142
+ return {"error": "Underwriting not available in Starter tier. Upgrade to Professional.", "status": 403}
143
+
144
+ allowed, msg = check_rate_limit(api_key)
145
+ if not allowed:
146
+ return {"error": msg, "status": 429}
147
+
148
+ result = {
149
+ "status": "success",
150
+ "policy_id": f"POL-{hashlib.md5(policy_data.encode()).hexdigest()[:8].upper()}",
151
+ "risk_score": 0.35,
152
+ "risk_category": "MODERATE",
153
+ "premium_adjustment": "+5%",
154
+ "factors": ["age", "location", "claims_history"],
155
+ "tier": tier
156
+ }
157
+ return result
158
+
159
+ def get_usage_stats(api_key):
160
+ """Get API usage statistics"""
161
+ valid, info = validate_api_key(api_key)
162
+ if not valid:
163
+ return {"error": "Invalid API key", "status": 401}
164
+
165
+ tier = info["tier"]
166
+ tier_info = PRICING_TIERS[tier]
167
+
168
+ return {
169
+ "organization": info["org"],
170
+ "tier": tier,
171
+ "price": f"${tier_info['price']}/month",
172
+ "requests_used": usage_tracker[api_key]["requests"],
173
+ "requests_limit": tier_info["requests_per_month"],
174
+ "rate_limit": f"{tier_info['rate_limit_per_minute']}/min",
175
+ "features": tier_info["features"],
176
+ "support_level": tier_info["support"]
177
+ }
178
+
179
+ # Gradio Interface
180
+ with gr.Blocks(title="GCC Insurance Intelligence API Gateway", theme=gr.themes.Soft()) as demo:
181
+ gr.Markdown("""
182
+ # 🏒 GCC Insurance Intelligence Lab - API Gateway
183
+ ### Unified AI-Powered Insurance Platform
184
+
185
+ **Available Endpoints:**
186
+ - `/claims` - Process insurance claims with AI
187
+ - `/fraud` - Detect fraudulent transactions
188
+ - `/underwriting` - Risk assessment for policies
189
+ - `/usage` - Check your API usage stats
190
+
191
+ **Demo API Keys:**
192
+ - `demo-starter-key` - Starter tier ($500/mo)
193
+ - `demo-pro-key` - Professional tier ($2,000/mo)
194
+ - `demo-enterprise-key` - Enterprise tier ($5,000/mo)
195
+ """)
196
+
197
+ with gr.Tab("πŸ” Authentication"):
198
+ api_key_input = gr.Textbox(label="API Key", placeholder="Enter your API key...")
199
+ auth_btn = gr.Button("Validate Key", variant="primary")
200
+ auth_output = gr.JSON(label="Authentication Result")
201
+ auth_btn.click(fn=lambda k: get_usage_stats(k), inputs=api_key_input, outputs=auth_output)
202
+
203
+ with gr.Tab("πŸ“‹ Claims Processing"):
204
+ gr.Markdown("### Process Insurance Claims with AI")
205
+ claims_key = gr.Textbox(label="API Key")
206
+ claims_data = gr.Textbox(label="Claim Data (JSON)", lines=5,
207
+ value='{"policy_number": "POL-12345", "claim_type": "auto", "amount": 5000, "description": "Vehicle damage from accident"}')
208
+ claims_btn = gr.Button("Process Claim", variant="primary")
209
+ claims_output = gr.JSON(label="Processing Result")
210
+ claims_btn.click(fn=process_claims, inputs=[claims_key, claims_data], outputs=claims_output)
211
+
212
+ with gr.Tab("πŸ” Fraud Detection"):
213
+ gr.Markdown("### AI-Powered Fraud Detection")
214
+ fraud_key = gr.Textbox(label="API Key")
215
+ fraud_data = gr.Textbox(label="Transaction Data (JSON)", lines=5,
216
+ value='{"transaction_id": "TXN-001", "amount": 15000, "merchant": "Auto Repair Shop", "location": "Dubai"}')
217
+ fraud_btn = gr.Button("Analyze Transaction", variant="primary")
218
+ fraud_output = gr.JSON(label="Fraud Analysis Result")
219
+ fraud_btn.click(fn=detect_fraud, inputs=[fraud_key, fraud_data], outputs=fraud_output)
220
+
221
+ with gr.Tab("πŸ“Š Underwriting"):
222
+ gr.Markdown("### Risk Assessment for Underwriting")
223
+ gr.Markdown("*Requires Professional or Enterprise tier*")
224
+ uw_key = gr.Textbox(label="API Key")
225
+ uw_data = gr.Textbox(label="Policy Data (JSON)", lines=5,
226
+ value='{"applicant_age": 35, "policy_type": "comprehensive", "vehicle_value": 50000, "location": "Riyadh"}')
227
+ uw_btn = gr.Button("Assess Risk", variant="primary")
228
+ uw_output = gr.JSON(label="Underwriting Result")
229
+ uw_btn.click(fn=assess_underwriting, inputs=[uw_key, uw_data], outputs=uw_output)
230
+
231
+ with gr.Tab("πŸ’° Pricing Tiers"):
232
+ gr.Markdown("""
233
+ ### Pricing Plans
234
+
235
+ | Tier | Price | Requests/Month | Rate Limit | Features |
236
+ |------|-------|----------------|------------|----------|
237
+ | **Starter** | $500/mo | 1,000 | 10/min | Claims, Basic Fraud |
238
+ | **Professional** | $2,000/mo | 10,000 | 50/min | + Underwriting, Document RAG |
239
+ | **Enterprise** | $5,000/mo | 100,000 | 200/min | All Features + Dedicated Support |
240
+
241
+ Contact sales@gcc-insurance-lab.ai for custom enterprise pricing.
242
+ """)
243
+
244
+ gr.Markdown("""
245
+ ---
246
+ **GCC Insurance Intelligence Lab** | [Documentation](https://huggingface.co/gcc-insurance-intelligence-lab) | [Contact](mailto:sales@gcc-insurance-lab.ai)
247
+ """)
248
+
249
+ demo.launch()