Installation
Install the Asguard Python SDK from PyPI:
pip install asguard
Requirements
- Python: >= 3.9
- urllib3: >= 2.1.0, < 3.0.0
- python_dateutil: >= 2.8.2
- pydantic: >= 2.11
- typing-extensions: >= 4.7.1
Setup & Configuration
Asguard runs two independent services: Fraud Detection on port 8081 and Face Verification on port 8082. Configure both clients:
import asguard
from asguard.api import fraud_detection_api, face_verification_api
# Fraud Detection Client
fraud_config = asguard.Configuration(host="http://localhost:8081")
fraud_client = asguard.ApiClient(fraud_config)
fraud_client.set_default_header("X-API-Key", "your-api-key")
fraud_api = fraud_detection_api.FraudDetectionApi(fraud_client)
# Face Verification Client
face_config = asguard.Configuration(host="http://localhost:8082")
face_client = asguard.ApiClient(face_config)
face_client.set_default_header("Authorization", "Bearer your-token")
face_api = face_verification_api.FaceVerificationApi(face_client)
Fraud Detection API
Analyzing Transactions
Analyze transactions for fraud risk with AI-powered recommendations:
from asguard.models import FraudCheckRequest
fraud_request = FraudCheckRequest(
user_id="user_123",
transaction_id="txn_456",
amount=250000,
currency="USD",
ip_address="192.168.1.5",
device_id="device_789",
location="Lagos, Nigeria"
)
try:
response = fraud_api.check_fraud(fraud_request)
print(f"Risk Score: {response.risk_score}")
print(f"Risk Level: {response.risk_level}")
print(f"AI Recommendation: {response.ai_recommendation}")
print(f"Reasons: {response.reasons}")
except asguard.ApiException as e:
print(f"Error: {e.status} - {e.reason}")
Request Fields
| Field | Type | Required | Description |
|---|---|---|---|
user_id |
string | Yes | Unique user identifier |
transaction_id |
string | Yes | Unique transaction identifier |
amount |
number | Yes | Transaction amount |
currency |
string | Yes | ISO 4217 currency code |
ip_address |
string | No | Source IP address |
device_id |
string | No | Device fingerprint |
location |
string | No | Geographic location |
Response Fields
| Field | Type | Description |
|---|---|---|
risk_score |
number | Risk score 0-100 |
risk_level |
string | LOW, MEDIUM, HIGH, CRITICAL |
reasons |
array | List of reasons for the risk assessment |
ai_triggered |
boolean | Whether AI analysis was triggered |
ai_confidence |
number | Confidence score 0-1 |
ai_recommendation |
string | APPROVE, REVIEW, BLOCK, CHALLENGE |
ai_fraud_probability |
number | Fraud probability 0-1 |
ai_summary |
string | Human-readable AI analysis |
Fraud Detection API Reference
POST /analyze
Analyze a transaction for fraudulent activity.
Example Request
POST http://localhost:8081/analyze
X-API-Key: your-api-key
Content-Type: application/json
{
"user_id": "user_123",
"transaction_id": "txn_456",
"amount": 250000,
"currency": "USD",
"ip_address": "192.168.1.5",
"device_id": "device_789",
"location": "Lagos, Nigeria"
}
Example Response (200 OK)
{
"transaction_id": "txn_456",
"risk_score": 41,
"risk_level": "MEDIUM",
"reasons": [
"High transaction amount (>100k)",
"Foreign currency transaction (USD)"
],
"ai_triggered": true,
"ai_confidence": 0.85,
"ai_recommendation": "REVIEW",
"ai_fraud_probability": 0.45,
"ai_summary": "Large USD transaction from Lagos warrants manual review",
"message": "Transaction analyzed successfully"
}
GET /health
Check if the fraud detection service is healthy.
GET http://localhost:8081/health
Response: { "status": "asguard health running" }
Face Verification API
Analyzing Faces
Extract facial embeddings and quality metrics from images:
import base64
from asguard.models import AnalyzeFaceRequest
# Load and encode image
with open("selfie.jpg", "rb") as f:
image_data = base64.b64encode(f.read()).decode('utf-8')
data_uri = f"data:image/jpeg;base64,{image_data}"
# Create request
analyze_request = AnalyzeFaceRequest(
image=data_uri,
quality_checks=True
)
# Execute
try:
response = face_api.analyze_face(analyze_request)
if response.success:
print(f"Embedding: {len(response.embedding)}D vector")
print(f"Quality: {response.quality_score}")
print(f"Sharpness: {response.sharpness}")
print(f"Brightness: {response.brightness}")
except asguard.ApiException as e:
print(f"Error: {e.status}")
Request Fields
| Field | Type | Required | Description |
|---|---|---|---|
image |
string | Yes | Base64-encoded image (data URI) |
quality_checks |
boolean | No | Enable quality metrics |
Response Fields
| Field | Type | Description |
|---|---|---|
success |
boolean | Whether analysis succeeded |
face_detected |
boolean | Whether a face was detected |
embedding |
number[] | 128-dimensional embedding vector |
quality_score |
number | Overall quality (0-1) |
sharpness |
number | Image sharpness metric |
brightness |
number | Average brightness (0-255) |
face_size_ratio |
number | Face to image size ratio |
processing_time_ms |
number | Processing time in milliseconds |
Comparing Faces
Compare two faces to verify identity:
import base64
from asguard.models import CompareFacesRequest
# Load probe image
with open("verification.jpg", "rb") as f:
probe_data = base64.b64encode(f.read()).decode('utf-8')
probe_uri = f"data:image/jpeg;base64,{probe_data}"
# Create request (use embedding from analyze)
compare_request = CompareFacesRequest(
probe_image=probe_uri,
reference_embedding=stored_embedding,
threshold=0.6
)
# Execute
try:
response = face_api.compare_faces(compare_request)
if response.match:
print(f"Match! Confidence: {response.confidence}")
else:
print(f"No match. Distance: {response.distance}")
except asguard.ApiException as e:
print(f"Error: {e.status}")
Request Fields
| Field | Type | Required | Description |
|---|---|---|---|
probe_image |
string | Yes | Base64-encoded image |
reference_embedding |
number[] | Yes | 128D reference embedding |
threshold |
number | No | Confidence threshold (default 0.6) |
Response Fields
| Field | Type | Description |
|---|---|---|
success |
boolean | Whether comparison succeeded |
match |
boolean | Whether faces match |
confidence |
number | Confidence score (0-1) |
distance |
number | Euclidean distance |
threshold_used |
number | Applied threshold |
probe_quality |
number | Probe image quality (0-1) |
processing_time_ms |
number | Processing time |
Face Verification API Reference
POST /v1/analyze
Extract facial embeddings and quality metrics.
Example Request
POST http://localhost:8082/v1/analyze
Authorization: Bearer your-token
Content-Type: application/json
{
"image": "data:image/jpeg;base64,/9j/4AAQSkZJRg...",
"quality_checks": true
}
Example Response (200 OK)
{
"success": true,
"face_detected": true,
"embedding": [0.023, -0.14, 0.082, ...],
"quality_score": 1.0,
"sharpness": 0.82,
"brightness": 142.5,
"face_size_ratio": 0.34,
"warnings": [],
"processing_time_ms": 312
}
POST /v1/compare
Compare a probe image against a reference embedding.
Example Request
POST http://localhost:8082/v1/compare
Authorization: Bearer your-token
Content-Type: application/json
{
"probe_image": "data:image/jpeg;base64,/9j/4AAQSkZJRg...",
"reference_embedding": [0.023, -0.14, 0.082, ...],
"threshold": 0.6
}
Example Response (200 OK)
{
"success": true,
"match": true,
"confidence": 0.78,
"distance": 0.131,
"threshold_used": 0.6,
"probe_quality": 1.0,
"processing_time_ms": 287
}
GET /health
Check service health and version.
GET http://localhost:8082/health
Response: { "status": "healthy", "service": "asguard-face", "version": "1.0.0" }
Error Handling
All API calls throw asguard.ApiException on errors. Always implement proper error handling:
try:
response = fraud_api.check_fraud(fraud_request)
except asguard.ApiException as e:
if e.status == 400:
print("Bad request - check input parameters")
elif e.status == 401:
print("Unauthorized - verify API key/token")
elif e.status == 429:
print("Rate limited - implement backoff")
elif e.status == 500:
print("Server error - retry with backoff")
# Access error details
print(f"Status: {e.status}")
print(f"Reason: {e.reason}")
print(f"Body: {e.body}")
HTTP Status Codes
| Code | Meaning | Action |
|---|---|---|
200 |
Success | Process response normally |
400 |
Bad Request | Check input parameters |
401 |
Unauthorized | Verify credentials |
429 |
Rate Limited | Implement backoff |
500 |
Server Error | Retry with backoff |
Best Practices
Image Encoding
Always encode images as base64 data URIs with correct MIME type:
import base64
with open("photo.jpg", "rb") as f:
data = base64.b64encode(f.read()).decode('utf-8')
uri = f"data:image/jpeg;base64,{data}"
Retry Logic
Implement exponential backoff for rate limits:
import time
def call_with_retry(api_func, request, max_retries=3):
for attempt in range(max_retries):
try:
return api_func(request)
except asguard.ApiException as e:
if e.status == 429 and attempt < max_retries - 1:
wait_time = 2 ** attempt
time.sleep(wait_time)
else:
raise
Quality Checks
Always enable quality checks for face verification:
analyze_request = AnalyzeFaceRequest(
image=data_uri,
quality_checks=True
)
response = face_api.analyze_face(analyze_request)
if response.quality_score < 0.7:
print("Warning: Low image quality")
Threshold Selection
Choose appropriate thresholds based on use case:
- High Security (0.75-0.80): KYC, access control
- Standard (0.60-0.70): User verification, login
- Lenient (0.50-0.60): Lower false negatives