-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathcompliance_plugin.py
More file actions
368 lines (305 loc) · 12 KB
/
compliance_plugin.py
File metadata and controls
368 lines (305 loc) · 12 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
"""
Compliance Plugin - Production Example
Demonstrates production plugin architecture with:
- Dependency injection (policy database, email service)
- Input validation with Pydantic
- Error handling and metrics
- Multiple kernel functions
- Cross-plugin composition
KB Reference: Use Cases → Financial Services Compliance
"""
from typing import Dict, Optional, List
from pydantic import BaseModel, Field, validator
from semantic_kernel.functions import kernel_function
from .base_plugin import BaseProductionPlugin, PluginConfig
import asyncio
class PolicyDatabase:
"""Simulated policy database (in production, use real DB)"""
def __init__(self):
self.policies = {
"refund": {
"title": "Refund Policy",
"content": "Full refunds within 30 days of purchase",
"approval_required": False,
"version": "2.0"
},
"expense": {
"title": "Expense Approval Policy",
"content": "Expenses under $500: auto-approved. $500-$5000: manager approval. Over $5000: director approval",
"approval_required": True,
"version": "1.5"
},
"data_access": {
"title": "Data Access Policy",
"content": "Employee data access requires manager approval and audit logging",
"approval_required": True,
"version": "3.0"
}
}
async def get_policy(self, policy_type: str) -> Optional[Dict]:
"""Get policy by type"""
# Simulate async database call
await asyncio.sleep(0.01)
return self.policies.get(policy_type.lower())
async def search_policies(self, query: str) -> List[Dict]:
"""Search policies by keyword"""
await asyncio.sleep(0.01)
results = []
query_lower = query.lower()
for policy_type, policy in self.policies.items():
if query_lower in policy["content"].lower() or query_lower in policy["title"].lower():
results.append({
"type": policy_type,
**policy
})
return results
class EmailService:
"""Simulated email service (in production, use SendGrid, Azure Communication Services)"""
async def send_email(
self,
to: str,
subject: str,
body: str,
cc: Optional[List[str]] = None
) -> bool:
"""Send email notification"""
# Simulate email sending
await asyncio.sleep(0.01)
print(f"📧 Email sent to {to}: {subject}")
return True
class ComplianceQueryInput(BaseModel):
"""Input validation for compliance queries"""
query: str = Field(..., min_length=5, max_length=500)
user_id: str = Field(..., min_length=3)
user_clearance: str = Field(default="standard")
@validator('user_clearance')
def validate_clearance(cls, v):
allowed = ["standard", "confidential", "secret"]
if v not in allowed:
raise ValueError(f"Clearance must be one of {allowed}")
return v
class ApprovalRequest(BaseModel):
"""Input validation for approval requests"""
request_type: str = Field(..., description="Type of request (refund, expense, data_access)")
amount: Optional[float] = Field(None, ge=0, description="Amount for expense requests")
user_id: str = Field(..., min_length=3)
justification: str = Field(..., min_length=10, max_length=1000)
class CompliancePluginConfig(PluginConfig):
"""Extended configuration for compliance plugin"""
max_query_length: int = Field(default=500)
email_notifications: bool = Field(default=True)
audit_logging: bool = Field(default=True)
class CompliancePlugin(BaseProductionPlugin):
"""
Production compliance plugin for financial services.
Features:
- Policy lookup and search
- Approval workflow automation
- Email notifications
- Audit logging
- Input validation
Dependencies:
- PolicyDatabase: Policy storage and retrieval
- EmailService: Notification delivery
Example:
config = CompliancePluginConfig(plugin_name="Compliance")
policy_db = PolicyDatabase()
email_svc = EmailService()
plugin = CompliancePlugin(
config=config,
policy_database=policy_db,
email_service=email_svc
)
result = await plugin.check_policy(query="What is the refund policy?")
"""
def __init__(
self,
config: CompliancePluginConfig,
policy_database: PolicyDatabase,
email_service: EmailService
):
super().__init__(config)
self.policy_db = policy_database
self.email_service = email_service
async def _initialize_impl(self):
"""Initialize compliance plugin"""
self.logger.info("Loading compliance policies...")
# In production: load policies from database, validate connections
await asyncio.sleep(0.1) # Simulate loading
self.logger.info("Compliance policies loaded")
@kernel_function(
name="check_policy",
description="Check company policy for a specific action or question"
)
async def check_policy(self, query: str, user_id: str = "system") -> str:
"""
Check compliance policy.
Args:
query: Policy question or action to check
user_id: User making the request
Returns:
Policy information or guidance
"""
def _execute():
# Validate input
input_data = ComplianceQueryInput(
query=query,
user_id=user_id
)
# Log query for audit
if self.config.audit_logging:
self.logger.info(f"Policy query from {user_id}: {query}")
# Search for relevant policies
loop = asyncio.get_event_loop()
policies = loop.run_until_complete(
self.policy_db.search_policies(query)
)
if not policies:
return "❌ No matching policy found. Please contact your compliance officer."
# Format response
if len(policies) == 1:
policy = policies[0]
return f"✓ Policy found: {policy['title']}\n\n{policy['content']}\n\n(Version {policy['version']})"
else:
result = f"Found {len(policies)} relevant policies:\n\n"
for i, policy in enumerate(policies, 1):
result += f"{i}. {policy['title']}\n {policy['content']}\n\n"
return result
return self.execute_with_metrics("check_policy", _execute)
@kernel_function(
name="get_approval_requirements",
description="Get approval requirements for a request type and amount"
)
def get_approval_requirements(
self,
request_type: str,
amount: str = "0"
) -> str:
"""
Get approval requirements.
Args:
request_type: Type of request (refund, expense, data_access)
amount: Amount (for expense requests)
Returns:
Approval requirements
"""
def _execute():
# Parse amount
try:
amount_value = float(amount.replace("$", "").replace(",", ""))
except ValueError:
amount_value = 0.0
# Determine approval chain
if request_type.lower() == "expense":
if amount_value < 500:
return "✓ Auto-approved (under $500)\nNo approval required."
elif amount_value < 5000:
return "⚠️ Manager approval required\nApprox. 1-2 business days"
else:
return "⚠️ Director approval required\nManager → Director chain\nApprox. 3-5 business days"
elif request_type.lower() == "refund":
return "✓ Auto-approved\nRefunds processed within 5-7 business days"
elif request_type.lower() == "data_access":
return "⚠️ Manager approval + Audit logging required\nApprox. 2-3 business days"
else:
return f"❌ Unknown request type: {request_type}"
return self.execute_with_metrics("get_approval_requirements", _execute)
@kernel_function(
name="submit_approval_request",
description="Submit an approval request with automatic routing"
)
async def submit_approval_request(
self,
request_type: str,
amount: str = "0",
user_id: str = "user_001",
justification: str = "No justification provided"
) -> str:
"""
Submit approval request.
Args:
request_type: Type of request
amount: Amount (if applicable)
user_id: Requesting user ID
justification: Request justification
Returns:
Submission status and next steps
"""
def _execute():
# Validate input
try:
amount_value = float(amount.replace("$", "").replace(",", ""))
except ValueError:
amount_value = 0.0
request = ApprovalRequest(
request_type=request_type,
amount=amount_value,
user_id=user_id,
justification=justification
)
# Log for audit
self.logger.info(
f"Approval request: {request_type} - ${amount_value} - User: {user_id}"
)
# Determine routing
if request_type.lower() == "expense" and amount_value < 500:
approval_status = "APPROVED"
next_steps = "Request auto-approved. Processing immediately."
else:
approval_status = "PENDING"
next_steps = "Request submitted for approval. You will receive email notification."
# Send email notification
if self.config.email_notifications:
loop = asyncio.get_event_loop()
loop.run_until_complete(
self.email_service.send_email(
to=f"{user_id}@company.com",
subject=f"Approval Request Submitted: {request_type}",
body=f"Your {request_type} request has been submitted for approval.\n\n"
f"Amount: ${amount_value}\n"
f"Justification: {justification}\n\n"
f"You will be notified once approved."
)
)
return f"""
📋 Approval Request Submitted
Request ID: APR-{user_id}-{hash(justification) % 10000:04d}
Type: {request_type}
Amount: ${amount_value:.2f}
Status: {approval_status}
{next_steps}
"""
return self.execute_with_metrics("submit_approval_request", _execute)
@kernel_function(
name="validate_and_notify",
description="Validate request against policy and send notification (composite function)"
)
async def validate_and_notify(
self,
request_type: str,
amount: str = "0",
user_id: str = "user_001"
) -> str:
"""
Composite function: Validate + Submit + Notify
Demonstrates plugin function composition.
"""
def _execute():
# Step 1: Get requirements
requirements = self.get_approval_requirements(request_type, amount)
# Step 2: Submit request
loop = asyncio.get_event_loop()
submission = loop.run_until_complete(
self.submit_approval_request(
request_type=request_type,
amount=amount,
user_id=user_id,
justification="Auto-generated request"
)
)
return f"""
{requirements}
---
{submission}
"""
return self.execute_with_metrics("validate_and_notify", _execute)