-
Notifications
You must be signed in to change notification settings - Fork 6
Expand file tree
/
Copy pathworkflows.py
More file actions
656 lines (562 loc) · 30.9 KB
/
workflows.py
File metadata and controls
656 lines (562 loc) · 30.9 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
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
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
import asyncio
from datetime import datetime, timedelta
from dataclasses import dataclass
from typing import List
from temporalio import workflow
from temporalio.common import RetryPolicy
from temporalio.exceptions import ActivityError, ApplicationError
with workflow.unsafe.imports_passed_through():
from activities import analyze, detect, plan_repair, notify, execute_repairs, report, \
single_tool_repair, process_order, single_agent_repair, load_data, report_with_original_data
ITERATIONS_BEFORE_CONTINUE_AS_NEW = 10 # Number of iterations before exiting the workflow
'''RepairAgentWorkflow:
This is an agent implemented as a Temporal Workflow that orchestrates repairs.
Key logic is in the planning activity.
It will analyze the system, repair it, and report the results.
It will wait for approval before proceeding with the repair.
It will also allow for rejection of the repair.
Tools are static Activities that implement automated helper agents.
It can be used as a long-running interactive tool-agent via MCP or as a standalone workflow.'''
@workflow.defn
class RepairAgentWorkflow:
def __init__(self) -> None:
self.approved: bool = False
self.rejected: bool = False
self.planned: bool = False
self.status: str = "INITIALIZING"
self.context: dict = {}
@workflow.run
async def run(self, inputs: dict) -> str:
self.context["prompt"] = inputs.get("prompt", {})
self.context["metadata"] = inputs.get("metadata", {})
workflow.logger.debug(f"Starting repair workflow with inputs: {inputs}")
# Execute the detection agent
self.problems_found_confidence_score = await self.perform_detection(self.context)
# if confidence is low, no need to repair
if self.problems_found_confidence_score < 0.5:
analysis_notes = self.context["detection_result"].get("additional_notes", "")
workflow.logger.info(f"Low confidence score from detection: {self.problems_found_confidence_score} ({analysis_notes}). No repair needed.")
self.set_workflow_status("NO-REPAIR-NEEDED")
return f"No repair needed based on detection result: confidence score for repair: {self.problems_found_confidence_score} ({analysis_notes})"
#execute the analysis agent
await self.analyze_problems(self.context)
# Execute the planning for this agent
await self.create_plan(self.context)
# Wait for the approval or reject signal
self.set_workflow_status("PENDING-APPROVAL")
workflow.logger.info(f"Waiting for approval for repair")
await workflow.wait_condition(
lambda: self.approved is not False or self.rejected is not False,
timeout=timedelta(hours=12),
)
if self.rejected:
workflow.logger.info(f"Repair REJECTED by user {self.context.get('rejected_by', 'unknown')}")
self.set_workflow_status("REJECTED")
return f"Repair REJECTED by user {self.context.get('rejected_by', 'unknown')}"
self.set_workflow_status("APPROVED")
workflow.logger.info(f"Repair approved by user {self.context.get('approved_by', 'unknown')}")
# Proceed with the repair
await self.execute_repair()
# Create the report with the report agent
report_summary = await self.generate_report()
return f"Repair workflow completed with status: {self.status}. Report Summary: {report_summary}"
# workflow helper functions
def set_workflow_status(self, status: str) -> None:
"""Set the current status of the workflow."""
self.status = status
# set workflow current details in Markdown format. Include status, iteration count, and timestamp.
details: str = f"## Workflow Status \n\n" \
f"- **Phase:** {status}\n"
if hasattr(self, 'iteration_count'):
details += f"- **Iteration:** {self.iteration_count}\n"
details += f"- **Last Status Set:** {workflow.now().isoformat()}\n"
if status == "REPORT-COMPLETED":
details += f"- **Repairs Complete:** \n"
details += f"- **Report Summary:** {self.context.get('report_result', {}).get('repairs_summary', 'No summary available')}\n"
details += f"- See [Repairs Report](file://pathto/directory/tool_execution_report.md)\n"
elif self.planned:
details += f"- **Repair Planned:** {self.planned}\n"
details += f"- See [Planned Repairs](file://pathto/directory/planning_report.md)\n"
workflow.set_current_details(details)
workflow.logger.debug(f"Workflow status set to: {status}")
async def perform_detection(self, context: dict) -> float:
"""Detect problems in the system.
This function executes the detect activity and updates the context with the detection result.
It returns a confidence score indicating the likelihood of problems being present."""
self.set_workflow_status("DETECTING-PROBLEMS")
workflow.logger.info("Detecting problems in the system")
context["detection_result"] = await workflow.execute_activity(
detect,
context,
start_to_close_timeout=timedelta(minutes=5),
retry_policy=RetryPolicy(
initial_interval=timedelta(seconds=1),
maximum_interval=timedelta(seconds=30),
),
heartbeat_timeout=timedelta(seconds=20),
)
workflow.logger.debug(f"Detection result: {context["detection_result"]}")
detection_confidence_score = context["detection_result"].get("confidence_score", 0.0)
return detection_confidence_score
async def analyze_problems(self: any, context: dict) -> None:
"""Analyze the problems detected in the system.
This function executes the analyze activity and updates the context with the analysis result.
"""
self.set_workflow_status( "ANALYZING-PROBLEMS")
context["analysis_result"] = await workflow.execute_activity(
analyze,
context,
start_to_close_timeout=timedelta(minutes=5),
retry_policy=RetryPolicy(
initial_interval=timedelta(seconds=1),
maximum_interval=timedelta(seconds=30),
),
heartbeat_timeout=timedelta(seconds=20),
)
workflow.logger.debug(f"Analysis result: {context["analysis_result"]}")
# If the analysis result indicates a need for repair, proceed with planning
context["problems_to_repair"] = context["analysis_result"]
async def create_plan(self, context: dict) -> None:
"""Create a plan for repairing the detected problems.
This function executes the plan_repair activity and updates the context with the planning result.
Once approved, planned repairs are executed in the repair step."""
self.set_workflow_status("PLANNING-REPAIR")
self.context["planning_result"] = await workflow.execute_activity(
plan_repair,
self.context,
start_to_close_timeout=timedelta(minutes=5),
retry_policy=RetryPolicy(
initial_interval=timedelta(seconds=1),
maximum_interval=timedelta(seconds=30),
),
heartbeat_timeout=timedelta(seconds=30),
)
workflow.logger.debug(f"Planning result: {self.context["planning_result"]}")
self.planned = True
self.planning_confidence_score = self.context.get("planning_result", {}).get("overall_confidence_score", 0.0)
async def execute_repair(self):
"""Execute the repair based on the planned repairs.
These are approved in the workflow via a signal.
This function executes the repair activity and updates the context with the repair result.
"""
self.set_workflow_status("PENDING-REPAIR")
self.context["repair_result"] = await workflow.execute_activity(
execute_repairs,
self.context,
start_to_close_timeout=timedelta(minutes=5),
retry_policy=RetryPolicy(
initial_interval=timedelta(seconds=1),
maximum_interval=timedelta(seconds=30),
),
heartbeat_timeout=timedelta(seconds=20),
)
workflow.logger.debug(f"Repair result: {self.context["repair_result"]}")
async def generate_report(self):
self.set_workflow_status("PENDING-REPORT")
self.context["report_result"] = await workflow.execute_activity(
report,
self.context,
start_to_close_timeout=timedelta(minutes=5),
retry_policy=RetryPolicy(
initial_interval=timedelta(seconds=1),
maximum_interval=timedelta(seconds=30),
),
heartbeat_timeout=timedelta(seconds=20),
)
self.set_workflow_status("REPAIR-COMPLETED")
workflow.logger.debug(f"Report result: {self.context["report_result"]}")
report_summary = self.context["report_result"].get("repairs_summary", "No summary available")
return report_summary
@workflow.signal
async def ApproveRepair(self, approver: str) -> None:
self.approved = True
if approver is None or approver == "":
approver = self.context.get("metadata", {}).get("user", "unknown")
self.context["approved_by"] = approver
@workflow.signal
async def RejectRepair(self, rejecter: str) -> None:
self.rejected = True
self.context["rejected_by"] = rejecter
@workflow.query
async def IsRepairPlanned(self) -> bool:
if self.planned is None:
raise ApplicationError("Repair approval status is not set yet.")
return self.planned
@workflow.query
async def GetProblemsConfidenceScore(self) -> float:
if self.problems_found_confidence_score is None:
return 0.0
return self.problems_found_confidence_score
@workflow.query
async def GetPlannedRepairConfidenceScore(self) -> float:
if self.planning_confidence_score is None:
return 0.0
return self.planning_confidence_score
@workflow.query
async def IsRepairApproved(self) -> bool:
if self.approved is None:
raise ApplicationError("Repair approval status is not set yet.")
return self.approved
@workflow.query
async def GetRepairStatus(self) -> str:
return self.status
@workflow.query
async def GetRepairContext(self) -> dict:
return self.context
@workflow.query
async def GetRepairContextValue(self, key: str) -> str:
if key not in self.context:
raise ApplicationError(f"Context key '{key}' not found.")
return self.context[key]
@workflow.query
async def GetRepairContextKeys(self) -> List[str]:
return list(self.context.keys())
@workflow.query
async def GetRepairAnalysisResult(self) -> dict:
if "analysis_result" not in self.context:
raise ApplicationError("Analysis result is not available yet.")
return self.context["analysis_result"]
@workflow.query
async def GetRepairDetectionResult(self) -> dict:
if "detection_result" not in self.context:
raise ApplicationError("Detection result is not available yet.")
return self.context["detection_result"]
@workflow.query
async def GetRepairPlanningResult(self) -> dict:
if "planning_result" not in self.context:
raise ApplicationError("Planning result is not available yet.")
return self.context["planning_result"]
@workflow.query
async def GetRepairToolResults(self) -> dict:
if "repair_result" not in self.context:
raise ApplicationError("Repair Tool Execution results are not available yet.")
return self.context["repair_result"]
@workflow.query
async def GetRepairReport(self) -> dict:
if "report_result" not in self.context:
raise ApplicationError("Repair results are not available yet.")
return self.context["report_result"]
'''RepairAgentWorkflowProactive:
This is an agent implemented as a Temporal Workflow that orchestrates repairs.
It's much like RepairAgentWorkflow, but it is designed to run proactively.
It's intended to be always running:
- detecting problems repairing problems in the system
- optionally without waiting for user approval if confidence is high enough.
- waiting for some time (or a signal) before the next iteration.
Tools are static Activities that implement automated helper agents.'''
@workflow.defn
class RepairAgentWorkflowProactive(RepairAgentWorkflow):
def __init__(self) -> None:
RepairAgentWorkflow.__init__(self)
self.exit_requested: bool = False
self.continue_as_new_requested: bool = False
self.iteration_count: int = 0
self.stop_waiting: bool = False
@workflow.run
async def run(self, inputs: dict) -> str:
self.context["prompt"] = inputs.get("prompt", {})
self.context["metadata"] = inputs.get("metadata", {})
self.context["notification_info"] = inputs.get("callback", None)
workflow.logger.debug(f"Starting repair workflow with inputs: {inputs}")
while not self.exit_requested and not self.continue_as_new_requested and self.iteration_count < ITERATIONS_BEFORE_CONTINUE_AS_NEW:
self.iteration_count += 1
self.approved = False
self.stop_waiting = False
self.set_workflow_status("WAITING-FOR-NEXT-CYCLE")
await workflow.wait_condition(
lambda: self.exit_requested is True or
self.continue_as_new_requested is True or
self.stop_waiting is True,
timeout=timedelta(days=1), # Wait a day for the next detect->analysis->repair cycle.
# Could make this a dynamic timer if you wanted to always run at a certain time
timeout_summary="Check Again Tomorrow",
)
if self.continue_as_new_requested or self.exit_requested:
workflow.logger.info("Continuing as new or exit requested. Skipping analysis for this iteration.")
else:
# Execute the detection agent
self.problems_found_confidence_score = await self.perform_detection(self.context)
self.problems_found_confidence_score = self.context["detection_result"].get("confidence_score", 0.0)
if self.problems_found_confidence_score < 0.5:
analysis_notes = self.context["detection_result"].get("additional_notes", "")
workflow.logger.info(f"Low confidence score from detection: {self.problems_found_confidence_score} ({analysis_notes}). No repair needed at this time.")
self.set_workflow_status("NO-REPAIR-NEEDED")
continue # Skip to the next iteration if no repair is needed
#execute the analysis agent
await self.analyze_problems(self.context)
# Execute the planning for this agent
await self.create_plan(self.context)
# for low planning confidence scores, we will notify the user and wait for approval
if self.planning_confidence_score <= 0.95:
# Notify the user about the planned repairs
await self.execute_notification()
# Wait for the approval or reject signal
self.set_workflow_status("PENDING-APPROVAL")
workflow.logger.info(f"Waiting for approval for repair")
await workflow.wait_condition(
lambda: self.approved is not False or self.rejected is not False,
timeout=timedelta(hours=20), # Wait for up to 24 hours for approval
timeout_summary="Tool Approval",
)
if self.rejected:
workflow.logger.info(f"Repair REJECTED by user {self.context.get('rejected_by', 'unknown')}. No repair needed at this time - will check again later.")
self.set_workflow_status("REJECTED")
continue # Skip to the next iteration if repair is rejected
self.set_workflow_status("APPROVED")
workflow.logger.info(f"Repair approved by user {self.context.get('approved_by', 'unknown')}")
else:
# If the planning confidence score is high enough, we can proceed without waiting for approval
self.approved = True
self.context["approved_by"] = f"Agentically Approved with confidence score {self.context['planning_result'].get('overall_confidence_score', 0.0)}"
self.set_workflow_status("APPROVED")
workflow.logger.info("Planning confidence score is high enough. Proceeding with repair without waiting for approval.")
# Proceed with the repair
await self.execute_repair()
# Create the report with the report agent
report_summary = await self.generate_report()
workflow.logger.info(f"Repair completed with status: {self.status}. Report Summary: {report_summary}")
if self.exit_requested:
workflow.logger.info("Exit requested. Ending workflow.")
return "Repair workflow exited as requested."
if self.continue_as_new_requested or self.iteration_count >= ITERATIONS_BEFORE_CONTINUE_AS_NEW:
workflow.logger.info("Continuing as new-")
# Continue as new workflow
workflow.continue_as_new(
inputs,
)
await workflow.wait_condition(lambda: workflow.all_handlers_finished())
return "Repair workflow continued as new with status: WAITING-FOR-NEXT-CYCLE."
@workflow.signal
async def RequestExit(self) -> None:
self.exit_requested = True
@workflow.signal
async def StopWaiting(self) -> None:
self.stop_waiting = True
@workflow.query
async def GetIterationCount(self) -> int:
return self.iteration_count
@workflow.signal
async def RequestContinueAsNew(self) -> None:
self.continue_as_new_requested = True
async def execute_notification(self):
"""Inform the user about the planned repairs.
Notification information is passed in the context."""
await workflow.execute_activity(
notify,
self.context,
start_to_close_timeout=timedelta(minutes=5),
retry_policy=RetryPolicy(
initial_interval=timedelta(seconds=1),
maximum_interval=timedelta(seconds=30),
),
heartbeat_timeout=timedelta(seconds=30),
)
'''RepairAgentWorkflowMonolith:
This is an agent implemented as a Temporal Workflow that orchestrates repairs.
It's supposed to do the same thing as RepairAgentWorkflow, but it is built as a single agent
with no helpers, to demonstrate that monolith agents are harder to work with. '''
@workflow.defn
class RepairAgentWorkflowMonolith(RepairAgentWorkflow):
def __init__(self) -> None:
RepairAgentWorkflow.__init__(self)
self.exit_requested: bool = False
self.continue_as_new_requested: bool = False
self.iteration_count: int = 0
self.stop_waiting: bool = False
@workflow.run
async def run(self, inputs: dict) -> str:
self.set_workflow_status("INITIALIZING")
self.context["prompt"] = inputs.get("prompt", {})
self.context["metadata"] = inputs.get("metadata", {})
self.context["notification_info"] = inputs.get("callback", None)
workflow.logger.debug(f"Starting repair monolith workflow with inputs: {inputs}")
self.set_workflow_status("EXECUTING-REPAIR")
# Execute the detection agent
agent_results = await workflow.execute_activity(
single_agent_repair,
self.context,
start_to_close_timeout=timedelta(minutes=5),
retry_policy=RetryPolicy(
initial_interval=timedelta(seconds=1),
maximum_interval=timedelta(seconds=10),
),
heartbeat_timeout=timedelta(seconds=30),
)
self.planned = True
self.approved = agent_results.get("approved_for_repair", True)
if not self.approved:
self.set_workflow_status("REJECTED")
workflow.logger.warning(f"Repair self-rejected due to low confidence score.")
self.set_workflow_status("REPAIR-COMPLETED")
self.context["report_result"] = agent_results.get("repair_result", {}) # we don't have a report agent here, so just return the repair result as the report
workflow.logger.debug(f"Monolith repair result: {self.context["report_result"]}")
return "Repair workflow completed."
'''RepairAgentWorkflowSharingContext:
This is an agent implemented as a Temporal Workflow that orchestrates repairs.
It's supposed to do the same thing as RepairAgentWorkflow, but instead it shares context between all agents,
to demonstrate the downsides of context bloat and poisoning. '''
@workflow.defn
class RepairAgentWorkflowSharingContext(RepairAgentWorkflow):
def __init__(self) -> None:
RepairAgentWorkflow.__init__(self)
self.exit_requested: bool = False
self.continue_as_new_requested: bool = False
self.iteration_count: int = 0
self.stop_waiting: bool = False
@workflow.run
async def run(self, inputs: dict) -> str:
self.context["prompt"] = inputs.get("prompt", {})
self.context["metadata"] = inputs.get("metadata", {})
workflow.logger.debug(f"Starting repair workflow with inputs: {inputs}")
#load orders and inventory data into context here for all agents to use <-- probably a bad plan since these will change after tools run
await self.load_initial_data(self.context)
# Execute the detection agent
self.problems_found_confidence_score = await self.perform_detection(self.context)
# if confidence is low, no need to repair
if self.problems_found_confidence_score < 0.5:
analysis_notes = self.context["detection_result"].get("additional_notes", "")
workflow.logger.info(f"Low confidence score from detection: {self.problems_found_confidence_score} ({analysis_notes}). No repair needed.")
self.set_workflow_status("NO-REPAIR-NEEDED")
return f"No repair needed based on detection result: confidence score for repair: {self.problems_found_confidence_score} ({analysis_notes})"
#execute the analysis agent
await self.analyze_problems(self.context)
# Execute the planning for this agent
await self.create_plan(self.context)
# Skip approval for this demo
# self.set_workflow_status("PENDING-APPROVAL")
# workflow.logger.info(f"Waiting for approval for repair")
# await workflow.wait_condition(
# lambda: self.approved is not False or self.rejected is not False,
# timeout=timedelta(hours=12),
# )
if self.rejected:
workflow.logger.info(f"Repair REJECTED by user {self.context.get('rejected_by', 'unknown')}")
self.set_workflow_status("REJECTED")
return f"Repair REJECTED by user {self.context.get('rejected_by', 'unknown')}"
self.set_workflow_status("APPROVED")
workflow.logger.info(f"Repair approved by user {self.context.get('approved_by', 'unknown')}")
# Proceed with the repair
await self.execute_repair()
# Create the report with the report agent
# This version has the report agent use the shared context instead of its own limited/refreshed context <--- this is also a bad idea, can cause context poisoning
report_summary = await self.generate_report_with_original_data()
return f"Repair workflow completed with status: {self.status}. Report Summary: {report_summary}"
async def load_initial_data(self: any, context: dict) -> None:
"""Load orders and inventory data into the shared context for all agents to use. <-- may be a bad idea and cause context poisoning
This is for demonstration purposes only."""
self.set_workflow_status( "LOADING-DATA")
data_load_result = await workflow.execute_activity(
load_data,
context,
start_to_close_timeout=timedelta(minutes=5),
retry_policy=RetryPolicy(
initial_interval=timedelta(seconds=1),
maximum_interval=timedelta(seconds=30),
),
heartbeat_timeout=timedelta(seconds=20),
)
workflow.logger.debug(f"Data loaded: {data_load_result}")
context["initial_orders_data"] = data_load_result.get("orders_to_detect", {})
context["initial_inventory_data"] = data_load_result.get("inventory_data", {})
async def generate_report_with_original_data(self):
self.set_workflow_status("PENDING-REPORT")
self.context["report_result"] = await workflow.execute_activity(
report_with_original_data,
self.context,
start_to_close_timeout=timedelta(minutes=5),
retry_policy=RetryPolicy(
initial_interval=timedelta(seconds=1),
maximum_interval=timedelta(seconds=30),
),
heartbeat_timeout=timedelta(seconds=20),
)
self.set_workflow_status("REPAIR-COMPLETED")
workflow.logger.debug(f"Report result: {self.context["report_result"]}")
report_summary = self.context["report_result"].get("repairs_summary", "No summary available")
return report_summary
'''OrderWorkflow:
This is a Temporal Workflow that orchestrates the order management process.
It's just a simple demo workflow to demonstrate order repairs
'''
@workflow.defn
class OrderWorkflow:
def __init__(self) -> None:
self.status: str = "INITIALIZING"
self.context: dict = {}
@workflow.run
async def run(self, inputs: dict) -> str:
self.context["metadata"] = inputs.get("metadata", {})
self.context["order_details"] = inputs.get("order_details", {})
self.order_id = inputs.get("order_id", "unknown")
workflow.logger.debug(f"Order ID: {self.order_id}")
workflow.logger.debug(f"Order details: {self.context['order_details']}")
self.set_workflow_status("INITIALIZING")
workflow.logger.debug(f"Starting order workflow with inputs: {inputs}")
order_result = "pending"
# Execute the order management steps
while self.status not in ["ORDER-COMPLETED", "ORDER-FAILED"]:
self.set_workflow_status("PROCESSING-ORDER")
# try to process the order
try:
process_order_status = await workflow.execute_activity(
process_order,
self.context,
start_to_close_timeout=timedelta(minutes=5),
retry_policy=RetryPolicy(
initial_interval=timedelta(seconds=1),
maximum_interval=timedelta(seconds=30),
),
heartbeat_timeout=timedelta(seconds=20),
)
workflow.logger.debug(f"Process order result: {process_order_status}")
order_result = process_order_status
except ActivityError as e:
# Handle activity errors
workflow.logger.error(f"Activity error while processing order: {e}")
self.set_workflow_status("ORDER-FAILED")
return f"Order processing failed with error: {e}"
if process_order_status not in ["pending", "in-progress", "completed", "approved-preparing-shipment"]:
workflow.logger.warning(f"Order processing returned stuck: {process_order_status}. Initiating troubleshooting.")
# If the order processing fails or returns an unexpected status, initiate troubleshooting
self.set_workflow_status("ORDER-TROUBLESHOOTING")
try:
repair_result = await workflow.execute_activity(
single_tool_repair,
self.context,
start_to_close_timeout=timedelta(minutes=5),
retry_policy=RetryPolicy(
initial_interval=timedelta(seconds=1),
maximum_interval=timedelta(seconds=30),
),
heartbeat_timeout=timedelta(seconds=20),
)
workflow.logger.debug(f"Repair result: {repair_result}")
except ActivityError as e:
# if repair fails, mark the order as failed
self.set_workflow_status("ORDER-FAILED")
return f"Order processing failed with error: {str(e)}"
elif process_order_status in ["pending", "in-progress", "approved-preparing-shipment"]:
#wait a bit for the order to be processed
workflow.logger.info(f"Order is still in progress: {process_order_status}. Waiting for processing.")
await workflow.wait_condition(
lambda: self.status in ["ORDER-COMPLETED", "ORDER-FAILED"],
timeout=timedelta(days=1),
)
elif process_order_status == "completed":
# If the order is completed, we can finalize the workflow
workflow.logger.info(f"Order processing completed successfully: {process_order_status}.")
self.set_workflow_status("ORDER-COMPLETED")
order_result = "Order completed successfully"
break
# Finalize the workflow
return f"Order workflow completed with status: {self.status}. Order Result: {order_result}"
# workflow helper functions
def set_workflow_status(self, status: str) -> None:
"""Set the current status of the workflow."""
self.status = status
# set workflow current details in Markdown format. Include status, iteration count, and timestamp.
details: str = f"## Workflow Status \n\n" \
f"- **Phase:** {status}\n"
details += f"- **Last Status Set:** {workflow.now().isoformat()}\n"
workflow.set_current_details(details)
workflow.logger.debug(f"Workflow status set to: {status}")