-
Notifications
You must be signed in to change notification settings - Fork 4
Expand file tree
/
Copy pathworkflow.py
More file actions
298 lines (251 loc) · 9.36 KB
/
Copy pathworkflow.py
File metadata and controls
298 lines (251 loc) · 9.36 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
"""
Workflow Engine for Context Graph
Demonstrates human-in-the-loop automation where:
1. Agents propose actions
2. Context is gathered from multiple systems
3. Approvals are routed and recorded
4. Decision traces become searchable precedent
"""
from dataclasses import dataclass, field
from datetime import datetime
from typing import Any, Callable, Optional
from enum import Enum
from models import Entity, EntityType, DecisionTrace, DecisionType, Context
from graph import ContextGraph
from search import PrecedentSearch
class WorkflowStatus(Enum):
PENDING = "pending"
AWAITING_APPROVAL = "awaiting_approval"
APPROVED = "approved"
REJECTED = "rejected"
AUTO_APPROVED = "auto_approved"
@dataclass
class WorkflowRequest:
"""A request that needs a decision."""
id: str
request_type: str
description: str
requestor_id: str
requestor_name: str
entity_ids: list[str] = field(default_factory=list)
data: dict[str, Any] = field(default_factory=dict)
tags: list[str] = field(default_factory=list)
created_at: datetime = field(default_factory=datetime.now)
status: WorkflowStatus = WorkflowStatus.PENDING
class ContextGatherer:
"""
Simulates gathering context from multiple systems.
In a real implementation, this would connect to:
- CRM (Salesforce, HubSpot)
- Support (Zendesk, Intercom)
- Finance (Stripe, billing systems)
- Internal tools
"""
def __init__(self):
# Simulated system data
self._crm_data = {
"CUST-001": {"tier": "enterprise", "arr": 150000, "health_score": 85},
"CUST-002": {"tier": "startup", "arr": 12000, "health_score": 92},
"CUST-003": {"tier": "enterprise", "arr": 500000, "health_score": 45},
}
self._support_data = {
"CUST-001": {"open_tickets": 2, "avg_resolution_time": "4h", "csat": 4.5},
"CUST-002": {"open_tickets": 0, "avg_resolution_time": "2h", "csat": 4.8},
"CUST-003": {"open_tickets": 8, "avg_resolution_time": "24h", "csat": 2.1},
}
self._finance_data = {
"CUST-001": {"payment_status": "current", "lifetime_value": 450000},
"CUST-002": {"payment_status": "current", "lifetime_value": 36000},
"CUST-003": {"payment_status": "30_days_overdue", "lifetime_value": 1500000},
}
def gather(self, entity_ids: list[str]) -> list[Context]:
"""Gather context from all systems for given entities."""
contexts = []
for entity_id in entity_ids:
# CRM context
if entity_id in self._crm_data:
contexts.append(Context(
source_system="crm",
data={"entity_id": entity_id, **self._crm_data[entity_id]}
))
# Support context
if entity_id in self._support_data:
contexts.append(Context(
source_system="support",
data={"entity_id": entity_id, **self._support_data[entity_id]}
))
# Finance context
if entity_id in self._finance_data:
contexts.append(Context(
source_system="finance",
data={"entity_id": entity_id, **self._finance_data[entity_id]}
))
return contexts
class WorkflowEngine:
"""
Orchestrates decision-making workflows with context graph integration.
Key behaviors:
- Gathers cross-system context at decision time
- Searches for precedent before routing decisions
- Can auto-approve based on sufficient precedent
- Records all decisions as traces for future reference
"""
def __init__(self, graph: ContextGraph):
self.graph = graph
self.search = PrecedentSearch(graph)
self.gatherer = ContextGatherer()
self._requests: dict[str, WorkflowRequest] = {}
self._auto_approve_threshold = 0.8 # Confidence threshold for auto-approval
def submit_request(self, request: WorkflowRequest) -> dict:
"""
Submit a new request for decision.
This triggers:
1. Context gathering from multiple systems
2. Precedent search
3. Potentially auto-approval if precedent is strong enough
"""
self._requests[request.id] = request
# Step 1: Gather context
contexts = self.gatherer.gather(request.entity_ids)
# Step 2: Search for precedent
suggestion = self.search.suggest_decision(
description=request.description,
entity_ids=request.entity_ids,
tags=request.tags
)
result = {
"request_id": request.id,
"contexts": contexts,
"precedent_found": suggestion is not None,
"suggestion": suggestion,
"auto_approved": False
}
# Step 3: Check for auto-approval
if suggestion and suggestion["confidence"] >= self._auto_approve_threshold:
# Strong precedent exists - auto-approve
request.status = WorkflowStatus.AUTO_APPROVED
decision = DecisionTrace(
type=DecisionType.AUTOMATION,
description=request.description,
outcome=suggestion["suggested_outcome"],
actor_id="system",
actor_name="Auto-Approval System",
entity_ids=request.entity_ids,
contexts=contexts,
tags=request.tags + ["auto-approved"],
attributes={
"confidence": suggestion["confidence"],
"precedent_count": suggestion["based_on"]
}
)
self.graph.record_decision(decision)
result["auto_approved"] = True
result["decision_id"] = decision.id
else:
# Route for human approval
request.status = WorkflowStatus.AWAITING_APPROVAL
result["requires_approval"] = True
return result
def approve(
self,
request_id: str,
approver_id: str,
approver_name: str,
outcome: str,
reason: str = "",
channel: str = "system"
) -> DecisionTrace:
"""
Approve a pending request and record the decision trace.
"""
request = self._requests.get(request_id)
if not request:
raise ValueError(f"Request {request_id} not found")
if request.status != WorkflowStatus.AWAITING_APPROVAL:
raise ValueError(f"Request {request_id} is not awaiting approval")
# Gather fresh context at approval time
contexts = self.gatherer.gather(request.entity_ids)
# Create the decision trace
decision = DecisionTrace(
type=DecisionType.APPROVAL,
description=request.description,
outcome=outcome,
actor_id=approver_id,
actor_name=approver_name,
entity_ids=request.entity_ids,
contexts=contexts,
tags=request.tags
)
# Record the approval
decision.add_approval(
approver_id=approver_id,
approver_name=approver_name,
reason=reason,
channel=channel
)
# Store the decision
self.graph.record_decision(decision)
request.status = WorkflowStatus.APPROVED
# Rebuild search index
return decision
def reject(
self,
request_id: str,
rejector_id: str,
rejector_name: str,
reason: str = ""
) -> DecisionTrace:
"""Reject a pending request."""
request = self._requests.get(request_id)
if not request:
raise ValueError(f"Request {request_id} not found")
contexts = self.gatherer.gather(request.entity_ids)
decision = DecisionTrace(
type=DecisionType.APPROVAL,
description=request.description,
outcome="rejected",
actor_id=rejector_id,
actor_name=rejector_name,
entity_ids=request.entity_ids,
contexts=contexts,
tags=request.tags + ["rejected"],
attributes={"rejection_reason": reason}
)
self.graph.record_decision(decision)
request.status = WorkflowStatus.REJECTED
return decision
def record_exception(
self,
description: str,
entity_ids: list[str],
outcome: str,
actor_id: str,
actor_name: str,
reason: str,
tags: Optional[list[str]] = None
) -> DecisionTrace:
"""
Record an exception decision.
Exceptions are deviations from standard policy that should
be captured as precedent for future reference.
"""
contexts = self.gatherer.gather(entity_ids)
decision = DecisionTrace(
type=DecisionType.EXCEPTION,
description=description,
outcome=outcome,
actor_id=actor_id,
actor_name=actor_name,
entity_ids=entity_ids,
contexts=contexts,
tags=(tags or []) + ["exception"],
attributes={"exception_reason": reason}
)
decision.add_approval(
approver_id=actor_id,
approver_name=actor_name,
reason=reason,
channel="exception_process"
)
self.graph.record_decision(decision)
return decision