File size: 55,200 Bytes
24c2665
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
"""
IPO Triple Extractor

AZR Python Executor 기반 (Input, Program, Output) νŠΈλ¦¬ν”Œ μΆ”μΆœ μ‹œμŠ€ν…œ
μš”κ΅¬μ‚¬ν•­ 2: "AZR Python Executorλ₯Ό μ΄μš©ν•˜μ—¬ (i,p,o) pairλ₯Ό λ§Œλ“ λ‹€"
"""

import ast
import re
import json
from typing import Dict, List, Any, Tuple, Optional
from concurrent.futures import TimeoutError

from ..utils.code_utils.python_executor import PythonExecutor
from .config import TestTimeConfig
from .logger import TestTimeLogger
from .solution_generator import InitialSolutionGenerator


class IPOBuffer:
    """IPO triple을 μ €μž₯ν•˜κ³  κ΄€λ¦¬ν•˜λŠ” 버퍼"""
    
    def __init__(self):
        self.buffer = {}  # {problem_id: [ipo_triples]}
        
    def add(self, problem_id: str, ipo_triple: Dict[str, Any]):
        """IPO triple을 버퍼에 μΆ”κ°€"""
        if problem_id not in self.buffer:
            self.buffer[problem_id] = []
        self.buffer[problem_id].append(ipo_triple)
        
    def get_all(self, problem_id: str) -> List[Dict[str, Any]]:
        """νŠΉμ • 문제의 λͺ¨λ“  IPO triple λ°˜ν™˜"""
        return self.buffer.get(problem_id, [])
        
    def clear(self, problem_id: str = None):
        """버퍼 μ΄ˆκΈ°ν™”"""
        if problem_id:
            self.buffer.pop(problem_id, None)
        else:
            self.buffer.clear()
            
    def size(self, problem_id: str = None) -> int:
        """버퍼 크기 λ°˜ν™˜"""
        if problem_id:
            return len(self.buffer.get(problem_id, []))
        return sum(len(triples) for triples in self.buffer.values())


class IPOTripleExtractor:
    """(Input, Program, Output) νŠΈλ¦¬ν”Œ μΆ”μΆœ 및 검증"""
    
    def __init__(self, config: TestTimeConfig, logger: Optional[TestTimeLogger] = None,
                 model=None, tokenizer=None):
        self.config = config
        self.logger = logger or TestTimeLogger()
        self.model = model
        self.tokenizer = tokenizer
        
        # AZR Python Executor μ΄ˆκΈ°ν™” (κΈ°μ‘΄ 방식)
        self.executor = PythonExecutor(
            timeout_length=config.python_executor_timeout,
            ast_check=True,  # AZR κΈ°λ³Έ μ„€μ •
            max_workers=config.max_workers
        )
        
        self.extracted_triples = []
        
        # μž…λ ₯ 생성 ν”„λ‘¬ν”„νŠΈμ™€ 응닡 μ €μž₯용
        self.last_generation_prompt = ""
        self.last_generation_response = ""
        
        # VLLM 배치 처리λ₯Ό μœ„ν•œ μ°Έμ‘°
        self.solution_generator = None
        
    def extract_triples(self, problem: Dict[str, Any], solution: str) -> List[Dict[str, Any]]:
        """벀치마크 λ¬Έμ œμ™€ μ†”λ£¨μ…˜μ—μ„œ IPO νŠΈλ¦¬ν”Œ μΆ”μΆœ"""
        
        problem_id = problem.get('task_id', 'unknown')
        self.logger.log_info(f"πŸ” Extracting IPO triples for {problem_id}")
        
        triples = []
        
        try:
            # 1. ν•¨μˆ˜ 정보 μΆ”μΆœ (entry point μš°μ„ )
            entry_point = problem.get('entry_point', 'unknown')
            func_info = self._extract_function_info(solution, entry_point)
            if not func_info:
                self.logger.log_error(f"Failed to extract function info from solution")
                return []
            
            # 2. ν…ŒμŠ€νŠΈ μΌ€μ΄μŠ€μ—μ„œ μž…λ ₯-좜λ ₯ 쌍 생성 (LLM μ†”λ£¨μ…˜ 기반)
            test_cases = self._extract_test_cases(problem, solution)
            
            # 3. μ†”λ£¨μ…˜ μ‹€ν–‰μœΌλ‘œ IPO νŠΈλ¦¬ν”Œ 생성
            for i, (test_input_str, expected_output) in enumerate(test_cases):
                if len(triples) >= self.config.max_ipo_triples:
                    break
                
                # test_input_strμ—μ„œ μ‹€μ œ 인자 μΆ”μΆœ (예: "strlen('')" -> "''")
                import re
                match = re.match(rf'{entry_point}\((.*)\)', test_input_str)
                if match:
                    actual_args = match.group(1)
                else:
                    actual_args = test_input_str  # fallback
                    
                triple = self._create_ipo_triple(
                    func_info['full_code'],  # πŸ”§ μˆ˜μ •: 전체 μ½”λ“œ μ‚¬μš© (λ„μš°λ―Έ ν•¨μˆ˜ 포함)
                    func_info, 
                    actual_args,  # μ‹€μ œ 인자만 전달
                    expected_output,
                    triple_id=f"{problem_id}_triple_{i}",
                    full_input_str=test_input_str  # 전체 μž…λ ₯ λ¬Έμžμ—΄λ„ 전달
                )
                
                if triple:
                    triples.append(triple)
            
            # πŸ”§ μˆ˜μ •: Synthetic νŠΈλ¦¬ν”Œ 생성 제거 (단일 μ˜ˆμ‹œλ§Œ μ‚¬μš©ν•˜μ—¬ μΉ˜νŒ… λ°©μ§€)
            # Synthetic νŠΈλ¦¬ν”Œ 생성 λ‘œμ§μ„ μ œκ±°ν•˜μ—¬ μ§„μ§œ 단일 μ˜ˆμ‹œλ§Œ μ‚¬μš©
            
            # 검증 및 λ‘œκΉ…
            validation_results = [self._validate_triple(triple) for triple in triples]
            self.logger.log_ipo_extraction(problem_id, triples, validation_results)
            
            # μœ νš¨ν•œ νŠΈλ¦¬ν”Œλ§Œ λ°˜ν™˜
            valid_triples = [triple for triple, valid in zip(triples, validation_results) if valid]
            
            self.logger.log_info(f"βœ… Extracted {len(valid_triples)}/{len(triples)} valid IPO triples")
            return valid_triples
            
        except Exception as e:
            self.logger.log_error(f"IPO extraction failed: {e}")
            return []
    
    def _extract_function_info(self, solution: str, entry_point: str = None) -> Optional[Dict[str, str]]:
        """μ†”λ£¨μ…˜μ—μ„œ ν•¨μˆ˜ 정보 μΆ”μΆœ (entry point μš°μ„ )"""
        
        try:
            # πŸ”§ κ°œμ„ : Raw LLM response인지 ν™•μΈν•˜κ³  ν•¨μˆ˜ μ½”λ“œ μΆ”μΆœ
            processed_solution = solution
            if "LLM GENERATED SOLUTION:" in solution:
                self.logger.log_info("πŸ“ Raw LLM response detected, extracting function code")
                processed_solution = self._extract_function_from_llm_response(solution)
                if not processed_solution:
                    self.logger.log_error("Failed to extract function from LLM response")
                    return None
            
            # AST둜 ν•¨μˆ˜ μ •μ˜ νŒŒμ‹±
            tree = ast.parse(processed_solution)
            
            # πŸ”§ μˆ˜μ •: Entry point ν•¨μˆ˜ μš°μ„  검색
            target_function = None
            all_functions = []
            
            for node in ast.walk(tree):
                if isinstance(node, ast.FunctionDef):
                    func_info = {
                        'name': node.name,
                        'args': [arg.arg for arg in node.args.args],
                        'signature': f"def {node.name}({', '.join([arg.arg for arg in node.args.args])}):",
                        'full_code': processed_solution
                    }
                    all_functions.append(func_info)
                    
                    # Entry point와 μΌμΉ˜ν•˜λŠ” ν•¨μˆ˜ μš°μ„  선택
                    if entry_point and node.name == entry_point:
                        target_function = func_info
                        # 이 λ‘œκ·ΈλŠ” λ„ˆλ¬΄ 자주 좜λ ₯λ˜λ―€λ‘œ debug 레벨둜 λ³€κ²½
                        self.logger.log_debug(f"🎯 Found entry point function: {entry_point}")
                        break
            
            # Entry point ν•¨μˆ˜λ₯Ό μ°Ύμ•˜μœΌλ©΄ λ°˜ν™˜
            if target_function:
                return target_function
            
            # Entry pointλ₯Ό μ°Ύμ§€ λͺ»ν–ˆμœΌλ©΄ 첫 번째 ν•¨μˆ˜ λ°˜ν™˜ (κΈ°μ‘΄ 방식)
            if all_functions:
                self.logger.log_warning(f"⚠️  Entry point '{entry_point}' not found, using first function: {all_functions[0]['name']}")
                return all_functions[0]
            
            return None
            
        except Exception as e:
            self.logger.log_error(f"Function parsing failed: {e}")
            return None
    
    def _extract_function_from_llm_response(self, llm_response: str) -> str:
        """Raw LLM responseμ—μ„œ ν•¨μˆ˜ μ½”λ“œ μΆ”μΆœ (solution_generator와 λ™μΌν•œ 둜직)"""
        
        lines = llm_response.split('\n')
        solution_lines = []
        in_solution = False
        
        # "LLM GENERATED SOLUTION:" μ„Ήμ…˜ μΆ”μΆœ (μˆ˜μ •λœ 둜직)
        for i, line in enumerate(lines):
            if "LLM GENERATED SOLUTION:" in line:
                in_solution = True
                continue
            elif in_solution:
                # "===============" 라인이 λ‚˜μ˜€λ©΄ μ’…λ£Œν•˜λ˜, 첫 번째 "==============="λŠ” κ±΄λ„ˆλ›°κΈ°
                if "===============" in line:
                    # μ‹€μ œ μ†”λ£¨μ…˜ 라인듀이 μžˆλŠ”μ§€ 확인
                    if solution_lines and any(l.strip() for l in solution_lines):
                        break
                    else:
                        # 아직 μ†”λ£¨μ…˜ 라인이 μ—†μœΌλ©΄ 계속 μ§„ν–‰ (첫 번째 ꡬ뢄선 κ±΄λ„ˆλ›°κΈ°)
                        continue
                solution_lines.append(line)
        
        if not solution_lines:
            return ""  # μΆ”μΆœ μ‹€νŒ¨μ‹œ 빈 λ¬Έμžμ—΄ λ°˜ν™˜
        
        extracted_solution = '\n'.join(solution_lines).strip()
        
        # ν•¨μˆ˜ μ •μ˜μ™€ import μΆ”μΆœ (solution_generator 둜직과 동일)
        lines = extracted_solution.split('\n')
        import_lines = []
        func_lines = []
        in_function = False
        indent_level = 0
        
        # 1. import λ¬Έ μˆ˜μ§‘
        for line in lines:
            stripped = line.strip()
            if (stripped.startswith('import ') or stripped.startswith('from ')) and not stripped.startswith('#'):
                import_lines.append(line)
        
        # 2. ν•¨μˆ˜ μ •μ˜ μ°ΎκΈ°
        for line in lines:
            if line.strip().startswith('def '):
                in_function = True
                func_lines = [line]
                indent_level = len(line) - len(line.lstrip())
            elif in_function:
                if not line.strip() or (line.strip() and len(line) - len(line.lstrip()) > indent_level):
                    func_lines.append(line)
                else:
                    break
        
        # 3. import + function κ²°ν•©
        if func_lines:
            result_lines = import_lines + [''] + func_lines if import_lines else func_lines
            return '\n'.join(result_lines)
        else:
            return extracted_solution
    
    def _fix_humaneval_canonical_solution(self, problem: Dict[str, Any]) -> str:
        """HumanEval canonical solution 볡원 (ν•¨μˆ˜ μ‹œκ·Έλ‹ˆμ²˜ μΆ”κ°€)"""
        
        canonical_code = problem.get('canonical_solution', '')
        entry_point = problem.get('entry_point', '')
        prompt = problem.get('prompt', '')
        
        # HumanEval인지 확인
        task_id = problem.get('task_id', '')
        if not task_id.startswith('HumanEval/'):
            return canonical_code
        
        # 이미 ν•¨μˆ˜ μ‹œκ·Έλ‹ˆμ²˜κ°€ μžˆλŠ”μ§€ 확인
        if f"def {entry_point}" in canonical_code:
            return canonical_code
        
        try:
            # Promptμ—μ„œ ν•¨μˆ˜ μ‹œκ·Έλ‹ˆμ²˜ μΆ”μΆœ
            import re
            def_pattern = rf'def\s+{re.escape(entry_point)}\s*\([^)]*\)[^:]*:'
            match = re.search(def_pattern, prompt, re.MULTILINE)
            
            if match:
                function_signature = match.group(0)
                
                # Import 문도 μΆ”μΆœ (μžˆλ‹€λ©΄)
                import_lines = []
                for line in prompt.split('\n'):
                    stripped = line.strip()
                    if (stripped.startswith('import ') or stripped.startswith('from ')) and not stripped.startswith('#'):
                        import_lines.append(line)
                
                # μ™„μ „ν•œ canonical solution ꡬ성
                if import_lines:
                    complete_canonical = '\n'.join(import_lines) + '\n\n' + function_signature + canonical_code
                else:
                    complete_canonical = function_signature + canonical_code
                
                self.logger.log_info(f"πŸ”§ Fixed HumanEval canonical solution for {entry_point}")
                return complete_canonical
            else:
                self.logger.log_warning(f"⚠️  Could not extract function signature for {entry_point}")
                return canonical_code
                
        except Exception as e:
            self.logger.log_error(f"Failed to fix HumanEval canonical solution: {e}")
            return canonical_code
    
    def _extract_single_prompt_example(self, problem: Dict[str, Any]) -> Optional[Tuple[str, str]]:
        """πŸ”§ μƒˆλ‘œμš΄ λ©”μ„œλ“œ: ν”„λ‘¬ν”„νŠΈμ˜ 단일 μ˜ˆμ‹œλ§Œ μΆ”μΆœ (μΉ˜νŒ… λ°©μ§€)"""
        
        try:
            # base_input의 첫 번째 ν•­λͺ©μ„ 단일 μ˜ˆμ‹œλ‘œ μ‚¬μš©
            if 'base_input' in problem and problem['base_input']:
                first_input = problem['base_input'][0]
                entry_point = problem['entry_point']
                
                self.logger.log_info(f"πŸ“₯ Using first base_input as single example: {first_input}")
                
                # πŸ”§ μˆ˜μ •: HumanEval canonical solution 볡원
                canonical_code = self._fix_humaneval_canonical_solution(problem)
                if canonical_code:
                    actual_output = self._execute_llm_solution(canonical_code, entry_point, first_input)
                    
                    if actual_output is not None:
                        # μž…λ ₯ λ¬Έμžμ—΄ ν˜•μ‹ 생성
                        if isinstance(first_input, list):
                            if len(first_input) == 1 and isinstance(first_input[0], list):
                                # [[args]] -> 단일 리슀트 인자둜 ν‘œμ‹œ
                                input_str = repr(first_input[0])
                            elif len(first_input) == 1:
                                # [λ‹¨μΌμΈμž] -> λ‹¨μΌμΈμž
                                input_str = repr(first_input[0])
                            else:
                                # [λ‹€μ€‘μΈμž] -> λ‹€μ€‘μΈμž
                                input_str = ', '.join(repr(arg) for arg in first_input)
                        else:
                            input_str = repr(first_input)
                        
                        result = (input_str, str(actual_output))
                        self.logger.log_info(f"βœ… Single example extracted: Input={input_str}, Output={actual_output}")
                        return result
                    else:
                        self.logger.log_warning("❌ Failed to compute output with canonical solution")
                else:
                    self.logger.log_warning("❌ No canonical solution available")
            else:
                self.logger.log_warning("❌ No base_input available")
        
        except Exception as e:
            self.logger.log_error(f"Single example extraction failed: {e}")
        
        return None
    
    def _extract_docstring_examples(self, prompt: str, func_name: str) -> List[Tuple[str, str]]:
        """docstringμ—μ„œ >>> 예제 μΆ”μΆœ"""
        
        examples = []
        lines = prompt.split('\n')
        
        i = 0
        while i < len(lines):
            line = lines[i].strip()
            # >>> func_name(...) νŒ¨ν„΄ μ°ΎκΈ°
            if line.startswith('>>>') and func_name in line:
                # μž…λ ₯ μΆ”μΆœ
                input_line = line[3:].strip()  # >>> 제거
                
                # λ‹€μŒ μ€„μ—μ„œ 좜λ ₯ μΆ”μΆœ
                if i + 1 < len(lines):
                    output_line = lines[i + 1].strip()
                    # 좜λ ₯이 >>> 둜 μ‹œμž‘ν•˜μ§€ μ•ŠμœΌλ©΄ 좜λ ₯κ°’
                    if not output_line.startswith('>>>'):
                        examples.append((input_line, output_line))
                        i += 2
                        continue
                i += 1
            else:
                i += 1
        
        return examples
    
    def _extract_test_cases(self, problem: Dict[str, Any], solution: str) -> List[Tuple[str, str]]:
        """docstring의 μ˜ˆμ œμ—μ„œ ν…ŒμŠ€νŠΈ μΌ€μ΄μŠ€ μΆ”μΆœ (μΉ˜νŒ… λ°©μ§€)"""
        
        test_cases = []
        func_name = problem.get('entry_point', 'unknown')
        problem_id = problem.get('task_id', '')
        
        # HumanEvalκ³Ό MBPP λͺ¨λ‘ docstring 예제만 μ‚¬μš©
        self.logger.log_info(f"🎯 Extracting docstring examples for {problem_id}")
        
        # ν”„λ‘¬ν”„νŠΈμ—μ„œ docstring 예제 μΆ”μΆœ
        prompt = problem.get('prompt', '')
        examples = self._extract_docstring_examples(prompt, func_name)
        
        if examples:
            self.logger.log_info(f"πŸ“ Found {len(examples)} docstring examples")
            for i, (input_str, expected_output) in enumerate(examples):
                try:
                    # μž…λ ₯ νŒŒμ‹± (func_name(args) ν˜•νƒœμ—μ„œ args μΆ”μΆœ)
                    import ast
                    # "func_name(args)" -> args μΆ”μΆœ
                    if input_str.startswith(func_name + '(') and input_str.endswith(')'):
                        args_str = input_str[len(func_name)+1:-1]
                        # μ•ˆμ „ν•œ 평가λ₯Ό μœ„ν•΄ ast.literal_eval μ‚¬μš©
                        try:
                            # 단일 인자인 경우
                            input_args = ast.literal_eval(args_str)
                            if not isinstance(input_args, tuple):
                                input_args = (input_args,)
                        except:
                            # μ—¬λŸ¬ 인자인 경우 
                            input_args = ast.literal_eval(f"({args_str})")
                        
                        # LLM μ†”λ£¨μ…˜ μ‹€ν–‰
                        actual_output = self._execute_llm_solution(solution, func_name, list(input_args))
                        if actual_output is not None:
                            test_cases.append((input_str, str(actual_output)))
                            self.logger.log_info(f"βœ… Example {i+1}: {input_str} -> {actual_output}")
                        else:
                            self.logger.log_warning(f"❌ Example {i+1} execution failed")
                    
                except Exception as e:
                    self.logger.log_error(f"Example {i+1} parsing failed: {e}")
        else:
            self.logger.log_warning(f"⚠️ No docstring examples found, falling back to first base_input")
            # docstring μ˜ˆμ œκ°€ μ—†μœΌλ©΄ 첫 번째 base_input만 μ‚¬μš© (MBPP처럼)
            if 'base_input' in problem and problem['base_input']:
                inp_args = problem['base_input'][0]
                # μž…λ ₯ λ¬Έμžμ—΄ 생성
                if isinstance(inp_args, list):
                    args_str = ', '.join(repr(arg) for arg in inp_args)
                    input_str = f"{func_name}({args_str})"
                else:
                    input_str = f"{func_name}({repr(inp_args)})"
                
                actual_output = self._execute_llm_solution(solution, func_name, inp_args)
                if actual_output is not None:
                    test_cases.append((input_str, str(actual_output)))
        
        self.logger.log_info(f"πŸ“Š Extracted {len(test_cases)} test cases from docstring examples")
        return test_cases
    
    def _execute_llm_solution(self, llm_solution: str, func_name: str, input_args) -> Optional[str]:
        """LLM 생성 μ†”λ£¨μ…˜μ„ μ‹€ν–‰ν•˜μ—¬ μ‹€μ œ 좜λ ₯ 계산"""
        
        try:
            if not llm_solution or func_name == 'unknown':
                return None
            
            # πŸ”§ μˆ˜μ •: μ‹€ν–‰μš© μ½”λ“œ ꡬ성 (MBPP+ 이쀑 리슀트 처리)
            if isinstance(input_args, list):
                # MBPP+ 데이터가 이쀑 리슀트둜 감싸진 경우 처리
                if len(input_args) == 1 and isinstance(input_args[0], list):
                    # [[args]] -> 단일 리슀트 인자둜 전달
                    args_str = repr(input_args[0])
                elif len(input_args) == 1:
                    # [λ‹¨μΌμΈμž] -> 단일 인자둜 전달
                    args_str = repr(input_args[0])
                else:
                    # [λ‹€μ€‘μΈμž] -> 닀쀑 인자둜 전달
                    args_str = ', '.join(repr(arg) for arg in input_args)
            else:
                args_str = repr(input_args)
            
            execution_code = f"""
{llm_solution}

# Execute LLM solution
try:
    result = {func_name}({args_str})
    print(repr(result))
except Exception as e:
    print(f"EXECUTION_ERROR: {{e}}")
"""
            
            # AZR Python Executor둜 μ‹€ν–‰
            output, status = self.executor.apply(execution_code)
            
            if 'error' in status.lower() or 'EXECUTION_ERROR' in output:
                return None
                
            # 좜λ ₯μ—μ„œ κ²°κ³Ό μΆ”μΆœ
            output_lines = output.strip().split('\n')
            if output_lines:
                result_line = output_lines[-1].strip()
                # repr()둜 좜λ ₯된 κ²°κ³Όλ₯Ό κ·ΈλŒ€λ‘œ λ°˜ν™˜
                return result_line
            
            return None
            
        except Exception as e:
            self.logger.log_error(f"LLM solution execution failed: {e}")
            return None
    
    def _create_ipo_triple(self, solution: str, func_info: Dict[str, str], 
                          test_input: str, expected_output: str, 
                          triple_id: str, full_input_str: str = None) -> Optional[Dict[str, Any]]:
        """IPO νŠΈλ¦¬ν”Œ 생성 및 검증 (AZR Python Executor μ‚¬μš©)"""
        
        try:
            # 1. μ†”λ£¨μ…˜ μ‹€ν–‰μœΌλ‘œ μ‹€μ œ 좜λ ₯ 확인
            actual_output = self._execute_function(solution, func_info['name'], test_input)
            
            if actual_output is None:
                return None
            
            # 2. IPO νŠΈλ¦¬ν”Œ ꡬ성
            triple = {
                'id': triple_id,
                'input': test_input,  # μ‹€μ œ 인자만 μ €μž₯ (예: "''", "3.5")
                'full_input_str': full_input_str or f"{func_info['name']}({test_input})",  # 전체 μž…λ ₯ λ¬Έμžμ—΄μ€ 별도 ν•„λ“œμ—
                'program': solution,  # 이미 func_info['full_code']κ°€ 전달됨
                'expected_output': expected_output,
                'actual_output': actual_output,
                'function_name': func_info['name'],
                'function_args': func_info['args'],
                'is_correct': str(actual_output) == str(expected_output),
                'extraction_method': 'test_case'
            }
            
            return triple
            
        except Exception as e:
            self.logger.log_error(f"Triple creation failed for {triple_id}: {e}")
            return None
    
    def _execute_function(self, code: str, func_name: str, inputs: str) -> Optional[str]:
        """AZR Python Executor둜 ν•¨μˆ˜ μ‹€ν–‰"""
        
        try:
            # μ‹€ν–‰μš© μ½”λ“œ ꡬ성 (AZR ν…œν”Œλ¦Ώ μŠ€νƒ€μΌ)
            execution_code = f"""
{code}

# Execute function with inputs
try:
    result = {func_name}({inputs})
    print(repr(result))
except Exception as e:
    print(f"EXECUTION_ERROR: {{e}}")
"""
            
            # AZR λ°©μ‹μœΌλ‘œ μ‹€ν–‰
            output, status = self.executor.apply(execution_code)
            
            if 'error' in status.lower() or 'EXECUTION_ERROR' in output:
                return None
                
            # 좜λ ₯μ—μ„œ κ²°κ³Ό μΆ”μΆœ
            output_lines = output.strip().split('\n')
            if output_lines:
                return output_lines[-1].strip()
            
            return None
            
        except Exception as e:
            self.logger.log_error(f"Function execution failed: {e}")
            return None
    
    # πŸ”§ 제거: Synthetic νŠΈλ¦¬ν”Œ 생성 λ©”μ„œλ“œλ“€ 제거
    # 단일 μ˜ˆμ‹œλ§Œ μ‚¬μš©ν•˜μ—¬ μΉ˜νŒ… λ°©μ§€ λͺ©μ μ— 맞게 λΆˆν•„μš”ν•œ λ©”μ„œλ“œλ“€ 제거
    
    def _validate_triple(self, triple: Dict[str, Any]) -> bool:
        """IPO νŠΈλ¦¬ν”Œ 검증"""
        
        if not self.config.validate_triples:
            return True
            
        try:
            # 1. κΈ°λ³Έ ν•„λ“œ 쑴재 확인
            required_fields = ['input', 'program', 'expected_output', 'function_name']
            if not all(field in triple for field in required_fields):
                return False
            
            # 2. μ½”λ“œ ꡬ문 검증
            try:
                ast.parse(triple['program'])
            except SyntaxError:
                return False
            
            # 3. μž¬μ‹€ν–‰μœΌλ‘œ 일관성 검증 (AZR 방식)
            # 이제 triple['input']은 이미 μ‹€μ œ 인자만 포함
            actual_output = self._execute_function(
                triple['program'], 
                triple['function_name'], 
                triple['input']
            )
            
            if actual_output is None:
                return False
            
            # 4. 좜λ ₯ 일치 확인
            return str(actual_output) == str(triple['expected_output'])
            
        except Exception as e:
            self.logger.log_error(f"Triple validation failed: {e}")
            return False
    
    def get_triple_statistics(self) -> Dict[str, Any]:
        """μΆ”μΆœλœ νŠΈλ¦¬ν”Œ 톡계"""
        
        if not self.extracted_triples:
            return {"total": 0, "valid": 0, "invalid": 0}
        
        valid_count = sum(1 for triple in self.extracted_triples if triple.get('is_correct', False))
        
        return {
            "total": len(self.extracted_triples),
            "valid": valid_count,
            "invalid": len(self.extracted_triples) - valid_count,
            "extraction_methods": {
                "test_case": sum(1 for t in self.extracted_triples if t.get('extraction_method') == 'test_case'),
                "synthetic": sum(1 for t in self.extracted_triples if t.get('extraction_method') == 'synthetic')
            }
        }
    
    def generate_diverse_inputs(self, problem: Dict[str, Any], solution: str, 
                              existing_examples: List[Tuple[str, str]]) -> List[Dict[str, Any]]:
        """LLM을 μ‚¬μš©ν•˜μ—¬ λ‹€μ–‘ν•œ μž…λ ₯ 생성"""
        
        problem_id = problem.get('task_id', 'unknown')
        self.logger.log_info(f"🎲 Generating diverse inputs for {problem_id}")
        
        try:
            # 1. ν•¨μˆ˜ 정보 μΆ”μΆœ
            entry_point = problem.get('entry_point', 'unknown')
            func_info = self._extract_function_info(solution, entry_point)
            if not func_info:
                self.logger.log_error("Failed to extract function info for input generation")
                return []
            
            # 2. 인자 νƒ€μž… 정보 μΆ”λ‘ 
            arg_type_info = self._infer_argument_types(func_info, existing_examples, solution)
            
            # 3. ν”„λ‘¬ν”„νŠΈ 생성
            prompt = self._create_input_generation_prompt(
                problem_description=problem.get('prompt', ''),
                existing_examples=existing_examples,
                full_code=solution,
                arg_type_info=arg_type_info
            )
            
            # 4. LLM으둜 μž…λ ₯ 생성
            generated_inputs = self._call_llm_for_inputs(prompt, existing_examples, func_info, arg_type_info)
            
            # 5. μƒμ„±λœ μž…λ ₯ 검증
            valid_inputs = self._validate_generated_inputs(generated_inputs, func_info, solution)
            
            self.logger.log_info(f"βœ… Generated {len(valid_inputs)} valid diverse inputs")
            return valid_inputs
            
        except Exception as e:
            self.logger.log_error(f"Failed to generate diverse inputs: {e}")
            return []
    
    def generate_diverse_inputs_batch(self, program_input_pairs: List[Dict[str, Any]]) -> Tuple[List[List[Dict[str, Any]]], List[Optional[Dict[str, Any]]]]:
        """배치둜 μ—¬λŸ¬ ν”„λ‘œκ·Έλž¨μ˜ diverse input 생성"""
        
        if not self.solution_generator:
            self.logger.log_error("Solution generator not set for batch processing")
            return [], []
        
        self.logger.log_info(f"🎲 Generating diverse inputs for {len(program_input_pairs)} programs (BATCH)")
        
        try:
            # λͺ¨λ“  ν”„λ‘œκ·Έλž¨μ˜ μž…λ ₯ 생성 ν”„λ‘¬ν”„νŠΈ 생성
            batch_prompts = []
            program_contexts = []
            
            for pair in program_input_pairs:
                problem = pair['problem']
                solution = pair['solution']
                existing_examples = pair['existing_examples']
                
                # ν•¨μˆ˜ 정보 μΆ”μΆœ
                entry_point = problem.get('entry_point', 'unknown')
                func_info = self._extract_function_info(solution, entry_point)
                if not func_info:
                    program_contexts.append(None)
                    batch_prompts.append("")
                    continue
                
                # 인자 νƒ€μž… 정보 μΆ”λ‘ 
                arg_type_info = self._infer_argument_types(func_info, existing_examples, solution)
                
                # ν”„λ‘¬ν”„νŠΈ 생성
                prompt = self._create_input_generation_prompt(
                    problem_description=problem.get('prompt', ''),
                    existing_examples=existing_examples,
                    full_code=solution,
                    arg_type_info=arg_type_info
                )
                
                batch_prompts.append(prompt)
                program_contexts.append({
                    'func_info': func_info,
                    'solution': solution,
                    'problem': problem
                })
            
            # VLLM 배치둜 LLM 호좜
            if not batch_prompts or all(not p for p in batch_prompts):
                return [], []
            
            self.logger.log_info(f"πŸ” Sending {len(batch_prompts)} prompts to VLLM for input generation")
            self.logger.log_info(f"πŸ” First prompt preview: {batch_prompts[0][:200]}..." if batch_prompts else "No prompts")
            
            # Input generation은 μ½”λ“œ 생성이 μ•„λ‹ˆλ―€λ‘œ ν›„μ²˜λ¦¬ 없이 μ›μ‹œ 응닡 μ‚¬μš©
            # generate_batch의 ν›„μ²˜λ¦¬(ν•¨μˆ˜ μΆ”μΆœ λ“±)λŠ” input generation에 뢀적합
            batch_responses = self.solution_generator._generate_batch_with_vllm(
                batch_prompts, 
                temperature=0.7  # Input generationμ—λŠ” μ•½κ°„μ˜ λžœλ€μ„± ν•„μš”
            )
            
            self.logger.log_info(f"πŸ” Received {len(batch_responses)} responses from VLLM")
            for i, response in enumerate(batch_responses[:2]):  # 처음 2개만 λ‘œκΉ…
                self.logger.log_info(f"πŸ” Response {i} preview: {response[:200]}...")
            
            # 각 응닡을 νŒŒμ‹±ν•˜μ—¬ μž…λ ₯ 생성
            batch_results = []
            batch_generation_info = []  # 각 ν”„λ‘œκ·Έλž¨μ˜ input generation 정보 μ €μž₯
            
            for i, (response, context) in enumerate(zip(batch_responses, program_contexts)):
                if context is None:
                    batch_results.append([])
                    batch_generation_info.append(None)
                    continue
                
                try:
                    # μ‘λ‹΅μ—μ„œ μž…λ ₯ μΆ”μΆœ
                    generated_inputs = self._parse_llm_input_response(
                        response, 
                        context['func_info'], 
                        context['problem'].get('task_id', 'unknown')
                    )
                    
                    # 디버깅: νŒŒμ‹±λœ μž…λ ₯ 개수 λ‘œκΉ…
                    self.logger.log_info(f"πŸ” Parsed {len(generated_inputs)} inputs from response {i}")
                    if generated_inputs:
                        self.logger.log_info(f"πŸ” First parsed input: {generated_inputs[0]}")
                    
                    # μƒμ„±λœ μž…λ ₯ 검증
                    valid_inputs = self._validate_generated_inputs(
                        generated_inputs, 
                        context['func_info'], 
                        context['solution']
                    )
                    
                    # 디버깅: 검증 ν›„ μž…λ ₯ 개수 λ‘œκΉ…
                    self.logger.log_info(f"πŸ” {len(valid_inputs)} inputs passed validation from response {i}")
                    
                    batch_results.append(valid_inputs)
                    
                    # Input generation 정보 μ €μž₯
                    generation_info = {
                        'prompt': batch_prompts[i] if i < len(batch_prompts) else '',
                        'llm_response': response,
                        'extracted_inputs': generated_inputs,
                        'valid_inputs': valid_inputs,
                        'existing_examples': program_input_pairs[i]['existing_examples'] if i < len(program_input_pairs) else [],
                        'function_info': context['func_info'],
                        'arg_type_info': self._infer_argument_types(
                            context['func_info'], 
                            program_input_pairs[i]['existing_examples'] if i < len(program_input_pairs) else [],
                            context['solution']
                        )
                    }
                    batch_generation_info.append(generation_info)
                    
                except Exception as e:
                    self.logger.log_error(f"Failed to process batch item {i}: {e}")
                    # 더 μžμ„Έν•œ 디버깅 정보 μΆ”κ°€
                    self.logger.log_error(f"Response preview: {response[:200]}...")
                    import traceback
                    self.logger.log_error(f"Traceback: {traceback.format_exc()}")
                    batch_results.append([])
                    
                    # μ—λŸ¬ 정보도 μ €μž₯
                    batch_generation_info.append({
                        'error': str(e),
                        'prompt': batch_prompts[i] if i < len(batch_prompts) else '',
                        'llm_response': response,
                        'traceback': traceback.format_exc()
                    })
            
            total_generated = sum(len(inputs) for inputs in batch_results)
            self.logger.log_info(f"βœ… Generated {total_generated} diverse inputs across {len(program_input_pairs)} programs")
            
            # Return both inputs and generation info as a tuple
            return batch_results, batch_generation_info
            
        except Exception as e:
            self.logger.log_error(f"Batch input generation failed: {e}")
            return [], []
    
    def _parse_llm_input_response(self, llm_response: str, func_info: Dict[str, Any], problem_id: str) -> List[Dict[str, Any]]:
        """LLM μ‘λ‹΅μ—μ„œ μž…λ ₯ 예제 νŒŒμ‹±"""
        
        self.logger.log_info(f"πŸ” Parsing LLM response for {problem_id}, response length: {len(llm_response)}")
        
        try:
            # ```python ... ``` λΈ”λ‘μ—μ„œ μ½”λ“œ μΆ”μΆœ
            import re
            code_pattern = r'```python\n(.*?)\n```'
            matches = re.findall(code_pattern, llm_response, re.DOTALL)
            
            if not matches:
                self.logger.log_info("πŸ” No code block found, searching for examples = [")
                # 블둝이 μ—†μœΌλ©΄ 전체 μ‘λ‹΅μ—μ„œ examples = μ°ΎκΈ°
                if 'examples = [' in llm_response:
                    start = llm_response.find('examples = [')
                    # κ· ν˜•μž‘νžŒ κ΄„ν˜Έ μ°ΎκΈ°
                    bracket_count = 0
                    end = start
                    for i, char in enumerate(llm_response[start:]):
                        if char == '[':
                            bracket_count += 1
                        elif char == ']':
                            bracket_count -= 1
                            if bracket_count == 0:
                                end = start + i + 1
                                break
                    
                    if end > start:
                        code = llm_response[start:end]
                        self.logger.log_info(f"πŸ” Found examples code: {code[:100]}...")
                        exec_globals = {}
                        exec(code, exec_globals)
                        examples = exec_globals.get('examples', [])
                        self.logger.log_info(f"πŸ” Extracted {len(examples)} examples")
                        return examples
                else:
                    self.logger.log_info("πŸ” No 'examples = [' found in response")
            else:
                # μ½”λ“œ λΈ”λ‘μ—μ„œ examples μΆ”μΆœ
                self.logger.log_info(f"πŸ” Found {len(matches)} code blocks")
                code = matches[0]
                self.logger.log_info(f"πŸ” Code block preview: {code[:100]}...")
                exec_globals = {}
                exec(code, exec_globals)
                examples = exec_globals.get('examples', [])
                self.logger.log_info(f"πŸ” Extracted {len(examples)} examples from code block")
                
                # examplesκ°€ dictκ°€ μ•„λ‹Œ 경우 처리
                if examples and len(examples) > 0:
                    self.logger.log_info(f"πŸ” First example type: {type(examples[0])}")
                    if isinstance(examples[0], dict):
                        # expected_output, description λ“± λΆˆν•„μš”ν•œ ν‚€ 제거
                        cleaned_examples = []
                        for ex in examples:
                            cleaned = {k: v for k, v in ex.items() 
                                     if k not in ['expected_output', 'description']}
                            if cleaned:  # 빈 dictκ°€ μ•„λ‹Œ 경우만 μΆ”κ°€
                                cleaned_examples.append(cleaned)
                        self.logger.log_info(f"πŸ” Cleaned {len(cleaned_examples)} examples")
                        return cleaned_examples
                
                return examples
            
            return []
            
        except Exception as e:
            self.logger.log_error(f"Failed to parse generated examples for {problem_id}: {e}")
            import traceback
            self.logger.log_error(f"Traceback: {traceback.format_exc()}")
            return []
    
    def _infer_argument_types(self, func_info: Dict[str, str], 
                            examples: List[Tuple[str, str]], 
                            solution: str) -> Dict[str, str]:
        """κΈ°μ‘΄ μ˜ˆμ œμ™€ AST λΆ„μ„μœΌλ‘œ 인자 νƒ€μž… μΆ”λ‘ """
        
        arg_types = {}
        func_name = func_info['name']
        arg_names = func_info['args']
        
        # 1. ASTμ—μ„œ type annotation μΆ”μΆœ
        try:
            tree = ast.parse(solution)
            for node in ast.walk(tree):
                if isinstance(node, ast.FunctionDef) and node.name == func_name:
                    for i, arg in enumerate(node.args.args):
                        if i < len(arg_names) and arg.annotation:
                            # Type annotation이 μžˆλŠ” 경우
                            arg_types[arg_names[i]] = ast.unparse(arg.annotation)
        except:
            pass
        
        # 2. κΈ°μ‘΄ μ˜ˆμ œμ—μ„œ νƒ€μž… μΆ”λ‘ 
        if examples:
            for input_str, _ in examples:
                # "func_name(args)" ν˜•νƒœμ—μ„œ args μΆ”μΆœ
                if input_str.startswith(func_name + '(') and input_str.endswith(')'):
                    args_str = input_str[len(func_name)+1:-1]
                    try:
                        # 인자 νŒŒμ‹±
                        parsed_args = eval(f"({args_str},)")
                        if not isinstance(parsed_args, tuple):
                            parsed_args = (parsed_args,)
                        
                        # 각 인자의 νƒ€μž… μΆ”λ‘ 
                        for i, arg_value in enumerate(parsed_args):
                            if i < len(arg_names):
                                arg_name = arg_names[i]
                                arg_type = type(arg_value).__name__
                                
                                # νŠΉλ³„ν•œ μΌ€μ΄μŠ€ 처리
                                if isinstance(arg_value, list):
                                    if arg_value and all(isinstance(x, type(arg_value[0])) for x in arg_value):
                                        inner_type = type(arg_value[0]).__name__
                                        arg_type = f"List[{inner_type}]"
                                    else:
                                        arg_type = "List"
                                
                                # κΈ°μ‘΄ νƒ€μž…κ³Ό 병합
                                if arg_name not in arg_types:
                                    arg_types[arg_name] = arg_type
                    except:
                        pass
        
        # 3. νƒ€μž… 정보 λ”•μ…”λ„ˆλ¦¬λ‘œ λ°˜ν™˜
        # arg_typesκ°€ λΉ„μ–΄μžˆμœΌλ©΄ unknown νƒ€μž…μœΌλ‘œ μ±„μš°κΈ°
        for arg_name in arg_names:
            if arg_name not in arg_types:
                arg_types[arg_name] = "Any (type unknown)"
        
        return arg_types
    
    def _create_input_generation_prompt(self, problem_description: str, 
                                      existing_examples: List[Tuple[str, str]], 
                                      full_code: str, 
                                      arg_type_info: Dict[str, str]) -> str:
        """μž…λ ₯ 생성을 μœ„ν•œ ν”„λ‘¬ν”„νŠΈ 생성"""
        
        # λͺ¨λ“  κΈ°μ‘΄ 예제λ₯Ό ν¬λ§·νŒ…
        examples_text = ""
        for i, (input_str, output_str) in enumerate(existing_examples):
            examples_text += f"Example {i+1}:\n"
            examples_text += f"Input: {input_str}\n"
            examples_text += f"Output: {output_str}\n\n"
        
        # arg_type_infoλ₯Ό λ¬Έμžμ—΄λ‘œ ν¬λ§·νŒ…
        arg_type_text = "Argument types:\n"
        for arg, arg_type in arg_type_info.items():
            arg_type_text += f"- {arg}: {arg_type}\n"
        
        prompt = f"""Given the following problem description and its Python function implementation, first analyze the types and valid ranges of the function arguments, then write **5 different example inputs** for the function that cover a diverse mix of typical (general) cases and edge/boundary cases.

Problem Description:
'''
{problem_description}
'''

Existing Examples from Problem:
{examples_text}

Function Implementation:
```python
{full_code}
```

{arg_type_text}

Based on the existing examples above, generate 5 NEW diverse test inputs that are different from the existing ones. Each input should be a Python dict where:
- Keys are the exact parameter names from the function signature
- Values are appropriate test values for each parameter

Format your response as:
```python
examples = [
    {{dict_with_all_function_parameters}},  # Description of this test case
    {{dict_with_all_function_parameters}},  # Description of this test case
    ...  # Continue for all 5 examples
]
```

Ensure your examples include:
- At least 2 typical/general cases
- At least 2 edge/boundary cases  
- 1 special case (empty, zero, maximum values, etc.)
- All examples should be DIFFERENT from the existing examples shown above"""
        
        return prompt
    
    def _call_llm_for_inputs(self, prompt: str, existing_examples: List[Tuple[str, str]], 
                           func_info: Dict[str, Any], arg_type_info: str) -> List[Dict[str, Any]]:
        """LLM을 ν˜ΈμΆœν•˜μ—¬ μž…λ ₯ 생성 및 νŒŒμ‹±"""
        
        # ν”„λ‘¬ν”„νŠΈ μ €μž₯
        self.last_generation_prompt = prompt
        
        try:
            # Input μƒμ„±μš© μ „μš© LLM 호좜 (temperature=0.5)
            if self.model is not None and self.tokenizer is not None:
                # VLLM μ‚¬μš© 확인
                try:
                    from vllm import LLM
                    if isinstance(self.model, LLM):
                        response = self._generate_with_vllm_for_inputs(prompt)
                    else:
                        response = self._generate_with_hf_for_inputs(prompt)
                except ImportError:
                    response = self._generate_with_hf_for_inputs(prompt)
                
                # 응닡 μ €μž₯
                self.last_generation_response = response
                
                # μ‘λ‹΅μ—μ„œ examples μΆ”μΆœ
                parsed_inputs = self._parse_generated_examples(response)
                
                # μž…λ ₯ 생성 정보 μ €μž₯
                self.last_input_generation_info = {
                    'prompt': prompt,
                    'llm_response': response,
                    'extracted_inputs': parsed_inputs,
                    'existing_examples': existing_examples,
                    'function_info': func_info,
                    'arg_type_info': arg_type_info
                }
                
                return parsed_inputs
            else:
                # λͺ¨λΈμ΄ μ—†μœΌλ©΄ 빈 리슀트 λ°˜ν™˜ (ν…ŒμŠ€νŠΈ ν™˜κ²½)
                self.logger.log_warning("No model available for input generation")
                self.last_generation_response = "No model available"
                
                # μ‹€νŒ¨ν•œ κ²½μš°μ—λ„ 정보 μ €μž₯
                self.last_input_generation_info = {
                    'prompt': prompt,
                    'llm_response': "No model available",
                    'extracted_inputs': [],
                    'existing_examples': existing_examples,
                    'function_info': func_info,
                    'arg_type_info': arg_type_info,
                    'error': "No model available"
                }
                return []
            
        except Exception as e:
            self.logger.log_error(f"Failed to call LLM for inputs: {e}")
            self.last_generation_response = f"Error: {str(e)}"
            
            # μ—λŸ¬ λ°œμƒ μ‹œμ—λ„ 정보 μ €μž₯
            self.last_input_generation_info = {
                'prompt': locals().get('prompt', 'N/A'),
                'llm_response': f"Error: {str(e)}",
                'extracted_inputs': [],
                'existing_examples': locals().get('existing_examples', []),
                'function_info': locals().get('func_info', {}),
                'arg_type_info': locals().get('arg_type_info', 'N/A'),
                'error': str(e)
            }
            return []
    
    def _generate_with_vllm_for_inputs(self, prompt: str) -> str:
        """Input μƒμ„±μš© VLLM λ°±μ—”λ“œ (temperature=0.5둜 λ‹€μ–‘μ„± 확보)"""
        try:
            from vllm import SamplingParams
            
            # Input μƒμ„±μš© 높은 temperature μ„€μ •
            sampling_params = SamplingParams(
                temperature=0.5,        # λ‹€μ–‘ν•œ μž…λ ₯ 생성을 μœ„ν•œ 높은 temperature
                max_tokens=2048,
                top_p=0.95,            # 닀양성을 μœ„ν•΄ top_p μ‚¬μš©
                stop=["\n```\n"],      # μ½”λ“œ 블둝 μ’…λ£Œ μ‹œ μ •μ§€
            )
            
            outputs = self.model.generate([prompt], sampling_params, use_tqdm=False)
            return outputs[0].outputs[0].text.replace("\t", "    ").strip()
            
        except Exception as e:
            self.logger.log_error(f"VLLM input generation failed: {e}")
            return ""
    
    def _generate_with_hf_for_inputs(self, prompt: str) -> str:
        """Input μƒμ„±μš© HuggingFace λ°±μ—”λ“œ (temperature=0.5둜 λ‹€μ–‘μ„± 확보)"""
        try:
            import torch
            
            # ν† ν¬λ‚˜μ΄μ € 처리
            inputs = self.tokenizer(prompt, return_tensors='pt', truncation=True, max_length=4096)
            
            # attention mask λͺ…μ‹œμ μœΌλ‘œ μ„€μ •
            if 'attention_mask' not in inputs:
                inputs['attention_mask'] = torch.ones_like(inputs['input_ids'])
            
            # λ””λ°”μ΄μŠ€ 이동
            inputs = {k: v.to(self.model.device) for k, v in inputs.items()}
            
            with torch.no_grad():
                # λ©”λͺ¨λ¦¬ 정리
                if torch.cuda.is_available():
                    torch.cuda.empty_cache()
                
                # Input μƒμ„±μš© sampling μ„€μ •
                outputs = self.model.generate(
                    inputs['input_ids'],
                    attention_mask=inputs['attention_mask'],
                    max_new_tokens=2048,
                    do_sample=True,         # sampling ν™œμ„±ν™”
                    temperature=0.5,        # λ‹€μ–‘ν•œ μž…λ ₯ 생성을 μœ„ν•œ temperature
                    top_p=0.95,            # 닀양성을 μœ„ν•΄ top_p μ‚¬μš©
                    pad_token_id=self.tokenizer.eos_token_id,
                    eos_token_id=self.tokenizer.eos_token_id
                )
            
            # 응닡 μΆ”μΆœ
            response = self.tokenizer.decode(outputs[0], skip_special_tokens=True)
            response = response[len(prompt):].strip()
            return response
            
        except Exception as e:
            self.logger.log_error(f"HuggingFace input generation failed: {e}")
            return ""
    
    def _parse_generated_examples(self, llm_response: str) -> List[Dict[str, Any]]:
        """LLM μ‘λ‹΅μ—μ„œ 예제 νŒŒμ‹±"""
        
        try:
            # ```python ... ``` λΈ”λ‘μ—μ„œ μ½”λ“œ μΆ”μΆœ
            import re
            code_pattern = r'```python\n(.*?)\n```'
            matches = re.findall(code_pattern, llm_response, re.DOTALL)
            
            if not matches:
                # 블둝이 μ—†μœΌλ©΄ 전체 μ‘λ‹΅μ—μ„œ examples = μ°ΎκΈ°
                if 'examples = [' in llm_response:
                    start = llm_response.find('examples = [')
                    # κ· ν˜•μž‘νžŒ κ΄„ν˜Έ μ°ΎκΈ°
                    bracket_count = 0
                    end = start
                    for i, char in enumerate(llm_response[start:]):
                        if char == '[':
                            bracket_count += 1
                        elif char == ']':
                            bracket_count -= 1
                            if bracket_count == 0:
                                end = start + i + 1
                                break
                    
                    if end > start:
                        code = llm_response[start:end]
                        exec_globals = {}
                        exec(code, exec_globals)
                        return exec_globals.get('examples', [])
            else:
                # μ½”λ“œ λΈ”λ‘μ—μ„œ examples μΆ”μΆœ
                code = matches[0]
                exec_globals = {}
                exec(code, exec_globals)
                return exec_globals.get('examples', [])
            
            return []
            
        except Exception as e:
            self.logger.log_error(f"Failed to parse generated examples: {e}")
            return []
    
    def _validate_generated_inputs(self, generated_inputs: List[Dict[str, Any]], 
                                 func_info: Dict[str, str], 
                                 solution: str) -> List[Dict[str, Any]]:
        """μƒμ„±λœ μž…λ ₯의 μœ νš¨μ„± 검증"""
        
        valid_inputs = []
        func_name = func_info['name']
        
        for i, input_dict in enumerate(generated_inputs):
            try:
                # 1. ν•„μˆ˜ 인자 확인
                required_args = set(func_info['args'])
                provided_args = set(input_dict.keys())
                
                if not required_args.issubset(provided_args):
                    self.logger.log_warning(f"Input {i+1} missing required args: {required_args - provided_args}")
                    continue
                
                # 2. μ‹€μ œ μ‹€ν–‰μœΌλ‘œ 검증
                # 인자λ₯Ό μˆœμ„œλŒ€λ‘œ λ°°μ—΄
                args = [input_dict[arg] for arg in func_info['args'] if arg in input_dict]
                
                # μ‹€ν–‰ ν…ŒμŠ€νŠΈ
                output = self._execute_llm_solution(solution, func_name, args)
                if output is not None:
                    valid_inputs.append(input_dict)
                    self.logger.log_info(f"βœ… Valid input {i+1}: {input_dict}")
                else:
                    self.logger.log_warning(f"❌ Input {i+1} execution failed")
                    
            except Exception as e:
                self.logger.log_error(f"Input {i+1} validation error: {e}")
        
        return valid_inputs
    
    def create_ipo_from_input(self, problem: Dict[str, Any], 
                            solution: str, 
                            input_dict: Dict[str, Any]) -> Optional[Dict[str, Any]]:
        """μƒˆλ‘œμš΄ μž…λ ₯으둜 IPO triple 생성"""
        
        try:
            problem_id = problem.get('task_id', 'unknown')
            entry_point = problem.get('entry_point', 'unknown')
            
            # ν•¨μˆ˜ 정보 μΆ”μΆœ
            func_info = self._extract_function_info(solution, entry_point)
            if not func_info:
                return None
            
            # 인자λ₯Ό μˆœμ„œλŒ€λ‘œ λ°°μ—΄
            args = [input_dict[arg] for arg in func_info['args'] if arg in input_dict]
            
            # μ‹€ν–‰ν•˜μ—¬ 좜λ ₯ μ–»κΈ°
            output = self._execute_llm_solution(solution, func_info['name'], args)
            if output is None:
                return None
            
            # μž…λ ₯ λ¬Έμžμ—΄ 생성
            args_str = ', '.join(repr(arg) for arg in args)
            full_input_str = f"{func_info['name']}({args_str})"
            
            # IPO triple 생성
            triple_id = f"{problem_id}_generated_{len(self.extracted_triples)}"
            
            triple = {
                'id': triple_id,
                'input': args_str,  # μ‹€μ œ 인자만
                'full_input_str': full_input_str,  # 전체 ν•¨μˆ˜ 호좜
                'program': solution,
                'expected_output': output,
                'actual_output': output,
                'function_name': func_info['name'],
                'function_args': func_info['args'],
                'is_correct': True,  # μƒμ„±λœ 것은 항상 μ •ν™•
                'extraction_method': 'generated'
            }
            
            return triple
            
        except Exception as e:
            self.logger.log_error(f"Failed to create IPO from input: {e}")
            return None
    
    def cleanup(self):
        """λ¦¬μ†ŒμŠ€ 정리"""
        if hasattr(self.executor, 'cleanup'):
            self.executor.cleanup()