Spaces:
Running
Running
File size: 10,313 Bytes
3ef5d3c |
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 |
# BDR Agent Factory - Examples
This directory contains example implementations demonstrating how to use the BDR Agent Factory capabilities.
## Available Examples
### 1. Text Classification Example
**File**: `text_classification_example.py`
**Description**: Demonstrates how to implement and use the text classification capability for categorizing insurance claims.
**Features**:
- Text classification with BERT-based model
- Explainability using SHAP-like feature importance
- Audit trail creation and retrieval
- Batch processing support
- GDPR and IFRS17 compliance
**Usage**:
```bash
python text_classification_example.py
```
**Example Output**:
```
Predicted Class: property_damage
Confidence: 92.0%
Processing Time: 142.50ms
Audit ID: audit_a1b2c3d4e5f6g7h8
```
---
### 2. Fraud Detection Example
**File**: `fraud_detection_example.py`
**Description**: Demonstrates fraud detection capability for identifying potentially fraudulent insurance claims.
**Features**:
- Multi-factor fraud risk analysis
- Risk scoring and level determination
- Detailed explanations and recommendations
- AML and GDPR compliance
- Audit trail support
**Usage**:
```bash
python fraud_detection_example.py
```
**Example Output**:
```
Fraud Score: 78.5%
Risk Level: HIGH
Recommendation: ESCALATE
Risk Factors Detected: 5
```
---
### 3. Integration Example
**File**: `integration_example.py`
**Description**: Demonstrates how to integrate multiple capabilities into a complete claims processing workflow.
**Features**:
- End-to-end claims processing
- Multi-capability integration
- Decision-making logic
- Batch processing
- Complete audit trail
**Usage**:
```bash
python integration_example.py
```
**Workflow Steps**:
1. Text Classification - Categorize claim type
2. Fraud Detection - Assess fraud risk
3. Decision Making - Approve, review, or reject
4. Audit Trail - Track entire process
---
### 4. Sample Test Cases
**File**: `test_examples.py`
**Description**: Unit tests for the example implementations.
**Usage**:
```bash
python -m pytest test_examples.py -v
```
---
## Quick Start
### Prerequisites
```bash
# Install required dependencies
pip install transformers torch numpy pytest
```
### Running All Examples
```bash
# Run text classification example
python text_classification_example.py
# Run fraud detection example
python fraud_detection_example.py
# Run integration example
python integration_example.py
# Run tests
python -m pytest test_examples.py -v
```
---
## Example Data Structures
### Claim Data Format
```python
claim_data = {
'claim_id': 'CLM-2026-001',
'description': 'Customer reported water damage to basement after heavy rain',
'claim_amount': 5000,
'claim_type': 'property_damage',
'claim_date': '2026-01-03T10:30:00Z',
'policy_start_date': '2023-01-01T00:00:00Z',
'claimant_history': {
'previous_claims': 2,
'years_as_customer': 3
},
'incident_details': 'Heavy rain caused flooding in basement',
'witnesses': 0,
'third_party_involved': False
}
```
### Classification Result Format
```python
{
'predicted_class': 'property_damage',
'confidence': 0.92,
'all_scores': {
'property_damage': 0.92,
'auto_accident': 0.03,
'health_claim': 0.02,
'liability': 0.02,
'other': 0.01
},
'explanation': {
'method': 'SHAP',
'key_features': [
{'feature': 'water', 'importance': 0.45},
{'feature': 'damage', 'importance': 0.32},
{'feature': 'basement', 'importance': 0.18}
]
},
'metadata': {
'capability_id': 'cap_text_classification',
'version': '2.1.0',
'processing_time_ms': 142.5
},
'audit_id': 'audit_a1b2c3d4e5f6g7h8'
}
```
### Fraud Detection Result Format
```python
{
'fraud_score': 0.785,
'risk_level': 'high',
'risk_factors': [
{
'factor': 'high_claim_amount',
'description': 'Claim amount $75,000 exceeds threshold',
'severity': 'medium',
'weight': 0.15,
'score': 0.75
},
{
'factor': 'frequent_claims',
'description': 'Claimant has 5 previous claims',
'severity': 'high',
'weight': 0.20,
'score': 0.50
}
],
'recommendation': 'escalate',
'explanation': {
'human_readable_summary': 'This claim shows a high fraud risk (78.5%). Escalation recommended due to 2 serious risk factor(s).'
},
'metadata': {
'capability_id': 'cap_fraud_detection',
'version': '1.5.0',
'processing_time_ms': 89.3
},
'audit_id': 'audit_x9y8z7w6v5u4t3s2'
}
```
---
## API Integration Examples
### Using REST API
```python
import requests
# Authenticate
response = requests.post(
'https://api.bdragentfactory.com/v1/auth/token',
json={
'client_id': 'your_client_id',
'client_secret': 'your_client_secret',
'grant_type': 'client_credentials'
}
)
token = response.json()['access_token']
# Invoke text classification
response = requests.post(
'https://api.bdragentfactory.com/v1/capabilities/cap_text_classification/invoke',
headers={'Authorization': f'Bearer {token}'},
json={
'input': {
'text': 'Customer reported water damage to basement'
},
'options': {
'explain': True,
'audit_trail': True
}
}
)
result = response.json()
print(f"Predicted Class: {result['result']['predicted_class']}")
print(f"Confidence: {result['result']['confidence']}")
```
### Using Python SDK
```python
from bdr_agent_factory import Client
# Initialize client
client = Client(api_key='your_api_key')
# Invoke capability
result = client.capabilities.invoke(
capability_id='cap_text_classification',
input={'text': 'Customer reported water damage to basement'},
options={'explain': True, 'audit_trail': True}
)
print(f"Predicted Class: {result.predicted_class}")
print(f"Confidence: {result.confidence}")
```
---
## Common Use Cases
### Use Case 1: Automated Claims Triage
```python
from text_classification_example import TextClassificationCapability
classifier = TextClassificationCapability()
# Classify incoming claim
result = classifier.classify(
text="Customer's vehicle was damaged in parking lot collision",
explain=True
)
# Route to appropriate department
if result.predicted_class == 'auto_accident':
route_to_department('auto_claims')
elif result.predicted_class == 'property_damage':
route_to_department('property_claims')
```
### Use Case 2: Fraud Screening
```python
from fraud_detection_example import FraudDetectionCapability
fraud_detector = FraudDetectionCapability()
# Screen claim for fraud
result = fraud_detector.detect(
claim_data=claim_data,
explain=True
)
# Take action based on risk level
if result.risk_level in ['high', 'critical']:
escalate_to_investigator(claim_data['claim_id'])
elif result.risk_level == 'medium':
flag_for_manual_review(claim_data['claim_id'])
else:
proceed_with_processing(claim_data['claim_id'])
```
### Use Case 3: Batch Processing
```python
from integration_example import ClaimsProcessingWorkflow
workflow = ClaimsProcessingWorkflow()
# Process multiple claims
claims = load_claims_from_database()
results = workflow.batch_process_claims(claims)
# Generate report
for result in results:
print(f"{result.claim_id}: {result.final_decision}")
```
---
## Testing
### Running Unit Tests
```bash
# Run all tests
pytest test_examples.py -v
# Run specific test
pytest test_examples.py::TestTextClassification::test_basic_classification -v
# Run with coverage
pytest test_examples.py --cov=. --cov-report=html
```
### Example Test
```python
import pytest
from text_classification_example import TextClassificationCapability
def test_text_classification():
classifier = TextClassificationCapability()
result = classifier.classify(
text="Water damage to basement after storm",
explain=True
)
assert result.predicted_class == "property_damage"
assert result.confidence > 0.7
assert result.explanation is not None
assert result.audit_id is not None
```
---
## Performance Benchmarks
### Text Classification
- **Average Latency**: 142ms
- **P95 Latency**: 280ms
- **Throughput**: ~100 requests/second
- **Accuracy**: 95%
### Fraud Detection
- **Average Latency**: 89ms
- **P95 Latency**: 150ms
- **Throughput**: ~150 requests/second
- **Detection Rate**: 92%
### Integrated Workflow
- **Average Latency**: 250ms
- **P95 Latency**: 450ms
- **Throughput**: ~60 workflows/second
---
## Troubleshooting
### Common Issues
#### Issue: "transformers not installed"
**Solution**: Install transformers library
```bash
pip install transformers torch
```
#### Issue: "Model not found"
**Solution**: The examples use mock models by default. For production, specify model path:
```python
classifier = TextClassificationCapability(model_path='/path/to/model')
```
#### Issue: "Import error"
**Solution**: Make sure you're running from the examples directory:
```bash
cd examples
python text_classification_example.py
```
---
## Best Practices
1. **Always enable audit trails** for compliance
2. **Use explanations** for transparency
3. **Validate input data** before processing
4. **Handle errors gracefully** with try-except blocks
5. **Monitor performance** metrics
6. **Test thoroughly** before production deployment
7. **Keep models updated** for best accuracy
8. **Follow security guidelines** for API keys
9. **Implement rate limiting** for production use
10. **Review audit logs** regularly
---
## Additional Resources
- [API Documentation](../docs/API_SPECIFICATION.md)
- [Testing Framework](../docs/TESTING_FRAMEWORK.md)
- [Security Framework](../docs/SECURITY_FRAMEWORK.md)
- [Monitoring & Logging](../docs/MONITORING_LOGGING.md)
- [Version Control Strategy](../docs/VERSION_CONTROL_STRATEGY.md)
---
## Support
For questions or issues:
- Email: support@bdragentfactory.com
- Documentation: https://docs.bdragentfactory.com
- GitHub Issues: https://github.com/BDR-AI/BDR-Agent-Factory/issues
---
## License
MIT License - See [LICENSE](../LICENSE) for details
|