-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmain.py
More file actions
571 lines (485 loc) Β· 23.9 KB
/
main.py
File metadata and controls
571 lines (485 loc) Β· 23.9 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
#!/usr/bin/env python3
"""
FastAPI application for risk_manager (LangGraph)
Following FastAPI best practices for production deployment
"""
import os
from typing import Dict, Any, List
from contextlib import asynccontextmanager
import aiohttp
from fastapi import FastAPI, HTTPException, Request, status
from fastapi.middleware.cors import CORSMiddleware
from fastapi.middleware.trustedhost import TrustedHostMiddleware
from fastapi.responses import JSONResponse
from pydantic import BaseModel, Field
import uvicorn
from dotenv import load_dotenv
# Load environment variables
load_dotenv()
# Configure Handit
from src.agent import LangGraphAgent
# Global agent instance
agent = None
async def fetch_metrics(session_id: str) -> Dict[str, Any]:
"""
Fetch metrics for a session from the self-improving engine
Args:
session_id: Session ID to fetch metrics for
Returns:
Dictionary containing aggregated metrics scores
"""
if not session_id:
return {"score": 0.0}
try:
# Get the base URL from environment or use default
trace_url = os.getenv("TRACE_API_URL", "https://self-improving-engine-api-299768392189.us-central1.run.app/api/v1/trace")
# Extract base URL by removing /trace or /context
base_url = trace_url.replace("/trace", "").replace("/context", "")
metrics_url = f"{base_url}/metrics/{session_id}"
async with aiohttp.ClientSession() as session:
async with session.get(metrics_url, timeout=aiohttp.ClientTimeout(total=300)) as response:
if response.status == 200:
result = await response.json()
# Extract and aggregate metrics
metrics = result.get("metrics", {})
total_accuracy = 0.0
count = 0
# Aggregate accuracies across all runs
for run_id, run_metrics in metrics.items():
if isinstance(run_metrics, dict):
for metric_type, metric_data in run_metrics.items():
if isinstance(metric_data, dict):
for subtype, subtype_data in metric_data.items():
if isinstance(subtype_data, dict) and "accuracy" in subtype_data:
total_accuracy += subtype_data["accuracy"]
count += 1
avg_score = total_accuracy / count if count > 0 else 0.0
return {
"score": round(avg_score, 4),
"details": result
}
else:
print(f"β οΈ Metrics API call failed with status {response.status}")
return {"score": 0.0}
except Exception as e:
print(f"β οΈ Failed to fetch metrics: {e}")
return {"score": 0.0}
@asynccontextmanager
async def lifespan(app: FastAPI):
"""Application lifespan manager"""
global agent
# Startup
print(f"π Starting risk_manager (LangGraph + FastAPI)")
# Initialize agent
agent = LangGraphAgent()
# Print graph information
graph_info = agent.get_graph_info()
print(f"β
risk_manager initialized successfully")
yield
# Shutdown
print(f"π Shutting down risk_manager")
# Create FastAPI app with lifespan
app = FastAPI(
title="risk_manager",
description="LangGraph-powered AI agent API",
version="1.0.0",
lifespan=lifespan,
docs_url="/docs",
redoc_url="/redoc"
)
# Add security middleware - Commented out to allow all connections
# Cloud Run handles security at the infrastructure level
# app.add_middleware(
# TrustedHostMiddleware,
# allowed_hosts=["localhost", "127.0.0.1", "0.0.0.0"]
# )
# Add CORS middleware
app.add_middleware(
CORSMiddleware,
allow_origins=["*"], # Allow all origins
allow_credentials=True,
allow_methods=["GET", "POST", "PUT", "DELETE", "OPTIONS"],
allow_headers=["*"],
)
# Request/Response Models
class ProcessRequest(BaseModel):
# Accept either a string or a dictionary for flexible input
input_data: Any = Field(None, description="Input data to process (optional for compatibility)")
# Accept array of transactions for batch processing
transactions: List[Dict[str, Any]] = Field(None, description="Array of transactions to process")
# Model types to run (vanilla, full, online)
model_types: List[str] = Field(default=["vanilla", "full", "online"], description="Model types to execute")
# Session ID for tracking multiple runs
session_id: str = Field(None, description="Session ID to track multiple runs of the same transaction")
# Run ID within session
run_id: str = Field(None, description="Run ID within session (e.g., 'run-1', 'run-2', 'run-3')")
# Allow direct transaction fields (fraud detection)
transaction: Dict[str, Any] = Field(None, description="Transaction details")
financial: Dict[str, Any] = Field(None, description="Financial information")
card: Dict[str, Any] = Field(None, description="Card details")
merchant: Dict[str, Any] = Field(None, description="Merchant information")
customer: Dict[str, Any] = Field(None, description="Customer details")
device: Dict[str, Any] = Field(None, description="Device information")
location: Dict[str, Any] = Field(None, description="Location data")
behavioral_profile: Dict[str, Any] = Field(None, description="Behavioral profile")
velocity_counters: Dict[str, Any] = Field(None, description="Velocity metrics")
risk_signals: Dict[str, Any] = Field(None, description="Risk signals")
session: Dict[str, Any] = Field(None, description="Session data")
channel: Dict[str, Any] = Field(None, description="Channel information")
authentication: Dict[str, Any] = Field(None, description="Authentication data")
# Simple transaction fields for basic testing
user_id: str = Field(None, description="User ID")
user_age_days: int = Field(None, description="Account age in days")
total_transactions: int = Field(None, description="Total transaction count")
amount: float = Field(None, description="Transaction amount")
time: str = Field(None, description="Transaction time (HH:MM format)")
merchant_name: str = Field(None, description="Merchant name")
merchant_category: str = Field(None, description="Merchant category")
currency: str = Field(None, description="Transaction currency code")
metadata: Dict[str, Any] = Field(default_factory=dict, description="Optional metadata")
class Config:
schema_extra = {
"example": {
"transaction": {
"transaction_id": "TXN-001",
"transaction_type": "PURCHASE"
},
"financial": {
"amount": 150.00,
"currency": "USD"
},
"merchant": {
"merchant_name": "Amazon",
"merchant_category_code": "5732"
},
"customer": {
"customer_id": "CUST-001",
"age_of_account_days": 365
}
}
}
class ProcessResponse(BaseModel):
result: Any = Field(..., description="Processing result")
success: bool = Field(..., description="Whether processing was successful")
metadata: Dict[str, Any] = Field(..., description="Response metadata")
class Config:
schema_extra = {
"example": {
"result": "I can help you with various tasks...",
"success": True,
"metadata": {
"agent": "risk_manager",
"framework": "langgraph",
"processing_time_ms": 150
}
}
}
class HealthResponse(BaseModel):
status: str = Field(..., description="Health status")
agent: str = Field(..., description="Agent name")
framework: str = Field(..., description="Framework used")
uptime: str = Field(..., description="Application uptime")
class GraphInfoResponse(BaseModel):
graph_info: Dict[str, Any] = Field(..., description="Graph structure information")
# Exception handlers
@app.exception_handler(HTTPException)
async def http_exception_handler(request: Request, exc: HTTPException):
return JSONResponse(
status_code=exc.status_code,
content={"detail": exc.detail, "status_code": exc.status_code}
)
@app.exception_handler(Exception)
async def general_exception_handler(request: Request, exc: Exception):
return JSONResponse(
status_code=500,
content={"detail": "Internal server error", "error": str(exc)}
)
# API Routes
@app.get("/", tags=["Root"])
async def root():
"""Root endpoint"""
return {
"message": "Welcome to risk_manager API",
"framework": "langgraph",
"docs": "/docs",
"health": "/health"
}
@app.post("/process", response_model=ProcessResponse, tags=["Agent"])
async def process_endpoint(request: ProcessRequest):
"""
Main processing endpoint - sends input through the LangGraph agent
This is the main entry point for agent execution, so it has tracing.
Accepts flexible transaction data in multiple formats.
Can process single transactions or arrays of transactions.
Accepts session_id and run_id as parameters for tracking multiple runs.
"""
if not agent:
raise HTTPException(status_code=503, detail="Agent not initialized")
try:
import time
import uuid
start_time = time.time()
# Check if this is a batch request (array of transactions)
if request.transactions:
from src.utils import get_generated_bullets, clear_generated_bullets
# Clear generated bullets at the start of processing
clear_generated_bullets()
# Process multiple transactions
results = []
for idx, tx in enumerate(request.transactions):
try:
# Ensure transaction has an ID
if "transaction_id" not in tx:
tx["transaction_id"] = f"TXN-{uuid.uuid4().hex[:12].upper()}"
# Process through the agent with specified model types
transaction_results = {}
for model_type in request.model_types:
try:
# Run once per model type
result = await agent.process(tx, model_type=model_type, session_id=request.session_id, run_id=request.run_id)
# Extract only analyzer results and final decision
final_output = {}
# If result is a dict containing 'results' (from graph execution)
if isinstance(result, dict):
# Get the results section which contains analyzer outputs
if 'results' in result:
analyzer_results = result['results']
# Include all analyzer outputs
for analyzer in ['pattern_detector', 'behavioral_analizer', 'velocity_checker',
'merchant_risk_analizer', 'geographic_analizer']:
if analyzer in analyzer_results:
final_output[analyzer] = analyzer_results[analyzer]
# Include the decision aggregator (final decision)
if 'decision_aggregator' in analyzer_results:
final_output['decision'] = analyzer_results['decision_aggregator']
# Alternative: Check if analyzers are directly in result
else:
for key in ['pattern_detector', 'behavioral_analizer', 'velocity_checker',
'merchant_risk_analizer', 'geographic_analizer', 'decision_aggregator']:
if key in result:
if key == 'decision_aggregator':
final_output['decision'] = result[key]
else:
final_output[key] = result[key]
# If no analyzers found, return the raw result
transaction_results[model_type] = final_output if final_output else result
except Exception as e:
transaction_results[model_type] = {"error": str(e)}
results.append({
"transaction_id": tx.get("transaction_id"),
"results": transaction_results
})
except Exception as e:
results.append({"error": str(e), "transaction_id": tx.get("transaction_id", "unknown")})
processing_time = (time.time() - start_time) * 1000
# Get generated bullets
generated_bullets = get_generated_bullets()
# Fetch metrics if session_id is provided
metrics = {}
if request.session_id:
metrics = await fetch_metrics(request.session_id)
return ProcessResponse(
result=results,
success=True,
metadata={
"agent": "risk_manager",
"framework": "langgraph",
"processing_time_ms": round(processing_time, 2),
"transaction_count": len(request.transactions),
"model_types": request.model_types,
"session_id": request.session_id,
"run_id": request.run_id,
"metrics": metrics,
"generated_bullets": generated_bullets,
**request.metadata
}
)
# Single transaction processing (existing logic)
from src.utils import get_generated_bullets, clear_generated_bullets
# Clear generated bullets at the start of processing
clear_generated_bullets()
# Build transaction data from whatever format is provided
transaction_data = {}
# Option 1: If input_data is provided (backwards compatibility)
if request.input_data:
if isinstance(request.input_data, dict):
transaction_data = request.input_data
elif isinstance(request.input_data, str):
# Try to parse as JSON if it's a string
try:
import json
transaction_data = json.loads(request.input_data)
except:
# If not JSON, create a simple transaction
transaction_data = {"raw_input": request.input_data}
# Option 2: Build from structured fields (complex transaction)
elif request.transaction or request.financial or request.merchant:
# Complex transaction format
if request.transaction:
transaction_data.update(request.transaction)
if request.financial and "amount" in request.financial:
transaction_data["amount"] = request.financial["amount"]
transaction_data["currency"] = request.financial.get("currency", "USD")
if request.card:
transaction_data["card_info"] = request.card
if request.merchant:
if "merchant_name" in request.merchant:
transaction_data["merchant"] = request.merchant["merchant_name"]
transaction_data["merchant_category_code"] = request.merchant.get("merchant_category_code")
transaction_data["merchant_data"] = request.merchant
if request.customer:
if "customer_id" in request.customer:
transaction_data["user_id"] = request.customer["customer_id"]
if "age_of_account_days" in request.customer:
transaction_data["user_age_days"] = request.customer["age_of_account_days"]
transaction_data["customer_data"] = request.customer
if request.device:
transaction_data["device_data"] = request.device
if request.location:
if "transaction_city" in request.location:
transaction_data["location"] = f"{request.location.get('transaction_city', '')}, {request.location.get('transaction_country', '')}"
transaction_data["location_data"] = request.location
if request.behavioral_profile:
transaction_data["behavioral_profile"] = request.behavioral_profile
if request.velocity_counters:
transaction_data["velocity_counters"] = request.velocity_counters
if request.risk_signals:
transaction_data["risk_signals"] = request.risk_signals
if request.session:
transaction_data["session_data"] = request.session
if request.channel:
transaction_data["channel_data"] = request.channel
if request.authentication:
transaction_data["authentication_data"] = request.authentication
# Option 3: Build from simple fields (basic transaction)
elif request.user_id or request.amount:
transaction_data = {
"user_id": request.user_id or f"user_{uuid.uuid4().hex[:8]}",
"user_age_days": request.user_age_days or 180,
"total_transactions": request.total_transactions or 10,
"amount": request.amount or 100.0,
"time": request.time or "14:00",
"merchant": request.merchant_name or "Unknown Merchant",
"merchant_category": request.merchant_category or "General",
"currency": request.currency or "USD",
"location": "Unknown",
"previous_location": "Unknown"
}
# Option 4: Use the raw request dict if nothing else works
else:
# Get all non-None fields from the request
request_dict = request.dict(exclude_none=True, exclude={"metadata"})
if request_dict:
transaction_data = request_dict
else:
# Default minimal transaction
transaction_data = {
"user_id": f"user_{uuid.uuid4().hex[:8]}",
"amount": 100.0,
"merchant": "Test Merchant",
"user_age_days": 180,
"total_transactions": 10
}
# Ensure transaction has an ID
if "transaction_id" not in transaction_data:
transaction_data["transaction_id"] = f"TXN-{uuid.uuid4().hex[:12].upper()}"
# Process through the agent with specified model types
transaction_results = {}
for model_type in request.model_types:
try:
# Run once per model type
result = await agent.process(transaction_data, model_type=model_type, session_id=request.session_id, run_id=request.run_id)
# Extract only analyzer results and final decision
final_output = {}
# If result is a dict containing 'results' (from graph execution)
if isinstance(result, dict):
# Get the results section which contains analyzer outputs
if 'results' in result:
analyzer_results = result['results']
# Include all analyzer outputs
for analyzer in ['pattern_detector', 'behavioral_analizer', 'velocity_checker',
'merchant_risk_analizer', 'geographic_analizer']:
if analyzer in analyzer_results:
final_output[analyzer] = analyzer_results[analyzer]
# Include the decision aggregator (final decision)
if 'decision_aggregator' in analyzer_results:
final_output['decision'] = analyzer_results['decision_aggregator']
# Alternative: Check if analyzers are directly in result
else:
for key in ['pattern_detector', 'behavioral_analizer', 'velocity_checker',
'merchant_risk_analizer', 'geographic_analizer', 'decision_aggregator']:
if key in result:
if key == 'decision_aggregator':
final_output['decision'] = result[key]
else:
final_output[key] = result[key]
# If no analyzers found, return the raw result
transaction_results[model_type] = final_output if final_output else result
except Exception as e:
transaction_results[model_type] = {"error": str(e)}
processing_time = (time.time() - start_time) * 1000
# Get generated bullets
generated_bullets = get_generated_bullets()
# Fetch metrics if session_id is provided
metrics = {}
if request.session_id:
metrics = await fetch_metrics(request.session_id)
return ProcessResponse(
result={
"transaction_id": transaction_data.get("transaction_id"),
"results": transaction_results
},
success=True,
metadata={
"agent": "risk_manager",
"framework": "langgraph",
"processing_time_ms": round(processing_time, 2),
"model_types": request.model_types,
"session_id": request.session_id,
"run_id": request.run_id,
"metrics": metrics,
"generated_bullets": generated_bullets,
**request.metadata
}
)
except Exception as e:
raise HTTPException(
status_code=500,
detail=f"Processing failed: {str(e)}"
)
@app.get("/health", response_model=HealthResponse, tags=["Health"])
async def health_check():
"""Health check endpoint"""
import time
uptime = time.time() - start_time if 'start_time' in globals() else 0
return HealthResponse(
status="healthy",
agent="risk_manager",
framework="langgraph",
uptime=f"{uptime:.2f} seconds"
)
@app.get("/graph/info", response_model=GraphInfoResponse, tags=["Graph"])
async def graph_info():
"""Get graph structure information"""
if not agent:
raise HTTPException(status_code=503, detail="Agent not initialized")
return GraphInfoResponse(
graph_info=agent.get_graph_info()
)
# Development server
if __name__ == "__main__":
import time
start_time = time.time()
port = 8001
host = os.getenv("HOST", "0.0.0.0")
print(f"π Starting risk_manager FastAPI server")
print(f"π Server will be available at: http://{host}:{port}")
print(f"π API Documentation: http://{host}:{port}/docs")
print(f"π Alternative docs: http://{host}:{port}/redoc")
uvicorn.run(
"main:app",
host=host,
port=port,
reload=os.getenv("ENVIRONMENT") == "development",
log_level=os.getenv("LOG_LEVEL", "info").lower()
)