Bader Alabddan commited on
Commit
8036886
·
1 Parent(s): 3ef5d3c

Add core implementation: API, registry, audit, Docker config, and quickstart guide

Browse files
.env.example ADDED
@@ -0,0 +1,44 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Application
2
+ ENVIRONMENT=development
3
+ DEBUG=False
4
+
5
+ # API
6
+ API_HOST=0.0.0.0
7
+ API_PORT=8000
8
+
9
+ # Database
10
+ DATABASE_URL=postgresql://bdr_user:bdr_pass@localhost:5432/bdr_agent_factory
11
+ DATABASE_POOL_SIZE=10
12
+ DATABASE_MAX_OVERFLOW=20
13
+
14
+ # Redis
15
+ REDIS_URL=redis://localhost:6379/0
16
+ REDIS_TTL=3600
17
+
18
+ # Security
19
+ SECRET_KEY=your-secret-key-change-in-production
20
+ ACCESS_TOKEN_EXPIRE_MINUTES=30
21
+ REFRESH_TOKEN_EXPIRE_DAYS=7
22
+
23
+ # Rate Limiting
24
+ RATE_LIMIT_PER_MINUTE=60
25
+ RATE_LIMIT_PER_HOUR=1000
26
+
27
+ # Monitoring
28
+ ENABLE_METRICS=True
29
+ METRICS_PORT=9090
30
+ LOG_LEVEL=INFO
31
+
32
+ # Audit
33
+ AUDIT_RETENTION_DAYS=2555
34
+ ENABLE_AUDIT_TRAIL=True
35
+
36
+ # ML Models
37
+ MODEL_CACHE_DIR=./models
38
+ MAX_BATCH_SIZE=32
39
+ INFERENCE_TIMEOUT=30
40
+
41
+ # Governance
42
+ REQUIRE_EXPLAINABILITY=True
43
+ REQUIRE_AUDIT_TRAIL=True
44
+ COMPLIANCE_FRAMEWORKS=IFRS17,HIPAA,GDPR,AML
Dockerfile ADDED
@@ -0,0 +1,26 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ FROM python:3.11-slim
2
+
3
+ WORKDIR /app
4
+
5
+ # Install system dependencies
6
+ RUN apt-get update && apt-get install -y \
7
+ gcc \
8
+ postgresql-client \
9
+ && rm -rf /var/lib/apt/lists/*
10
+
11
+ # Copy requirements
12
+ COPY pyproject.toml .
13
+
14
+ # Install Python dependencies
15
+ RUN pip install --no-cache-dir -e .[ml]
16
+
17
+ # Copy application code
18
+ COPY src/ ./src/
19
+ COPY AI_CAPABILITY_DICTIONARY.yaml .
20
+ COPY CAPABILITY_SYSTEM_MAP.yaml .
21
+
22
+ # Expose port
23
+ EXPOSE 8000
24
+
25
+ # Run application
26
+ CMD ["uvicorn", "bdr_agent_factory.main:app", "--host", "0.0.0.0", "--port", "8000"]
QUICKSTART.md ADDED
@@ -0,0 +1,213 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # 🚀 BDR Agent Factory - Quick Start Guide
2
+
3
+ ## Prerequisites
4
+
5
+ - Python 3.11+
6
+ - Docker & Docker Compose (optional)
7
+ - PostgreSQL 16+ (if not using Docker)
8
+ - Redis 7+ (if not using Docker)
9
+
10
+ ## Installation
11
+
12
+ ### Option 1: Docker (Recommended)
13
+
14
+ ```bash
15
+ # Clone the repository
16
+ git clone https://huggingface.co/spaces/BDR-AI/BDR-Agent-Factory
17
+ cd BDR-Agent-Factory
18
+
19
+ # Start all services
20
+ docker-compose up -d
21
+
22
+ # Check logs
23
+ docker-compose logs -f api
24
+ ```
25
+
26
+ The API will be available at http://localhost:8000
27
+
28
+ ### Option 2: Local Development
29
+
30
+ ```bash
31
+ # Clone the repository
32
+ git clone https://huggingface.co/spaces/BDR-AI/BDR-Agent-Factory
33
+ cd BDR-Agent-Factory
34
+
35
+ # Create virtual environment
36
+ python3 -m venv venv
37
+ source venv/bin/activate # On Windows: venv\\Scripts\\activate
38
+
39
+ # Install dependencies
40
+ pip install -e .[ml,dev]
41
+
42
+ # Copy environment file
43
+ cp .env.example .env
44
+ # Edit .env with your configuration
45
+
46
+ # Start PostgreSQL and Redis (if not using Docker)
47
+ # Then run the application
48
+ uvicorn bdr_agent_factory.main:app --reload
49
+ ```
50
+
51
+ ## Quick Test
52
+
53
+ ### 1. Health Check
54
+
55
+ ```bash
56
+ curl http://localhost:8000/api/v1/health
57
+ ```
58
+
59
+ Expected response:
60
+ ```json
61
+ {
62
+ "status": "healthy",
63
+ "timestamp": "2026-01-03T00:00:00",
64
+ "service": "BDR Agent Factory"
65
+ }
66
+ ```
67
+
68
+ ### 2. List Capabilities
69
+
70
+ ```bash
71
+ curl http://localhost:8000/api/v1/capabilities
72
+ ```
73
+
74
+ ### 3. Get Specific Capability
75
+
76
+ ```bash
77
+ curl http://localhost:8000/api/v1/capabilities/cap_text_classification
78
+ ```
79
+
80
+ ### 4. Search Capabilities
81
+
82
+ ```bash
83
+ curl http://localhost:8000/api/v1/capabilities/search/fraud
84
+ ```
85
+
86
+ ## API Documentation
87
+
88
+ Once the server is running, visit:
89
+
90
+ - **Swagger UI**: http://localhost:8000/docs
91
+ - **ReDoc**: http://localhost:8000/redoc
92
+
93
+ ## Project Structure
94
+
95
+ ```
96
+ BDR-Agent-Factory/
97
+ ├── src/
98
+ │ └── bdr_agent_factory/
99
+ │ ├── api/ # API endpoints
100
+ │ ├── capabilities/ # AI capability implementations
101
+ │ ├── core/ # Core functionality
102
+ │ ├── models/ # Data models
103
+ │ ├── services/ # Business logic
104
+ │ └── utils/ # Utilities
105
+ ├── docs/ # Documentation
106
+ ├── examples/ # Example implementations
107
+ ├── tests/ # Test suite
108
+ ├── AI_CAPABILITY_DICTIONARY.yaml
109
+ ├── CAPABILITY_SYSTEM_MAP.yaml
110
+ ├── pyproject.toml
111
+ ├── Dockerfile
112
+ └── docker-compose.yml
113
+ ```
114
+
115
+ ## Development Workflow
116
+
117
+ ### Running Tests
118
+
119
+ ```bash
120
+ # Run all tests
121
+ pytest
122
+
123
+ # Run with coverage
124
+ pytest --cov=bdr_agent_factory --cov-report=html
125
+
126
+ # Run specific test file
127
+ pytest tests/test_registry.py
128
+ ```
129
+
130
+ ### Code Quality
131
+
132
+ ```bash
133
+ # Format code
134
+ black src/ tests/
135
+
136
+ # Lint code
137
+ ruff check src/ tests/
138
+
139
+ # Type checking
140
+ mypy src/
141
+
142
+ # Security scan
143
+ bandit -r src/
144
+ ```
145
+
146
+ ### Database Migrations
147
+
148
+ ```bash
149
+ # Create migration
150
+ alembic revision --autogenerate -m "description"
151
+
152
+ # Apply migrations
153
+ alembic upgrade head
154
+
155
+ # Rollback
156
+ alembic downgrade -1
157
+ ```
158
+
159
+ ## Next Steps
160
+
161
+ 1. **Read the Documentation**
162
+ - [API Specification](docs/API_SPECIFICATION.md)
163
+ - [Architecture](docs/ARCHITECTURE.md)
164
+ - [Security Framework](docs/SECURITY_FRAMEWORK.md)
165
+
166
+ 2. **Explore Examples**
167
+ - [Text Classification](examples/text_classification_example.py)
168
+ - [Fraud Detection](examples/fraud_detection_example.py)
169
+ - [Integration Example](examples/integration_example.py)
170
+
171
+ 3. **Deploy to Production**
172
+ - Review [Deployment Guide](docs/VERSION_CONTROL_STRATEGY.md)
173
+ - Configure monitoring and logging
174
+ - Set up CI/CD pipeline
175
+
176
+ ## Troubleshooting
177
+
178
+ ### Port Already in Use
179
+
180
+ ```bash
181
+ # Change port in docker-compose.yml or .env
182
+ API_PORT=8001
183
+ ```
184
+
185
+ ### Database Connection Error
186
+
187
+ ```bash
188
+ # Check PostgreSQL is running
189
+ docker-compose ps
190
+
191
+ # Check database logs
192
+ docker-compose logs db
193
+ ```
194
+
195
+ ### Redis Connection Error
196
+
197
+ ```bash
198
+ # Check Redis is running
199
+ docker-compose ps
200
+
201
+ # Test Redis connection
202
+ redis-cli ping
203
+ ```
204
+
205
+ ## Support
206
+
207
+ - **Documentation**: See `/docs` directory
208
+ - **Issues**: Open an issue on HuggingFace
209
+ - **Discussions**: Join the discussion board
210
+
211
+ ## License
212
+
213
+ MIT License - See [LICENSE](LICENSE) for details
create_implementation.py ADDED
@@ -0,0 +1,300 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python3
2
+ """Script to create all core implementation files for BDR Agent Factory."""
3
+
4
+ import os
5
+ from pathlib import Path
6
+
7
+ # Core configuration file
8
+ CONFIG_PY = '''"""Configuration management for BDR Agent Factory."""
9
+
10
+ from typing import Optional
11
+ from pydantic_settings import BaseSettings
12
+ from pydantic import Field
13
+
14
+ class Settings(BaseSettings):
15
+ """Application settings."""
16
+
17
+ # Application
18
+ app_name: str = "BDR Agent Factory"
19
+ app_version: str = "0.1.0"
20
+ environment: str = Field(default="development", env="ENVIRONMENT")
21
+ debug: bool = Field(default=False, env="DEBUG")
22
+
23
+ # API
24
+ api_host: str = Field(default="0.0.0.0", env="API_HOST")
25
+ api_port: int = Field(default=8000, env="API_PORT")
26
+ api_prefix: str = "/api/v1"
27
+
28
+ # Database
29
+ database_url: str = Field(
30
+ default="postgresql://bdr_user:bdr_pass@localhost:5432/bdr_agent_factory",
31
+ env="DATABASE_URL"
32
+ )
33
+
34
+ # Redis
35
+ redis_url: str = Field(default="redis://localhost:6379/0", env="REDIS_URL")
36
+ redis_ttl: int = Field(default=3600, env="REDIS_TTL")
37
+
38
+ # Security
39
+ secret_key: str = Field(default="change-in-production", env="SECRET_KEY")
40
+ algorithm: str = "HS256"
41
+ access_token_expire_minutes: int = 30
42
+
43
+ # Governance
44
+ require_explainability: bool = True
45
+ require_audit_trail: bool = True
46
+ audit_retention_days: int = 2555 # 7 years
47
+
48
+ class Config:
49
+ env_file = ".env"
50
+ case_sensitive = False
51
+
52
+ settings = Settings()
53
+ '''
54
+
55
+ # Capability Registry
56
+ REGISTRY_PY = '''"""Capability Registry for managing AI capabilities."""
57
+
58
+ from typing import Dict, List, Optional
59
+ from datetime import datetime
60
+ import yaml
61
+
62
+ class CapabilityRegistry:
63
+ """Central registry for AI capabilities."""
64
+
65
+ def __init__(self, capability_dict_path: str = "AI_CAPABILITY_DICTIONARY.yaml"):
66
+ self.capability_dict_path = capability_dict_path
67
+ self.capabilities: Dict[str, dict] = {}
68
+ self.load_capabilities()
69
+
70
+ def load_capabilities(self):
71
+ """Load capabilities from YAML file."""
72
+ try:
73
+ with open(self.capability_dict_path, 'r') as f:
74
+ data = yaml.safe_load(f)
75
+ if 'capabilities' in data:
76
+ for cap in data['capabilities']:
77
+ self.capabilities[cap['id']] = cap
78
+ except FileNotFoundError:
79
+ print(f"Warning: {self.capability_dict_path} not found")
80
+
81
+ def get_capability(self, capability_id: str) -> Optional[dict]:
82
+ """Get capability by ID."""
83
+ return self.capabilities.get(capability_id)
84
+
85
+ def list_capabilities(self, category: Optional[str] = None) -> List[dict]:
86
+ """List all capabilities, optionally filtered by category."""
87
+ if category:
88
+ return [c for c in self.capabilities.values() if c.get('category') == category]
89
+ return list(self.capabilities.values())
90
+
91
+ def search_capabilities(self, query: str) -> List[dict]:
92
+ """Search capabilities by name or description."""
93
+ query_lower = query.lower()
94
+ return [
95
+ c for c in self.capabilities.values()
96
+ if query_lower in c.get('name', '').lower()
97
+ or query_lower in c.get('description', '').lower()
98
+ ]
99
+ '''
100
+
101
+ # Audit Logger
102
+ AUDIT_PY = '''"""Audit logging for compliance and governance."""
103
+
104
+ from typing import Any, Dict, Optional
105
+ from datetime import datetime
106
+ import json
107
+ import hashlib
108
+
109
+ class AuditLogger:
110
+ """Audit trail logger for AI operations."""
111
+
112
+ def __init__(self, storage_backend: str = "database"):
113
+ self.storage_backend = storage_backend
114
+ self.audit_records = []
115
+
116
+ def log_request(
117
+ self,
118
+ capability_id: str,
119
+ user_id: str,
120
+ input_data: Any,
121
+ metadata: Optional[Dict] = None
122
+ ) -> str:
123
+ """Log an AI capability request."""
124
+ audit_id = self._generate_audit_id()
125
+
126
+ record = {
127
+ "audit_id": audit_id,
128
+ "timestamp": datetime.utcnow().isoformat(),
129
+ "capability_id": capability_id,
130
+ "user_id": user_id,
131
+ "input_hash": self._hash_data(input_data),
132
+ "metadata": metadata or {},
133
+ "event_type": "request"
134
+ }
135
+
136
+ self._store_record(record)
137
+ return audit_id
138
+
139
+ def log_response(
140
+ self,
141
+ audit_id: str,
142
+ output_data: Any,
143
+ explainability: Optional[Dict] = None,
144
+ decision_type: Optional[str] = None
145
+ ):
146
+ """Log an AI capability response."""
147
+ record = {
148
+ "audit_id": audit_id,
149
+ "timestamp": datetime.utcnow().isoformat(),
150
+ "output_hash": self._hash_data(output_data),
151
+ "explainability": explainability,
152
+ "decision_type": decision_type,
153
+ "event_type": "response"
154
+ }
155
+
156
+ self._store_record(record)
157
+
158
+ def _generate_audit_id(self) -> str:
159
+ """Generate unique audit ID."""
160
+ timestamp = datetime.utcnow().isoformat()
161
+ return hashlib.sha256(timestamp.encode()).hexdigest()[:16]
162
+
163
+ def _hash_data(self, data: Any) -> str:
164
+ """Hash data for audit trail."""
165
+ data_str = json.dumps(data, sort_keys=True, default=str)
166
+ return hashlib.sha256(data_str.encode()).hexdigest()
167
+
168
+ def _store_record(self, record: Dict):
169
+ """Store audit record."""
170
+ self.audit_records.append(record)
171
+ # In production, this would write to database
172
+ '''
173
+
174
+ # Main API application
175
+ MAIN_PY = '''"""Main FastAPI application."""
176
+
177
+ from fastapi import FastAPI
178
+ from fastapi.middleware.cors import CORSMiddleware
179
+ from .core.config import settings
180
+ from .core.registry import CapabilityRegistry
181
+ from .api import capabilities, health
182
+
183
+ app = FastAPI(
184
+ title=settings.app_name,
185
+ version=settings.app_version,
186
+ description="Enterprise AI Governance Framework for Insurance"
187
+ )
188
+
189
+ # CORS
190
+ app.add_middleware(
191
+ CORSMiddleware,
192
+ allow_origins=["*"],
193
+ allow_credentials=True,
194
+ allow_methods=["*"],
195
+ allow_headers=["*"],
196
+ )
197
+
198
+ # Initialize registry
199
+ registry = CapabilityRegistry()
200
+
201
+ # Include routers
202
+ app.include_router(health.router, prefix=settings.api_prefix, tags=["health"])
203
+ app.include_router(capabilities.router, prefix=settings.api_prefix, tags=["capabilities"])
204
+
205
+ @app.on_event("startup")
206
+ async def startup_event():
207
+ """Startup tasks."""
208
+ print(f"Starting {settings.app_name} v{settings.app_version}")
209
+ print(f"Loaded {len(registry.capabilities)} capabilities")
210
+
211
+ @app.on_event("shutdown")
212
+ async def shutdown_event():
213
+ """Shutdown tasks."""
214
+ print("Shutting down BDR Agent Factory")
215
+ '''
216
+
217
+ # Health check endpoints
218
+ HEALTH_PY = '''"""Health check endpoints."""
219
+
220
+ from fastapi import APIRouter
221
+ from datetime import datetime
222
+
223
+ router = APIRouter()
224
+
225
+ @router.get("/health")
226
+ async def health_check():
227
+ """Health check endpoint."""
228
+ return {
229
+ "status": "healthy",
230
+ "timestamp": datetime.utcnow().isoformat(),
231
+ "service": "BDR Agent Factory"
232
+ }
233
+
234
+ @router.get("/ready")
235
+ async def readiness_check():
236
+ """Readiness check endpoint."""
237
+ return {
238
+ "status": "ready",
239
+ "timestamp": datetime.utcnow().isoformat()
240
+ }
241
+ '''
242
+
243
+ # Capabilities API endpoints
244
+ CAPABILITIES_API_PY = '''"""Capabilities API endpoints."""
245
+
246
+ from fastapi import APIRouter, HTTPException
247
+ from typing import Optional, List
248
+ from ..core.registry import CapabilityRegistry
249
+ from ..core.audit import AuditLogger
250
+
251
+ router = APIRouter()
252
+ registry = CapabilityRegistry()
253
+ audit_logger = AuditLogger()
254
+
255
+ @router.get("/capabilities")
256
+ async def list_capabilities(category: Optional[str] = None):
257
+ """List all capabilities."""
258
+ capabilities = registry.list_capabilities(category=category)
259
+ return {
260
+ "count": len(capabilities),
261
+ "capabilities": capabilities
262
+ }
263
+
264
+ @router.get("/capabilities/{capability_id}")
265
+ async def get_capability(capability_id: str):
266
+ """Get capability by ID."""
267
+ capability = registry.get_capability(capability_id)
268
+ if not capability:
269
+ raise HTTPException(status_code=404, detail="Capability not found")
270
+ return capability
271
+
272
+ @router.get("/capabilities/search/{query}")
273
+ async def search_capabilities(query: str):
274
+ """Search capabilities."""
275
+ results = registry.search_capabilities(query)
276
+ return {
277
+ "query": query,
278
+ "count": len(results),
279
+ "results": results
280
+ }
281
+ '''
282
+
283
+ # Create all files
284
+ files_to_create = {
285
+ "src/bdr_agent_factory/core/config.py": CONFIG_PY,
286
+ "src/bdr_agent_factory/core/registry.py": REGISTRY_PY,
287
+ "src/bdr_agent_factory/core/audit.py": AUDIT_PY,
288
+ "src/bdr_agent_factory/main.py": MAIN_PY,
289
+ "src/bdr_agent_factory/api/health.py": HEALTH_PY,
290
+ "src/bdr_agent_factory/api/capabilities.py": CAPABILITIES_API_PY,
291
+ }
292
+
293
+ print("Creating implementation files...")
294
+ for filepath, content in files_to_create.items():
295
+ Path(filepath).parent.mkdir(parents=True, exist_ok=True)
296
+ with open(filepath, 'w') as f:
297
+ f.write(content)
298
+ print(f"✓ Created {filepath}")
299
+
300
+ print("\n✅ All core implementation files created successfully!")
docker-compose.yml ADDED
@@ -0,0 +1,39 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ version: '3.8'
2
+
3
+ services:
4
+ api:
5
+ build: .
6
+ ports:
7
+ - "8000:8000"
8
+ environment:
9
+ - DATABASE_URL=postgresql://bdr_user:bdr_pass@db:5432/bdr_agent_factory
10
+ - REDIS_URL=redis://redis:6379/0
11
+ - ENVIRONMENT=development
12
+ depends_on:
13
+ - db
14
+ - redis
15
+ volumes:
16
+ - ./src:/app/src
17
+ - ./models:/app/models
18
+
19
+ db:
20
+ image: postgres:16-alpine
21
+ environment:
22
+ - POSTGRES_USER=bdr_user
23
+ - POSTGRES_PASSWORD=bdr_pass
24
+ - POSTGRES_DB=bdr_agent_factory
25
+ ports:
26
+ - "5432:5432"
27
+ volumes:
28
+ - postgres_data:/var/lib/postgresql/data
29
+
30
+ redis:
31
+ image: redis:7-alpine
32
+ ports:
33
+ - "6379:6379"
34
+ volumes:
35
+ - redis_data:/data
36
+
37
+ volumes:
38
+ postgres_data:
39
+ redis_data:
pyproject.toml ADDED
@@ -0,0 +1,93 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ [build-system]
2
+ requires = ["setuptools>=68.0", "wheel"]
3
+ build-backend = "setuptools.build_meta"
4
+
5
+ [project]
6
+ name = "bdr-agent-factory"
7
+ version = "0.1.0"
8
+ description = "Enterprise AI Governance Framework for Insurance"
9
+ readme = "README.md"
10
+ requires-python = ">=3.11"
11
+ license = {text = "MIT"}
12
+ authors = [{name = "BDR AI Team"}]
13
+
14
+ dependencies = [
15
+ "fastapi>=0.104.0",
16
+ "uvicorn[standard]>=0.24.0",
17
+ "pydantic>=2.5.0",
18
+ "pydantic-settings>=2.1.0",
19
+ "sqlalchemy>=2.0.0",
20
+ "alembic>=1.12.0",
21
+ "psycopg2-binary>=2.9.9",
22
+ "redis>=5.0.0",
23
+ "pyyaml>=6.0.1",
24
+ "python-jose[cryptography]>=3.3.0",
25
+ "passlib[bcrypt]>=1.7.4",
26
+ "python-multipart>=0.0.6",
27
+ "httpx>=0.25.0",
28
+ ]
29
+
30
+ [project.optional-dependencies]
31
+ ml = [
32
+ "transformers>=4.35.0",
33
+ "torch>=2.1.0",
34
+ "scikit-learn>=1.3.0",
35
+ "shap>=0.43.0",
36
+ "numpy>=1.24.0",
37
+ "pandas>=2.1.0",
38
+ ]
39
+
40
+ dev = [
41
+ "pytest>=7.4.0",
42
+ "pytest-asyncio>=0.21.0",
43
+ "pytest-cov>=4.1.0",
44
+ "black>=23.11.0",
45
+ "ruff>=0.1.6",
46
+ "mypy>=1.7.0",
47
+ "pre-commit>=3.5.0",
48
+ ]
49
+
50
+ test = [
51
+ "pytest>=7.4.0",
52
+ "pytest-asyncio>=0.21.0",
53
+ "pytest-cov>=4.1.0",
54
+ "httpx>=0.25.0",
55
+ "faker>=20.1.0",
56
+ ]
57
+
58
+ security = [
59
+ "bandit>=1.7.5",
60
+ "safety>=2.3.5",
61
+ "pip-audit>=2.6.1",
62
+ ]
63
+
64
+ all = [
65
+ "bdr-agent-factory[ml,dev,test,security]",
66
+ ]
67
+
68
+ [project.scripts]
69
+ bdr-factory = "bdr_agent_factory.cli:main"
70
+
71
+ [tool.setuptools.packages.find]
72
+ where = ["src"]
73
+
74
+ [tool.black]
75
+ line-length = 88
76
+ target-version = ["py311"]
77
+
78
+ [tool.ruff]
79
+ line-length = 88
80
+ target-version = "py311"
81
+
82
+ [tool.mypy]
83
+ python_version = "3.11"
84
+ strict = true
85
+ warn_return_any = true
86
+ warn_unused_configs = true
87
+
88
+ [tool.pytest.ini_options]
89
+ testpaths = ["tests"]
90
+ python_files = ["test_*.py"]
91
+ python_classes = ["Test*"]
92
+ python_functions = ["test_*"]
93
+ addopts = "--cov=bdr_agent_factory --cov-report=html --cov-report=term"
requirements.txt ADDED
@@ -0,0 +1,22 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Core dependencies
2
+ fastapi>=0.104.0
3
+ uvicorn[standard]>=0.24.0
4
+ pydantic>=2.5.0
5
+ pydantic-settings>=2.1.0
6
+ sqlalchemy>=2.0.0
7
+ alembic>=1.12.0
8
+ psycopg2-binary>=2.9.9
9
+ redis>=5.0.0
10
+ pyyaml>=6.0.1
11
+ python-jose[cryptography]>=3.3.0
12
+ passlib[bcrypt]>=1.7.4
13
+ python-multipart>=0.0.6
14
+ httpx>=0.25.0
15
+
16
+ # ML dependencies (optional)
17
+ transformers>=4.35.0
18
+ torch>=2.1.0
19
+ scikit-learn>=1.3.0
20
+ shap>=0.43.0
21
+ numpy>=1.24.0
22
+ pandas>=2.1.0
src/bdr_agent_factory/__init__.py ADDED
@@ -0,0 +1,14 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """BDR Agent Factory - Enterprise AI Governance Framework."""
2
+
3
+ __version__ = "0.1.0"
4
+ __author__ = "BDR AI Team"
5
+ __description__ = "Single Source of Truth for Governed AI Capabilities in Insurance"
6
+
7
+ from .core.config import settings
8
+ from .core.registry import CapabilityRegistry
9
+
10
+ __all__ = [
11
+ "settings",
12
+ "CapabilityRegistry",
13
+ "__version__",
14
+ ]
src/bdr_agent_factory/api/__init__.py ADDED
@@ -0,0 +1 @@
 
 
1
+ """Api module for BDR Agent Factory."""
src/bdr_agent_factory/api/capabilities.py ADDED
@@ -0,0 +1,37 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Capabilities API endpoints."""
2
+
3
+ from fastapi import APIRouter, HTTPException
4
+ from typing import Optional, List
5
+ from ..core.registry import CapabilityRegistry
6
+ from ..core.audit import AuditLogger
7
+
8
+ router = APIRouter()
9
+ registry = CapabilityRegistry()
10
+ audit_logger = AuditLogger()
11
+
12
+ @router.get("/capabilities")
13
+ async def list_capabilities(category: Optional[str] = None):
14
+ """List all capabilities."""
15
+ capabilities = registry.list_capabilities(category=category)
16
+ return {
17
+ "count": len(capabilities),
18
+ "capabilities": capabilities
19
+ }
20
+
21
+ @router.get("/capabilities/{capability_id}")
22
+ async def get_capability(capability_id: str):
23
+ """Get capability by ID."""
24
+ capability = registry.get_capability(capability_id)
25
+ if not capability:
26
+ raise HTTPException(status_code=404, detail="Capability not found")
27
+ return capability
28
+
29
+ @router.get("/capabilities/search/{query}")
30
+ async def search_capabilities(query: str):
31
+ """Search capabilities."""
32
+ results = registry.search_capabilities(query)
33
+ return {
34
+ "query": query,
35
+ "count": len(results),
36
+ "results": results
37
+ }
src/bdr_agent_factory/api/health.py ADDED
@@ -0,0 +1,23 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Health check endpoints."""
2
+
3
+ from fastapi import APIRouter
4
+ from datetime import datetime
5
+
6
+ router = APIRouter()
7
+
8
+ @router.get("/health")
9
+ async def health_check():
10
+ """Health check endpoint."""
11
+ return {
12
+ "status": "healthy",
13
+ "timestamp": datetime.utcnow().isoformat(),
14
+ "service": "BDR Agent Factory"
15
+ }
16
+
17
+ @router.get("/ready")
18
+ async def readiness_check():
19
+ """Readiness check endpoint."""
20
+ return {
21
+ "status": "ready",
22
+ "timestamp": datetime.utcnow().isoformat()
23
+ }
src/bdr_agent_factory/capabilities/__init__.py ADDED
@@ -0,0 +1 @@
 
 
1
+ """Capabilities module for BDR Agent Factory."""
src/bdr_agent_factory/core/__init__.py ADDED
@@ -0,0 +1 @@
 
 
1
+ """Core module for BDR Agent Factory."""
src/bdr_agent_factory/core/audit.py ADDED
@@ -0,0 +1,70 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Audit logging for compliance and governance."""
2
+
3
+ from typing import Any, Dict, Optional
4
+ from datetime import datetime
5
+ import json
6
+ import hashlib
7
+
8
+ class AuditLogger:
9
+ """Audit trail logger for AI operations."""
10
+
11
+ def __init__(self, storage_backend: str = "database"):
12
+ self.storage_backend = storage_backend
13
+ self.audit_records = []
14
+
15
+ def log_request(
16
+ self,
17
+ capability_id: str,
18
+ user_id: str,
19
+ input_data: Any,
20
+ metadata: Optional[Dict] = None
21
+ ) -> str:
22
+ """Log an AI capability request."""
23
+ audit_id = self._generate_audit_id()
24
+
25
+ record = {
26
+ "audit_id": audit_id,
27
+ "timestamp": datetime.utcnow().isoformat(),
28
+ "capability_id": capability_id,
29
+ "user_id": user_id,
30
+ "input_hash": self._hash_data(input_data),
31
+ "metadata": metadata or {},
32
+ "event_type": "request"
33
+ }
34
+
35
+ self._store_record(record)
36
+ return audit_id
37
+
38
+ def log_response(
39
+ self,
40
+ audit_id: str,
41
+ output_data: Any,
42
+ explainability: Optional[Dict] = None,
43
+ decision_type: Optional[str] = None
44
+ ):
45
+ """Log an AI capability response."""
46
+ record = {
47
+ "audit_id": audit_id,
48
+ "timestamp": datetime.utcnow().isoformat(),
49
+ "output_hash": self._hash_data(output_data),
50
+ "explainability": explainability,
51
+ "decision_type": decision_type,
52
+ "event_type": "response"
53
+ }
54
+
55
+ self._store_record(record)
56
+
57
+ def _generate_audit_id(self) -> str:
58
+ """Generate unique audit ID."""
59
+ timestamp = datetime.utcnow().isoformat()
60
+ return hashlib.sha256(timestamp.encode()).hexdigest()[:16]
61
+
62
+ def _hash_data(self, data: Any) -> str:
63
+ """Hash data for audit trail."""
64
+ data_str = json.dumps(data, sort_keys=True, default=str)
65
+ return hashlib.sha256(data_str.encode()).hexdigest()
66
+
67
+ def _store_record(self, record: Dict):
68
+ """Store audit record."""
69
+ self.audit_records.append(record)
70
+ # In production, this would write to database
src/bdr_agent_factory/core/config.py ADDED
@@ -0,0 +1,45 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Configuration management for BDR Agent Factory."""
2
+
3
+ from typing import Optional
4
+ from pydantic_settings import BaseSettings
5
+ from pydantic import Field
6
+
7
+ class Settings(BaseSettings):
8
+ """Application settings."""
9
+
10
+ # Application
11
+ app_name: str = "BDR Agent Factory"
12
+ app_version: str = "0.1.0"
13
+ environment: str = Field(default="development", env="ENVIRONMENT")
14
+ debug: bool = Field(default=False, env="DEBUG")
15
+
16
+ # API
17
+ api_host: str = Field(default="0.0.0.0", env="API_HOST")
18
+ api_port: int = Field(default=8000, env="API_PORT")
19
+ api_prefix: str = "/api/v1"
20
+
21
+ # Database
22
+ database_url: str = Field(
23
+ default="postgresql://bdr_user:bdr_pass@localhost:5432/bdr_agent_factory",
24
+ env="DATABASE_URL"
25
+ )
26
+
27
+ # Redis
28
+ redis_url: str = Field(default="redis://localhost:6379/0", env="REDIS_URL")
29
+ redis_ttl: int = Field(default=3600, env="REDIS_TTL")
30
+
31
+ # Security
32
+ secret_key: str = Field(default="change-in-production", env="SECRET_KEY")
33
+ algorithm: str = "HS256"
34
+ access_token_expire_minutes: int = 30
35
+
36
+ # Governance
37
+ require_explainability: bool = True
38
+ require_audit_trail: bool = True
39
+ audit_retention_days: int = 2555 # 7 years
40
+
41
+ class Config:
42
+ env_file = ".env"
43
+ case_sensitive = False
44
+
45
+ settings = Settings()
src/bdr_agent_factory/core/registry.py ADDED
@@ -0,0 +1,43 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Capability Registry for managing AI capabilities."""
2
+
3
+ from typing import Dict, List, Optional
4
+ from datetime import datetime
5
+ import yaml
6
+
7
+ class CapabilityRegistry:
8
+ """Central registry for AI capabilities."""
9
+
10
+ def __init__(self, capability_dict_path: str = "AI_CAPABILITY_DICTIONARY.yaml"):
11
+ self.capability_dict_path = capability_dict_path
12
+ self.capabilities: Dict[str, dict] = {}
13
+ self.load_capabilities()
14
+
15
+ def load_capabilities(self):
16
+ """Load capabilities from YAML file."""
17
+ try:
18
+ with open(self.capability_dict_path, 'r') as f:
19
+ data = yaml.safe_load(f)
20
+ if 'capabilities' in data:
21
+ for cap in data['capabilities']:
22
+ self.capabilities[cap['id']] = cap
23
+ except FileNotFoundError:
24
+ print(f"Warning: {self.capability_dict_path} not found")
25
+
26
+ def get_capability(self, capability_id: str) -> Optional[dict]:
27
+ """Get capability by ID."""
28
+ return self.capabilities.get(capability_id)
29
+
30
+ def list_capabilities(self, category: Optional[str] = None) -> List[dict]:
31
+ """List all capabilities, optionally filtered by category."""
32
+ if category:
33
+ return [c for c in self.capabilities.values() if c.get('category') == category]
34
+ return list(self.capabilities.values())
35
+
36
+ def search_capabilities(self, query: str) -> List[dict]:
37
+ """Search capabilities by name or description."""
38
+ query_lower = query.lower()
39
+ return [
40
+ c for c in self.capabilities.values()
41
+ if query_lower in c.get('name', '').lower()
42
+ or query_lower in c.get('description', '').lower()
43
+ ]
src/bdr_agent_factory/main.py ADDED
@@ -0,0 +1,40 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Main FastAPI application."""
2
+
3
+ from fastapi import FastAPI
4
+ from fastapi.middleware.cors import CORSMiddleware
5
+ from .core.config import settings
6
+ from .core.registry import CapabilityRegistry
7
+ from .api import capabilities, health
8
+
9
+ app = FastAPI(
10
+ title=settings.app_name,
11
+ version=settings.app_version,
12
+ description="Enterprise AI Governance Framework for Insurance"
13
+ )
14
+
15
+ # CORS
16
+ app.add_middleware(
17
+ CORSMiddleware,
18
+ allow_origins=["*"],
19
+ allow_credentials=True,
20
+ allow_methods=["*"],
21
+ allow_headers=["*"],
22
+ )
23
+
24
+ # Initialize registry
25
+ registry = CapabilityRegistry()
26
+
27
+ # Include routers
28
+ app.include_router(health.router, prefix=settings.api_prefix, tags=["health"])
29
+ app.include_router(capabilities.router, prefix=settings.api_prefix, tags=["capabilities"])
30
+
31
+ @app.on_event("startup")
32
+ async def startup_event():
33
+ """Startup tasks."""
34
+ print(f"Starting {settings.app_name} v{settings.app_version}")
35
+ print(f"Loaded {len(registry.capabilities)} capabilities")
36
+
37
+ @app.on_event("shutdown")
38
+ async def shutdown_event():
39
+ """Shutdown tasks."""
40
+ print("Shutting down BDR Agent Factory")
src/bdr_agent_factory/models/__init__.py ADDED
@@ -0,0 +1 @@
 
 
1
+ """Models module for BDR Agent Factory."""
src/bdr_agent_factory/services/__init__.py ADDED
@@ -0,0 +1 @@
 
 
1
+ """Services module for BDR Agent Factory."""
src/bdr_agent_factory/utils/__init__.py ADDED
@@ -0,0 +1 @@
 
 
1
+ """Utils module for BDR Agent Factory."""