File size: 55,094 Bytes
3d06fab
 
 
 
 
 
 
4d3bd77
3d06fab
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
158a4cb
3d06fab
 
865add6
e43acaf
158a4cb
e43acaf
 
158a4cb
 
e43acaf
 
 
 
 
3d06fab
 
 
 
 
 
 
 
 
 
 
 
 
 
4d3bd77
3d06fab
 
 
 
 
 
 
 
 
4d3bd77
3d06fab
 
 
4d3bd77
3d06fab
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
65a5416
 
 
 
 
 
3d06fab
 
c73e677
65a5416
 
 
3d06fab
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
65a5416
 
 
 
 
 
3d06fab
 
 
 
c73e677
65a5416
 
 
 
 
3d06fab
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
65a5416
3d06fab
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127

import os
import openai
import random
import pandas as pd
import uuid
import pickle
import re

# Module seeds
context_types = {
    "Work/Professional": [
        "Working on a project or task",
        "Attending a meeting or briefing",
        "Collaborating with colleagues or team members",
        "Presenting a proposal or idea",
        "Responding to client or customer feedback",
        "Managing or resolving a workplace conflict",
        "Negotiating a contract or agreement",
        "Performing routine tasks",
        "Handling unexpected challenges"
    ],
    "Social": [
        "Engaging in a social gathering or event",
        "Having a one-on-one conversation with a friend or acquaintance",
        "Participating in a group activity or hobby",
        "Sharing ideas or opinions in a casual discussion",
        "Dealing with a social conflict or disagreement",
        "Networking at a professional or social event"
    ],
    "Physical Activity": [
        "Participating in a team sport or physical competition",
        "Engaging in an outdoor activity",
        "Training or practicing with a coach or instructor",
        "Competing in a tournament or race",
        "Engaging in a personal fitness routine or challenge",
        "Performing a physical task that requires coordination or teamwork"
    ],
    "Reflection": [
        "Reflecting on a past decision or action",
        "Planning future goals or strategies",
        "Evaluating personal or professional progress",
        "Contemplating a challenging situation or conflict",
        "Revisiting a difficult conversation or interaction",
        "Assessing personal strengths, weaknesses, or skills"
    ],
    "Educational": [
        "Participating in a class, lecture, or seminar",
        "Collaborating on a study project or research",
        "Receiving feedback from a teacher or mentor",
        "Preparing for or taking an exam",
        "Engaging in group study or discussion",
        "Presenting academic work or research findings"
    ],
    "Creative": [
        "Working on a creative project",
        "Collaborating with others on a creative endeavor",
        "Receiving feedback on a creative piece",
        "Presenting a creative work to an audience",
        "Brainstorming or ideating new concepts",
        "Experimenting with new techniques or styles"
    ]
}

interaction_types = {
    "Authority Feedback": [
        "Receiving feedback or critique from a supervisor, boss, or mentor",
        "Listening to advice or guidance from a coach or teacher",
        "Engaging in a performance review or evaluation",
        "Responding to managerial decisions or directives"
    ],
    "Peer Reaction": [
        "Receiving input, advice, or reactions from a colleague, friend, or teammate",
        "Discussing ideas or opinions with peers in a group setting",
        "Addressing concerns, compliments, or criticisms from a peer",
        "Collaborating on a task or project with equal responsibility"
    ],
    "Group Dynamics": [
        "Participating in a group discussion or brainstorming session",
        "Leading or following in a team activity or project",
        "Managing group feedback or collective opinions",
        "Navigating differing opinions, conflicts, or agreements within a group"
    ],
    "Self-Reflection": [
        "Analyzing personal decisions, actions, or behaviors",
        "Contemplating improvements or changes based on past experiences",
        "Reflecting on feedback received from others",
        "Re-evaluating personal goals, priorities, or values"
    ],
    "Creative Feedback": [
        "Seeking opinions or critiques on a creative project from peers or mentors",
        "Engaging in a discussion about a creative piece's direction or style",
        "Presenting creative work to a group and receiving diverse reactions"
    ],
    "Social Participation": [
        "Engaging in a group activity or event related to a hobby or interest",
        "Discussing or sharing personal achievements or interests in a social setting",
        "Navigating group dynamics during a leisure activity or social gathering"
    ]
}

tones = ["Positive", "Negative"]

actions_events = {
    "Work/Professional": [
        "Receiving feedback",
        "Observing reactions",
        "Presenting ideas",
        "Responding to a situation"
    ],
    "Creative/Personal Projects": [
        "Completing a creative project",
        "Seeking feedback",
        "Engaging in competition",
        "Sharing achievements"
    ],
    "Social/Leisure Activities": [
        "Socializing at an event",
        "Participating in a hobby",
        "Competing in a friendly match",
        "Celebrating an achievement"
    ]
}

outcomes_reveals = {
    "Feedback Becomes More Detailed": [
        "The feedback received becomes more specific, highlighting both strengths and weaknesses",
        "Additional information is provided about how your work or actions have been perceived"
    ],
    "Reactions Evolve": [
        "Others in the group or interaction begin to share their thoughts, leading to a broader or more complex discussion",
        "A different or unexpected perspective is introduced, challenging initial reactions or assumptions"
    ],
    "Situation Becomes More Complex": [
        "A new element or complication is introduced, adding layers to the initial problem or challenge",
        "Additional context or background information is revealed, shifting the interpretation of the situation"
    ],
    "Personal Reflection Deepens": [
        "You start to see patterns or broader implications of your actions or decisions",
        "A realization or new insight occurs that changes how you view the initial event or scenario"
    ]
}

def interpret_response(user_input, options_text, user_state):
    stage = user_state.get("stage", "")
    
    if stage == "internal_external":
        # Expecting a numeric rating from 1 to 10
        try:
            rating = int(user_input)
            if 1 <= rating <= 5:
                return '1'  # Option 1: Internal factors are more likely
            elif 6 <= rating <= 10:
                return '2'  # Option 2: External factors are more likely
            else:
                return "Please clarify."
        except ValueError:
            return "Please clarify."
    
    else:
        # Existing logic for other stages
        prompt = f"""
        You are tasked with interpreting user responses to multiple-choice questions.
        Options provided:
        {options_text}
        User's response: "{user_input}"
        Identify the matching option number (e.g., '1', '2', etc.) based on the options. 
        Respond with the option number only.
        If the user's response is unclear or doesn't match any option, respond with "Please clarify.".
        """

        response = openai.chat.completions.create(
            model="gpt-4o-mini",
            messages=[{"role": "user", "content": prompt}],
            temperature=0.3,
            max_tokens=5
        )

        assistant_response = response.choices[0].message.content.strip()
        print(f"interpret_result() output: {assistant_response}")

        # Validate the response
        option_numbers = [str(i) for i in range(1, len(options_text.split('\n')) + 1)]
        if assistant_response in option_numbers:
            return assistant_response
        elif assistant_response.lower() == "please clarify.":
            return "Please clarify."
        else:
            return "Invalid response."


def standardize_response(question, response):
    prompt_lower = question.lower()
     
    if "scale from 1 to 10" in prompt_lower:
        try:
            rating = int(response)
            if 1 <= rating <= 10:
                return rating  # Return as integer for consistency
            else:
                return None
        except ValueError:
            return None
     
    
    # Handle other questions as before
    else:
        prompt = f"""
        Standardize the following user response for analysis:
        Question: "{question}"
        User Response: "{response}"
        Extract the key information relevant to the question and provide it as a standardized response.
        Examples:
        - Age: "I'm 25 years old" → "25"
        - Profession: "I work as a teacher" → "teacher"
        - Interests: "I enjoy hiking and painting" → "hiking, painting"
        Respond with only the standardized response. Do not include any additional text or explanations.
        """
    
        standardized_response = openai.chat.completions.create(
            model="gpt-4o-mini",
            messages=[
                {"role": "system", "content": "You are an assistant standardizing user responses for data analysis."},
                {"role": "user", "content": prompt}
            ],
            temperature=0.1
        ).choices[0].message.content.strip()
        
        print(f"standardize_response() output: {standardized_response}")
        
        if standardized_response.lower().startswith("standardized response:"):
            standardized_response = standardized_response.split(":", 1)[1].strip()
    
        # Validate the format based on the question type
        if "age" in question.lower() and standardized_response.isdigit():
            return int(standardized_response)
        elif "profession" in question.lower():
            return standardized_response
        elif "interests" in question.lower():
            return standardized_response
        else:
            return standardized_response

# def load_vignette_data(vignette_number, user_state):
#     """
#     Fetches the vignette and reveal for a given participant from the Excel file.
#     Arguments:
#         - vignette_number: The specific vignette number (1 to 16)
#     Returns:
#         - vignette_text: The text of the vignette for the selected participant
#         - tone: The tone associated with the vignette (e.g., Positive or Negative)
#         - first_reveal: The first reveal for the given vignette
#     """

#     # Load the Excel data
#     data = pd.read_excel("assessment_data.xlsx")

#     # Select a random user ID if it's not set yet
#     if selected_user_id is None:
#         user_ids = data['User ID'].unique()
#         if len(user_ids) == 0:
#             print("No User IDs found in the assessment data.")
#             return None, None, None
#         selected_user_id = random.choice(user_ids)

#     # Filter the data based on selected_user_id and vignette_number
#     user_data = data[(data['User ID'] == selected_user_id) & (data['Vignette Number'] == vignette_number)]

#     if not user_data.empty:
#         vignette_text = user_data['Vignette'].values[0]
#         tone = user_data['Tone'].values[0]
#         first_reveal = user_data['First Reveal'].values[0]

#         return vignette_text, tone, first_reveal
#     else:
#         print(f"No data found for user_id {selected_user_id} and vignette {vignette_number}")
#         return None, None, None

# Function to generate the vignette
def generate_vignette(chat_history, topic_choice, desired_tone, user_state):
    # Extract user profile from standardized data
    user_profile = user_state.get("standardized_data", {})
    user_age = user_profile.get("Age", "Unknown")
    user_profession = user_profile.get("Profession", "Unknown")
    user_interests = user_profile.get("Interests", "Unknown")
    
    # Build the prompt to select modules and generate the vignette
    prompt = f"""
    Based on the user's profile and preferences, create a vignette tailored to the following details:
    - Age: {user_age}
    - Profession: {user_profession}
    - Interests: {user_interests}
    - Chat history: {chat_history}

    Select the most appropriate modules from these categories to create a relatable situation:
    - Context type (Work/Professional, Social, Physical Activity, Reflection, Educational, Creative)
    - Interaction type (Authority Feedback, Peer Reaction, Group Dynamics, Creative Feedback, Social Participation, Conflict/Disagreement, Support Interaction)
    - Tone (Must be either clearly Positive or clearly Negative!)
    - Action/Event (Receiving Feedback, Observing Reactions, Presenting Ideas, Responding to a Situation, Completing a Creative Project, Seeking Feedback, Engaging in Competition, Sharing Achievements, Socializing at an Event, Competing in a Friendly Match, Celebrating an Achievement, Providing/Receiving Emotional Support, Conflict Resolution, Handling Unexpected Situations, Facing Disapproval)

    Use these selected modules to generate a vignette for a psychological assessment.

    Guidelines:
    - Analyze the conversation history to understand the user's age, profession, and interests.
    - **The user has chosen topic {topic_choice}:**
        - **If the user chose '1', focus on a situation related to their profession.**
        - **If the user chose '2', focus on a situation related to their personal interests.**
        - **If the user chose '3', focus on a situation related to their most recent input in the {chat_history}.**

    Only select one module per category.
    
    The selected tone should clearly shape the atmosphere of the scenario and remain consistent throughout the vignette.
    
    Avoid mixed tones.
    
    Keep the vignettes fresh and varied.
    
    Consider all clarifying information the user has provided throughout the {chat_history} when creating a vignette.

    Do not include the module names or categories in the output.

    Only provide the vignette text and do not include phrases like "Sure", "Here is your vignette", or any other extra text.

    Ensure that the vignette is directly related to the user's profile and context. **Focus on describing the external events without including any inner reflections, thoughts, or feelings.**

    **Do not mention how the user feels or thinks about the situation.**

    Describe the vignette in a second-person view.

    Keep the vignette concise, under a 50-token limit.

    Use neutral and professional but simple language suitable for a psychological assessment.

    Do not include any personal identifying information.
    """

    # Prepare the messages for the API call
    messages = [
        {"role": "system", "content": """
            You are tasked with selecting appropriate modules and generating a standardized vignette for a psychological assessment.
            The vignette should assess attribution styles across three dimensions: Internal-External, Stable-Unstable, and Global-Specific.
        """},
        {"role": "user", "content": prompt}
    ]

    # Append the conversation history to the messages
    for message in chat_history:
        messages.append(message)

    # Call the OpenAI API
    response = openai.chat.completions.create(
        model="gpt-4o-mini",
        messages=messages,
        temperature=0.3
    )



    # Extract the response content
    content = response.choices[0].message.content.strip()

    vignette = content
    tone = desired_tone
    return vignette, tone

# Function to generate internal-external options
def generate_internal_external_options(chat_history, vignette, user_state):
    prompt = f"""
        Based on the following scenario:

        "{vignette}"

        Provide two possible causes for why this situation occurred, focusing on **internal** and **external** factors that are directly related to the scenario.

        Ensure each explanation is **concise** and captures the essence of an internal or external cause, without excessive detail. The causes should be easy for the user to understand, without overwhelming them with too many specifics.

        Describe these explanations from the user's point of view, making them relatable and personal.

        Present the options in the following format exactly:

        A: [Specific internal reason]
        B: [Specific external reason]

        Do not include any additional text or explanation.

        Use simple, but neutral and professional language suitable for a psychological assessment.
    """

    try:
        response = openai.chat.completions.create(
            model="gpt-4o-mini",
            temperature=0.3,
            messages=[
                {"role": "system", "content": "You are assisting in generating attribution options based on a given scenario for a psychological assessment. Directly address the user. Present a single brief sentence for each option."},
                {"role": "user", "content": prompt},
            ],
        )
        content = response.choices[0].message.content.strip()
        print(f"Raw internal_external_options response: {content}")  # Logging
    
        # Split the response into lines
        lines = content.split('\n')
    
        # Filter lines that start with "A:" or "B:"
        options = [line.strip() for line in lines if line.strip().startswith(("A:", "B:"))]
    
        # If more than 2 options are present, trim the list to the first two
        if len(options) > 2:
            options = options[:2]
    
        # If fewer than 2 options are present, handle accordingly (e.g., add placeholders)
        while len(options) < 2:
            options.append("Option missing due to system error.")
    
        # Join the options into a single string separated by newlines
        options_text = "\n".join(options)
    
        return options_text
    
    except Exception as e:
        print(f"Error generating internal_external options: {e}")
        return "Option missing due to system error.\nOption missing due to system error."


# Function to generate stable-unstable and global-specific options
def generate_stable_unstable_options(vignette, previous_choice, user_state):
    """
    Generates exactly two short statements explaining what might have led to a situation.
    Ensures only lines starting with "A:" or "B:" are returned.
    """
    
    # Determine the attribution type based on the user's previous choice
    if previous_choice == '1':
        attribution_type = 'Internal'
    elif previous_choice == '2':
        attribution_type = 'External'
    else:
        attribution_type = 'Internal'  # Default to Internal if unexpected input

    prompt = f"""
    Generate exactly two short statements explaining what might have led to this situation, each on its own line.
    They must strictly reflect a {attribution_type.lower()} cause, with no references to outside factors if {attribution_type.lower()} is "internal," 
    and no references to personal traits if {attribution_type.lower()} is "external." 
    
    1) Provide a stable explanation
    2) Provide a more temporary or unstable explanation
    
    Instructions:
    - Phrase all statements in second person.
    - Do not mention external influences if you're generating an internal cause.
    - Do not mention internal traits if you're generating an external cause.
    - Do not label the options as stable/unstable/etc. in the text itself.
    - Start each line with "A:" or "B:" only.
    - Keep the language simple, pragmatic, and relevant to the scenario:
    "{vignette}"
    
    - Each statement should be concise, neutral, and easy to understand, without extra commentary.
    - Do not include disclaimers, personal info, or text beyond the four statements.
    """

    messages = [
        {"role": "system", "content": "You are a strict output assistant. Produce only the specified lines."},
        {"role": "user", "content": prompt},
    ]

    # Append formatted chat history if necessary
    # formatted_history = []
    # for user_msg, assistant_msg in chat_history:
    #     if user_msg:
    #         formatted_history.append({"role": "user", "content": user_msg})
    #     if assistant_msg:
    #         formatted_history.append({"role": "assistant", "content": assistant_msg})
    # messages += formatted_history

    try:
        response = openai.chat.completions.create(
            model="gpt-4o-mini",
            messages=messages,
            temperature=0.3,
            max_tokens=300
        )

        content = response.choices[0].message.content.strip()
        print("stable_unstable options before line split:")
        print(content)
        # Split the response into lines
        lines = content.split('\n')
        
        # Filter lines that start with "A:" or "B:"
        options = [line.strip() for line in lines if line.strip().startswith(("A:", "B:"))]

        print("stable_unstable options after A/B filter:")
        print(options)
        # If more than 2 options are present, trim the list to the first two
        if len(options) > 2:
            options = options[:2]
        
        # If fewer than 2 options are present, handle accordingly (e.g., add placeholders)
        while len(options) < 2:
            options.append("Option missing due to system error.")
        
        # Join the options into a single string separated by newlines
        options_text = "\n".join(options)
        
        return options_text

    except Exception as e:
        print(f"Error generating options: {e}")
        return "Error generating options. Please try again."



def generate_global_specific_options(vignette, previous_choice, user_state):
    """
    Generates exactly two short statements explaining what might have led to a situation.
    Ensures only lines starting with "A:" or "B:" are returned.
    """
    
    # Determine the attribution type based on the user's previous choice
    if previous_choice == '1':
        attribution_type = 'Internal'
    elif previous_choice == '2':
        attribution_type = 'External'
    else:
        attribution_type = 'Internal'  # Default to Internal if unexpected input

    prompt = f"""
    Generate exactly two short statements explaining what might have led to this situation, each on its own line, with no additional commentary. They must strictly reflect a {attribution_type.lower()} cause.
    
    - If {attribution_type.lower()} is "internal," do not reference any outside factors such as environment, other people, or external circumstances.
    - If {attribution_type.lower()} is "external," do not reference personal traits, inherent aptitudes, or individual qualities.
    
    Focus on these two points:
    1) A broader/global explanation that applies widely.
    2) A more situation-specific explanation.
    
    Instructions:
    - Phrase all statements in second person.
    - Start each line with "A:" or "B:" only, and provide no other lines.
    - Keep the language simple, neutral, and directly relevant to:
      "{vignette}"
    - Each statement should be concise and easy to understand, with no disclaimers or extra text.
    - Output only those two lines, nothing else.
    """

    messages = [
        {"role": "system", "content": "You are a strict output assistant. Produce only the specified lines."},
        {"role": "user", "content": prompt},
    ]

    # # Append formatted chat history if necessary
    # formatted_history = []
    # for user_msg, assistant_msg in chat_history:
    #     if user_msg:
    #         formatted_history.append({"role": "user", "content": user_msg})
    #     if assistant_msg:
    #         formatted_history.append({"role": "assistant", "content": assistant_msg})
    # messages += formatted_history

    try:
        response = openai.chat.completions.create(
            model="gpt-4o-mini",
            messages=messages,
            temperature=0.3,
            max_tokens=300
        )

        content = response.choices[0].message.content.strip()
        print("global_specific options before line split:")
        print(content)
        
        # Split the response into lines
        lines = content.split('\n')
        
        # Filter lines that start with "A:" or "B:"
        options = [line.strip() for line in lines if line.strip().startswith(("A:", "B:"))]
        print("global_specific options after A/B filter:")
        print(options)
        
        # If more than 2 options are present, trim the list to the first two
        if len(options) > 2:
            options = options[:2]
        
        # If fewer than 2 options are present, handle accordingly (e.g., add placeholders)
        while len(options) < 2:
            options.append("Option missing due to system error.")
        
        # Join the options into a single string separated by newlines
        options_text = "\n".join(options)
        
        return options_text

    except Exception as e:
        print(f"Error generating options: {e}")
        return "Error generating options. Please try again."
        

# First reveal
def generate_first_reveal(vignette, user_state):
    prompt = f"""
    Based on the following scenario:

    "{vignette}"

    Present a first reveal that adds complexity to the situation. The reveal should provide new information that challenges the user's previous attributions.

    Use neutral and professional language suitable for a psychological assessment.

    Keep the reveal concise.
    
    Only provide the vignette text and do not include phrases like "Sure", "Here is your vignette", or any other extra text.
    """

    response = openai.chat.completions.create(
        model="gpt-4o-mini",
        temperature=0.3,
        messages=[
            {"role": "system", "content": "You are assisting in generating attribution options based on a given scenario for a psychological assessment. Directly address the user. Present a single brief sentence for eacht option."},
            {"role": "user", "content": prompt},
        ],
    )
    return response.choices[0].message.content.strip()

# Second reveal
def generate_second_reveal(vignette, first_reveal):
    prompt = f"""
    Based on the following scenario:

    "{vignette}"

    And the first reveal:

    "{first_reveal}"

    Present a second reveal that significantly alters the user's interpretation of the situation. The reveal should provide additional context or details that prompt a re-evaluation of the initial attribution.

    Use neutral and professional language suitable for a psychological assessment.

    Keep the reveal concise.

    Only provide the vignette text and do not include phrases like "Sure", "Here is your vignette", or any other extra text.
    """

    response = openai.chat.completions.create(
        model="gpt-4o-mini",
        temperature=0.3,
        messages=[
            {"role": "system", "content": "You are assisting in generating attribution options based on a given scenario for a psychological assessment. Directly address the user. Present a single brief sentence for eacht option."},
            {"role": "user", "content": prompt},
        ],
    )
    return response.choices[0].message.content.strip()


# Save to Excel
def save_data_to_excel(data):
    # Read the existing Excel file
    df = pd.read_excel('assessment_data.xlsx')

    # Convert the data dictionary to a DataFrame
    new_entry = pd.DataFrame([data])

    # Append the new entry to the DataFrame
    df = pd.concat([df, new_entry], ignore_index=True)

    # Save the updated DataFrame back to the Excel file
    df.to_excel('assessment_data.xlsx', index=False)

# Excel for control condition
def save_data_to_control_excel(data):
    # Read the existing Excel file
    df = pd.read_excel('assessment_data_nonpersonal.xlsx')

    # Convert the data dictionary to a DataFrame
    new_entry = pd.DataFrame([data])

    # Append the new entry to the DataFrame
    df = pd.concat([df, new_entry], ignore_index=True)

    # Save the updated DataFrame back to the Excel file
    df.to_excel('assessment_data_nonpersonal.xlsx', index=False)


# Save to Pickle
def save_data_to_pickle(data):
    # Read the existing Excel file
    df = pd.read_pickle(pickle_file)

    # Convert the data dictionary to a DataFrame
    new_entry = pd.DataFrame([data])

    # Append the new entry to the DataFrame
    df = pd.concat([df, new_entry], ignore_index=True)

    # Save the updated DataFrame back to the Excel file
    df.to_pickle(pickle_file)

# Pickle for control condition
def save_data_to_control_pickle(data):
    # Read the existing Excel file
    df = pd.read_pickle(pickle_file2)

    # Convert the data dictionary to a DataFrame
    new_entry = pd.DataFrame([data])

    # Append the new entry to the DataFrame
    df = pd.concat([df, new_entry], ignore_index=True)

    # Save the updated DataFrame back to the Excel file
    df.to_pickle(pickle_file2)


def chat(fn_print, fn_input):
    print("test")
    conversation_history = []
    user_responses = []  # List to store raw user responses
    standardized_data = {}  # Dictionary to store standardized data for the Excel file
    stage = "start" 
    user_id = str(uuid.uuid4())  # Generate a unique user ID
    topic_choice = None
    
    vignette_tones = ['Positive', 'Negative', 'Negative', 'Positive']  # Two positive and two negative
    vignette_counter = 1  # To keep track of the current vignette number
    
    while True:
        if stage == "start":
            fn_print("Welcome! Before we begin, please note that your responses will be used for research purposes. Your data will be kept confidential and anonymous.")
            options_text = "Yes\nNo"
            while True:
                user_input = fn_input("Do you consent to participate? (yes/no): ")
                user_responses.append({'stage': 'consent', 'response': user_input})
                conversation_history.append({"role": "user", "content": user_input})
                mapped_option = interpret_response(user_input, options_text)
                if mapped_option == '1' or user_input.strip().lower() in ['yes', 'y']:
                    standardized_data['Consent'] = 'Yes'
                    stage = "user_profile"
                    break
                elif mapped_option == '2' or user_input.strip().lower() in ['no', 'n']:
                    standardized_data['Consent'] = 'No'
                    fn_print("Thank you for your time. Goodbye!")
                    return conversation_history, user_responses  # Exit the chat
                else:
                    fn_print("Sorry, I couldn't understand your response. Please answer 'yes' or 'no'.")

            stage = "user_profile"
            
        elif stage == "user_profile":        
            fn_print("""Great! During the course of this assessment you will be confronted with descriptions of fictional everyday situations. Please try to immerse yourself in these scenarios as if they were happening to you personally.
        
        In order to provide you with situations that might be more relevant to you specifically, 
        we need some general information about you. Don't worry, you will remain anonymous!
        
        Please tell us your age, profession and one of your personal interests.""")
            user_profile_response = fn_input("You: ")
            user_responses.append({'stage': 'user_profile', 'response': user_profile_response})
            conversation_history.append({"role": "user", "content": user_profile_response})

            standardized_data['Age'] = standardize_response("Please extract the user's age from the following input.", user_profile_response)
            standardized_data['Profession'] = standardize_response("Please extract the user's profession from the following input.", user_profile_response)
            standardized_data['Interests'] = standardize_response("Please extract the user's interests from the following input.", user_profile_response)

            stage = "topic_choice"

        elif stage == "topic_choice":
            fn_print("Let's create a scenario for you.")
            fn_print("Which topic would you prefer?")
            fn_print("1. A situation related to your profession.")
            fn_print("2. A situation related to your personal interests.")
            options_text = "1. A situation related to your profession.\n2. A situation related to your personal interests."
            while True:
                user_input = fn_input("You: ")
                user_responses.append({'stage': 'topic_choice', 'response': user_input})
                conversation_history.append({"role": "user", "content": user_input})
                mapped_option = interpret_response(user_input, options_text)
                if mapped_option in ['1', '2']:
                    topic_choice_response = mapped_option
                    standardized_data['Topic Choice'] = topic_choice_response
                    topic_choice = topic_choice_response
                    stage = "vignette"
                    break
                else:
                    fn_print("Sorry, I couldn't understand your response. Could you please specify your choice?")
                    
        elif stage == "vignette":
            if vignette_counter > 4:
                # All vignettes have been presented
                fn_print("You have completed all scenarios. Thank you for your participation! You will now be redirected to Prolific. Please don't close the browser yet. Goodbye!")
                save_data_to_excel(standardized_data)
                fn_print(f"Total vignettes presented: {vignette_counter - 1}")
                break
        
            # Determine the desired tone for the current vignette
            desired_tone = vignette_tones[vignette_counter - 1]
        
            vignette, tone = generate_vignette(conversation_history, topic_choice, desired_tone)
            if vignette is None:
                fn_print("There was an error generating the vignette. Exiting the assessment.")
                break
        
            fn_print("Alright, please imagine you are witnessing the following scene:")
            fn_print(f"Chatbot: {vignette}")
            conversation_history.append({"role": "assistant", "content": vignette})
            user_responses.append({'stage': 'vignette', 'content': vignette, 'tone': tone})
        
            # Temporarily store the vignette and tone with a unique key per vignette
            standardized_data[f'Vignette{vignette_counter}'] = vignette
            standardized_data[f'Tone{vignette_counter}'] = tone
        
            stage = "vignette_usability_assessment"
            
        elif stage == "vignette_usability_assessment":
            fn_print(f"Vignette {vignette_counter} Usability Assessment:")
            fn_print("On a scale from 1 to 10, how relevant, immersive, or relatable is the depicted scenario to you personally? (1 = not at all, 10 = completely)")
            relevance_rating = fn_input("You: ")
            user_responses.append({'stage': 'vignette_usability_assessment', 'response': relevance_rating})
            conversation_history.append({"role": "user", "content": relevance_rating})
        
            # Store the initial relevance rating if not already stored
            if f'Initial Relevance Rating{vignette_counter}' not in standardized_data:
                standardized_data[f'Initial Relevance Rating{vignette_counter}'] = int(relevance_rating)
        
            if int(relevance_rating) >= 7:
                # Accept the vignette
                standardized_data[f'Vignette{vignette_counter}'] = vignette
                standardized_data[f'Tone{vignette_counter}'] = tone
                # Store the final relevance rating
                standardized_data[f'Final Relevance Rating{vignette_counter}'] = int(relevance_rating)
                stage = "internal_external"
            else:
                # Ask for further clarification
                fn_print("I'm sorry to hear that the scenario wasn't quite fitting. Could you please provide more details about your specific context, so we can come up with a better one?")
                additional_info = fn_input("You: ")
                user_responses.append({'stage': 'additional_info', 'response': additional_info})
                conversation_history.append({"role": "user", "content": additional_info})
                # Use the additional info to regenerate the vignette
                
                stage = "vignette_regeneration"
                
        elif stage == "vignette_regeneration":
            # Use the additional info in the conversation history to regenerate the vignette
            vignette, tone = generate_vignette(conversation_history, topic_choice, desired_tone)
            fn_print("Okay, let's try again. Please imagine you are witnessing the following scene:")
            fn_print(f"Chatbot: {vignette}")
            conversation_history.append({"role": "assistant", "content": vignette})
            user_responses.append({'stage': 'vignette_regenerated', 'content': vignette, 'tone': tone})
            # Temporarily store the new vignette and tone
            standardized_data[f'Vignette{vignette_counter}'] = vignette
            standardized_data[f'Tone{vignette_counter}'] = tone
            
            # Go back to usability assessment
            stage = "vignette_usability_assessment"

        elif stage == "internal_external":
            options_text = generate_internal_external_options(conversation_history, standardized_data[f'Vignette{vignette_counter}'])
            fn_print("Based on the scenario above, which of the following explanations do you think is most likely?:")
            fn_print(f"Options:\n{options_text}")
            while True:
                user_input = fn_input("Your explanation: ")
                user_responses.append({'stage': 'internal_external', 'options': options_text, 'response': user_input})
                conversation_history.append({"role": "user", "content": user_input})
                mapped_option = interpret_response(user_input, options_text)
                if mapped_option in ['1', '2']:
                    explanation_response = mapped_option
                    break
                else:
                    fn_print("Sorry, I couldn't understand your response. Could you please rephrase or specify your choice?")
            # Store the initial internal/external attribution numerically
            if explanation_response == '1':
                standardized_data[f'Initial Internal{vignette_counter}'] = 1
                standardized_data[f'Initial External{vignette_counter}'] = 0
            elif explanation_response == '2':
                standardized_data[f'Initial Internal{vignette_counter}'] = 0
                standardized_data[f'Initial External{vignette_counter}'] = 1
            else:
                standardized_data[f'Initial Internal{vignette_counter}'] = None
                standardized_data[f'Initial External{vignette_counter}'] = None


            stage = "stable_unstable_global_specific"

        elif stage == "stable_unstable_global_specific":
            previous_choice = explanation_response
            options_text = generate_stable_unstable_options(conversation_history, standardized_data[f'Vignette{vignette_counter}'], previous_choice)
            fn_print("Now, considering your previous choice, please select which option best explains the situation:")
            fn_print(f"Options:\n{options_text}")
            while True:
                user_input = fn_input("Your explanation: ")
                user_responses.append({'stage': 'stable_unstable_global_specific', 'options': options_text, 'response': user_input})
                conversation_history.append({"role": "user", "content": user_input})
                mapped_option = interpret_response(user_input, options_text)
                if mapped_option in ['1', '2', '3', '4']:
                    explanation_stable_unstable_response = mapped_option
                    break
                else:
                    fn_print("Sorry, I couldn't understand your response. Could you please rephrase or specify your choice?")
            # Store the initial stable/unstable and global/specific attributions numerically
            if explanation_stable_unstable_response == '1':
                standardized_data[f'Initial Stable{vignette_counter}'] = 1
                standardized_data[f'Initial Unstable{vignette_counter}'] = 0
                standardized_data[f'Initial Global{vignette_counter}'] = 1
                standardized_data[f'Initial Specific{vignette_counter}'] = 0
            elif explanation_stable_unstable_response == '2':
                standardized_data[f'Initial Stable{vignette_counter}'] = 1
                standardized_data[f'Initial Unstable{vignette_counter}'] = 0
                standardized_data[f'Initial Global{vignette_counter}'] = 0
                standardized_data[f'Initial Specific{vignette_counter}'] = 1
            elif explanation_stable_unstable_response == '3':
                standardized_data[f'Initial Stable{vignette_counter}'] = 0
                standardized_data[f'Initial Unstable{vignette_counter}'] = 1
                standardized_data[f'Initial Global{vignette_counter}'] = 1
                standardized_data[f'Initial Specific{vignette_counter}'] = 0
            elif explanation_stable_unstable_response == '4':
                standardized_data[f'Initial Stable{vignette_counter}'] = 0
                standardized_data[f'Initial Unstable{vignette_counter}'] = 1
                standardized_data[f'Initial Global{vignette_counter}'] = 0
                standardized_data[f'Initial Specific{vignette_counter}'] = 1
            else:
                standardized_data[f'Initial Stable{vignette_counter}'] = None
                standardized_data[f'Initial Unstable{vignette_counter}'] = None
                standardized_data[f'Initial Global{vignette_counter}'] = None
                standardized_data[f'Initial Specific{vignette_counter}'] = None

            stage = "first_reveal"

        elif stage == "first_reveal":
            first_reveal = generate_first_reveal(vignette)
            fn_print("Alright, noted. Now, please imagine the following:")
            fn_print(f"Chatbot: {first_reveal}")
            conversation_history.append({"role": "assistant", "content": first_reveal})
            user_responses.append({'stage': 'first_reveal', 'content': first_reveal})
            standardized_data[f'First Reveal{vignette_counter}'] = first_reveal
            stage = "internal_external_reassessment"

        elif stage == "internal_external_reassessment":
            options_text = generate_internal_external_options(conversation_history, standardized_data[f'Vignette{vignette_counter}'] + " " + standardized_data[f'First Reveal{vignette_counter}'])
            fn_print("Considering these new developments, please select which of these options seems more likely to you:")
            fn_print(f"Options:\n{options_text}")
            while True:
                user_input = fn_input("Your explanation: ")
                user_responses.append({'stage': 'internal_external_reassessment', 'options': options_text, 'response': user_input})
                conversation_history.append({"role": "user", "content": user_input})
                mapped_option = interpret_response(user_input, options_text)
                if mapped_option in ['1', '2']:
                    assessment_internal_external_response = mapped_option
                    break
                else:
                    fn_print("Sorry, I couldn't understand your response. Could you please rephrase or specify your choice?")

            # Store the reassessment internal/external attribution numerically
            if assessment_internal_external_response == '1':
                standardized_data[f'Reassessment Internal{vignette_counter}'] = 1
                standardized_data[f'Reassessment External{vignette_counter}'] = 0
            elif assessment_internal_external_response == '2':
                standardized_data[f'Reassessment Internal{vignette_counter}'] = 0
                standardized_data[f'Reassessment External{vignette_counter}'] = 1
            else:
                standardized_data[f'Reassessment Internal{vignette_counter}'] = None
                standardized_data[f'Reassessment External{vignette_counter}'] = None

            stage = "stable_unstable_global_specific_reassessment"

        elif stage == "stable_unstable_global_specific_reassessment":
            previous_choice = assessment_internal_external_response
            options_text = generate_stable_unstable_options(conversation_history, standardized_data[f'Vignette{vignette_counter}'] + " " + standardized_data[f'First Reveal{vignette_counter}'], previous_choice)
            fn_print("Now, based on your previous choice, once again select, which option best explains the situation:")
            fn_print(f"Options:\n{options_text}")
            while True:
                user_input = fn_input("Your explanation: ")
                user_responses.append({'stage': 'stable_unstable_global_specific_reassessment', 'options': options_text, 'response': user_input})
                conversation_history.append({"role": "user", "content": user_input})
                mapped_option = interpret_response(user_input, options_text)
                if mapped_option in ['1', '2', '3', '4']:
                    assessment_stable_unstable_response = mapped_option
                    break
                else:
                    fn_print("Sorry, I couldn't understand your response. Could you please rephrase or specify your choice?")

            # Store the reassessment stable/unstable and global/specific attributions numerically
            if assessment_stable_unstable_response == '1':
                standardized_data[f'Reassessment Stable{vignette_counter}'] = 1
                standardized_data[f'Reassessment Unstable{vignette_counter}'] = 0
                standardized_data[f'Reassessment Global{vignette_counter}'] = 1
                standardized_data[f'Reassessment Specific{vignette_counter}'] = 0
            elif assessment_stable_unstable_response == '2':
                standardized_data[f'Reassessment Stable{vignette_counter}'] = 1
                standardized_data[f'Reassessment Unstable{vignette_counter}'] = 0
                standardized_data[f'Reassessment Global{vignette_counter}'] = 0
                standardized_data[f'Reassessment Specific{vignette_counter}'] = 1
            elif assessment_stable_unstable_response == '3':
                standardized_data[f'Reassessment Stable{vignette_counter}'] = 0
                standardized_data[f'Reassessment Unstable{vignette_counter}'] = 1
                standardized_data[f'Reassessment Global{vignette_counter}'] = 1
                standardized_data[f'Reassessment Specific{vignette_counter}'] = 0
            elif assessment_stable_unstable_response == '4':
                standardized_data[f'Reassessment Stable{vignette_counter}'] = 0
                standardized_data[f'Reassessment Unstable{vignette_counter}'] = 1
                standardized_data[f'Reassessment Global{vignette_counter}'] = 0
                standardized_data[f'Reassessment Specific{vignette_counter}'] = 1
            else:
                standardized_data[f'Reassessment Stable{vignette_counter}'] = None
                standardized_data[f'Reassessment Unstable{vignette_counter}'] = None
                standardized_data[f'Reassessment Global{vignette_counter}'] = None
                standardized_data[f'Reassessment Specific{vignette_counter}'] = None

            stage = "second_reveal"

        elif stage == "second_reveal":
            second_reveal = generate_second_reveal(vignette, first_reveal)
            fn_print("Okay. Finally, please imagine this:")
            fn_print(f"Chatbot: {second_reveal}")
            conversation_history.append({"role": "assistant", "content": second_reveal})
            user_responses.append({'stage': 'second_reveal', 'content': second_reveal})
            standardized_data[f'Second Reveal{vignette_counter}'] = second_reveal
            stage = "evolved_internal_external"

        elif stage == "evolved_internal_external":
            options_text = generate_internal_external_options(conversation_history, standardized_data[f'Vignette{vignette_counter}'] + " " + standardized_data[f'First Reveal{vignette_counter}'] + " " + standardized_data[f'Second Reveal{vignette_counter}'])
            fn_print("With the new information, what do you think why the situation occurred:")
            fn_print(f"Options:\n{options_text}")
            while True:
                user_input = fn_input("Your explanation: ")
                user_responses.append({'stage': 'evolved_internal_external', 'options': options_text, 'response': user_input})
                conversation_history.append({"role": "user", "content": user_input})
                mapped_option = interpret_response(user_input, options_text)
                if mapped_option in ['1', '2']:
                    evolved_internal_external_response = mapped_option
                    break
                else:
                    fn_print("Sorry, I couldn't understand your response. Could you please rephrase or specify your choice?")

            # Store the final internal/external attribution numerically
            if evolved_internal_external_response == '1':
                standardized_data[f'Final Internal{vignette_counter}'] = 1
                standardized_data[f'Final External{vignette_counter}'] = 0
            elif evolved_internal_external_response == '2':
                standardized_data[f'Final Internal{vignette_counter}'] = 0
                standardized_data[f'Final External{vignette_counter}'] = 1
            else:
                standardized_data[f'Final Internal{vignette_counter}'] = None
                standardized_data[f'Final External{vignette_counter}'] = None

            stage = "evolved_stable_unstable_global_specific"

        elif stage == "evolved_stable_unstable_global_specific":
            previous_choice = evolved_internal_external_response
            options_text = generate_stable_unstable_options(conversation_history, standardized_data[f'Vignette{vignette_counter}'] + " " + standardized_data[f'First Reveal{vignette_counter}'] + " " + standardized_data[f'Second Reveal{vignette_counter}'], previous_choice)
            fn_print("One last time, based on your previous choice, which option best explains the situation:")
            fn_print(f"Options:\n{options_text}")
            while True:
                user_input = fn_input("Your explanation: ")
                user_responses.append({'stage': 'evolved_stable_unstable_global_specific', 'options': options_text, 'response': user_input})
                conversation_history.append({"role": "user", "content": user_input})
                mapped_option = interpret_response(user_input, options_text)
                if mapped_option in ['1', '2', '3', '4']:
                    evolved_stable_unstable_response = mapped_option
                    break
                else:
                    fn_print("Sorry, I couldn't understand your response. Could you please rephrase or specify your choice?")

            # Store the final stable/unstable and global/specific attributions numerically
            if evolved_stable_unstable_response == '1':
                standardized_data[f'Final Stable{vignette_counter}'] = 1
                standardized_data[f'Final Unstable{vignette_counter}'] = 0
                standardized_data[f'Final Global{vignette_counter}'] = 1
                standardized_data[f'Final Specific{vignette_counter}'] = 0
            elif evolved_stable_unstable_response == '2':
                standardized_data[f'Final Stable{vignette_counter}'] = 1
                standardized_data[f'Final Unstable{vignette_counter}'] = 0
                standardized_data[f'Final Global{vignette_counter}'] = 0
                standardized_data[f'Final Specific{vignette_counter}'] = 1
            elif evolved_stable_unstable_response == '3':
                standardized_data[f'Final Stable{vignette_counter}'] = 0
                standardized_data[f'Final Unstable{vignette_counter}'] = 1
                standardized_data[f'Final Global{vignette_counter}'] = 1
                standardized_data[f'Final Specific{vignette_counter}'] = 0
            elif evolved_stable_unstable_response == '4':
                standardized_data[f'Final Stable{vignette_counter}'] = 0
                standardized_data[f'Final Unstable{vignette_counter}'] = 1
                standardized_data[f'Final Global{vignette_counter}'] = 0
                standardized_data[f'Final Specific{vignette_counter}'] = 1
            else:
                standardized_data[f'Final Stable{vignette_counter}'] = None
                standardized_data[f'Final Unstable{vignette_counter}'] = None
                standardized_data[f'Final Global{vignette_counter}'] = None
                standardized_data[f'Final Specific{vignette_counter}'] = None

            stage = "likelihood_of_change"

        elif stage == "likelihood_of_change":
            fn_print("Think back to your initial interpretation of the scene. On a scale from 1 to 10, how likely are you to change that initial interpretation after receiving the new information? (1 = least likely, 10 = most likely)")
            user_input = fn_input("You: ")
            user_responses.append({'stage': 'likelihood_of_change', 'response': user_input})
            conversation_history.append({"role": "user", "content": user_input})

            # Interpret the user's response to extract the numerical rating
            prompt = f"""
            The user was asked to rate their likelihood of changing their initial interpretation on a scale from 1 to 10.

            The user responded: "{user_input}"

            Extract the numerical rating from the user's response. Provide the number only.

            If you cannot determine the rating, respond with "Unable to determine".
            """

            response = openai.chat.completions.create(
                model="gpt-4o-mini",
                messages=[{"role": "user", "content": prompt}],
                temperature=0.0,
                max_tokens=5
            )

            assistant_response = response.choices[0].message.content.strip()
            if assistant_response.isdigit() and 1 <= int(assistant_response) <= 10:
                standardized_data[f'Likelihood of Change{vignette_counter}'] = int(assistant_response)
                stage = "subsequent_vignettes"
            else:
                fn_print("Sorry, I couldn't understand your response. Please provide a number between 1 and 10.")

        elif stage == "subsequent_vignettes":
            fn_print("Thank you! We are now finished with this scene. In total you will be seeing four scenes.")
           
            vignette_counter += 1  # Move to the next vignette
            
            stage = "topic_choice"  # Reset stage to process the next vignette

    return conversation_history, user_responses