-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathbuilder.py
More file actions
1727 lines (1489 loc) · 78.4 KB
/
Copy pathbuilder.py
File metadata and controls
1727 lines (1489 loc) · 78.4 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
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
"""
Main ProcessBuilder class for building and managing processes.
"""
import os
import sys
import time
import logging
from pathlib import Path
from typing import List, Optional, Tuple, Callable
import openai
from datetime import datetime
import io
from typing import List, Optional, Tuple, Dict, Any, Callable
# Setup logger
log = logging.getLogger(__name__)
log.setLevel(logging.INFO) # Default log level
# Add a stream handler if none exists
if not log.handlers:
handler = logging.StreamHandler()
formatter = logging.Formatter('%(levelname)s - %(message)s')
handler.setFormatter(formatter)
log.addHandler(handler)
# Import local modules
from .config import Config
from .models import ProcessStep, ProcessNote
from .utils import (
sanitize_id,
validate_process_flow,
validate_notes,
write_csv
)
def default_input_handler(prompt: str) -> str:
"""Default input handler that uses the built-in input function.
This serves as a fallback when get_step_input from cli isn't available."""
while True:
response = input(f"\n{prompt}\n> ").strip()
if response:
return response
# Function to sanitize strings to prevent issues with quotes
def sanitize_string(text):
"""Sanitize a string to prevent issues with quotes."""
if not text:
return text
return text.replace("'", "\\'")
# Set log level based on verbose mode
def set_log_level(verbose=False):
"""Set the log level based on verbose mode."""
logger = logging.getLogger(__name__)
# Set the appropriate log level based on verbose mode
# Make sure WARNING level is always visible regardless of verbose mode
logger_level = logging.DEBUG if verbose else logging.INFO
logger.setLevel(logger_level)
# Ensure we have at least one handler
if not logger.handlers:
handler = logging.StreamHandler()
formatter = logging.Formatter('%(levelname)s - %(message)s')
handler.setFormatter(formatter)
logger.addHandler(handler)
# Update log level for all handlers
# Always set handlers to DEBUG level to ensure warnings are captured
# regardless of the logger's level
for handler in logger.handlers:
handler.setLevel(logging.DEBUG)
# Log a message to confirm level change
logger.debug(f"Debug logging {'enabled' if verbose else 'disabled'}")
# Log a message to verify warnings are working
logger.debug("Log levels properly configured")
def show_loading_animation(message: str, duration: float = 0.5) -> None:
"""Show a simple loading animation while waiting for AI response.
Args:
message: The message to display while loading
duration: How long to show each frame in seconds
"""
frames = ["⠋", "⠙", "⠹", "⠸", "⠼", "⠴", "⠦", "⠧", "⠇", "⠏"]
start_time = time.time()
try:
i = 0
while True:
frame = frames[i % len(frames)]
sys.stdout.write(f"\r{message} {frame}")
sys.stdout.flush()
time.sleep(duration)
i += 1
# Optional timeout to prevent infinite animation
elapsed = time.time() - start_time
if elapsed > 30: # Safety timeout after 30 seconds
break
except KeyboardInterrupt:
pass
finally:
sys.stdout.write("\r\033[K") # Clear the line
sys.stdout.flush()
class ProcessBuilder:
"""Main class for building and managing process flows."""
# Class-level input handler (allows custom input methods to be injected)
_input_handler = default_input_handler
# Initialize class variable for verbose mode
_verbose: bool = False
def __init__(self, process_name, config=None, verbose=None):
"""Initialize a new ProcessBuilder.
Args:
process_name: The name of the process to build
config: Optional Config object, will create default if None
verbose: Optional boolean to override class-level verbose setting
"""
self.process_name = process_name
self.config = config or Config()
self.steps = []
self.notes = []
self.current_note_id = 1
self.output_dir = None
self.timestamp = datetime.now().strftime("%Y%m%d_%H%M%S")
self.step_count = 0 # Initialize step counter
# Set instance-level verbose mode if specified
self.verbose = verbose if verbose is not None else self.__class__._verbose
# If verbose mode is specified at instance level and different from class level, update the class setting
if verbose is not None and verbose != self.__class__._verbose:
self.__class__.set_verbose_mode(verbose)
log.debug(f"Updated class verbose mode to {verbose}")
# Log the initialization with verbose mode setting
log.debug(f"ProcessBuilder initialized with verbose={self.verbose}")
# Initialize OpenAI client if API key is available
try:
if os.environ.get("OPENAI_API_KEY"):
self.openai_client = openai.OpenAI()
log.debug("OpenAI client initialized successfully")
else:
self.openai_client = None
# Always use warning level for missing API key, regardless of verbose mode
log.warning("No OpenAI API key found. AI features will be disabled.")
log.debug("Warning about missing API key has been logged")
except Exception as e:
self.openai_client = None
# Always use warning level for errors, regardless of verbose mode
log.warning(f"Failed to initialize OpenAI client: {str(e)}")
@property
def suggested_first_step(self) -> str:
"""Generate a suggested name for the first step when there are 0 steps in the process.
Returns:
A verb-based, actionable step name or empty string if OpenAI is not available
"""
if not self.openai_client or len(self.steps) > 0:
return ""
try:
# Sanitize process name to prevent syntax errors from unescaped single quotes
safe_process_name = sanitize_string(self.process_name)
prompt = (
f"I'm creating a business process called '{safe_process_name}'.\n\n"
f"Please suggest a name for the first step in this process. The step name should:\n"
f"1. Start with a strong action verb (e.g., Collect, Review, Analyze)\n"
f"2. Be clear and descriptive (2-5 words)\n"
f"3. Be specific to the '{safe_process_name}' process\n"
f"4. Follow business process naming conventions\n"
f"5. Be actionable and task-oriented\n\n"
f"Provide only the step name, nothing else."
)
if self.verbose:
log.debug(f"Sending OpenAI prompt for first step suggestion: \n{prompt}")
response = self.openai_client.chat.completions.create(
model="gpt-4-turbo-preview",
messages=[
{"role": "system", "content": "You are a process design expert. Create clear, descriptive step names that follow best practices."},
{"role": "user", "content": prompt}
],
temperature=0.7,
max_tokens=50
)
suggestion = response.choices[0].message.content.strip()
if self.verbose:
log.debug(f"Received OpenAI first step suggestion: '{suggestion}'")
words = suggestion.split()
if len(words) > 5:
suggestion = ' '.join(words[:5])
log.debug(f"Truncated suggestion to: '{suggestion}'")
return suggestion
except Exception as e:
log.warning(f"Error generating first step suggestion: {str(e)}")
@classmethod
def set_input_handler(cls, handler: Callable[[str], str]) -> None:
"""Set the input handler for receiving user input.
Args:
handler: A callable that takes a prompt string and returns user input
Must accept a string parameter and return a string
Returns:
None
Raises:
TypeError: If the handler is not callable
"""
# Validate that the handler is callable
if not callable(handler):
raise TypeError("Input handler must be callable")
# Update class variable
cls._input_handler = handler
log.debug("Input handler updated")
@classmethod
def set_verbose_mode(cls, verbose: bool) -> None:
"""Set the verbose mode for detailed OpenAI response logging.
Args:
verbose: If True, OpenAI response details will be logged at DEBUG level
Returns:
None
"""
# Store original verbose setting for comparison
old_verbose = cls._verbose
# Update class variable
cls._verbose = verbose
# Log the change (use debug if it's a repeat call with same value)
if old_verbose == verbose:
log.debug(f"Verbose mode remained {'enabled' if verbose else 'disabled'}")
else:
log.info(f"Verbose mode {'enabled' if verbose else 'disabled'}")
# Always update log level to ensure consistency
set_log_level(verbose)
def get_input(self, prompt: str) -> str:
"""Get input from the user with the configured input handler."""
return self.__class__._input_handler(prompt)
def generate_error_codes(self, step_id: str, description: str, decision: str, success_outcome: str, failure_outcome: str) -> str:
"""Generate suggested error codes for a step using OpenAI."""
if not self.openai_client:
return ""
try:
# Sanitize inputs
safe_process_name = sanitize_string(self.process_name)
safe_step_id = sanitize_string(step_id)
safe_description = sanitize_string(description)
safe_decision = sanitize_string(decision)
safe_success = sanitize_string(success_outcome)
safe_failure = sanitize_string(failure_outcome)
# Build prompt context using string concatenation
context = (
f"Process: {safe_process_name}\n"
f"Step ID: {safe_step_id}\n"
f"Description: {safe_description}\n"
f"Decision: {safe_decision}\n"
f"Success Outcome: {safe_success}\n"
f"Failure Outcome: {safe_failure}\n\n"
"Please suggest error codes for this step that:\n"
"1. Are specific to potential failure scenarios\n"
"2. Follow a consistent naming convention\n"
"3. Include both technical and business error codes\n"
"4. Are descriptive and meaningful\n"
"5. Can be used for logging and monitoring\n\n"
"Format the response as a bulleted list of error codes with brief descriptions."
)
response = self.openai_client.chat.completions.create(
model="gpt-4-turbo-preview",
messages=[
{"role": "system", "content": "You are a process error handling expert. Provide clear, specific error codes for process steps."},
{"role": "user", "content": context}
],
temperature=0.7,
max_tokens=200
)
return response.choices[0].message.content.strip()
except Exception as e:
print(f"Error generating error codes suggestion: {str(e)}")
return ""
def validate_next_step_id(self, next_step_id: str) -> bool:
"""Validate that a next step ID is either 'End' or an existing step.
Args:
next_step_id: The next step ID to validate
Returns:
True if the next step is valid (either 'End' or an existing step ID),
False otherwise
"""
# "End" is always a valid next step
if next_step_id.lower() == 'end':
return True
# Check if the step ID exists in the current steps
if any(step.step_id == next_step_id for step in self.steps):
return True
# Return False for any other value
return False
def find_missing_steps(self) -> List[Tuple[str, str, str]]:
"""Find steps that are referenced but not yet defined.
Returns:
A list of tuples (missing_step_id, referencing_step_id, path_type),
where path_type is either 'success' or 'failure'.
"""
missing_steps = []
existing_step_ids = {step.step_id for step in self.steps}
for step in self.steps:
if (step.next_step_success.lower() != 'end' and
step.next_step_success not in existing_step_ids):
missing_steps.append((step.next_step_success, step.step_id, 'success'))
if (step.next_step_failure.lower() != 'end' and
step.next_step_failure not in existing_step_ids):
missing_steps.append((step.next_step_failure, step.step_id, 'failure'))
return missing_steps
def parse_ai_suggestions(self, suggestions: str) -> dict:
"""Parse AI suggestions into a structured format.
Args:
suggestions: The raw AI suggestions text
Returns:
Dictionary containing suggested updates for each field
"""
# Initialize with empty suggestions
suggested_updates = {
'description': None,
'decision': None,
'success_outcome': None,
'failure_outcome': None,
'validation_rules': None,
'error_codes': None
}
try:
# Create a prompt to parse the suggestions
# Rewrite the prompt with proper string formatting
parse_prompt = (
f"Parse the following process step suggestions into specific field updates:\n\n"
f"{suggestions}\n\n"
f"Please provide the updates in this exact format:\n"
f"Description: [new description or None]\n"
f"Decision: [new decision or None]\n"
f"Success Outcome: [new success outcome or None]\n"
f"Failure Outcome: [new failure outcome or None]\n"
f"Validation Rules: [new validation rules or None]\n"
f"Error Codes: [new error codes or None]\n\n"
f"If a field should not be updated, use None."
)
response = self.openai_client.chat.completions.create(
model="gpt-4-turbo-preview",
messages=[
{"role": "system", "content": "You are a process design expert. Parse suggestions into specific field updates."},
{"role": "user", "content": parse_prompt}
],
temperature=0.3, # Lower temperature for more consistent parsing
max_tokens=500
)
# Parse the response
parsed = response.choices[0].message.content.strip()
for line in parsed.split('\n'):
if ':' in line:
field, value = line.split(':', 1)
field = field.strip().lower()
value = value.strip()
if value.lower() != 'none':
suggested_updates[field] = value
return suggested_updates
except Exception as e:
print(f"Error parsing AI suggestions: {str(e)}")
return suggested_updates
def generate_step_description(self, step_id: str, predecessor_id: Optional[str] = None, path_type: Optional[str] = None) -> str:
"""Generate an intelligent step description based on context.
Args:
step_id: The current step ID
predecessor_id: Optional ID of the step that references this step
path_type: Optional path type ('success' or 'failure') that led here
"""
if not self.openai_client:
return ""
try:
# Build context for the prompt
context = f"Process Name: {self.process_name}\n"
context += f"Current Step: {step_id}\n"
if predecessor_id:
predecessor = next((s for s in self.steps if s.step_id == predecessor_id), None)
if predecessor:
context += f"Predecessor Step: {predecessor.step_id}\n"
context += f"Predecessor Description: {predecessor.description}\n"
context += f"Predecessor Decision: {predecessor.decision}\n"
if path_type:
context += f"Path Type: {path_type}\n"
# Rewrite the prompt with proper string formatting
prompt = (
f"Given the following process context:\n\n"
f"{context}\n\n"
f"Suggest a clear and concise description of what happens in this step. The description should:\n"
f"1. Be specific and actionable\n"
f"2. Include key activities and inputs\n"
f"3. Explain the purpose of the step\n"
f"4. Be between 50-100 words\n"
f"5. Follow business process documentation best practices\n\n"
f"Please provide just the description, no additional text."
)
response = self.openai_client.chat.completions.create(
model="gpt-4-turbo-preview",
messages=[
{"role": "system", "content": "You are a business process expert. Create clear, concise step descriptions that follow best practices."},
{"role": "user", "content": prompt}
],
temperature=0.7,
max_tokens=200
)
description = response.choices[0].message.content.strip()
# Validate word count
words = description.split()
if len(words) > 100:
# If too long, truncate to 100 words
description = ' '.join(words[:100])
elif len(words) < 50:
# If too short, try to generate a more detailed description
prompt += "\nThe description was too short. Please provide a more detailed description between 50-100 words."
response = self.openai_client.chat.completions.create(
model="gpt-4-turbo-preview",
messages=[
{"role": "system", "content": "You are a business process expert. Create clear, concise step descriptions that follow best practices."},
{"role": "user", "content": prompt}
],
temperature=0.7,
max_tokens=200
)
description = response.choices[0].message.content.strip()
return description
except Exception as e:
print(f"Error generating step description: {str(e)}")
return ""
def generate_step_decision(self, step_id: str, description: str, predecessor_id: Optional[str] = None, path_type: Optional[str] = None) -> str:
"""Generate a suggested decision for a step using OpenAI."""
if not self.openai_client:
return ""
try:
# Build context string
context = f"Process: {self.process_name}\n"
context += f"Current Step: {step_id}\n"
context += f"Step Description: {description}\n"
if predecessor_id:
predecessor = next((s for s in self.steps if s.step_id == predecessor_id), None)
if predecessor:
context += f"Previous Step: {predecessor.step_id}\n"
context += f"Previous Step Description: {predecessor.description}\n"
if path_type:
context += f"Path Type: {path_type}\n"
# Sanitize context to prevent syntax errors from unescaped single quotes
safe_context = sanitize_string(context)
# Rewrite the prompt with proper string formatting
prompt = (
f"Based on the following process context:\n\n"
f"{safe_context}\n\n"
f"Please suggest a clear, specific decision point for this step. The decision should:\n"
f"1. Be a yes/no question\n"
f"2. Be directly related to the step's purpose\n"
f"3. Be specific and actionable\n"
f"4. Help determine the next step in the process\n\n"
f"Return only the decision question, without any additional explanation or formatting."
)
response = self.openai_client.chat.completions.create(
model="gpt-4-turbo-preview",
messages=[
{"role": "system", "content": "You are a process design expert. Provide clear, actionable decision points for process steps."},
{"role": "user", "content": prompt}
],
temperature=0.7,
max_tokens=100
)
return response.choices[0].message.content.strip()
except Exception as e:
print(f"Error generating decision suggestion: {str(e)}")
return ""
def generate_step_success_outcome(self, step_id: str, description: str, decision: str, predecessor_id: Optional[str] = None, path_type: Optional[str] = None) -> str:
"""Generate a suggested success outcome for a step using OpenAI."""
if not self.openai_client:
return ""
try:
# Build context string
context = f"Process: {self.process_name}\n"
context += f"Current Step: {step_id} - {description}\n"
context += f"Decision: {decision}\n"
if predecessor_id:
predecessor = next((s for s in self.steps if s.step_id == predecessor_id), None)
if predecessor:
context += f"Previous Step: {predecessor.step_id} - {predecessor.description}\n"
if path_type:
context += f"Path Type: {path_type}\n"
# Sanitize context to prevent syntax errors from unescaped single quotes
safe_context = sanitize_string(context)
# Rewrite the prompt with proper string formatting
prompt = (
f"Based on the following process context:\n\n"
f"{safe_context}\n\n"
f"Please suggest a clear, specific success outcome for this step. The success outcome should:\n"
f"1. Be a clear yes/no question\n"
f"2. Directly relate to the step's purpose\n"
f"3. Be specific and actionable\n"
f"4. Help determine the next step\n\n"
f"Format the response as a single question that can be answered with yes/no."
)
response = self.openai_client.chat.completions.create(
model="gpt-4-turbo-preview",
messages=[
{"role": "system", "content": "You are a process design expert. Provide clear, specific success outcomes for process steps."},
{"role": "user", "content": prompt}
],
temperature=0.7,
max_tokens=100
)
return response.choices[0].message.content.strip()
except Exception as e:
print(f"Error generating success outcome suggestion: {str(e)}")
return ""
def generate_step_failure_outcome(self, step_id: str, description: str, decision: str, predecessor_id: Optional[str] = None, path_type: Optional[str] = None) -> str:
"""Generate a suggested failure outcome for a step using OpenAI."""
if not self.openai_client:
return ""
try:
# Build context string
context = f"Process: {self.process_name}\n"
context += f"Current Step: {step_id} - {description}\n"
context += f"Decision: {decision}\n"
if predecessor_id:
predecessor = next((s for s in self.steps if s.step_id == predecessor_id), None)
if predecessor:
context += f"Previous Step: {predecessor.step_id} - {predecessor.description}\n"
if path_type:
context += f"Path Type: {path_type}\n"
# Sanitize context to prevent syntax errors from unescaped single quotes
safe_context = sanitize_string(context)
# Rewrite the prompt with proper string formatting
prompt = (
f"Based on the following process context:\n\n"
f"{safe_context}\n\n"
f"Please suggest a clear, specific failure outcome for this step. The failure outcome should:\n"
f"1. Clearly describe what happens when the step fails\n"
f"2. Be specific about error handling or recovery steps\n"
f"3. Help determine the next step in the failure path\n"
f"4. Be actionable and informative\n\n"
f"Format the response as a clear, concise statement describing the failure outcome."
)
response = self.openai_client.chat.completions.create(
model="gpt-4-turbo-preview",
messages=[
{"role": "system", "content": "You are a process design expert. Provide clear, specific failure outcomes for process steps."},
{"role": "user", "content": prompt}
],
temperature=0.7,
max_tokens=100
)
return response.choices[0].message.content.strip()
except Exception as e:
print(f"Error generating failure outcome suggestion: {str(e)}")
return ""
def create_missing_step_noninteractive(self, step_id: str, predecessor_id: Optional[str] = None, path_type: Optional[str] = None) -> ProcessStep:
"""Create a missing step with default values without requiring user input.
Args:
step_id: ID of the step to create
predecessor_id: Optional ID of the step that references this one
path_type: Optional path type ('success' or 'failure')
Returns:
A new ProcessStep with default values
"""
print(f"\nFound missing step: {step_id}")
if predecessor_id:
print(f"Referenced by step: {predecessor_id} on {path_type} path")
# Create default values
description = f"Automatically generated step for: {step_id}"
decision = f"Does the {step_id} step complete successfully?"
success_outcome = "The step completed successfully."
failure_outcome = "The step failed to complete."
# Create and return the step with default values
step = ProcessStep(
step_id=step_id,
description=description,
decision=decision,
success_outcome=success_outcome,
failure_outcome=failure_outcome,
note_id=None,
next_step_success="End", # Default to End, will be updated later
next_step_failure="End", # Default to End, will be updated later
validation_rules=None,
error_codes=None
)
return step
def create_missing_step(self, step_id: str, predecessor_id: Optional[str] = None, path_type: Optional[str] = None) -> ProcessStep:
"""Create a missing step that was referenced by another step."""
print(f"\nCreating missing step: {step_id}")
# Initial AI confirmation
use_ai = False
if self.openai_client:
use_ai = self.get_input("\nWould you like to use AI suggestions for this step? (y/n)").lower() == 'y'
if use_ai:
print("\nI'll ask for your input first, then offer AI suggestions if you'd like.")
# Get step description
print("\nThe step name is used as a label in the process diagram.")
description = self.get_input("What happens in this step?")
if use_ai and self.openai_client:
want_ai_help = self.get_input("\nWould you like to see an AI suggestion for the description? (y/n)").lower() == 'y'
if want_ai_help:
try:
show_loading_animation("Generating step description")
suggested_description = self.generate_step_description(step_id, predecessor_id, path_type)
if suggested_description:
safe_description = sanitize_string(suggested_description)
print(f"\nAI suggests the following description: '{safe_description}'")
use_suggested = self.get_input("Use this suggestion? (y/n)").lower()
if use_suggested == 'y':
description = suggested_description
except Exception as e:
print(f"Error generating description suggestion: {str(e)}")
# Get decision
print("\nThe decision is a yes/no question that determines which path to take next.")
decision = self.get_input("What decision needs to be made?")
if use_ai and self.openai_client:
want_ai_help = self.get_input("\nWould you like to see an AI suggestion for the decision? (y/n)").lower() == 'y'
if want_ai_help:
try:
show_loading_animation("Generating decision suggestion")
suggested_decision = self.generate_step_decision(step_id, description, predecessor_id, path_type)
if suggested_decision:
safe_decision = sanitize_string(suggested_decision)
print(f"\nAI suggests the following decision: '{safe_decision}'")
use_suggested = self.get_input("Use this suggestion? (y/n)").lower()
if use_suggested == 'y':
decision = suggested_decision
except Exception as e:
print(f"Error generating decision suggestion: {str(e)}")
# Get success outcome
print("\nThe success outcome tells you which step to go to next when the decision is 'yes'.")
success_outcome = self.get_input("What happens if this step succeeds?")
if use_ai and self.openai_client:
want_ai_help = self.get_input("\nWould you like to see an AI suggestion for the success outcome? (y/n)").lower() == 'y'
if want_ai_help:
try:
show_loading_animation("Generating success outcome suggestion")
suggested_success = self.generate_step_success_outcome(step_id, description, decision, predecessor_id, path_type)
if suggested_success:
safe_success = sanitize_string(suggested_success)
print(f"\nAI suggests the following success outcome: '{safe_success}'")
use_suggested = self.get_input("Use this suggestion? (y/n)").lower()
if use_suggested == 'y':
success_outcome = suggested_success
except Exception as e:
print(f"Error generating success outcome suggestion: {str(e)}")
# Get failure outcome
print("\nThe failure outcome tells you which step to go to next when the decision is 'no'.")
failure_outcome = self.get_input("What happens if this step fails?")
if use_ai and self.openai_client:
want_ai_help = self.get_input("\nWould you like to see an AI suggestion for the failure outcome? (y/n)").lower() == 'y'
if want_ai_help:
try:
show_loading_animation("Generating failure outcome suggestion")
suggested_failure = self.generate_step_failure_outcome(step_id, description, decision, predecessor_id, path_type)
if suggested_failure:
safe_failure = sanitize_string(suggested_failure)
print(f"\nAI suggests the following failure outcome: '{safe_failure}'")
use_suggested = self.get_input("Use this suggestion? (y/n)").lower()
if use_suggested == 'y':
failure_outcome = suggested_failure
except Exception as e:
print(f"Error generating failure outcome suggestion: {str(e)}")
# Optional note
print("\nA note is a brief comment that appears next to the step in the diagram.")
add_note = self.get_input("Would you like to add a note for this step? (y/n)").lower()
note_id = None
if add_note == 'y':
note_content = self.get_input("What's the note content?")
if use_ai and self.openai_client:
want_ai_help = self.get_input("\nWould you like to see an AI suggestion for the note? (y/n)").lower() == 'y'
if want_ai_help:
try:
show_loading_animation("Generating note suggestion")
suggested_note = self.generate_step_note(step_id, description, decision, success_outcome, failure_outcome)
if suggested_note:
safe_note = sanitize_string(suggested_note)
print(f"\nAI suggests the following note: '{safe_note}'")
use_suggested = self.get_input("Use this suggestion? (y/n)").lower()
if use_suggested == 'y':
note_content = suggested_note
except Exception as e:
print(f"Error generating note suggestion: {str(e)}")
note_id = f"Note{self.current_note_id}"
self.notes.append(ProcessNote(note_id, note_content, step_id))
self.current_note_id += 1
# Enhanced fields
print("\nValidation rules help ensure the step receives good input data.")
add_validation = self.get_input("Would you like to add validation rules? (y/n)").lower()
validation_rules = None
if add_validation == 'y':
validation_rules = self.get_input("Enter validation rules:") or None
if use_ai and self.openai_client:
want_ai_help = self.get_input("\nWould you like to see an AI suggestion for the validation rules? (y/n)").lower() == 'y'
if want_ai_help:
try:
show_loading_animation("Generating validation rules suggestion")
suggested_validation = self.generate_validation_rules(step_id, description, decision, success_outcome, failure_outcome)
if suggested_validation:
print(f"\nAI suggests the following validation rules:\n{suggested_validation}")
safe_validation = sanitize_string(suggested_validation)
print(f"\nAI suggests the following validation rules:\n{safe_validation}")
use_suggested = self.get_input("Use this suggestion? (y/n)").lower()
if use_suggested == 'y':
validation_rules = suggested_validation
except Exception as e:
print(f"Error generating validation rules suggestion: {str(e)}")
print("\nError codes help identify and track specific problems that might occur.")
add_error_codes = self.get_input("Would you like to add error codes? (y/n)").lower()
error_codes = None
if add_error_codes == 'y':
error_codes = self.get_input("Enter error codes:") or None
if use_ai and self.openai_client:
want_ai_help = self.get_input("\nWould you like to see an AI suggestion for the error codes? (y/n)").lower() == 'y'
if want_ai_help:
try:
show_loading_animation("Generating error codes suggestion")
suggested_error_codes = self.generate_error_codes(step_id, description, decision, success_outcome, failure_outcome)
if suggested_error_codes:
safe_error_codes = sanitize_string(suggested_error_codes)
print(f"\nAI suggests the following error codes:\n{safe_error_codes}")
use_suggested = self.get_input("Use this suggestion? (y/n)").lower()
if use_suggested == 'y':
error_codes = suggested_error_codes
except Exception as e:
print(f"Error generating error codes suggestion: {str(e)}")
# Create and return the step
step = ProcessStep(
step_id=step_id,
description=description,
decision=decision,
success_outcome=success_outcome,
failure_outcome=failure_outcome,
note_id=note_id,
next_step_success="End", # Default to End, will be updated later
next_step_failure="End", # Default to End, will be updated later
validation_rules=validation_rules,
error_codes=error_codes
)
return step
def generate_step_title(self, step_id: str, predecessor_id: str, path_type: str) -> str:
"""Generate an intelligent step title based on context.
Args:
step_id: The current step ID
predecessor_id: The ID of the step that references this step
path_type: Either 'success' or 'failure' indicating which path led here
"""
if not self.openai_client:
return step_id
try:
# Get predecessor step details
predecessor = next((s for s in self.steps if s.step_id == predecessor_id), None)
if not predecessor:
return step_id
# Sanitize strings to prevent syntax errors from unescaped single quotes
safe_process_name = sanitize_string(self.process_name)
safe_pred_id = sanitize_string(predecessor.step_id)
safe_pred_desc = sanitize_string(predecessor.description)
safe_pred_decision = sanitize_string(predecessor.decision)
safe_path_type = sanitize_string(path_type)
safe_step_id = sanitize_string(step_id)
# Rewrite the prompt with proper string formatting
prompt = (
f"Given the following process context:\n"
f"Process Name: {safe_process_name}\n"
f"Predecessor Step: {safe_pred_id}\n"
f"Predecessor Description: {safe_pred_desc}\n"
f"Predecessor Decision: {safe_pred_decision}\n"
f"Path Type: {safe_path_type}\n"
f"Current Step ID: {safe_step_id}\n\n"
f"Suggest an appropriate title for this step that:\n"
f"1. Follows logically from the predecessor step\n"
f"2. Is clear and descriptive\n"
f"3. Starts with a verb\n"
f"4. Is specific to the process\n"
f"5. Is concise (2-5 words)\n"
f"6. Follows business process naming conventions\n\n"
f"Please provide just the step title, no additional text."
)
response = self.openai_client.chat.completions.create(
model="gpt-4-turbo-preview",
messages=[
{"role": "system", "content": "You are a business process expert. Create clear, concise step titles that follow best practices."},
{"role": "user", "content": prompt}
],
temperature=0.7,
max_tokens=50
)
return response.choices[0].message.content.strip()
except Exception as e:
print(f"Error generating step title: {str(e)}")
return step_id
def add_step(self, step: ProcessStep, interactive: bool = True) -> List[str]:
"""Add a new step to the process and validate it.
Args:
step: The ProcessStep to add
interactive: Whether to use interactive mode for missing steps
If False, will auto-generate missing steps without prompts
"""
# Validate the step
issues = step.validate()
if issues:
return issues
# Check for duplicate step ID
if any(s.step_id == step.step_id for s in self.steps):
issues.append(f"Step ID '{step.step_id}' already exists")
return issues
# Add the step
self.steps.append(step)
self.step_count += 1
# Find and create any missing steps
while True:
missing_steps = self.find_missing_steps()
if not missing_steps:
break
for missing_step_id, predecessor_id, path_type in missing_steps:
# Create the missing step using either interactive or non-interactive mode
if interactive:
print(f"\nFound missing step: {missing_step_id}")
print(f"Referenced by step: {predecessor_id} on {path_type} path")
new_step = self.create_missing_step(missing_step_id, predecessor_id, path_type)
else:
new_step = self.create_missing_step_noninteractive(missing_step_id, predecessor_id, path_type)
# Add the new step with the same interactivity setting
step_issues = self.add_step(new_step, interactive=interactive)
if step_issues:
print("\n=== Validation Issues ===")
for issue in step_issues:
print(f"- {issue}")
print("\nPlease fix these issues and try again.")
continue
# Validate the process flow
flow_issues = validate_process_flow(self.steps)
note_issues = validate_notes(self.notes, self.steps)
return flow_issues + note_issues
def add_note(self, note: ProcessNote) -> List[str]:
"""Add a new note to the process and validate it."""
# Validate the note
issues = note.validate()
if issues:
return issues
# Check for duplicate note ID
if any(n.note_id == note.note_id for n in self.notes):
issues.append(f"Note ID '{note.note_id}' already exists")
return issues
# Check if related step exists
if not any(s.step_id == note.related_step_id for s in self.steps):
issues.append(f"Related step '{note.related_step_id}' does not exist")
return issues
# Add the note
self.notes.append(note)
# Link note to step
for step in self.steps:
if step.step_id == note.related_step_id:
step.note_id = note.note_id
break
return []
def evaluate_step_design(self, step: ProcessStep) -> str:
"""Evaluate a step's design using OpenAI."""
if not self.openai_client:
return "AI evaluation is not available - OPENAI_API_KEY not found or invalid."
try:
# Rewrite the prompt with proper string formatting
prompt = (
f"Evaluate the following process step design:\n\n"
f"Process Name: {self.process_name}\n"
f"Step ID: {step.step_id}\n"
f"Description: {step.description}\n"
f"Decision: {step.decision}\n"
f"Success Outcome: {step.success_outcome}\n"
f"Failure Outcome: {step.failure_outcome}\n"
f"Next Step (Success): {step.next_step_success}\n"
f"Next Step (Failure): {step.next_step_failure}\n"
f"Validation Rules: {step.validation_rules or 'None'}\n"
f"Error Codes: {step.error_codes or 'None'}\n\n"
f"Please provide:\n"
f"1. A brief assessment of the step's design\n"
f"2. Potential improvements or considerations\n"
f"3. Any missing elements that should be addressed\n"
f"4. Specific recommendations for validation or error handling if not provided\n\n"
f"Keep the response concise and actionable."
)