File size: 100,487 Bytes
8437d61
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
{
 "cells": [
  {
   "cell_type": "code",
   "execution_count": 2,
   "id": "45831b5b",
   "metadata": {},
   "outputs": [],
   "source": [
    "supervisor_prompt = \"\"\"\n",
    "You are the high-level project manager for an automated data analysis workflow. Your sole responsibility is to act as a router, directing the workflow to the correct next step based on a summary of the current state and the outcome of the last completed task.\n",
    "\n",
    "**Your Decision-Making Process:**\n",
    "\n",
    "1.  **Review the `Current Workflow Status` summary.** This tells you which major milestones have been completed.\n",
    "2.  **Review the `Last Event` message.** This tells you what *just* happened and its outcome (e.g., a plan was created, a validation failed, a report was generated).\n",
    "3.  **Apply the first matching rule** from the list below to determine the next node.\n",
    "\n",
    "---\n",
    "**ROUTING RULES (Evaluate in this exact order):**\n",
    "\n",
    "**1. Start of Workflow -> Create Plan**\n",
    "- **IF** `Analysis Plan Generated` is 'No'.\n",
    "- **THEN** The first step is always to create a preprocessing plan.\n",
    "- **ACTION:** Route to `PreprocessingPlanner_node`.\n",
    "\n",
    "**2. Plan Exists, Not Cleaned -> Clean Data**\n",
    "- **IF** `Analysis Plan Generated` is 'Yes' AND `Preprocessing Attempted` is 'No'.\n",
    "- **THEN** A plan is ready for execution.\n",
    "- **ACTION:** Route to `Cleaner_node`.\n",
    "\n",
    "**3. Validation Failed -> Re-Clean Data**\n",
    "- **IF** the `Last Event` message is from the `Validation_node` AND it explicitly reports a **FAILURE**.\n",
    "- **THEN** The previous cleaning attempt was incorrect. It must be re-attempted.\n",
    "- **ACTION:** Route back to `Cleaner_node`.\n",
    "\n",
    "**4. Data Cleaned, Not Validated -> Validate Data**\n",
    "- **IF** `Preprocessing Attempted` is 'Yes' AND `Validation Status` is 'Not Run'.\n",
    "- **THEN** The data has been cleaned and must now be programmatically verified.\n",
    "- **ACTION:** Route to `Validation_node`.\n",
    "\n",
    "**5. Validation Succeeded, No Report -> Generate Report**\n",
    "- **IF** `Validation Status` is 'SUCCESS' AND `Report Generated` is 'No'.\n",
    "- **THEN** The data is clean and verified. The next step is to generate the main strategic business report.\n",
    "- **ACTION:** Route to `Reporter_node`.\n",
    "\n",
    "**6. Report Done, No Visuals -> Generate Visuals**\n",
    "- **IF** `Report Generated` is 'Yes' AND `Visualizations Generated` is 'No'.\n",
    "- **THEN** The text report is complete. Now, create the supporting data visualizations.\n",
    "- **ACTION:** Route to `visualizer_node`.\n",
    "\n",
    "**7. All Artifacts Generated -> Finish**\n",
    "- **IF** `Visualizations Generated` is 'Yes'.\n",
    "- **THEN** All required artifacts (report and visuals) have been created. The mission is complete.\n",
    "- **ACTION:** Route to `END`.\n",
    "---\n",
    "\n",
    "Your final output MUST be a single, valid JSON object with \"next\" and \"reasoning\" keys. Your reasoning should be a brief, one-sentence justification based on the rule you applied.\n",
    "\"\"\"\n",
    "\n",
    "PreprocessingPlanner_prompt = \"\"\"\n",
    "You are an expert, execution-focused DataFrame analyzer. Your sole purpose is to create a specific and actionable preprocessing plan suitable for Exploratory Data Analysis (EDA).\n",
    "\n",
    "**CRITICAL INSTRUCTIONS:**\n",
    "\n",
    "1.  You MUST first call the `eda_fact_sheet` tool to analyze the data's schema and quality.\n",
    "2.  Based on the fact sheet, you will decide on a single, precise action for each column.\n",
    "3.  Your action for each column **MUST** be chosen from this exact list of approved commands:\n",
    "    - `none` (Use this if no change is needed.)\n",
    "    - `convert_to_datetime` (For date-like object/string columns.)\n",
    "    - `convert_to_time` (For time-like object/string columns.)\n",
    "    - `strip_whitespace` (For object/string columns with leading/trailing spaces.)\n",
    "    - `fill_missing_with_mean` (Use ONLY for numeric columns.)\n",
    "    - `fill_missing_with_median` (Use ONLY for numeric columns.)\n",
    "    - `fill_missing_with_mode` (Use for numeric or categorical columns.)\n",
    "    - `fill_missing_with_constant: 'VALUE'` (Replace 'VALUE' with a specific constant, e.g., 'Unknown' for strings, '00:00:00' for time.)\n",
    "    - `drop_column` (Use ONLY if a column is constant or a useless identifier.)\n",
    "\n",
    "4.  **SAFETY RULES:**\n",
    "    - Do NOT suggest any Machine Learning preparations (e.g., one-hot encoding, scaling).\n",
    "    - Do NOT suggest dropping rows. Handling missing values via filling is preferred.\n",
    "    - Your plan should only enable basic EDA (data type correction, cleaning, and imputation).\n",
    "\n",
    "**FINAL OUTPUT FORMATTING:**\n",
    "- After analyzing the fact sheet, your final answer **MUST** be a single, valid JSON object.\n",
    "- This JSON object must conform **EXACTLY** to the schema provided below.\n",
    "- Do NOT output any other text, explanation, or markdown.\n",
    "\n",
    "**Schema:**\n",
    "```json\n",
    "{\n",
    "  \"plan\": [\n",
    "    {\"column\": \"<column_name>\", \"action\": \"<chosen_command_from_list>\"},\n",
    "    ...\n",
    "  ],\n",
    "  \"summary\": \"<A concise, one-sentence summary of the overall plan.>\",\n",
    "  \"details\": \"<A detailed, human-readable summary of all the actions to be taken.>\"\n",
    "}\"\"\"\n",
    "\n",
    "\n",
    "\n",
    "cleaner_prompt = \"\"\"\n",
    "You are a data preprocessing execution agent. Your mission is to permanently modify a CSV file based on a given plan and **any previous validation feedback provided in the prompt**.\n",
    "\n",
    "You must follow these steps precisely:\n",
    "\n",
    "1.  **Analyze the Request:**\n",
    "    - Review the preprocessing plan.\n",
    "    - **CRITICAL:** Check if `Validation Feedback` is provided. If it is, your primary goal is to write Python code that **specifically fixes the reported errors** while still respecting the overall plan.\n",
    "\n",
    "2.  **Load Data**: Read the CSV file from the provided path into a pandas DataFrame.\n",
    "\n",
    "3.  **Apply Transformations**: Write and execute Python code to perform all required steps. You MUST write robust code to handle potential errors.\n",
    "    - **CRITICAL - For Date/Time Conversions**: When using `pd.to_datetime`, you MUST include the `errors='coerce'` parameter (e.g., `df['Time'] = pd.to_datetime(df['Time'], errors='coerce').dt.time`). This prevents the entire process from failing if it encounters a single invalid time format.\n",
    "    - **CRITICAL - For Dropping Columns**: Before attempting to drop a column, you MUST first check if it exists in the DataFrame (e.g., `if 'cash_type' in df.columns:`).\n",
    "\n",
    "4.  **Save Changes (CRITICAL STEP)**: After all transformations are applied, you MUST save the modified DataFrame back to the original file path to make the changes permanent. Use `df.to_csv(path, index=False)`.\n",
    "\n",
    "5.  **Format Final Output**: Your final answer MUST be a single, valid JSON object that strictly follows this schema:\n",
    "    ```json\n",
    "    {\"summary\": \"A concise, one-sentence summary of the cleaning outcome.\", \"details\": \"A detailed summary of all actions taken and confirmation of the save.\"}\n",
    "    ```\n",
    "\"\"\"\n",
    "\n",
    "validation_prompt = \"\"\"\n",
    "You are a hyper-vigilant and strict data validation agent. Your sole purpose is to programmatically verify that a data cleaning plan was executed correctly on a CSV file. You will use the `python_repl_ast` tool to run pandas code to check the file on disk.\n",
    "\n",
    "Your mission is to validate each action from the provided analysis plan. You must follow this Validation Playbook precisely:\n",
    "\n",
    "**Validation Playbook:**\n",
    "\n",
    "1.  **For \"convert to datetime\" actions:**\n",
    "    *   **Your primary method:** Attempt to reload the entire CSV using `pd.read_csv(path, parse_dates=['column_name_here'])`.\n",
    "    *   If this command executes without error, the validation is a **SUCCESS**.\n",
    "    *   If it raises an exception, it's a **FAILURE**.\n",
    "\n",
    "2.  **For \"strip whitespace\" actions:**\n",
    "    *   Load the CSV. Check if any value in the column contains leading/trailing whitespace using `df['column'].str.strip() != df['column']`. If this finds any `True` values, it's a **FAILURE**.\n",
    "\n",
    "3.  **For actions like \"fill missing with mean/median/mode\":**\n",
    "    *   Load the CSV. Check for any remaining nulls using `df['column'].isnull().sum()`. If the sum is greater than `0`, it's a **FAILURE**.\n",
    "\n",
    "4.  **For any other action:**\n",
    "    *   You must infer the most logical programmatic test.\n",
    "\n",
    "**Output Requirements (CRITICAL):**\n",
    "Your final answer **MUST** be a JSON object that strictly follows this schema:\n",
    "```json\n",
    "{\"status\": \"SUCCESS\" | \"FAILURE\", \"message\": \"Your finding\"}\"\"\"\n",
    "\n",
    "\n",
    "Reporter_prompt = \"\"\"You are an elite business intelligence consultant, renowned for your ability to parachute into any business, analyze a raw dataset, and emerge with a strategic plan that creates significant value. Your client, a business owner, has given you a CSV file and a simple request: \"Find the single biggest opportunity hidden in this data and tell me exactly how to capitalize on it.\"\n",
    "\n",
    "Your mission: Perform a comprehensive, hypothesis-driven analysis of the provided data. You must autonomously identify the key metrics, dimensions, and relationships within the dataset to build a compelling business case study.\n",
    "\n",
    "Your Tools:\n",
    "1. `eda_fact_sheet(df_path)`: Use this once at the very beginning to perform initial data reconnaissance.\n",
    "2. `python_repl_ast`: This is your primary analytical tool. You will use it multiple times to explore hypotheses, segment the data, and quantify your findings.\n",
    "\n",
    "---\n",
    "\n",
    "### Your Mandated Investigative Framework:\n",
    "\n",
    "1.  **Data Reconnaissance & Profiling:** Use `eda_fact_sheet` to get a high-level overview.\n",
    "2.  **Hypothesis Generation & Deep-Dive Analysis:** After your initial recon, form hypotheses about the data and use `python_repl_ast` to test them, covering:\n",
    "    - **Core Metric Identification:** What are the most important KPIs? (e.g., `Sales`, `Revenue`, `Profit`).\n",
    "    - **Dimensional Analysis:** How do the core metrics perform across different segments? (e.g., `Region`, `Product_Category`).\n",
    "    - **Temporal Analysis:** Are there trends over time? (e.g., year-over-year growth, seasonality).\n",
    "    - **Correlation & Relationship Analysis:** How do numerical features interact?\n",
    "    - **Segmentation & Outlier Analysis:** Can you identify distinct groups or outliers?\n",
    "3.  **Synthesize and Report:** After your investigation, you must weave all your quantitative findings into the mandatory JSON report format below.\n",
    "\n",
    "---\n",
    "\n",
    "### Mandatory Report Structure (To be formatted as a JSON object):\n",
    "\n",
    "- **Subject:** \"Strategic Deep-Dive: Unlocking Growth Opportunities in [Dataset Theme]\"\n",
    "- **Executive Summary:** A brief, 3-4 sentence overview for a C-suite audience.\n",
    "- **Current State of the Business:** An overview of macro trends and key segments.\n",
    "- **The Core Insight:** Detail your main finding with specific, hard numbers.\n",
    "- **Supporting Analysis:** Add layers with other detailed findings (e.g., temporal or behavioral patterns).\n",
    "- **The Go-Forward Strategic Plan:** A multi-phase action plan.\n",
    "    - **Phase 1: Immediate Realignment & Proof of Concept (Next 30 Days):** Detail a strategic focus shift and an initial test.\n",
    "    - **Phase 2: Scale & Market Capture (Next Quarter):** Describe a full-scale rollout and operational adjustments.\n",
    "- **Metrics for Success:** A list of KPIs to track the plan's success.\n",
    "\n",
    "---\n",
    "\n",
    "### **FINAL OUTPUT FORMATTING (CRITICAL):**\n",
    "- After completing your entire analysis using your tools, your final answer **MUST** be a single, valid JSON object.\n",
    "- This JSON object must conform **EXACTLY** to the schema of the `BusinessReport` model.\n",
    "- **Do NOT output any other text, explanation, or markdown.** Your entire final response must be only the JSON object.\n",
    "\"\"\"\n",
    "\n",
    "VISUALIZATION_PROMPT = \"\"\"\n",
    "You are an expert Data Analyst serving a business owner. Your mission is to identify the **5 to 7 most impactful business insights** from the provided CSV dataset and present them as professional-quality visualizations. The goal is quality over quantity.\n",
    "\n",
    "**Your Mandated Workflow:**\n",
    "\n",
    "1.  **Initial Reconnaissance:** You MUST first call the `eda_fact_sheet` tool on the provided `df_path` to understand the data's structure and content.\n",
    "2.  **Strategic Visualization Plan:** After analyzing the fact sheet, you must formulate a plan to create between 5 and 7 highly relevant visualizations. Do not create more than 7. Focus on visuals that directly support key business decisions (e.g., top-selling products, sales trends, customer behavior).\n",
    "3.  **Iterative Generation:** For each planned visualization, you MUST perform the following steps:\n",
    "    a. Use the `python_repl_ast` tool to write and execute Python code using `pandas`, `matplotlib`, and `seaborn`.\n",
    "    b. Your code MUST generate a high-quality plot with a clear, business-focused title and labeled X/Y axes.\n",
    "    c. You MUST save the plot as a unique `.png` file into the `visualizations/` directory using a descriptive filename.\n",
    "    d. You MUST use `plt.close()` after saving each plot to manage memory.\n",
    "\n",
    "**CRITICAL FINAL OUTPUT INSTRUCTION:**\n",
    "\n",
    "- After you have generated and saved your **final** planned visualization (between 5 and 7 total), your next and **ABSOLUTELY FINAL action** is to output a single, valid JSON object.\n",
    "- This JSON object **MUST** conform exactly to the `VisualizationReport` schema provided. It will contain a list of objects, where each object details a visualization you created.\n",
    "- **DO NOT** call the `python_repl_ast` tool again after you have finished creating your plots. Your sole focus must be on generating the final JSON report.\n",
    "- **DO NOT** output any other text, markdown, or explanation. Your entire final response must be only the JSON object.\n",
    "\"\"\""
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 19,
   "id": "991afff6",
   "metadata": {},
   "outputs": [],
   "source": [
    "import pandas as pd\n",
    "import numpy as np\n",
    "\n",
    "def eda_fact_sheet_bakery(path: str, sample_size: int = 3, freq_top: int = 3):\n",
    "    \"\"\"\n",
    "    Generates a batchwise fact sheet for a dataset.\n",
    "\n",
    "    Args:\n",
    "        path (str): Path to CSV or Excel dataset.\n",
    "        sample_size (int): Number of example values per column.\n",
    "        freq_top (int): Number of top frequent values per column.\n",
    "\n",
    "    Returns:\n",
    "        dict: Fact sheet containing dataset-level info and column-level stats in batches.\n",
    "    \"\"\"\n",
    "    # --- Load dataset ---\n",
    "    if path.endswith(\".csv\"):\n",
    "        df = pd.read_csv(path)\n",
    "    elif path.endswith(\".xlsx\") or path.endswith(\".xls\"):\n",
    "        df = pd.read_excel(path)\n",
    "    else:\n",
    "        raise ValueError(\"Unsupported file format. Use CSV or Excel.\")\n",
    "\n",
    "    n_rows, n_columns = df.shape\n",
    "\n",
    "    fact_sheet = {\n",
    "        \"n_rows\": n_rows,\n",
    "        \"n_columns\": n_columns,\n",
    "        \"batches\": []\n",
    "    }\n",
    "\n",
    "    # --- Determine batch splits ---\n",
    "    batch_size = 15\n",
    "    batch_splits = [df.columns[i:i+batch_size].tolist() for i in range(0, n_columns, batch_size)]\n",
    "\n",
    "    # --- Process each batch ---\n",
    "    for batch_cols in batch_splits:\n",
    "        batch_profile = {\"columns\": {}}\n",
    "        for col in batch_cols:\n",
    "            series = df[col]\n",
    "            col_profile = {}\n",
    "\n",
    "            total = len(series)\n",
    "\n",
    "            # Core stats\n",
    "            col_profile[\"dtype\"] = str(series.dtype)\n",
    "            col_profile[\"null_percent\"] = round(float(series.isna().sum() / total * 100), 2)\n",
    "            col_profile[\"unique_percent\"] = round(float(series.nunique(dropna=True) / total * 100), 2)\n",
    "\n",
    "            # Example values\n",
    "            try:\n",
    "                col_profile[\"examples\"] = series.dropna().sample(\n",
    "                    min(sample_size, series.dropna().shape[0]),\n",
    "                    random_state=42\n",
    "                ).tolist()\n",
    "            except ValueError:\n",
    "                col_profile[\"examples\"] = []\n",
    "\n",
    "            # Top frequent values\n",
    "            if not series.isna().all():\n",
    "                top_freq = series.value_counts(dropna=True).head(freq_top)\n",
    "                col_profile[\"top_values\"] = {str(k): int(v) for k, v in top_freq.to_dict().items()}\n",
    "\n",
    "            # Numeric columns\n",
    "            if pd.api.types.is_numeric_dtype(series):\n",
    "                col_profile.update({\n",
    "                    \"min\": float(series.min(skipna=True)),\n",
    "                    \"max\": float(series.max(skipna=True)),\n",
    "                    \"mean\": float(series.mean(skipna=True)),\n",
    "                    \"std\": float(series.std(skipna=True))\n",
    "                })\n",
    "                if series.std(skipna=True) > 0:\n",
    "                    z_scores = ((series - series.mean(skipna=True)) / series.std(skipna=True)).abs()\n",
    "                    col_profile[\"has_outliers\"] = bool((z_scores > 3).any())\n",
    "                else:\n",
    "                    col_profile[\"has_outliers\"] = False\n",
    "\n",
    "            # Datetime columns\n",
    "            elif pd.api.types.is_datetime64_any_dtype(series):\n",
    "                if not series.dropna().empty:\n",
    "                    col_profile[\"min_date\"] = str(series.min())\n",
    "                    col_profile[\"max_date\"] = str(series.max())\n",
    "\n",
    "            # Text/categorical columns\n",
    "            elif pd.api.types.is_object_dtype(series):\n",
    "                lengths = series.dropna().astype(str).map(len)\n",
    "                if not lengths.empty:\n",
    "                    col_profile[\"avg_length\"] = float(lengths.mean())\n",
    "                    col_profile[\"max_length\"] = int(lengths.max())\n",
    "                unusual = series.dropna().astype(str).str.contains(r\"[^a-zA-Z0-9\\s]\", regex=True).sum()\n",
    "                col_profile[\"unusual_char_percent\"] = round(float(unusual / total * 100), 2)\n",
    "\n",
    "            # Flags\n",
    "            if series.nunique(dropna=True) == total:\n",
    "                col_profile[\"is_identifier\"] = True\n",
    "            elif series.nunique(dropna=True) <= 1:\n",
    "                col_profile[\"is_constant\"] = True\n",
    "\n",
    "            batch_profile[\"columns\"][col] = col_profile\n",
    "\n",
    "        fact_sheet[\"batches\"].append(batch_profile)\n",
    "\n",
    "    return fact_sheet\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 20,
   "id": "e10c0ea4",
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "{'n_rows': 234005,\n",
       " 'n_columns': 7,\n",
       " 'batches': [{'columns': {'Unnamed: 0': {'dtype': 'int64',\n",
       "     'null_percent': 0.0,\n",
       "     'unique_percent': 100.0,\n",
       "     'examples': [254689, 147840, 321961],\n",
       "     'top_values': {'0': 1, '1': 1, '4': 1},\n",
       "     'min': 0.0,\n",
       "     'max': 511395.0,\n",
       "     'mean': 255205.03585393474,\n",
       "     'std': 147501.62599208727,\n",
       "     'has_outliers': False,\n",
       "     'is_identifier': True},\n",
       "    'date': {'dtype': 'object',\n",
       "     'null_percent': 0.0,\n",
       "     'unique_percent': 0.26,\n",
       "     'examples': ['2021-11-04', '2021-07-19', '2022-03-07'],\n",
       "     'top_values': {'2022-08-14': 997, '2021-08-15': 961, '2022-07-17': 941},\n",
       "     'avg_length': 10.0,\n",
       "     'max_length': 10,\n",
       "     'unusual_char_percent': 100.0},\n",
       "    'time': {'dtype': 'object',\n",
       "     'null_percent': 0.0,\n",
       "     'unique_percent': 0.29,\n",
       "     'examples': ['12:37', '19:14', '16:20'],\n",
       "     'top_values': {'11:43': 859, '11:46': 850, '12:11': 850},\n",
       "     'avg_length': 5.0,\n",
       "     'max_length': 5,\n",
       "     'unusual_char_percent': 100.0},\n",
       "    'ticket_number': {'dtype': 'float64',\n",
       "     'null_percent': 0.0,\n",
       "     'unique_percent': 58.31,\n",
       "     'examples': [218841.0, 190030.0, 237182.0],\n",
       "     'top_values': {'225766.0': 13, '202116.0': 12, '155163.0': 12},\n",
       "     'min': 150040.0,\n",
       "     'max': 288913.0,\n",
       "     'mean': 219201.25873806115,\n",
       "     'std': 40053.22389631496,\n",
       "     'has_outliers': False},\n",
       "    'article': {'dtype': 'object',\n",
       "     'null_percent': 0.0,\n",
       "     'unique_percent': 0.06,\n",
       "     'examples': ['MOISSON', 'COUPE', 'BAGUETTE'],\n",
       "     'top_values': {'TRADITIONAL BAGUETTE': 67689,\n",
       "      'COUPE': 20470,\n",
       "      'BAGUETTE': 15292},\n",
       "     'avg_length': 12.91998461571334,\n",
       "     'max_length': 24,\n",
       "     'unusual_char_percent': 0.26},\n",
       "    'Quantity': {'dtype': 'float64',\n",
       "     'null_percent': 0.0,\n",
       "     'unique_percent': 0.02,\n",
       "     'examples': [1.0, 1.0, 1.0],\n",
       "     'top_values': {'1.0': 156712, '2.0': 49367, '3.0': 13677},\n",
       "     'min': -200.0,\n",
       "     'max': 200.0,\n",
       "     'mean': 1.538377385098609,\n",
       "     'std': 1.2896033140596856,\n",
       "     'has_outliers': True},\n",
       "    'unit_price': {'dtype': 'object',\n",
       "     'null_percent': 0.0,\n",
       "     'unique_percent': 0.05,\n",
       "     'examples': ['2,00 €', '0,15 €', '0,95 €'],\n",
       "     'top_values': {'1,20 €': 49080, '0,15 €': 20471, '1,30 €': 19778},\n",
       "     'avg_length': 6.006734898826948,\n",
       "     'max_length': 7,\n",
       "     'unusual_char_percent': 100.0}}}]}"
      ]
     },
     "execution_count": 20,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "eda_fact_sheet_bakery(r\"D:\\Code Assistant\\Bakery sales.csv\")"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 17,
   "id": "d79b1adf",
   "metadata": {},
   "outputs": [],
   "source": [
    "def eda_fact_sheet_bakery(sample_size: int = 3, freq_top: int = 3):\n",
    "    \"\"\"\n",
    "    Returns a fact sheet for the 'Bakery sales.csv' dataset.\n",
    "    \n",
    "    Args:\n",
    "        sample_size (int): Number of random sample values to show per column.\n",
    "        freq_top (int): Number of top frequent values to display.\n",
    "    \"\"\"\n",
    "    path = r\"D:\\Code Assistant\\Bakery sales.csv\"  # dataset path\n",
    "\n",
    "    # --- load dataset ---\n",
    "    if path.endswith(\".csv\"):\n",
    "        df = pd.read_csv(path)\n",
    "    elif path.endswith(\".xlsx\") or path.endswith(\".xls\"):\n",
    "        df = pd.read_excel(path)\n",
    "    else:\n",
    "        raise ValueError(\"Unsupported file format. Use CSV or Excel.\")\n",
    "\n",
    "    fact_sheet = {\n",
    "        \"n_rows\": len(df),\n",
    "        \"n_columns\": len(df.columns),\n",
    "        \"batches\": []\n",
    "    }\n",
    "\n",
    "    # --- decide split logic ---\n",
    "    n_cols = len(df.columns)\n",
    "    if n_cols <= 15:\n",
    "        batch_splits = [df.columns.tolist()]\n",
    "    elif n_cols <= 30:\n",
    "        mid = n_cols // 2\n",
    "        batch_splits = [df.columns[:mid].tolist(), df.columns[mid:].tolist()]\n",
    "    else:\n",
    "        batch_splits = [df.columns[i:i+15].tolist() for i in range(0, n_cols, 15)]\n",
    "\n",
    "    # --- process each batch ---\n",
    "    for batch_cols in batch_splits:\n",
    "        batch_profile = {\"columns\": {}}\n",
    "        for col in batch_cols:\n",
    "            series = df[col]\n",
    "            col_profile = {}\n",
    "            total = len(series)\n",
    "\n",
    "            # Core stats\n",
    "            col_profile[\"dtype\"] = str(series.dtype)\n",
    "            col_profile[\"null_percent\"] = round((series.isna().sum() / total) * 100, 2)\n",
    "            col_profile[\"unique_percent\"] = round((series.nunique(dropna=True) / total) * 100, 2)\n",
    "\n",
    "            # Example values\n",
    "            try:\n",
    "                col_profile[\"examples\"] = series.dropna().sample(\n",
    "                    min(sample_size, series.dropna().shape[0]),\n",
    "                    random_state=42\n",
    "                ).tolist()\n",
    "            except ValueError:\n",
    "                col_profile[\"examples\"] = []\n",
    "\n",
    "            # Top frequent values\n",
    "            if not series.isna().all():\n",
    "                top_freq = series.value_counts(dropna=True).head(freq_top)\n",
    "                col_profile[\"top_values\"] = top_freq.to_dict()\n",
    "\n",
    "            # Numeric columns\n",
    "            if pd.api.types.is_numeric_dtype(series):\n",
    "                col_profile.update({\n",
    "                    \"min\": float(series.min(skipna=True)),\n",
    "                    \"max\": float(series.max(skipna=True)),\n",
    "                    \"mean\": float(series.mean(skipna=True)),\n",
    "                    \"std\": float(series.std(skipna=True))\n",
    "                })\n",
    "                if series.std(skipna=True) > 0:\n",
    "                    z_scores = ((series - series.mean(skipna=True)) / series.std(skipna=True)).abs()\n",
    "                    col_profile[\"has_outliers\"] = bool((z_scores > 3).any())\n",
    "                else:\n",
    "                    col_profile[\"has_outliers\"] = False\n",
    "\n",
    "            # Datetime columns\n",
    "            elif pd.api.types.is_datetime64_any_dtype(series):\n",
    "                if not series.dropna().empty:\n",
    "                    col_profile[\"min_date\"] = str(series.min())\n",
    "                    col_profile[\"max_date\"] = str(series.max())\n",
    "\n",
    "            # Text/categorical columns\n",
    "            elif pd.api.types.is_object_dtype(series):\n",
    "                lengths = series.dropna().astype(str).map(len)\n",
    "                if not lengths.empty:\n",
    "                    col_profile[\"avg_length\"] = float(lengths.mean())\n",
    "                    col_profile[\"max_length\"] = int(lengths.max())\n",
    "                unusual = series.dropna().astype(str).str.contains(r\"[^a-zA-Z0-9\\s]\", regex=True).sum()\n",
    "                col_profile[\"unusual_char_percent\"] = round((unusual / total) * 100, 2)\n",
    "\n",
    "            # Flags\n",
    "            if series.nunique(dropna=True) == total:\n",
    "                col_profile[\"is_identifier\"] = True\n",
    "            elif series.nunique(dropna=True) <= 1:\n",
    "                col_profile[\"is_constant\"] = True\n",
    "\n",
    "            batch_profile[\"columns\"][col] = col_profile\n",
    "\n",
    "        fact_sheet[\"batches\"].append(batch_profile)\n",
    "\n",
    "    return fact_sheet\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "2bb01335",
   "metadata": {},
   "outputs": [],
   "source": []
  },
  {
   "cell_type": "code",
   "execution_count": 18,
   "id": "155309ff",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "{'n_rows': 234005, 'n_columns': 7, 'batches': [{'columns': {'Unnamed: 0': {'dtype': 'int64', 'null_percent': np.float64(0.0), 'unique_percent': 100.0, 'examples': [254689, 147840, 321961], 'top_values': {0: 1, 1: 1, 4: 1}, 'min': 0.0, 'max': 511395.0, 'mean': 255205.03585393474, 'std': 147501.62599208727, 'has_outliers': False, 'is_identifier': True}, 'date': {'dtype': 'object', 'null_percent': np.float64(0.0), 'unique_percent': 0.26, 'examples': ['2021-11-04', '2021-07-19', '2022-03-07'], 'top_values': {'2022-08-14': 997, '2021-08-15': 961, '2022-07-17': 941}, 'avg_length': 10.0, 'max_length': 10, 'unusual_char_percent': np.float64(100.0)}, 'time': {'dtype': 'object', 'null_percent': np.float64(0.0), 'unique_percent': 0.29, 'examples': ['12:37', '19:14', '16:20'], 'top_values': {'11:43': 859, '11:46': 850, '12:11': 850}, 'avg_length': 5.0, 'max_length': 5, 'unusual_char_percent': np.float64(100.0)}, 'ticket_number': {'dtype': 'float64', 'null_percent': np.float64(0.0), 'unique_percent': 58.31, 'examples': [218841.0, 190030.0, 237182.0], 'top_values': {225766.0: 13, 202116.0: 12, 155163.0: 12}, 'min': 150040.0, 'max': 288913.0, 'mean': 219201.25873806115, 'std': 40053.22389631496, 'has_outliers': False}, 'article': {'dtype': 'object', 'null_percent': np.float64(0.0), 'unique_percent': 0.06, 'examples': ['MOISSON', 'COUPE', 'BAGUETTE'], 'top_values': {'TRADITIONAL BAGUETTE': 67689, 'COUPE': 20470, 'BAGUETTE': 15292}, 'avg_length': 12.91998461571334, 'max_length': 24, 'unusual_char_percent': np.float64(0.26)}, 'Quantity': {'dtype': 'float64', 'null_percent': np.float64(0.0), 'unique_percent': 0.02, 'examples': [1.0, 1.0, 1.0], 'top_values': {1.0: 156712, 2.0: 49367, 3.0: 13677}, 'min': -200.0, 'max': 200.0, 'mean': 1.538377385098609, 'std': 1.2896033140596856, 'has_outliers': True}, 'unit_price': {'dtype': 'object', 'null_percent': np.float64(0.0), 'unique_percent': 0.05, 'examples': ['2,00 €', '0,15 €', '0,95 €'], 'top_values': {'1,20 €': 49080, '0,15 €': 20471, '1,30 €': 19778}, 'avg_length': 6.006734898826948, 'max_length': 7, 'unusual_char_percent': np.float64(100.0)}}}]}\n"
     ]
    }
   ],
   "source": [
    "fact_sheet = eda_fact_sheet_bakery()\n",
    "print(fact_sheet)\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 4,
   "id": "a2a8602d",
   "metadata": {},
   "outputs": [],
   "source": [
    "from langchain_groq import ChatGroq\n",
    "llm = ChatGroq(temperature=0, model_name=\"openai/gpt-oss-120b\")"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 5,
   "id": "82232a14",
   "metadata": {},
   "outputs": [],
   "source": [
    "# Import relevant functionality\n",
    "from langchain.chat_models import init_chat_model\n",
    "from langchain_tavily import TavilySearch\n",
    "from langgraph.checkpoint.memory import MemorySaver\n",
    "from langgraph.prebuilt import create_react_agent\n",
    "\n",
    "# Create the agent\n",
    "memory = MemorySaver()\n",
    "model = llm\n",
    "search = TavilySearch(max_results=2)\n",
    "tools = [search]\n",
    "agent_executor = create_react_agent(model, tools, checkpointer=memory)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 6,
   "id": "cb1a3fe4",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "================================\u001b[1m Human Message \u001b[0m=================================\n",
      "\n",
      "Hi, I'm Bob and I live in SF.\n",
      "==================================\u001b[1m Ai Message \u001b[0m==================================\n",
      "\n",
      "Hi Bob! 👋 Great to meet you. How can I help you today?\n"
     ]
    }
   ],
   "source": [
    "# Use the agent\n",
    "config = {\"configurable\": {\"thread_id\": \"abc123\"}}\n",
    "\n",
    "input_message = {\n",
    "    \"role\": \"user\",\n",
    "    \"content\": \"Hi, I'm Bob and I live in SF.\",\n",
    "}\n",
    "for step in agent_executor.stream(\n",
    "    {\"messages\": [input_message]}, config, stream_mode=\"values\"\n",
    "):\n",
    "    step[\"messages\"][-1].pretty_print()"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 8,
   "id": "6d1b9914",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "================================\u001b[1m Human Message \u001b[0m=================================\n",
      "\n",
      "What's my name and where do i live?\n",
      "==================================\u001b[1m Ai Message \u001b[0m==================================\n",
      "\n",
      "You introduced yourself as **Bob**, and you mentioned that you live in **San Francisco (SF)**.\n"
     ]
    }
   ],
   "source": [
    "input_message = {\n",
    "    \"role\": \"user\",\n",
    "    \"content\": \"What's my name and where do i live?\",\n",
    "}\n",
    "\n",
    "for step in agent_executor.stream(\n",
    "    {\"messages\": [input_message]}, config, stream_mode=\"values\"\n",
    "):\n",
    "    step[\"messages\"][-1].pretty_print()"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 11,
   "id": "a1c44f76",
   "metadata": {},
   "outputs": [],
   "source": [
    "import getpass\n",
    "import os\n",
    "\n",
    "if not os.environ.get(\"GROQ_API_KEY\"):\n",
    "  os.environ[\"GROQ_API_KEY\"] = getpass.getpass(\"Enter API key for Groq: \")\n",
    "\n",
    "from langchain.chat_models import init_chat_model\n",
    "\n",
    "model = init_chat_model(\"openai/gpt-oss-120b\", model_provider=\"groq\")"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 12,
   "id": "f3b5e365",
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "'Hello! How can I help you today?'"
      ]
     },
     "execution_count": 12,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "query = \"Hi!\"\n",
    "response = model.invoke([{\"role\": \"user\", \"content\": query}])\n",
    "response.text()"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 16,
   "id": "46488eea",
   "metadata": {},
   "outputs": [],
   "source": [
    "df = pd.read_csv(\"Bakery sales.csv\")"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 15,
   "id": "c8e23c5e",
   "metadata": {},
   "outputs": [],
   "source": [
    "import pandas as pd\n",
    "from langchain_groq import ChatGroq\n",
    "from langchain.agents import AgentExecutor, create_tool_calling_agent\n",
    "from langchain_core.prompts import ChatPromptTemplate\n",
    "from langchain_core.tools import tool\n",
    "from pydantic import BaseModel, Field\n",
    "import sys\n",
    "from io import StringIO\n",
    "\n",
    "class PythonInputs(BaseModel):\n",
    "    query: str = Field(description=\"A valid python command to run.\")\n",
    "\n",
    "# 3. Create the tool using the @tool decorator. This is the gold standard.\n",
    "@tool(args_schema=PythonInputs)\n",
    "def python_repl_ast(query: str) -> str:\n",
    "    \"\"\"\n",
    "    Runs a Python command and returns the result.\n",
    "    The command has access to a pandas DataFrame named `df`.\n",
    "    \"\"\"\n",
    "    # Create a restricted namespace for the execution to see the DataFrame\n",
    "    local_namespace = {\"df\": df}\n",
    "    global_namespace = {}\n",
    "\n",
    "    # Capture stdout to return print() statements\n",
    "    old_stdout = sys.stdout\n",
    "    sys.stdout = captured_output = StringIO()\n",
    "\n",
    "    try:\n",
    "        # Execute the code\n",
    "        exec(query, global_namespace, local_namespace)\n",
    "        \n",
    "        # Get the output\n",
    "        output = captured_output.getvalue()\n",
    "        if output:\n",
    "            return output\n",
    "        else:\n",
    "            # If nothing was printed, try to eval the last line for a result\n",
    "            try:\n",
    "                # Split the query into lines and eval the last non-empty one\n",
    "                lines = [line for line in query.strip().split('\\n') if line.strip()]\n",
    "                if lines:\n",
    "                    last_line_result = eval(lines[-1], global_namespace, local_namespace)\n",
    "                    return str(last_line_result)\n",
    "                else:\n",
    "                    return \"Executed successfully, but no output was produced.\"\n",
    "            except Exception:\n",
    "                 return \"Executed successfully, but no output was produced.\"\n",
    "\n",
    "    except Exception as e:\n",
    "        return f\"Execution failed with error: {e}\"\n",
    "    finally:\n",
    "        # Restore stdout\n",
    "        sys.stdout = old_stdout\n",
    "\n",
    "tools = [python_repl_ast]"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 17,
   "id": "fff3d56a",
   "metadata": {},
   "outputs": [],
   "source": [
    "model_with_tools = model.bind_tools(tools)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 22,
   "id": "21f60152",
   "metadata": {},
   "outputs": [
    {
     "ename": "TypeError",
     "evalue": "'str' object is not callable",
     "output_type": "error",
     "traceback": [
      "\u001b[31m---------------------------------------------------------------------------\u001b[39m",
      "\u001b[31mTypeError\u001b[39m                                 Traceback (most recent call last)",
      "\u001b[36mCell\u001b[39m\u001b[36m \u001b[39m\u001b[32mIn[22]\u001b[39m\u001b[32m, line 4\u001b[39m\n\u001b[32m      1\u001b[39m query = \u001b[33m\"\u001b[39m\u001b[33mGive the overview of the dataframe which the tool has access and the preprocessing steps needed to perform EDA on .\u001b[39m\u001b[33m\"\u001b[39m\n\u001b[32m      2\u001b[39m response = model_with_tools.invoke([{\u001b[33m\"\u001b[39m\u001b[33mrole\u001b[39m\u001b[33m\"\u001b[39m: \u001b[33m\"\u001b[39m\u001b[33muser\u001b[39m\u001b[33m\"\u001b[39m, \u001b[33m\"\u001b[39m\u001b[33mcontent\u001b[39m\u001b[33m\"\u001b[39m: query}])\n\u001b[32m----> \u001b[39m\u001b[32m4\u001b[39m \u001b[38;5;28mprint\u001b[39m(\u001b[33mf\u001b[39m\u001b[33m\"\u001b[39m\u001b[33mMessage content: \u001b[39m\u001b[38;5;132;01m{\u001b[39;00m\u001b[43mresponse\u001b[49m\u001b[43m.\u001b[49m\u001b[43mcontent\u001b[49m\u001b[43m(\u001b[49m\u001b[43m)\u001b[49m\u001b[38;5;132;01m}\u001b[39;00m\u001b[38;5;130;01m\\n\u001b[39;00m\u001b[33m\"\u001b[39m)\n",
      "\u001b[31mTypeError\u001b[39m: 'str' object is not callable"
     ]
    }
   ],
   "source": [
    "query = \"Give the overview of the dataframe which the tool has access and the preprocessing steps needed to perform EDA on .\"\n",
    "response = model_with_tools.invoke([{\"role\": \"user\", \"content\": query}])\n",
    "\n",
    "print(f\"Message content: {response.content()}\\n\")\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 21,
   "id": "3584b90f",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Tool calls: [{'name': 'python_repl_ast', 'args': {'query': \"import pandas as pd\\nprint('Shape:', df.shape)\\nprint('\\\\nColumns:', df.columns.tolist())\\nprint('\\\\nHead:')\\nprint(df.head())\\nprint('\\\\nInfo:')\\nprint(df.info())\\nprint('\\\\nDescribe:')\\nprint(df.describe(include='all'))\"}, 'id': 'fc_4d928c8c-d74b-47db-b093-c5dac571064e', 'type': 'tool_call'}]\n"
     ]
    }
   ],
   "source": [
    "print(f\"Tool calls: {response.tool_calls}\")"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 27,
   "id": "266e239b",
   "metadata": {},
   "outputs": [
    {
     "ename": "BadRequestError",
     "evalue": "Error code: 400 - {'error': {'message': \"'messages' : minimum number of items is 1\", 'type': 'invalid_request_error'}}",
     "output_type": "error",
     "traceback": [
      "\u001b[31m---------------------------------------------------------------------------\u001b[39m",
      "\u001b[31mBadRequestError\u001b[39m                           Traceback (most recent call last)",
      "\u001b[36mCell\u001b[39m\u001b[36m \u001b[39m\u001b[32mIn[27]\u001b[39m\u001b[32m, line 51\u001b[39m\n\u001b[32m     47\u001b[39m \u001b[38;5;66;03m# -------------------------\u001b[39;00m\n\u001b[32m     48\u001b[39m \u001b[38;5;66;03m# 5. Run query\u001b[39;00m\n\u001b[32m     49\u001b[39m \u001b[38;5;66;03m# -------------------------\u001b[39;00m\n\u001b[32m     50\u001b[39m query = \u001b[33m\"\u001b[39m\u001b[33mGive the overview of the dataframe `df` and the preprocessing steps needed for EDA.\u001b[39m\u001b[33m\"\u001b[39m\n\u001b[32m---> \u001b[39m\u001b[32m51\u001b[39m response = \u001b[43magent_executor\u001b[49m\u001b[43m.\u001b[49m\u001b[43minvoke\u001b[49m\u001b[43m(\u001b[49m\n\u001b[32m     52\u001b[39m \u001b[43m    \u001b[49m\u001b[43m{\u001b[49m\u001b[33;43m\"\u001b[39;49m\u001b[33;43minput\u001b[39;49m\u001b[33;43m\"\u001b[39;49m\u001b[43m:\u001b[49m\u001b[43m \u001b[49m\u001b[33;43m\"\u001b[39;49m\u001b[33;43mGive the overview of the dataframe `df` and the preprocessing steps needed for EDA.\u001b[39;49m\u001b[33;43m\"\u001b[39;49m\u001b[43m}\u001b[49m\u001b[43m,\u001b[49m\n\u001b[32m     53\u001b[39m \u001b[43m    \u001b[49m\u001b[43mconfig\u001b[49m\u001b[43m=\u001b[49m\u001b[43m{\u001b[49m\u001b[33;43m\"\u001b[39;49m\u001b[33;43mconfigurable\u001b[39;49m\u001b[33;43m\"\u001b[39;49m\u001b[43m:\u001b[49m\u001b[43m \u001b[49m\u001b[43m{\u001b[49m\u001b[33;43m\"\u001b[39;49m\u001b[33;43mthread_id\u001b[39;49m\u001b[33;43m\"\u001b[39;49m\u001b[43m:\u001b[49m\u001b[43m \u001b[49m\u001b[33;43m\"\u001b[39;49m\u001b[33;43mpreprocess-session-1\u001b[39;49m\u001b[33;43m\"\u001b[39;49m\u001b[43m}\u001b[49m\u001b[43m}\u001b[49m\n\u001b[32m     54\u001b[39m \u001b[43m)\u001b[49m\n\u001b[32m     57\u001b[39m \u001b[38;5;28mprint\u001b[39m(\u001b[33m\"\u001b[39m\u001b[38;5;130;01m\\n\u001b[39;00m\u001b[33m=== FINAL OUTPUT ===\u001b[39m\u001b[33m\"\u001b[39m)\n\u001b[32m     58\u001b[39m \u001b[38;5;28mprint\u001b[39m(response[\u001b[33m\"\u001b[39m\u001b[33moutput\u001b[39m\u001b[33m\"\u001b[39m])\n",
      "\u001b[36mFile \u001b[39m\u001b[32md:\\Code Assistant\\venv\\Lib\\site-packages\\langgraph\\pregel\\main.py:3026\u001b[39m, in \u001b[36mPregel.invoke\u001b[39m\u001b[34m(self, input, config, context, stream_mode, print_mode, output_keys, interrupt_before, interrupt_after, durability, **kwargs)\u001b[39m\n\u001b[32m   3023\u001b[39m chunks: \u001b[38;5;28mlist\u001b[39m[\u001b[38;5;28mdict\u001b[39m[\u001b[38;5;28mstr\u001b[39m, Any] | Any] = []\n\u001b[32m   3024\u001b[39m interrupts: \u001b[38;5;28mlist\u001b[39m[Interrupt] = []\n\u001b[32m-> \u001b[39m\u001b[32m3026\u001b[39m \u001b[43m\u001b[49m\u001b[38;5;28;43;01mfor\u001b[39;49;00m\u001b[43m \u001b[49m\u001b[43mchunk\u001b[49m\u001b[43m \u001b[49m\u001b[38;5;129;43;01min\u001b[39;49;00m\u001b[43m \u001b[49m\u001b[38;5;28;43mself\u001b[39;49m\u001b[43m.\u001b[49m\u001b[43mstream\u001b[49m\u001b[43m(\u001b[49m\n\u001b[32m   3027\u001b[39m \u001b[43m    \u001b[49m\u001b[38;5;28;43minput\u001b[39;49m\u001b[43m,\u001b[49m\n\u001b[32m   3028\u001b[39m \u001b[43m    \u001b[49m\u001b[43mconfig\u001b[49m\u001b[43m,\u001b[49m\n\u001b[32m   3029\u001b[39m \u001b[43m    \u001b[49m\u001b[43mcontext\u001b[49m\u001b[43m=\u001b[49m\u001b[43mcontext\u001b[49m\u001b[43m,\u001b[49m\n\u001b[32m   3030\u001b[39m \u001b[43m    \u001b[49m\u001b[43mstream_mode\u001b[49m\u001b[43m=\u001b[49m\u001b[43m[\u001b[49m\u001b[33;43m\"\u001b[39;49m\u001b[33;43mupdates\u001b[39;49m\u001b[33;43m\"\u001b[39;49m\u001b[43m,\u001b[49m\u001b[43m \u001b[49m\u001b[33;43m\"\u001b[39;49m\u001b[33;43mvalues\u001b[39;49m\u001b[33;43m\"\u001b[39;49m\u001b[43m]\u001b[49m\n\u001b[32m   3031\u001b[39m \u001b[43m    \u001b[49m\u001b[38;5;28;43;01mif\u001b[39;49;00m\u001b[43m \u001b[49m\u001b[43mstream_mode\u001b[49m\u001b[43m \u001b[49m\u001b[43m==\u001b[49m\u001b[43m \u001b[49m\u001b[33;43m\"\u001b[39;49m\u001b[33;43mvalues\u001b[39;49m\u001b[33;43m\"\u001b[39;49m\n\u001b[32m   3032\u001b[39m \u001b[43m    \u001b[49m\u001b[38;5;28;43;01melse\u001b[39;49;00m\u001b[43m \u001b[49m\u001b[43mstream_mode\u001b[49m\u001b[43m,\u001b[49m\n\u001b[32m   3033\u001b[39m \u001b[43m    \u001b[49m\u001b[43mprint_mode\u001b[49m\u001b[43m=\u001b[49m\u001b[43mprint_mode\u001b[49m\u001b[43m,\u001b[49m\n\u001b[32m   3034\u001b[39m \u001b[43m    \u001b[49m\u001b[43moutput_keys\u001b[49m\u001b[43m=\u001b[49m\u001b[43moutput_keys\u001b[49m\u001b[43m,\u001b[49m\n\u001b[32m   3035\u001b[39m \u001b[43m    \u001b[49m\u001b[43minterrupt_before\u001b[49m\u001b[43m=\u001b[49m\u001b[43minterrupt_before\u001b[49m\u001b[43m,\u001b[49m\n\u001b[32m   3036\u001b[39m \u001b[43m    \u001b[49m\u001b[43minterrupt_after\u001b[49m\u001b[43m=\u001b[49m\u001b[43minterrupt_after\u001b[49m\u001b[43m,\u001b[49m\n\u001b[32m   3037\u001b[39m \u001b[43m    \u001b[49m\u001b[43mdurability\u001b[49m\u001b[43m=\u001b[49m\u001b[43mdurability\u001b[49m\u001b[43m,\u001b[49m\n\u001b[32m   3038\u001b[39m \u001b[43m    \u001b[49m\u001b[43m*\u001b[49m\u001b[43m*\u001b[49m\u001b[43mkwargs\u001b[49m\u001b[43m,\u001b[49m\n\u001b[32m   3039\u001b[39m \u001b[43m\u001b[49m\u001b[43m)\u001b[49m\u001b[43m:\u001b[49m\n\u001b[32m   3040\u001b[39m \u001b[43m    \u001b[49m\u001b[38;5;28;43;01mif\u001b[39;49;00m\u001b[43m \u001b[49m\u001b[43mstream_mode\u001b[49m\u001b[43m \u001b[49m\u001b[43m==\u001b[49m\u001b[43m \u001b[49m\u001b[33;43m\"\u001b[39;49m\u001b[33;43mvalues\u001b[39;49m\u001b[33;43m\"\u001b[39;49m\u001b[43m:\u001b[49m\n\u001b[32m   3041\u001b[39m \u001b[43m        \u001b[49m\u001b[38;5;28;43;01mif\u001b[39;49;00m\u001b[43m \u001b[49m\u001b[38;5;28;43mlen\u001b[39;49m\u001b[43m(\u001b[49m\u001b[43mchunk\u001b[49m\u001b[43m)\u001b[49m\u001b[43m \u001b[49m\u001b[43m==\u001b[49m\u001b[43m \u001b[49m\u001b[32;43m2\u001b[39;49m\u001b[43m:\u001b[49m\n",
      "\u001b[36mFile \u001b[39m\u001b[32md:\\Code Assistant\\venv\\Lib\\site-packages\\langgraph\\pregel\\main.py:2647\u001b[39m, in \u001b[36mPregel.stream\u001b[39m\u001b[34m(self, input, config, context, stream_mode, print_mode, output_keys, interrupt_before, interrupt_after, durability, subgraphs, debug, **kwargs)\u001b[39m\n\u001b[32m   2645\u001b[39m \u001b[38;5;28;01mfor\u001b[39;00m task \u001b[38;5;129;01min\u001b[39;00m loop.match_cached_writes():\n\u001b[32m   2646\u001b[39m     loop.output_writes(task.id, task.writes, cached=\u001b[38;5;28;01mTrue\u001b[39;00m)\n\u001b[32m-> \u001b[39m\u001b[32m2647\u001b[39m \u001b[43m\u001b[49m\u001b[38;5;28;43;01mfor\u001b[39;49;00m\u001b[43m \u001b[49m\u001b[43m_\u001b[49m\u001b[43m \u001b[49m\u001b[38;5;129;43;01min\u001b[39;49;00m\u001b[43m \u001b[49m\u001b[43mrunner\u001b[49m\u001b[43m.\u001b[49m\u001b[43mtick\u001b[49m\u001b[43m(\u001b[49m\n\u001b[32m   2648\u001b[39m \u001b[43m    \u001b[49m\u001b[43m[\u001b[49m\u001b[43mt\u001b[49m\u001b[43m \u001b[49m\u001b[38;5;28;43;01mfor\u001b[39;49;00m\u001b[43m \u001b[49m\u001b[43mt\u001b[49m\u001b[43m \u001b[49m\u001b[38;5;129;43;01min\u001b[39;49;00m\u001b[43m \u001b[49m\u001b[43mloop\u001b[49m\u001b[43m.\u001b[49m\u001b[43mtasks\u001b[49m\u001b[43m.\u001b[49m\u001b[43mvalues\u001b[49m\u001b[43m(\u001b[49m\u001b[43m)\u001b[49m\u001b[43m \u001b[49m\u001b[38;5;28;43;01mif\u001b[39;49;00m\u001b[43m \u001b[49m\u001b[38;5;129;43;01mnot\u001b[39;49;00m\u001b[43m \u001b[49m\u001b[43mt\u001b[49m\u001b[43m.\u001b[49m\u001b[43mwrites\u001b[49m\u001b[43m]\u001b[49m\u001b[43m,\u001b[49m\n\u001b[32m   2649\u001b[39m \u001b[43m    \u001b[49m\u001b[43mtimeout\u001b[49m\u001b[43m=\u001b[49m\u001b[38;5;28;43mself\u001b[39;49m\u001b[43m.\u001b[49m\u001b[43mstep_timeout\u001b[49m\u001b[43m,\u001b[49m\n\u001b[32m   2650\u001b[39m \u001b[43m    \u001b[49m\u001b[43mget_waiter\u001b[49m\u001b[43m=\u001b[49m\u001b[43mget_waiter\u001b[49m\u001b[43m,\u001b[49m\n\u001b[32m   2651\u001b[39m \u001b[43m    \u001b[49m\u001b[43mschedule_task\u001b[49m\u001b[43m=\u001b[49m\u001b[43mloop\u001b[49m\u001b[43m.\u001b[49m\u001b[43maccept_push\u001b[49m\u001b[43m,\u001b[49m\n\u001b[32m   2652\u001b[39m \u001b[43m\u001b[49m\u001b[43m)\u001b[49m\u001b[43m:\u001b[49m\n\u001b[32m   2653\u001b[39m \u001b[43m    \u001b[49m\u001b[38;5;66;43;03m# emit output\u001b[39;49;00m\n\u001b[32m   2654\u001b[39m \u001b[43m    \u001b[49m\u001b[38;5;28;43;01myield from\u001b[39;49;00m\u001b[43m \u001b[49m\u001b[43m_output\u001b[49m\u001b[43m(\u001b[49m\n\u001b[32m   2655\u001b[39m \u001b[43m        \u001b[49m\u001b[43mstream_mode\u001b[49m\u001b[43m,\u001b[49m\u001b[43m \u001b[49m\u001b[43mprint_mode\u001b[49m\u001b[43m,\u001b[49m\u001b[43m \u001b[49m\u001b[43msubgraphs\u001b[49m\u001b[43m,\u001b[49m\u001b[43m \u001b[49m\u001b[43mstream\u001b[49m\u001b[43m.\u001b[49m\u001b[43mget\u001b[49m\u001b[43m,\u001b[49m\u001b[43m \u001b[49m\u001b[43mqueue\u001b[49m\u001b[43m.\u001b[49m\u001b[43mEmpty\u001b[49m\n\u001b[32m   2656\u001b[39m \u001b[43m    \u001b[49m\u001b[43m)\u001b[49m\n\u001b[32m   2657\u001b[39m loop.after_tick()\n",
      "\u001b[36mFile \u001b[39m\u001b[32md:\\Code Assistant\\venv\\Lib\\site-packages\\langgraph\\pregel\\_runner.py:162\u001b[39m, in \u001b[36mPregelRunner.tick\u001b[39m\u001b[34m(self, tasks, reraise, timeout, retry_policy, get_waiter, schedule_task)\u001b[39m\n\u001b[32m    160\u001b[39m t = tasks[\u001b[32m0\u001b[39m]\n\u001b[32m    161\u001b[39m \u001b[38;5;28;01mtry\u001b[39;00m:\n\u001b[32m--> \u001b[39m\u001b[32m162\u001b[39m     \u001b[43mrun_with_retry\u001b[49m\u001b[43m(\u001b[49m\n\u001b[32m    163\u001b[39m \u001b[43m        \u001b[49m\u001b[43mt\u001b[49m\u001b[43m,\u001b[49m\n\u001b[32m    164\u001b[39m \u001b[43m        \u001b[49m\u001b[43mretry_policy\u001b[49m\u001b[43m,\u001b[49m\n\u001b[32m    165\u001b[39m \u001b[43m        \u001b[49m\u001b[43mconfigurable\u001b[49m\u001b[43m=\u001b[49m\u001b[43m{\u001b[49m\n\u001b[32m    166\u001b[39m \u001b[43m            \u001b[49m\u001b[43mCONFIG_KEY_CALL\u001b[49m\u001b[43m:\u001b[49m\u001b[43m \u001b[49m\u001b[43mpartial\u001b[49m\u001b[43m(\u001b[49m\n\u001b[32m    167\u001b[39m \u001b[43m                \u001b[49m\u001b[43m_call\u001b[49m\u001b[43m,\u001b[49m\n\u001b[32m    168\u001b[39m \u001b[43m                \u001b[49m\u001b[43mweakref\u001b[49m\u001b[43m.\u001b[49m\u001b[43mref\u001b[49m\u001b[43m(\u001b[49m\u001b[43mt\u001b[49m\u001b[43m)\u001b[49m\u001b[43m,\u001b[49m\n\u001b[32m    169\u001b[39m \u001b[43m                \u001b[49m\u001b[43mretry_policy\u001b[49m\u001b[43m=\u001b[49m\u001b[43mretry_policy\u001b[49m\u001b[43m,\u001b[49m\n\u001b[32m    170\u001b[39m \u001b[43m                \u001b[49m\u001b[43mfutures\u001b[49m\u001b[43m=\u001b[49m\u001b[43mweakref\u001b[49m\u001b[43m.\u001b[49m\u001b[43mref\u001b[49m\u001b[43m(\u001b[49m\u001b[43mfutures\u001b[49m\u001b[43m)\u001b[49m\u001b[43m,\u001b[49m\n\u001b[32m    171\u001b[39m \u001b[43m                \u001b[49m\u001b[43mschedule_task\u001b[49m\u001b[43m=\u001b[49m\u001b[43mschedule_task\u001b[49m\u001b[43m,\u001b[49m\n\u001b[32m    172\u001b[39m \u001b[43m                \u001b[49m\u001b[43msubmit\u001b[49m\u001b[43m=\u001b[49m\u001b[38;5;28;43mself\u001b[39;49m\u001b[43m.\u001b[49m\u001b[43msubmit\u001b[49m\u001b[43m,\u001b[49m\n\u001b[32m    173\u001b[39m \u001b[43m            \u001b[49m\u001b[43m)\u001b[49m\u001b[43m,\u001b[49m\n\u001b[32m    174\u001b[39m \u001b[43m        \u001b[49m\u001b[43m}\u001b[49m\u001b[43m,\u001b[49m\n\u001b[32m    175\u001b[39m \u001b[43m    \u001b[49m\u001b[43m)\u001b[49m\n\u001b[32m    176\u001b[39m     \u001b[38;5;28mself\u001b[39m.commit(t, \u001b[38;5;28;01mNone\u001b[39;00m)\n\u001b[32m    177\u001b[39m \u001b[38;5;28;01mexcept\u001b[39;00m \u001b[38;5;167;01mException\u001b[39;00m \u001b[38;5;28;01mas\u001b[39;00m exc:\n",
      "\u001b[36mFile \u001b[39m\u001b[32md:\\Code Assistant\\venv\\Lib\\site-packages\\langgraph\\pregel\\_retry.py:42\u001b[39m, in \u001b[36mrun_with_retry\u001b[39m\u001b[34m(task, retry_policy, configurable)\u001b[39m\n\u001b[32m     40\u001b[39m     task.writes.clear()\n\u001b[32m     41\u001b[39m     \u001b[38;5;66;03m# run the task\u001b[39;00m\n\u001b[32m---> \u001b[39m\u001b[32m42\u001b[39m     \u001b[38;5;28;01mreturn\u001b[39;00m \u001b[43mtask\u001b[49m\u001b[43m.\u001b[49m\u001b[43mproc\u001b[49m\u001b[43m.\u001b[49m\u001b[43minvoke\u001b[49m\u001b[43m(\u001b[49m\u001b[43mtask\u001b[49m\u001b[43m.\u001b[49m\u001b[43minput\u001b[49m\u001b[43m,\u001b[49m\u001b[43m \u001b[49m\u001b[43mconfig\u001b[49m\u001b[43m)\u001b[49m\n\u001b[32m     43\u001b[39m \u001b[38;5;28;01mexcept\u001b[39;00m ParentCommand \u001b[38;5;28;01mas\u001b[39;00m exc:\n\u001b[32m     44\u001b[39m     ns: \u001b[38;5;28mstr\u001b[39m = config[CONF][CONFIG_KEY_CHECKPOINT_NS]\n",
      "\u001b[36mFile \u001b[39m\u001b[32md:\\Code Assistant\\venv\\Lib\\site-packages\\langgraph\\_internal\\_runnable.py:657\u001b[39m, in \u001b[36mRunnableSeq.invoke\u001b[39m\u001b[34m(self, input, config, **kwargs)\u001b[39m\n\u001b[32m    655\u001b[39m     \u001b[38;5;66;03m# run in context\u001b[39;00m\n\u001b[32m    656\u001b[39m     \u001b[38;5;28;01mwith\u001b[39;00m set_config_context(config, run) \u001b[38;5;28;01mas\u001b[39;00m context:\n\u001b[32m--> \u001b[39m\u001b[32m657\u001b[39m         \u001b[38;5;28minput\u001b[39m = \u001b[43mcontext\u001b[49m\u001b[43m.\u001b[49m\u001b[43mrun\u001b[49m\u001b[43m(\u001b[49m\u001b[43mstep\u001b[49m\u001b[43m.\u001b[49m\u001b[43minvoke\u001b[49m\u001b[43m,\u001b[49m\u001b[43m \u001b[49m\u001b[38;5;28;43minput\u001b[39;49m\u001b[43m,\u001b[49m\u001b[43m \u001b[49m\u001b[43mconfig\u001b[49m\u001b[43m,\u001b[49m\u001b[43m \u001b[49m\u001b[43m*\u001b[49m\u001b[43m*\u001b[49m\u001b[43mkwargs\u001b[49m\u001b[43m)\u001b[49m\n\u001b[32m    658\u001b[39m \u001b[38;5;28;01melse\u001b[39;00m:\n\u001b[32m    659\u001b[39m     \u001b[38;5;28minput\u001b[39m = step.invoke(\u001b[38;5;28minput\u001b[39m, config)\n",
      "\u001b[36mFile \u001b[39m\u001b[32md:\\Code Assistant\\venv\\Lib\\site-packages\\langgraph\\_internal\\_runnable.py:394\u001b[39m, in \u001b[36mRunnableCallable.invoke\u001b[39m\u001b[34m(self, input, config, **kwargs)\u001b[39m\n\u001b[32m    392\u001b[39m     \u001b[38;5;66;03m# run in context\u001b[39;00m\n\u001b[32m    393\u001b[39m     \u001b[38;5;28;01mwith\u001b[39;00m set_config_context(child_config, run) \u001b[38;5;28;01mas\u001b[39;00m context:\n\u001b[32m--> \u001b[39m\u001b[32m394\u001b[39m         ret = \u001b[43mcontext\u001b[49m\u001b[43m.\u001b[49m\u001b[43mrun\u001b[49m\u001b[43m(\u001b[49m\u001b[38;5;28;43mself\u001b[39;49m\u001b[43m.\u001b[49m\u001b[43mfunc\u001b[49m\u001b[43m,\u001b[49m\u001b[43m \u001b[49m\u001b[43m*\u001b[49m\u001b[43margs\u001b[49m\u001b[43m,\u001b[49m\u001b[43m \u001b[49m\u001b[43m*\u001b[49m\u001b[43m*\u001b[49m\u001b[43mkwargs\u001b[49m\u001b[43m)\u001b[49m\n\u001b[32m    395\u001b[39m \u001b[38;5;28;01mexcept\u001b[39;00m \u001b[38;5;167;01mBaseException\u001b[39;00m \u001b[38;5;28;01mas\u001b[39;00m e:\n\u001b[32m    396\u001b[39m     run_manager.on_chain_error(e)\n",
      "\u001b[36mFile \u001b[39m\u001b[32md:\\Code Assistant\\venv\\Lib\\site-packages\\langgraph\\prebuilt\\chat_agent_executor.py:627\u001b[39m, in \u001b[36mcreate_react_agent.<locals>.call_model\u001b[39m\u001b[34m(state, runtime, config)\u001b[39m\n\u001b[32m    625\u001b[39m     response = cast(AIMessage, dynamic_model.invoke(model_input, config))  \u001b[38;5;66;03m# type: ignore[arg-type]\u001b[39;00m\n\u001b[32m    626\u001b[39m \u001b[38;5;28;01melse\u001b[39;00m:\n\u001b[32m--> \u001b[39m\u001b[32m627\u001b[39m     response = cast(AIMessage, \u001b[43mstatic_model\u001b[49m\u001b[43m.\u001b[49m\u001b[43minvoke\u001b[49m\u001b[43m(\u001b[49m\u001b[43mmodel_input\u001b[49m\u001b[43m,\u001b[49m\u001b[43m \u001b[49m\u001b[43mconfig\u001b[49m\u001b[43m)\u001b[49m)  \u001b[38;5;66;03m# type: ignore[union-attr]\u001b[39;00m\n\u001b[32m    629\u001b[39m \u001b[38;5;66;03m# add agent name to the AIMessage\u001b[39;00m\n\u001b[32m    630\u001b[39m response.name = name\n",
      "\u001b[36mFile \u001b[39m\u001b[32md:\\Code Assistant\\venv\\Lib\\site-packages\\langchain_core\\runnables\\base.py:3245\u001b[39m, in \u001b[36mRunnableSequence.invoke\u001b[39m\u001b[34m(self, input, config, **kwargs)\u001b[39m\n\u001b[32m   3243\u001b[39m                 input_ = context.run(step.invoke, input_, config, **kwargs)\n\u001b[32m   3244\u001b[39m             \u001b[38;5;28;01melse\u001b[39;00m:\n\u001b[32m-> \u001b[39m\u001b[32m3245\u001b[39m                 input_ = \u001b[43mcontext\u001b[49m\u001b[43m.\u001b[49m\u001b[43mrun\u001b[49m\u001b[43m(\u001b[49m\u001b[43mstep\u001b[49m\u001b[43m.\u001b[49m\u001b[43minvoke\u001b[49m\u001b[43m,\u001b[49m\u001b[43m \u001b[49m\u001b[43minput_\u001b[49m\u001b[43m,\u001b[49m\u001b[43m \u001b[49m\u001b[43mconfig\u001b[49m\u001b[43m)\u001b[49m\n\u001b[32m   3246\u001b[39m \u001b[38;5;66;03m# finish the root run\u001b[39;00m\n\u001b[32m   3247\u001b[39m \u001b[38;5;28;01mexcept\u001b[39;00m \u001b[38;5;167;01mBaseException\u001b[39;00m \u001b[38;5;28;01mas\u001b[39;00m e:\n",
      "\u001b[36mFile \u001b[39m\u001b[32md:\\Code Assistant\\venv\\Lib\\site-packages\\langchain_core\\runnables\\base.py:5710\u001b[39m, in \u001b[36mRunnableBindingBase.invoke\u001b[39m\u001b[34m(self, input, config, **kwargs)\u001b[39m\n\u001b[32m   5703\u001b[39m \u001b[38;5;129m@override\u001b[39m\n\u001b[32m   5704\u001b[39m \u001b[38;5;28;01mdef\u001b[39;00m\u001b[38;5;250m \u001b[39m\u001b[34minvoke\u001b[39m(\n\u001b[32m   5705\u001b[39m     \u001b[38;5;28mself\u001b[39m,\n\u001b[32m   (...)\u001b[39m\u001b[32m   5708\u001b[39m     **kwargs: Optional[Any],\n\u001b[32m   5709\u001b[39m ) -> Output:\n\u001b[32m-> \u001b[39m\u001b[32m5710\u001b[39m     \u001b[38;5;28;01mreturn\u001b[39;00m \u001b[38;5;28;43mself\u001b[39;49m\u001b[43m.\u001b[49m\u001b[43mbound\u001b[49m\u001b[43m.\u001b[49m\u001b[43minvoke\u001b[49m\u001b[43m(\u001b[49m\n\u001b[32m   5711\u001b[39m \u001b[43m        \u001b[49m\u001b[38;5;28;43minput\u001b[39;49m\u001b[43m,\u001b[49m\n\u001b[32m   5712\u001b[39m \u001b[43m        \u001b[49m\u001b[38;5;28;43mself\u001b[39;49m\u001b[43m.\u001b[49m\u001b[43m_merge_configs\u001b[49m\u001b[43m(\u001b[49m\u001b[43mconfig\u001b[49m\u001b[43m)\u001b[49m\u001b[43m,\u001b[49m\n\u001b[32m   5713\u001b[39m \u001b[43m        \u001b[49m\u001b[43m*\u001b[49m\u001b[43m*\u001b[49m\u001b[43m{\u001b[49m\u001b[43m*\u001b[49m\u001b[43m*\u001b[49m\u001b[38;5;28;43mself\u001b[39;49m\u001b[43m.\u001b[49m\u001b[43mkwargs\u001b[49m\u001b[43m,\u001b[49m\u001b[43m \u001b[49m\u001b[43m*\u001b[49m\u001b[43m*\u001b[49m\u001b[43mkwargs\u001b[49m\u001b[43m}\u001b[49m\u001b[43m,\u001b[49m\n\u001b[32m   5714\u001b[39m \u001b[43m    \u001b[49m\u001b[43m)\u001b[49m\n",
      "\u001b[36mFile \u001b[39m\u001b[32md:\\Code Assistant\\venv\\Lib\\site-packages\\langchain_core\\language_models\\chat_models.py:395\u001b[39m, in \u001b[36mBaseChatModel.invoke\u001b[39m\u001b[34m(self, input, config, stop, **kwargs)\u001b[39m\n\u001b[32m    383\u001b[39m \u001b[38;5;129m@override\u001b[39m\n\u001b[32m    384\u001b[39m \u001b[38;5;28;01mdef\u001b[39;00m\u001b[38;5;250m \u001b[39m\u001b[34minvoke\u001b[39m(\n\u001b[32m    385\u001b[39m     \u001b[38;5;28mself\u001b[39m,\n\u001b[32m   (...)\u001b[39m\u001b[32m    390\u001b[39m     **kwargs: Any,\n\u001b[32m    391\u001b[39m ) -> BaseMessage:\n\u001b[32m    392\u001b[39m     config = ensure_config(config)\n\u001b[32m    393\u001b[39m     \u001b[38;5;28;01mreturn\u001b[39;00m cast(\n\u001b[32m    394\u001b[39m         \u001b[33m\"\u001b[39m\u001b[33mChatGeneration\u001b[39m\u001b[33m\"\u001b[39m,\n\u001b[32m--> \u001b[39m\u001b[32m395\u001b[39m         \u001b[38;5;28;43mself\u001b[39;49m\u001b[43m.\u001b[49m\u001b[43mgenerate_prompt\u001b[49m\u001b[43m(\u001b[49m\n\u001b[32m    396\u001b[39m \u001b[43m            \u001b[49m\u001b[43m[\u001b[49m\u001b[38;5;28;43mself\u001b[39;49m\u001b[43m.\u001b[49m\u001b[43m_convert_input\u001b[49m\u001b[43m(\u001b[49m\u001b[38;5;28;43minput\u001b[39;49m\u001b[43m)\u001b[49m\u001b[43m]\u001b[49m\u001b[43m,\u001b[49m\n\u001b[32m    397\u001b[39m \u001b[43m            \u001b[49m\u001b[43mstop\u001b[49m\u001b[43m=\u001b[49m\u001b[43mstop\u001b[49m\u001b[43m,\u001b[49m\n\u001b[32m    398\u001b[39m \u001b[43m            \u001b[49m\u001b[43mcallbacks\u001b[49m\u001b[43m=\u001b[49m\u001b[43mconfig\u001b[49m\u001b[43m.\u001b[49m\u001b[43mget\u001b[49m\u001b[43m(\u001b[49m\u001b[33;43m\"\u001b[39;49m\u001b[33;43mcallbacks\u001b[39;49m\u001b[33;43m\"\u001b[39;49m\u001b[43m)\u001b[49m\u001b[43m,\u001b[49m\n\u001b[32m    399\u001b[39m \u001b[43m            \u001b[49m\u001b[43mtags\u001b[49m\u001b[43m=\u001b[49m\u001b[43mconfig\u001b[49m\u001b[43m.\u001b[49m\u001b[43mget\u001b[49m\u001b[43m(\u001b[49m\u001b[33;43m\"\u001b[39;49m\u001b[33;43mtags\u001b[39;49m\u001b[33;43m\"\u001b[39;49m\u001b[43m)\u001b[49m\u001b[43m,\u001b[49m\n\u001b[32m    400\u001b[39m \u001b[43m            \u001b[49m\u001b[43mmetadata\u001b[49m\u001b[43m=\u001b[49m\u001b[43mconfig\u001b[49m\u001b[43m.\u001b[49m\u001b[43mget\u001b[49m\u001b[43m(\u001b[49m\u001b[33;43m\"\u001b[39;49m\u001b[33;43mmetadata\u001b[39;49m\u001b[33;43m\"\u001b[39;49m\u001b[43m)\u001b[49m\u001b[43m,\u001b[49m\n\u001b[32m    401\u001b[39m \u001b[43m            \u001b[49m\u001b[43mrun_name\u001b[49m\u001b[43m=\u001b[49m\u001b[43mconfig\u001b[49m\u001b[43m.\u001b[49m\u001b[43mget\u001b[49m\u001b[43m(\u001b[49m\u001b[33;43m\"\u001b[39;49m\u001b[33;43mrun_name\u001b[39;49m\u001b[33;43m\"\u001b[39;49m\u001b[43m)\u001b[49m\u001b[43m,\u001b[49m\n\u001b[32m    402\u001b[39m \u001b[43m            \u001b[49m\u001b[43mrun_id\u001b[49m\u001b[43m=\u001b[49m\u001b[43mconfig\u001b[49m\u001b[43m.\u001b[49m\u001b[43mpop\u001b[49m\u001b[43m(\u001b[49m\u001b[33;43m\"\u001b[39;49m\u001b[33;43mrun_id\u001b[39;49m\u001b[33;43m\"\u001b[39;49m\u001b[43m,\u001b[49m\u001b[43m \u001b[49m\u001b[38;5;28;43;01mNone\u001b[39;49;00m\u001b[43m)\u001b[49m\u001b[43m,\u001b[49m\n\u001b[32m    403\u001b[39m \u001b[43m            \u001b[49m\u001b[43m*\u001b[49m\u001b[43m*\u001b[49m\u001b[43mkwargs\u001b[49m\u001b[43m,\u001b[49m\n\u001b[32m    404\u001b[39m \u001b[43m        \u001b[49m\u001b[43m)\u001b[49m.generations[\u001b[32m0\u001b[39m][\u001b[32m0\u001b[39m],\n\u001b[32m    405\u001b[39m     ).message\n",
      "\u001b[36mFile \u001b[39m\u001b[32md:\\Code Assistant\\venv\\Lib\\site-packages\\langchain_core\\language_models\\chat_models.py:1023\u001b[39m, in \u001b[36mBaseChatModel.generate_prompt\u001b[39m\u001b[34m(self, prompts, stop, callbacks, **kwargs)\u001b[39m\n\u001b[32m   1014\u001b[39m \u001b[38;5;129m@override\u001b[39m\n\u001b[32m   1015\u001b[39m \u001b[38;5;28;01mdef\u001b[39;00m\u001b[38;5;250m \u001b[39m\u001b[34mgenerate_prompt\u001b[39m(\n\u001b[32m   1016\u001b[39m     \u001b[38;5;28mself\u001b[39m,\n\u001b[32m   (...)\u001b[39m\u001b[32m   1020\u001b[39m     **kwargs: Any,\n\u001b[32m   1021\u001b[39m ) -> LLMResult:\n\u001b[32m   1022\u001b[39m     prompt_messages = [p.to_messages() \u001b[38;5;28;01mfor\u001b[39;00m p \u001b[38;5;129;01min\u001b[39;00m prompts]\n\u001b[32m-> \u001b[39m\u001b[32m1023\u001b[39m     \u001b[38;5;28;01mreturn\u001b[39;00m \u001b[38;5;28;43mself\u001b[39;49m\u001b[43m.\u001b[49m\u001b[43mgenerate\u001b[49m\u001b[43m(\u001b[49m\u001b[43mprompt_messages\u001b[49m\u001b[43m,\u001b[49m\u001b[43m \u001b[49m\u001b[43mstop\u001b[49m\u001b[43m=\u001b[49m\u001b[43mstop\u001b[49m\u001b[43m,\u001b[49m\u001b[43m \u001b[49m\u001b[43mcallbacks\u001b[49m\u001b[43m=\u001b[49m\u001b[43mcallbacks\u001b[49m\u001b[43m,\u001b[49m\u001b[43m \u001b[49m\u001b[43m*\u001b[49m\u001b[43m*\u001b[49m\u001b[43mkwargs\u001b[49m\u001b[43m)\u001b[49m\n",
      "\u001b[36mFile \u001b[39m\u001b[32md:\\Code Assistant\\venv\\Lib\\site-packages\\langchain_core\\language_models\\chat_models.py:840\u001b[39m, in \u001b[36mBaseChatModel.generate\u001b[39m\u001b[34m(self, messages, stop, callbacks, tags, metadata, run_name, run_id, **kwargs)\u001b[39m\n\u001b[32m    837\u001b[39m \u001b[38;5;28;01mfor\u001b[39;00m i, m \u001b[38;5;129;01min\u001b[39;00m \u001b[38;5;28menumerate\u001b[39m(input_messages):\n\u001b[32m    838\u001b[39m     \u001b[38;5;28;01mtry\u001b[39;00m:\n\u001b[32m    839\u001b[39m         results.append(\n\u001b[32m--> \u001b[39m\u001b[32m840\u001b[39m             \u001b[38;5;28;43mself\u001b[39;49m\u001b[43m.\u001b[49m\u001b[43m_generate_with_cache\u001b[49m\u001b[43m(\u001b[49m\n\u001b[32m    841\u001b[39m \u001b[43m                \u001b[49m\u001b[43mm\u001b[49m\u001b[43m,\u001b[49m\n\u001b[32m    842\u001b[39m \u001b[43m                \u001b[49m\u001b[43mstop\u001b[49m\u001b[43m=\u001b[49m\u001b[43mstop\u001b[49m\u001b[43m,\u001b[49m\n\u001b[32m    843\u001b[39m \u001b[43m                \u001b[49m\u001b[43mrun_manager\u001b[49m\u001b[43m=\u001b[49m\u001b[43mrun_managers\u001b[49m\u001b[43m[\u001b[49m\u001b[43mi\u001b[49m\u001b[43m]\u001b[49m\u001b[43m \u001b[49m\u001b[38;5;28;43;01mif\u001b[39;49;00m\u001b[43m \u001b[49m\u001b[43mrun_managers\u001b[49m\u001b[43m \u001b[49m\u001b[38;5;28;43;01melse\u001b[39;49;00m\u001b[43m \u001b[49m\u001b[38;5;28;43;01mNone\u001b[39;49;00m\u001b[43m,\u001b[49m\n\u001b[32m    844\u001b[39m \u001b[43m                \u001b[49m\u001b[43m*\u001b[49m\u001b[43m*\u001b[49m\u001b[43mkwargs\u001b[49m\u001b[43m,\u001b[49m\n\u001b[32m    845\u001b[39m \u001b[43m            \u001b[49m\u001b[43m)\u001b[49m\n\u001b[32m    846\u001b[39m         )\n\u001b[32m    847\u001b[39m     \u001b[38;5;28;01mexcept\u001b[39;00m \u001b[38;5;167;01mBaseException\u001b[39;00m \u001b[38;5;28;01mas\u001b[39;00m e:\n\u001b[32m    848\u001b[39m         \u001b[38;5;28;01mif\u001b[39;00m run_managers:\n",
      "\u001b[36mFile \u001b[39m\u001b[32md:\\Code Assistant\\venv\\Lib\\site-packages\\langchain_core\\language_models\\chat_models.py:1089\u001b[39m, in \u001b[36mBaseChatModel._generate_with_cache\u001b[39m\u001b[34m(self, messages, stop, run_manager, **kwargs)\u001b[39m\n\u001b[32m   1087\u001b[39m     result = generate_from_stream(\u001b[38;5;28miter\u001b[39m(chunks))\n\u001b[32m   1088\u001b[39m \u001b[38;5;28;01melif\u001b[39;00m inspect.signature(\u001b[38;5;28mself\u001b[39m._generate).parameters.get(\u001b[33m\"\u001b[39m\u001b[33mrun_manager\u001b[39m\u001b[33m\"\u001b[39m):\n\u001b[32m-> \u001b[39m\u001b[32m1089\u001b[39m     result = \u001b[38;5;28;43mself\u001b[39;49m\u001b[43m.\u001b[49m\u001b[43m_generate\u001b[49m\u001b[43m(\u001b[49m\n\u001b[32m   1090\u001b[39m \u001b[43m        \u001b[49m\u001b[43mmessages\u001b[49m\u001b[43m,\u001b[49m\u001b[43m \u001b[49m\u001b[43mstop\u001b[49m\u001b[43m=\u001b[49m\u001b[43mstop\u001b[49m\u001b[43m,\u001b[49m\u001b[43m \u001b[49m\u001b[43mrun_manager\u001b[49m\u001b[43m=\u001b[49m\u001b[43mrun_manager\u001b[49m\u001b[43m,\u001b[49m\u001b[43m \u001b[49m\u001b[43m*\u001b[49m\u001b[43m*\u001b[49m\u001b[43mkwargs\u001b[49m\n\u001b[32m   1091\u001b[39m \u001b[43m    \u001b[49m\u001b[43m)\u001b[49m\n\u001b[32m   1092\u001b[39m \u001b[38;5;28;01melse\u001b[39;00m:\n\u001b[32m   1093\u001b[39m     result = \u001b[38;5;28mself\u001b[39m._generate(messages, stop=stop, **kwargs)\n",
      "\u001b[36mFile \u001b[39m\u001b[32md:\\Code Assistant\\venv\\Lib\\site-packages\\langchain_groq\\chat_models.py:533\u001b[39m, in \u001b[36mChatGroq._generate\u001b[39m\u001b[34m(self, messages, stop, run_manager, **kwargs)\u001b[39m\n\u001b[32m    528\u001b[39m message_dicts, params = \u001b[38;5;28mself\u001b[39m._create_message_dicts(messages, stop)\n\u001b[32m    529\u001b[39m params = {\n\u001b[32m    530\u001b[39m     **params,\n\u001b[32m    531\u001b[39m     **kwargs,\n\u001b[32m    532\u001b[39m }\n\u001b[32m--> \u001b[39m\u001b[32m533\u001b[39m response = \u001b[38;5;28;43mself\u001b[39;49m\u001b[43m.\u001b[49m\u001b[43mclient\u001b[49m\u001b[43m.\u001b[49m\u001b[43mcreate\u001b[49m\u001b[43m(\u001b[49m\u001b[43mmessages\u001b[49m\u001b[43m=\u001b[49m\u001b[43mmessage_dicts\u001b[49m\u001b[43m,\u001b[49m\u001b[43m \u001b[49m\u001b[43m*\u001b[49m\u001b[43m*\u001b[49m\u001b[43mparams\u001b[49m\u001b[43m)\u001b[49m\n\u001b[32m    534\u001b[39m \u001b[38;5;28;01mreturn\u001b[39;00m \u001b[38;5;28mself\u001b[39m._create_chat_result(response, params)\n",
      "\u001b[36mFile \u001b[39m\u001b[32md:\\Code Assistant\\venv\\Lib\\site-packages\\groq\\resources\\chat\\completions.py:448\u001b[39m, in \u001b[36mCompletions.create\u001b[39m\u001b[34m(self, messages, model, compound_custom, documents, exclude_domains, frequency_penalty, function_call, functions, include_domains, include_reasoning, logit_bias, logprobs, max_completion_tokens, max_tokens, metadata, n, parallel_tool_calls, presence_penalty, reasoning_effort, reasoning_format, response_format, search_settings, seed, service_tier, stop, store, stream, temperature, tool_choice, tools, top_logprobs, top_p, user, extra_headers, extra_query, extra_body, timeout)\u001b[39m\n\u001b[32m    238\u001b[39m \u001b[38;5;28;01mdef\u001b[39;00m\u001b[38;5;250m \u001b[39m\u001b[34mcreate\u001b[39m(\n\u001b[32m    239\u001b[39m     \u001b[38;5;28mself\u001b[39m,\n\u001b[32m    240\u001b[39m     *,\n\u001b[32m   (...)\u001b[39m\u001b[32m    295\u001b[39m     timeout: \u001b[38;5;28mfloat\u001b[39m | httpx.Timeout | \u001b[38;5;28;01mNone\u001b[39;00m | NotGiven = NOT_GIVEN,\n\u001b[32m    296\u001b[39m ) -> ChatCompletion | Stream[ChatCompletionChunk]:\n\u001b[32m    297\u001b[39m \u001b[38;5;250m    \u001b[39m\u001b[33;03m\"\"\"\u001b[39;00m\n\u001b[32m    298\u001b[39m \u001b[33;03m    Creates a model response for the given chat conversation.\u001b[39;00m\n\u001b[32m    299\u001b[39m \n\u001b[32m   (...)\u001b[39m\u001b[32m    446\u001b[39m \u001b[33;03m      timeout: Override the client-level default timeout for this request, in seconds\u001b[39;00m\n\u001b[32m    447\u001b[39m \u001b[33;03m    \"\"\"\u001b[39;00m\n\u001b[32m--> \u001b[39m\u001b[32m448\u001b[39m     \u001b[38;5;28;01mreturn\u001b[39;00m \u001b[38;5;28;43mself\u001b[39;49m\u001b[43m.\u001b[49m\u001b[43m_post\u001b[49m\u001b[43m(\u001b[49m\n\u001b[32m    449\u001b[39m \u001b[43m        \u001b[49m\u001b[33;43m\"\u001b[39;49m\u001b[33;43m/openai/v1/chat/completions\u001b[39;49m\u001b[33;43m\"\u001b[39;49m\u001b[43m,\u001b[49m\n\u001b[32m    450\u001b[39m \u001b[43m        \u001b[49m\u001b[43mbody\u001b[49m\u001b[43m=\u001b[49m\u001b[43mmaybe_transform\u001b[49m\u001b[43m(\u001b[49m\n\u001b[32m    451\u001b[39m \u001b[43m            \u001b[49m\u001b[43m{\u001b[49m\n\u001b[32m    452\u001b[39m \u001b[43m                \u001b[49m\u001b[33;43m\"\u001b[39;49m\u001b[33;43mmessages\u001b[39;49m\u001b[33;43m\"\u001b[39;49m\u001b[43m:\u001b[49m\u001b[43m \u001b[49m\u001b[43mmessages\u001b[49m\u001b[43m,\u001b[49m\n\u001b[32m    453\u001b[39m \u001b[43m                \u001b[49m\u001b[33;43m\"\u001b[39;49m\u001b[33;43mmodel\u001b[39;49m\u001b[33;43m\"\u001b[39;49m\u001b[43m:\u001b[49m\u001b[43m \u001b[49m\u001b[43mmodel\u001b[49m\u001b[43m,\u001b[49m\n\u001b[32m    454\u001b[39m \u001b[43m                \u001b[49m\u001b[33;43m\"\u001b[39;49m\u001b[33;43mcompound_custom\u001b[39;49m\u001b[33;43m\"\u001b[39;49m\u001b[43m:\u001b[49m\u001b[43m \u001b[49m\u001b[43mcompound_custom\u001b[49m\u001b[43m,\u001b[49m\n\u001b[32m    455\u001b[39m \u001b[43m                \u001b[49m\u001b[33;43m\"\u001b[39;49m\u001b[33;43mdocuments\u001b[39;49m\u001b[33;43m\"\u001b[39;49m\u001b[43m:\u001b[49m\u001b[43m \u001b[49m\u001b[43mdocuments\u001b[49m\u001b[43m,\u001b[49m\n\u001b[32m    456\u001b[39m \u001b[43m                \u001b[49m\u001b[33;43m\"\u001b[39;49m\u001b[33;43mexclude_domains\u001b[39;49m\u001b[33;43m\"\u001b[39;49m\u001b[43m:\u001b[49m\u001b[43m \u001b[49m\u001b[43mexclude_domains\u001b[49m\u001b[43m,\u001b[49m\n\u001b[32m    457\u001b[39m \u001b[43m                \u001b[49m\u001b[33;43m\"\u001b[39;49m\u001b[33;43mfrequency_penalty\u001b[39;49m\u001b[33;43m\"\u001b[39;49m\u001b[43m:\u001b[49m\u001b[43m \u001b[49m\u001b[43mfrequency_penalty\u001b[49m\u001b[43m,\u001b[49m\n\u001b[32m    458\u001b[39m \u001b[43m                \u001b[49m\u001b[33;43m\"\u001b[39;49m\u001b[33;43mfunction_call\u001b[39;49m\u001b[33;43m\"\u001b[39;49m\u001b[43m:\u001b[49m\u001b[43m \u001b[49m\u001b[43mfunction_call\u001b[49m\u001b[43m,\u001b[49m\n\u001b[32m    459\u001b[39m \u001b[43m                \u001b[49m\u001b[33;43m\"\u001b[39;49m\u001b[33;43mfunctions\u001b[39;49m\u001b[33;43m\"\u001b[39;49m\u001b[43m:\u001b[49m\u001b[43m \u001b[49m\u001b[43mfunctions\u001b[49m\u001b[43m,\u001b[49m\n\u001b[32m    460\u001b[39m \u001b[43m                \u001b[49m\u001b[33;43m\"\u001b[39;49m\u001b[33;43minclude_domains\u001b[39;49m\u001b[33;43m\"\u001b[39;49m\u001b[43m:\u001b[49m\u001b[43m \u001b[49m\u001b[43minclude_domains\u001b[49m\u001b[43m,\u001b[49m\n\u001b[32m    461\u001b[39m \u001b[43m                \u001b[49m\u001b[33;43m\"\u001b[39;49m\u001b[33;43minclude_reasoning\u001b[39;49m\u001b[33;43m\"\u001b[39;49m\u001b[43m:\u001b[49m\u001b[43m \u001b[49m\u001b[43minclude_reasoning\u001b[49m\u001b[43m,\u001b[49m\n\u001b[32m    462\u001b[39m \u001b[43m                \u001b[49m\u001b[33;43m\"\u001b[39;49m\u001b[33;43mlogit_bias\u001b[39;49m\u001b[33;43m\"\u001b[39;49m\u001b[43m:\u001b[49m\u001b[43m \u001b[49m\u001b[43mlogit_bias\u001b[49m\u001b[43m,\u001b[49m\n\u001b[32m    463\u001b[39m \u001b[43m                \u001b[49m\u001b[33;43m\"\u001b[39;49m\u001b[33;43mlogprobs\u001b[39;49m\u001b[33;43m\"\u001b[39;49m\u001b[43m:\u001b[49m\u001b[43m \u001b[49m\u001b[43mlogprobs\u001b[49m\u001b[43m,\u001b[49m\n\u001b[32m    464\u001b[39m \u001b[43m                \u001b[49m\u001b[33;43m\"\u001b[39;49m\u001b[33;43mmax_completion_tokens\u001b[39;49m\u001b[33;43m\"\u001b[39;49m\u001b[43m:\u001b[49m\u001b[43m \u001b[49m\u001b[43mmax_completion_tokens\u001b[49m\u001b[43m,\u001b[49m\n\u001b[32m    465\u001b[39m \u001b[43m                \u001b[49m\u001b[33;43m\"\u001b[39;49m\u001b[33;43mmax_tokens\u001b[39;49m\u001b[33;43m\"\u001b[39;49m\u001b[43m:\u001b[49m\u001b[43m \u001b[49m\u001b[43mmax_tokens\u001b[49m\u001b[43m,\u001b[49m\n\u001b[32m    466\u001b[39m \u001b[43m                \u001b[49m\u001b[33;43m\"\u001b[39;49m\u001b[33;43mmetadata\u001b[39;49m\u001b[33;43m\"\u001b[39;49m\u001b[43m:\u001b[49m\u001b[43m \u001b[49m\u001b[43mmetadata\u001b[49m\u001b[43m,\u001b[49m\n\u001b[32m    467\u001b[39m \u001b[43m                \u001b[49m\u001b[33;43m\"\u001b[39;49m\u001b[33;43mn\u001b[39;49m\u001b[33;43m\"\u001b[39;49m\u001b[43m:\u001b[49m\u001b[43m \u001b[49m\u001b[43mn\u001b[49m\u001b[43m,\u001b[49m\n\u001b[32m    468\u001b[39m \u001b[43m                \u001b[49m\u001b[33;43m\"\u001b[39;49m\u001b[33;43mparallel_tool_calls\u001b[39;49m\u001b[33;43m\"\u001b[39;49m\u001b[43m:\u001b[49m\u001b[43m \u001b[49m\u001b[43mparallel_tool_calls\u001b[49m\u001b[43m,\u001b[49m\n\u001b[32m    469\u001b[39m \u001b[43m                \u001b[49m\u001b[33;43m\"\u001b[39;49m\u001b[33;43mpresence_penalty\u001b[39;49m\u001b[33;43m\"\u001b[39;49m\u001b[43m:\u001b[49m\u001b[43m \u001b[49m\u001b[43mpresence_penalty\u001b[49m\u001b[43m,\u001b[49m\n\u001b[32m    470\u001b[39m \u001b[43m                \u001b[49m\u001b[33;43m\"\u001b[39;49m\u001b[33;43mreasoning_effort\u001b[39;49m\u001b[33;43m\"\u001b[39;49m\u001b[43m:\u001b[49m\u001b[43m \u001b[49m\u001b[43mreasoning_effort\u001b[49m\u001b[43m,\u001b[49m\n\u001b[32m    471\u001b[39m \u001b[43m                \u001b[49m\u001b[33;43m\"\u001b[39;49m\u001b[33;43mreasoning_format\u001b[39;49m\u001b[33;43m\"\u001b[39;49m\u001b[43m:\u001b[49m\u001b[43m \u001b[49m\u001b[43mreasoning_format\u001b[49m\u001b[43m,\u001b[49m\n\u001b[32m    472\u001b[39m \u001b[43m                \u001b[49m\u001b[33;43m\"\u001b[39;49m\u001b[33;43mresponse_format\u001b[39;49m\u001b[33;43m\"\u001b[39;49m\u001b[43m:\u001b[49m\u001b[43m \u001b[49m\u001b[43mresponse_format\u001b[49m\u001b[43m,\u001b[49m\n\u001b[32m    473\u001b[39m \u001b[43m                \u001b[49m\u001b[33;43m\"\u001b[39;49m\u001b[33;43msearch_settings\u001b[39;49m\u001b[33;43m\"\u001b[39;49m\u001b[43m:\u001b[49m\u001b[43m \u001b[49m\u001b[43msearch_settings\u001b[49m\u001b[43m,\u001b[49m\n\u001b[32m    474\u001b[39m \u001b[43m                \u001b[49m\u001b[33;43m\"\u001b[39;49m\u001b[33;43mseed\u001b[39;49m\u001b[33;43m\"\u001b[39;49m\u001b[43m:\u001b[49m\u001b[43m \u001b[49m\u001b[43mseed\u001b[49m\u001b[43m,\u001b[49m\n\u001b[32m    475\u001b[39m \u001b[43m                \u001b[49m\u001b[33;43m\"\u001b[39;49m\u001b[33;43mservice_tier\u001b[39;49m\u001b[33;43m\"\u001b[39;49m\u001b[43m:\u001b[49m\u001b[43m \u001b[49m\u001b[43mservice_tier\u001b[49m\u001b[43m,\u001b[49m\n\u001b[32m    476\u001b[39m \u001b[43m                \u001b[49m\u001b[33;43m\"\u001b[39;49m\u001b[33;43mstop\u001b[39;49m\u001b[33;43m\"\u001b[39;49m\u001b[43m:\u001b[49m\u001b[43m \u001b[49m\u001b[43mstop\u001b[49m\u001b[43m,\u001b[49m\n\u001b[32m    477\u001b[39m \u001b[43m                \u001b[49m\u001b[33;43m\"\u001b[39;49m\u001b[33;43mstore\u001b[39;49m\u001b[33;43m\"\u001b[39;49m\u001b[43m:\u001b[49m\u001b[43m \u001b[49m\u001b[43mstore\u001b[49m\u001b[43m,\u001b[49m\n\u001b[32m    478\u001b[39m \u001b[43m                \u001b[49m\u001b[33;43m\"\u001b[39;49m\u001b[33;43mstream\u001b[39;49m\u001b[33;43m\"\u001b[39;49m\u001b[43m:\u001b[49m\u001b[43m \u001b[49m\u001b[43mstream\u001b[49m\u001b[43m,\u001b[49m\n\u001b[32m    479\u001b[39m \u001b[43m                \u001b[49m\u001b[33;43m\"\u001b[39;49m\u001b[33;43mtemperature\u001b[39;49m\u001b[33;43m\"\u001b[39;49m\u001b[43m:\u001b[49m\u001b[43m \u001b[49m\u001b[43mtemperature\u001b[49m\u001b[43m,\u001b[49m\n\u001b[32m    480\u001b[39m \u001b[43m                \u001b[49m\u001b[33;43m\"\u001b[39;49m\u001b[33;43mtool_choice\u001b[39;49m\u001b[33;43m\"\u001b[39;49m\u001b[43m:\u001b[49m\u001b[43m \u001b[49m\u001b[43mtool_choice\u001b[49m\u001b[43m,\u001b[49m\n\u001b[32m    481\u001b[39m \u001b[43m                \u001b[49m\u001b[33;43m\"\u001b[39;49m\u001b[33;43mtools\u001b[39;49m\u001b[33;43m\"\u001b[39;49m\u001b[43m:\u001b[49m\u001b[43m \u001b[49m\u001b[43mtools\u001b[49m\u001b[43m,\u001b[49m\n\u001b[32m    482\u001b[39m \u001b[43m                \u001b[49m\u001b[33;43m\"\u001b[39;49m\u001b[33;43mtop_logprobs\u001b[39;49m\u001b[33;43m\"\u001b[39;49m\u001b[43m:\u001b[49m\u001b[43m \u001b[49m\u001b[43mtop_logprobs\u001b[49m\u001b[43m,\u001b[49m\n\u001b[32m    483\u001b[39m \u001b[43m                \u001b[49m\u001b[33;43m\"\u001b[39;49m\u001b[33;43mtop_p\u001b[39;49m\u001b[33;43m\"\u001b[39;49m\u001b[43m:\u001b[49m\u001b[43m \u001b[49m\u001b[43mtop_p\u001b[49m\u001b[43m,\u001b[49m\n\u001b[32m    484\u001b[39m \u001b[43m                \u001b[49m\u001b[33;43m\"\u001b[39;49m\u001b[33;43muser\u001b[39;49m\u001b[33;43m\"\u001b[39;49m\u001b[43m:\u001b[49m\u001b[43m \u001b[49m\u001b[43muser\u001b[49m\u001b[43m,\u001b[49m\n\u001b[32m    485\u001b[39m \u001b[43m            \u001b[49m\u001b[43m}\u001b[49m\u001b[43m,\u001b[49m\n\u001b[32m    486\u001b[39m \u001b[43m            \u001b[49m\u001b[43mcompletion_create_params\u001b[49m\u001b[43m.\u001b[49m\u001b[43mCompletionCreateParams\u001b[49m\u001b[43m,\u001b[49m\n\u001b[32m    487\u001b[39m \u001b[43m        \u001b[49m\u001b[43m)\u001b[49m\u001b[43m,\u001b[49m\n\u001b[32m    488\u001b[39m \u001b[43m        \u001b[49m\u001b[43moptions\u001b[49m\u001b[43m=\u001b[49m\u001b[43mmake_request_options\u001b[49m\u001b[43m(\u001b[49m\n\u001b[32m    489\u001b[39m \u001b[43m            \u001b[49m\u001b[43mextra_headers\u001b[49m\u001b[43m=\u001b[49m\u001b[43mextra_headers\u001b[49m\u001b[43m,\u001b[49m\u001b[43m \u001b[49m\u001b[43mextra_query\u001b[49m\u001b[43m=\u001b[49m\u001b[43mextra_query\u001b[49m\u001b[43m,\u001b[49m\u001b[43m \u001b[49m\u001b[43mextra_body\u001b[49m\u001b[43m=\u001b[49m\u001b[43mextra_body\u001b[49m\u001b[43m,\u001b[49m\u001b[43m \u001b[49m\u001b[43mtimeout\u001b[49m\u001b[43m=\u001b[49m\u001b[43mtimeout\u001b[49m\n\u001b[32m    490\u001b[39m \u001b[43m        \u001b[49m\u001b[43m)\u001b[49m\u001b[43m,\u001b[49m\n\u001b[32m    491\u001b[39m \u001b[43m        \u001b[49m\u001b[43mcast_to\u001b[49m\u001b[43m=\u001b[49m\u001b[43mChatCompletion\u001b[49m\u001b[43m,\u001b[49m\n\u001b[32m    492\u001b[39m \u001b[43m        \u001b[49m\u001b[43mstream\u001b[49m\u001b[43m=\u001b[49m\u001b[43mstream\u001b[49m\u001b[43m \u001b[49m\u001b[38;5;129;43;01mor\u001b[39;49;00m\u001b[43m \u001b[49m\u001b[38;5;28;43;01mFalse\u001b[39;49;00m\u001b[43m,\u001b[49m\n\u001b[32m    493\u001b[39m \u001b[43m        \u001b[49m\u001b[43mstream_cls\u001b[49m\u001b[43m=\u001b[49m\u001b[43mStream\u001b[49m\u001b[43m[\u001b[49m\u001b[43mChatCompletionChunk\u001b[49m\u001b[43m]\u001b[49m\u001b[43m,\u001b[49m\n\u001b[32m    494\u001b[39m \u001b[43m    \u001b[49m\u001b[43m)\u001b[49m\n",
      "\u001b[36mFile \u001b[39m\u001b[32md:\\Code Assistant\\venv\\Lib\\site-packages\\groq\\_base_client.py:1242\u001b[39m, in \u001b[36mSyncAPIClient.post\u001b[39m\u001b[34m(self, path, cast_to, body, options, files, stream, stream_cls)\u001b[39m\n\u001b[32m   1228\u001b[39m \u001b[38;5;28;01mdef\u001b[39;00m\u001b[38;5;250m \u001b[39m\u001b[34mpost\u001b[39m(\n\u001b[32m   1229\u001b[39m     \u001b[38;5;28mself\u001b[39m,\n\u001b[32m   1230\u001b[39m     path: \u001b[38;5;28mstr\u001b[39m,\n\u001b[32m   (...)\u001b[39m\u001b[32m   1237\u001b[39m     stream_cls: \u001b[38;5;28mtype\u001b[39m[_StreamT] | \u001b[38;5;28;01mNone\u001b[39;00m = \u001b[38;5;28;01mNone\u001b[39;00m,\n\u001b[32m   1238\u001b[39m ) -> ResponseT | _StreamT:\n\u001b[32m   1239\u001b[39m     opts = FinalRequestOptions.construct(\n\u001b[32m   1240\u001b[39m         method=\u001b[33m\"\u001b[39m\u001b[33mpost\u001b[39m\u001b[33m\"\u001b[39m, url=path, json_data=body, files=to_httpx_files(files), **options\n\u001b[32m   1241\u001b[39m     )\n\u001b[32m-> \u001b[39m\u001b[32m1242\u001b[39m     \u001b[38;5;28;01mreturn\u001b[39;00m cast(ResponseT, \u001b[38;5;28;43mself\u001b[39;49m\u001b[43m.\u001b[49m\u001b[43mrequest\u001b[49m\u001b[43m(\u001b[49m\u001b[43mcast_to\u001b[49m\u001b[43m,\u001b[49m\u001b[43m \u001b[49m\u001b[43mopts\u001b[49m\u001b[43m,\u001b[49m\u001b[43m \u001b[49m\u001b[43mstream\u001b[49m\u001b[43m=\u001b[49m\u001b[43mstream\u001b[49m\u001b[43m,\u001b[49m\u001b[43m \u001b[49m\u001b[43mstream_cls\u001b[49m\u001b[43m=\u001b[49m\u001b[43mstream_cls\u001b[49m\u001b[43m)\u001b[49m)\n",
      "\u001b[36mFile \u001b[39m\u001b[32md:\\Code Assistant\\venv\\Lib\\site-packages\\groq\\_base_client.py:1044\u001b[39m, in \u001b[36mSyncAPIClient.request\u001b[39m\u001b[34m(self, cast_to, options, stream, stream_cls)\u001b[39m\n\u001b[32m   1041\u001b[39m             err.response.read()\n\u001b[32m   1043\u001b[39m         log.debug(\u001b[33m\"\u001b[39m\u001b[33mRe-raising status error\u001b[39m\u001b[33m\"\u001b[39m)\n\u001b[32m-> \u001b[39m\u001b[32m1044\u001b[39m         \u001b[38;5;28;01mraise\u001b[39;00m \u001b[38;5;28mself\u001b[39m._make_status_error_from_response(err.response) \u001b[38;5;28;01mfrom\u001b[39;00m\u001b[38;5;250m \u001b[39m\u001b[38;5;28;01mNone\u001b[39;00m\n\u001b[32m   1046\u001b[39m     \u001b[38;5;28;01mbreak\u001b[39;00m\n\u001b[32m   1048\u001b[39m \u001b[38;5;28;01massert\u001b[39;00m response \u001b[38;5;129;01mis\u001b[39;00m \u001b[38;5;129;01mnot\u001b[39;00m \u001b[38;5;28;01mNone\u001b[39;00m, \u001b[33m\"\u001b[39m\u001b[33mcould not resolve response (should never happen)\u001b[39m\u001b[33m\"\u001b[39m\n",
      "\u001b[31mBadRequestError\u001b[39m: Error code: 400 - {'error': {'message': \"'messages' : minimum number of items is 1\", 'type': 'invalid_request_error'}}",
      "During task with name 'agent' and id '86cec74b-8de0-333f-a9bc-70cb56e8a6a1'"
     ]
    }
   ],
   "source": [
    "import os\n",
    "import pandas as pd\n",
    "from langchain.chat_models import init_chat_model\n",
    "from langchain_core.tools import tool\n",
    "from langgraph.checkpoint.memory import MemorySaver\n",
    "from langgraph.prebuilt import create_react_agent\n",
    "\n",
    "# -------------------------\n",
    "# 1. Dummy DataFrame\n",
    "# -------------------------\n",
    "data = {\n",
    "    \"age\": [25, 30, None, 40, 35],\n",
    "    \"income\": [50000, 60000, 55000, None, 65000],\n",
    "    \"gender\": [\"M\", \"F\", \"F\", \"M\", None]\n",
    "}\n",
    "df = pd.DataFrame(data)\n",
    "\n",
    "# -------------------------\n",
    "# 2. Define a Python tool\n",
    "# -------------------------\n",
    "@tool\n",
    "def python_repl_ast(query: str) -> str:\n",
    "    \"\"\"Run Python code with access to a pandas DataFrame `df`.\"\"\"\n",
    "    local_namespace = {\"df\": df}\n",
    "    try:\n",
    "        exec(query, {}, local_namespace)\n",
    "        # Capture last expression if exists\n",
    "        result = local_namespace.get(\"result\", \"Executed successfully.\")\n",
    "        return str(result)\n",
    "    except Exception as e:\n",
    "        return f\"Error: {e}\"\n",
    "\n",
    "# -------------------------\n",
    "# 3. Init LLM\n",
    "# -------------------------\n",
    "# pick a free model wrapper you have (e.g. Ollama, HuggingFace, or OpenAI key)\n",
    "# here I’ll assume you’re using an OpenAI-compatible model\n",
    "llm = ChatGroq(temperature=0, model_name=\"openai/gpt-oss-120b\")\n",
    "\n",
    "# -------------------------\n",
    "# 4. Create ReAct agent\n",
    "# -------------------------\n",
    "memory = MemorySaver()\n",
    "tools = [python_repl_ast]\n",
    "agent_executor = create_react_agent(llm, tools, checkpointer=memory)\n",
    "\n",
    "# -------------------------\n",
    "# 5. Run query\n",
    "# -------------------------\n",
    "query = \"Give the overview of the dataframe `df` and the preprocessing steps needed for EDA.\"\n",
    "response = agent_executor.invoke(\n",
    "    {\"input\": \"Give the overview of the dataframe `df` and the preprocessing steps needed for EDA.\"},\n",
    "    config={\"configurable\": {\"thread_id\": \"preprocess-session-1\"}}\n",
    ")\n",
    "\n",
    "\n",
    "print(\"\\n=== FINAL OUTPUT ===\")\n",
    "print(response[\"output\"])\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 2,
   "id": "01f78bd7",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "--- Running Query ---\n",
      "User Query: Give me a summary of the dataframe, including the data types and null values.\n",
      "\n",
      "\n",
      "\u001b[1m> Entering new AgentExecutor chain...\u001b[0m\n",
      "An error occurred: Tool choice is none, but model called a tool\n",
      "--- Running Query ---\n",
      "User Query: What is the total revenue from all sales?\n",
      "\n",
      "\n",
      "\u001b[1m> Entering new AgentExecutor chain...\u001b[0m\n",
      "An error occurred: Tool choice is none, but model called a tool\n",
      "--- Running Query ---\n",
      "User Query: Which product had the highest quantity sold?\n",
      "\n",
      "\n",
      "\u001b[1m> Entering new AgentExecutor chain...\u001b[0m\n",
      "An error occurred: Tool choice is none, but model called a tool\n",
      "--- Running Query ---\n",
      "User Query: What was the average unit price for products in the 'Electronics' category?\n",
      "\n",
      "\n",
      "\u001b[1m> Entering new AgentExecutor chain...\u001b[0m\n",
      "An error occurred: Tool choice is none, but model called a tool\n"
     ]
    }
   ],
   "source": [
    "import os\n",
    "import pandas as pd\n",
    "from langchain_experimental.agents.agent_toolkits import create_pandas_dataframe_agent\n",
    "from langchain_groq import ChatGroq\n",
    "\n",
    "# --- Configuration ---\n",
    "# 1. Get your Groq API key from https://console.groq.com/keys\n",
    "# 2. Set it as an environment variable\n",
    "os.environ[\"GROQ_API_KEY\"] = \"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\"\n",
    "\n",
    "# --- Create a Sample DataFrame ---\n",
    "data = {\n",
    "    'product_name': ['Laptop', 'Mouse', 'Keyboard', 'Monitor', 'Webcam'],\n",
    "    'category': ['Electronics', 'Electronics', 'Electronics', 'Electronics', 'Accessories'],\n",
    "    'quantity_sold': [120, 350, 275, 150, 400],\n",
    "    'unit_price': [1200, 25, 75, 300, 50],\n",
    "    'sale_date': pd.to_datetime(['2023-01-15', '2023-01-20', '2023-02-10', '2023-02-12', '2023-03-05'])\n",
    "}\n",
    "df = pd.DataFrame(data)\n",
    "df['total_revenue'] = df['quantity_sold'] * df['unit_price']\n",
    "\n",
    "\n",
    "# --- Initialize the Groq LLM ---\n",
    "# Using a model like Llama3 8b is a good choice for speed and capability\n",
    "# You can also use other models available on Groq, like \"mixtral-8x7b-32768\"\n",
    "llm = ChatGroq(temperature=0, model_name=\"openai/gpt-oss-120b\")\n",
    "\n",
    "# --- Create the Pandas DataFrame Agent ---\n",
    "# Note: allow_dangerous_code=True is required for the agent to execute python code.\n",
    "# This should only be used in a secure, sandboxed environment.\n",
    "agent = create_pandas_dataframe_agent(\n",
    "    llm,\n",
    "    df,\n",
    "    verbose=True,\n",
    "    allow_dangerous_code=True\n",
    ")\n",
    "\n",
    "# --- Define Queries for the Agent to Perform ---\n",
    "queries = [\n",
    "    \"Give me a summary of the dataframe, including the data types and null values.\",\n",
    "    \"What is the total revenue from all sales?\",\n",
    "    \"Which product had the highest quantity sold?\",\n",
    "    \"What was the average unit price for products in the 'Electronics' category?\",\n",
    "]\n",
    "\n",
    "# --- Run the Queries ---\n",
    "for query in queries:\n",
    "    print(f\"--- Running Query ---\")\n",
    "    print(f\"User Query: {query}\")\n",
    "    try:\n",
    "        response = agent.invoke(query)\n",
    "        print(f\"\\nAgent Response: {response['output']}\\n\")\n",
    "    except Exception as e:\n",
    "        print(f\"An error occurred: {e}\")"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "b208a483",
   "metadata": {},
   "outputs": [],
   "source": [
    "You are absolutely right. My apologies. In a true multi-agent supervisor pattern, the supervisor LLM must be the one making the routing decisions. A deterministic Python function breaks that pattern.\n",
    "\n",
    "The problem you're facing is a fascinating one: the LLM is correctly reasoning but failing at the last moment by hallucinating the tool name (json instead of Router). This is a known issue with some models when using the with_structured_output method.\n",
    "\n",
    "Let's force the LLM to do the right thing. There are two primary strategies to make this work reliably.\n",
    "\n",
    "Strategy 1: (Recommended) Bind the Tool Explicitly to the LLM\n",
    "\n",
    "This is the most modern and robust way to handle tool-calling with LangChain. Instead of just asking for structured output, you explicitly bind the tool (your Router Pydantic model) to the LLM. This gives the model a much stronger signal about the exact tool it is expected to use.\n",
    "\n",
    "This method is less prone to the \"hallucinated name\" error because the model is primed to use the specific tool you've given it.\n",
    "\n",
    "Here is how you modify your supervisor_node:\n",
    "\n",
    "code\n",
    "Python\n",
    "download\n",
    "content_copy\n",
    "expand_less\n",
    "\n",
    "from langchain_core.prompts import ChatPromptTemplate\n",
    "from langchain_core.pydantic_v1 import BaseModel, Field\n",
    "from typing import Literal\n",
    "\n",
    "# Make sure your Router model is defined correctly\n",
    "class Router(BaseModel):\n",
    "    \"\"\"Represents the routing decision and the reasoning behind it.\"\"\"\n",
    "    next: Literal[\"Analyzer_node\", \"__end__\"] = Field(\n",
    "        ...,\n",
    "        description=\"The next node to route to. Must be one of 'Analyzer_node' or '__end__'.\"\n",
    "    )\n",
    "    reasoning: str = Field(\n",
    "        ...,\n",
    "        description=\"A concise explanation of why this routing decision was made.\"\n",
    "    )\n",
    "\n",
    "# ... inside your supervisor_node ...\n",
    "def supervisor_node(self, state: AgentStateModel):\n",
    "    print(\"...\")\n",
    "\n",
    "    # --- NEW: Bind the Router tool to the LLM ---\n",
    "    # This creates a new runnable that is primed to use the Router tool.\n",
    "    llm_with_router_tool = self.tool_disabled_llm.bind_tools([Router])\n",
    "\n",
    "    # Your prompt can be simplified, as the model now knows its job is to call the tool.\n",
    "    prompt = ChatPromptTemplate.from_messages([\n",
    "        (\"system\", \"You are the supervisor. Your job is to review the current state and decide the next step. \"\n",
    "                   \"You must call the `Router` tool to indicate your decision.\"),\n",
    "        (\"user\", \"Here is the current state of the 'Analysis' field: {analysis_state}. \"\n",
    "                 \"If the field is an empty list (`[]`), route to 'Analyzer_node'. \"\n",
    "                 \"If it contains any data, route to '__end__'. Provide your reasoning.\"),\n",
    "    ])\n",
    "\n",
    "    # Create the chain: prompt -> LLM with tool -> (optional) parser\n",
    "    # The output of the LLM will now be a message containing a `tool_calls` attribute.\n",
    "    chain = prompt | llm_with_router_tool\n",
    "\n",
    "    print(\"***********************Invoking LLM for routing decision************************\")\n",
    "    \n",
    "    # Invoke the chain with the current state analysis\n",
    "    response_message = chain.invoke({\n",
    "        \"analysis_state\": str(state.Analysis) # Pass the state as a string for clarity\n",
    "    })\n",
    "\n",
    "    # --- NEW: Extract the arguments from the tool call ---\n",
    "    # The response is now a message object, not the parsed output directly.\n",
    "    tool_call = response_message.tool_calls[0]\n",
    "    if tool_call['name'] == \"Router\":\n",
    "        routing_decision = Router(**tool_call['args'])\n",
    "        goto = routing_decision.next\n",
    "        reasoning = routing_decision.reasoning\n",
    "    else:\n",
    "        # Fallback in case of another hallucination, though less likely now\n",
    "        print(f\"Warning: LLM called an unexpected tool: {tool_call['name']}\")\n",
    "        goto = \"__end__\" \n",
    "        reasoning = \"LLM failed to call the correct Router tool.\"\n",
    "\n",
    "    print(f\"********************************this is my goto*************************\\n{goto}\")\n",
    "    print(f\"********************************\\n{reasoning}\")\n",
    "\n",
    "    if goto == \"__end__\":\n",
    "        goto = END\n",
    "\n",
    "    return Command(\n",
    "        goto=goto,\n",
    "        update={'next': goto, 'current_reasoning': reasoning}\n",
    "    )\n",
    "\n",
    "Why this works better:\n",
    "\n",
    ".bind_tools([Router]) explicitly tells the Groq API that the Router tool is available for this call. The LLM is heavily incentivized to use it.\n",
    "\n",
    "The output is a standard AIMessage with a tool_calls attribute, which is a more standard and less \"magical\" way of handling tool use than with_structured_output.\n",
    "\n",
    "We manually parse the arguments from the tool call, giving us full control and visibility.\n",
    "\n",
    "Strategy 2: Force JSON Mode with a Specific Prompt\n",
    "\n",
    "If you want to stick closer to your original code, you can try to force the model into a JSON-only output mode with a very strong prompt. This is essentially \"prompt engineering\" a solution.\n",
    "\n",
    "code\n",
    "Python\n",
    "download\n",
    "content_copy\n",
    "expand_less\n",
    "IGNORE_WHEN_COPYING_START\n",
    "IGNORE_WHEN_COPYING_END\n",
    "# ... inside your supervisor_node ...\n",
    "def supervisor_node(self, state: AgentStateModel):\n",
    "    print(\"...\")\n",
    "\n",
    "    # Your Router Pydantic model is the same.\n",
    "    # We will use it with with_structured_output.\n",
    "\n",
    "    # --- NEW: A much more forceful prompt ---\n",
    "    # We explicitly tell the model its output format.\n",
    "    system_prompt = (\n",
    "        \"You are a supervisor agent. Your sole purpose is to act as a JSON router. \"\n",
    "        \"You will be given the current state of a task. \"\n",
    "        \"You must respond with ONLY a valid JSON object that conforms to the following Pydantic schema: \"\n",
    "        \"```json\\n\"\n",
    "        \"{\\\"title\\\": \\\"Router\\\", \\\"description\\\": \\\"...\\\", \\\"properties\\\": {\\\"next\\\": ..., \\\"reasoning\\\": ...}}\\n\"\n",
    "        \"```\\n\"\n",
    "        \"Do not add any other text, explanation, or markdown formatting around the JSON object.\"\n",
    "    )\n",
    "    \n",
    "    human_prompt = (\n",
    "        f\"Current 'Analysis' state: {state.Analysis}. \"\n",
    "        \"If 'Analysis' is empty, set 'next' to 'Analyzer_node'. \"\n",
    "        \"If 'Analysis' contains data, set 'next' to '__end__'. \"\n",
    "        \"Provide your reasoning in the 'reasoning' field.\"\n",
    "    )\n",
    "\n",
    "    messages_for_llm = [\n",
    "        SystemMessage(content=system_prompt),\n",
    "        HumanMessage(content=human_prompt),\n",
    "    ]\n",
    "\n",
    "    print(\"***********************Invoking LLM for routing decision************************\")\n",
    "    \n",
    "    # The invoke call remains the same\n",
    "    response = self.tool_disabled_llm.with_structured_output(Router).invoke(messages_for_llm)\n",
    "    \n",
    "    goto = response.next\n",
    "    reasoning = response.reasoning\n",
    "\n",
    "    print(f\"********************************this is my goto*************************\\n{goto}\")\n",
    "    print(f\"********************************\\n{reasoning}\")\n",
    "\n",
    "    if goto == \"__end__\":\n",
    "        goto = END\n",
    "\n",
    "    return Command(\n",
    "        goto=goto,\n",
    "        update={'next': goto, 'current_reasoning': reasoning}\n",
    "    )\n",
    "\n",
    "Why this might work:\n",
    "\n",
    "By explicitly telling the model to only output JSON and even showing it a schema snippet, you reduce its creative freedom and nudge it away from thinking it needs to wrap its output in a tool call.\n",
    "\n",
    "This approach relies more on the model's ability to follow instructions perfectly, which can still be brittle.\n",
    "\n",
    "Recommendation: Use Strategy 1 (bind_tools). It is the more modern, reliable, and idiomatic LangChain approach for this problem. It aligns with how models are being fine-tuned for tool use and is less susceptible to prompt-following errors."
   ]
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "venv",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.12.7"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 5
}