File size: 48,631 Bytes
4c0b7eb
bbc52c6
e7b4937
4c0b7eb
 
 
 
 
 
 
 
bbc52c6
4c0b7eb
bbc52c6
4c0b7eb
 
 
 
5890f66
a0fa418
 
5890f66
4c0b7eb
bbc52c6
4eed151
5890f66
4c0b7eb
 
 
 
 
bbc52c6
 
 
 
 
 
4eed151
b68b317
 
 
4eed151
5890f66
44d1862
5890f66
 
bbc52c6
4c0b7eb
 
 
91f84b2
ac73681
4c0b7eb
 
 
 
 
a0fa418
 
 
 
 
f1b095a
a0fa418
 
 
 
 
 
 
 
 
 
 
 
 
 
 
04ece4c
a0fa418
 
f1b095a
a0fa418
f1b095a
a0fa418
f1b095a
a0fa418
f1b095a
 
a0fa418
 
 
 
 
 
f1b095a
a0fa418
f1b095a
a0fa418
 
5890f66
 
 
 
6e73cae
5890f66
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
6e73cae
 
 
 
5890f66
 
 
 
6e73cae
5890f66
 
 
 
 
 
 
 
 
 
6e73cae
ac73681
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
41ac444
 
 
 
ac73681
 
 
 
 
 
 
 
 
41ac444
ac73681
91f84b2
 
ac73681
41ac444
 
 
 
 
ac73681
41ac444
ac73681
 
41ac444
ac73681
 
41ac444
 
 
44d1862
ac73681
 
4c0b7eb
 
 
 
6e73cae
bbc52c6
 
4c0b7eb
 
 
 
bbc52c6
4c0b7eb
 
 
bbc52c6
 
 
 
 
 
 
 
 
 
 
4eed151
 
 
 
 
 
 
 
 
 
5890f66
 
 
 
 
 
 
 
 
 
4c0b7eb
bbc52c6
4c0b7eb
 
6e73cae
bbc52c6
4c0b7eb
 
6e73cae
4c0b7eb
bbc52c6
 
4c0b7eb
 
 
 
 
 
 
 
 
 
 
 
6e73cae
 
 
4c0b7eb
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
bbc52c6
4c0b7eb
 
bbc52c6
4c0b7eb
 
 
6e73cae
4c0b7eb
 
 
bbc52c6
4c0b7eb
 
 
 
 
bbc52c6
4c0b7eb
 
6e73cae
bbc52c6
4c0b7eb
bbc52c6
6e73cae
bbc52c6
 
 
 
 
 
 
 
 
 
 
 
 
 
 
6e73cae
 
 
bbc52c6
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
6e73cae
 
bbc52c6
 
 
 
 
 
 
 
4eed151
 
 
 
6e73cae
4eed151
 
 
6e73cae
4eed151
 
 
 
 
 
 
 
 
 
 
 
 
 
 
6e73cae
 
 
4eed151
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
6e73cae
4eed151
 
 
6e73cae
4eed151
 
 
 
 
 
 
 
5890f66
 
 
 
6e73cae
5890f66
 
 
6e73cae
5890f66
 
 
 
 
 
 
 
 
 
 
 
 
 
 
6e73cae
 
 
5890f66
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
6e73cae
5890f66
 
 
 
 
 
6e73cae
5890f66
 
 
 
 
 
 
 
4eed151
 
 
 
6e73cae
bbc52c6
 
 
6e73cae
bbc52c6
4c0b7eb
bbc52c6
4c0b7eb
ac73681
 
5890f66
4c0b7eb
 
 
bbc52c6
 
4c0b7eb
 
bbc52c6
4c0b7eb
ac73681
bbc52c6
 
 
 
 
 
6e73cae
bbc52c6
41ac444
bbc52c6
 
 
4c0b7eb
 
 
 
6e73cae
 
 
 
 
 
 
 
 
4c0b7eb
6e73cae
4c0b7eb
41ac444
 
 
 
 
 
 
 
 
 
 
 
5890f66
4c0b7eb
5890f66
 
 
41ac444
 
5890f66
 
41ac444
4c0b7eb
 
 
 
 
 
5890f66
4c0b7eb
6e73cae
 
 
4c0b7eb
 
bbc52c6
4c0b7eb
 
 
 
6e73cae
4c0b7eb
 
 
 
 
 
6e73cae
 
 
 
 
 
 
4c0b7eb
bbc52c6
4c0b7eb
 
 
 
 
bbc52c6
4c0b7eb
 
6e73cae
bbc52c6
41ac444
bbc52c6
 
 
 
 
 
 
6e73cae
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
bbc52c6
6e73cae
 
 
bbc52c6
41ac444
 
 
 
 
 
 
 
 
 
 
 
5890f66
 
 
 
 
41ac444
 
bbc52c6
5890f66
41ac444
bbc52c6
 
 
 
 
 
5890f66
bbc52c6
6e73cae
 
 
bbc52c6
 
 
 
 
6e73cae
 
bbc52c6
 
 
 
 
6e73cae
bbc52c6
6e73cae
 
 
 
 
 
 
bbc52c6
 
 
 
 
 
4eed151
 
 
 
6e73cae
4eed151
41ac444
4eed151
 
 
 
 
 
 
 
 
 
 
 
 
 
 
6e73cae
 
 
4eed151
 
 
 
 
 
6e73cae
4eed151
 
 
 
41ac444
 
 
 
 
 
 
 
 
 
 
 
5890f66
4eed151
5890f66
 
 
41ac444
 
5890f66
 
41ac444
4eed151
 
 
 
 
 
5890f66
4eed151
6e73cae
41ac444
6e73cae
4eed151
 
 
6e73cae
4eed151
 
 
 
6e73cae
4eed151
 
 
 
6e73cae
 
 
 
4eed151
 
6e73cae
 
 
 
 
 
 
 
4eed151
 
 
 
 
 
5890f66
 
 
 
6e73cae
5890f66
41ac444
5890f66
 
 
 
 
 
 
 
 
 
 
 
 
 
 
6e73cae
 
 
5890f66
 
 
 
 
 
6e73cae
5890f66
 
 
 
41ac444
 
 
 
 
 
 
 
 
 
 
 
5890f66
 
 
 
 
41ac444
 
5890f66
 
41ac444
5890f66
 
 
 
 
 
 
 
6e73cae
 
 
5890f66
 
 
6e73cae
5890f66
 
 
 
 
 
 
 
6e73cae
5890f66
 
 
 
6e73cae
 
 
 
5890f66
 
6e73cae
 
 
 
 
 
 
 
5890f66
 
 
 
 
 
4eed151
 
 
 
6e73cae
bbc52c6
41ac444
bbc52c6
4c0b7eb
bbc52c6
4c0b7eb
ac73681
 
5890f66
4c0b7eb
 
bbc52c6
 
 
41ac444
4c0b7eb
 
bbc52c6
4c0b7eb
41ac444
bbc52c6
 
 
 
 
 
6e73cae
 
bbc52c6
 
4c0b7eb
 
6e73cae
 
 
4c0b7eb
 
 
 
 
c64957b
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
4c0b7eb
 
 
 
 
 
 
 
bbc52c6
4c0b7eb
 
bbc52c6
4c0b7eb
 
 
6e73cae
4c0b7eb
 
 
bbc52c6
4c0b7eb
 
 
 
bbc52c6
 
 
 
6e73cae
 
bbc52c6
 
 
 
6e73cae
 
 
bbc52c6
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
6e73cae
 
bbc52c6
 
 
 
 
 
 
 
4eed151
 
 
 
6e73cae
 
4eed151
f1b095a
 
4eed151
 
 
6e73cae
 
 
4eed151
 
 
 
 
c64957b
 
 
 
 
 
4eed151
c64957b
 
 
 
4eed151
c64957b
 
 
 
 
 
 
 
 
 
4eed151
 
 
 
 
 
 
 
86bc1db
f1b095a
86bc1db
a0fa418
f1b095a
86bc1db
f1b095a
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
86bc1db
4eed151
 
6e73cae
4eed151
 
 
 
c64957b
6e73cae
4eed151
 
c64957b
4eed151
c64957b
 
 
 
 
 
 
 
 
 
 
 
f1b095a
 
 
 
 
 
 
 
 
 
 
 
 
 
 
86bc1db
f1b095a
86bc1db
4eed151
 
 
5890f66
 
 
 
6e73cae
 
5890f66
 
 
 
6e73cae
 
 
5890f66
 
 
 
 
c64957b
 
 
 
 
 
5890f66
c64957b
 
 
 
5890f66
c64957b
 
 
 
 
 
 
 
 
 
5890f66
 
 
 
 
 
 
 
 
 
 
 
6e73cae
5890f66
 
 
 
 
 
6e73cae
5890f66
 
 
 
 
 
 
 
4eed151
 
 
 
6e73cae
 
bbc52c6
 
 
ac73681
 
5890f66
bbc52c6
 
 
 
 
 
 
 
ac73681
bbc52c6
 
4c0b7eb
 
 
 
6e73cae
4c0b7eb
 
 
 
 
 
bbc52c6
4c0b7eb
 
 
 
 
bbc52c6
4c0b7eb
bbc52c6
 
 
6e73cae
 
 
4c0b7eb
bbc52c6
4c0b7eb
 
 
 
 
 
 
bbc52c6
4c0b7eb
bbc52c6
4c0b7eb
 
 
 
 
 
 
 
 
 
bbc52c6
4c0b7eb
bbc52c6
 
6e73cae
bbc52c6
 
 
 
6e73cae
 
 
bbc52c6
 
 
6e73cae
 
 
bbc52c6
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
4c0b7eb
bbc52c6
 
 
 
 
6e73cae
bbc52c6
4c0b7eb
bbc52c6
 
 
6e73cae
bbc52c6
4c0b7eb
bbc52c6
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
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
"""
LLM Client Module - Multi-Provider LLM Integration
Author: @mangubee
Date: 2026-01-02

Handles all LLM calls for:
- Planning (question analysis and execution plan generation)
- Tool selection (function calling)
- Answer synthesis (factoid answer generation from evidence)
- Conflict resolution (evaluating contradictory information)

Based on Level 5 decision: Gemini 2.0 Flash (primary/free) + Claude Sonnet 4.5 (fallback/paid)
Based on Level 6 decision: LLM function calling for tool selection
Pattern: Matches Stage 2 tools (Gemini primary, Claude fallback)
"""

import os
import logging
import time
import datetime
from pathlib import Path
from typing import List, Dict, Optional, Any, Callable
from anthropic import Anthropic
import google.generativeai as genai
from huggingface_hub import InferenceClient
from groq import Groq

# ============================================================================
# CONFIG
# ============================================================================

# Claude Configuration
CLAUDE_MODEL = "claude-sonnet-4-5-20250929"

# Gemini Configuration
GEMINI_MODEL = "gemini-2.0-flash-exp"

# HuggingFace Configuration
HF_MODEL = "openai/gpt-oss-120b:scaleway"  # OpenAI's 120B open source model, strong reasoning
# Previous: "meta-llama/Llama-3.3-70B-Instruct:scaleway" (failed synthesis)
# Previous: "Qwen/Qwen2.5-72B-Instruct" (weaker at handling transcription errors)

# Groq Configuration
GROQ_MODEL = "openai/gpt-oss-120b"
# Alternatives: "llama-3.1-8b-instant", "mixtral-8x7b-32768"

# Shared Configuration
TEMPERATURE = 0  # Deterministic for factoid answers
MAX_TOKENS = 4096

# LLM Provider Selection (removed - now read at runtime for UI flexibility)

# ============================================================================
# Logging Setup
# ============================================================================
logger = logging.getLogger(__name__)

# ============================================================================
# Session Log File Management (Single file per evaluation run)
# ============================================================================

_SESSION_LOG_FILE = None
_SYSTEM_PROMPT_WRITTEN = False


def get_session_log_file() -> Path:
    """
    Get or create the session log file for LLM synthesis context.

    Creates a single log file per session (not per question) to avoid polluting
    the log/ folder with multiple files. All questions append to this one file.

    Returns:
        Path: Session log file path
    """
    global _SESSION_LOG_FILE

    if _SESSION_LOG_FILE is None:
        log_dir = Path("_log")
        log_dir.mkdir(exist_ok=True)

        # Create session filename with timestamp (use .md for Markdown)
        timestamp = datetime.datetime.now().strftime("%Y%m%d_%H%M%S")
        _SESSION_LOG_FILE = log_dir / f"llm_session_{timestamp}.md"

        # Write session header in Markdown
        with open(_SESSION_LOG_FILE, "w", encoding="utf-8") as f:
            f.write("# LLM Synthesis Session Log\n\n")
            f.write(f"**Session Start:** {datetime.datetime.now().isoformat()}\n\n")

    return _SESSION_LOG_FILE


def reset_session_log():
    """Reset session log file (for testing or new evaluation run)."""
    global _SESSION_LOG_FILE, _SYSTEM_PROMPT_WRITTEN
    _SESSION_LOG_FILE = None
    _SYSTEM_PROMPT_WRITTEN = False


# ============================================================================
# Retry Logic with Exponential Backoff
# ============================================================================


def retry_with_backoff(func: Callable, max_retries: int = 3) -> Any:
    """
    Retry function with exponential backoff on quota errors.

    Handles:
    - 429 rate limit errors
    - Quota exceeded errors
    - Respects retry_after header if present

    Args:
        func: Function to retry (should be a lambda or callable with no args)
        max_retries: Maximum number of retry attempts (default: 3)

    Returns:
        Result of successful function call

    Raises:
        Exception: If all retries exhausted or non-quota error encountered
    """
    for attempt in range(max_retries):
        try:
            return func()
        except Exception as e:
            error_str = str(e).lower()

            # Check if this is a quota/rate limit error
            is_quota_error = (
                "429" in str(e)
                or "quota" in error_str
                or "rate limit" in error_str
                or "too many requests" in error_str
            )

            if is_quota_error and attempt < max_retries - 1:
                # Exponential backoff: 1s, 2s, 4s
                wait_time = 2**attempt
                logger.warning(
                    f"Quota/rate limit error (attempt {attempt + 1}/{max_retries}): {e}. "
                    f"Retrying in {wait_time}s..."
                )
                time.sleep(wait_time)
                continue

            # If not a quota error, or last attempt, raise immediately
            raise


# ============================================================================
# LLM Provider Routing
# ============================================================================


def _get_provider_function(function_name: str, provider: str) -> Callable:
    """
    Get the provider-specific function for a given operation.

    Args:
        function_name: Base function name ("plan_question", "select_tools", "synthesize_answer")
        provider: Provider name ("gemini", "huggingface", "groq", "claude")

    Returns:
        Callable: Provider-specific function

    Raises:
        ValueError: If provider is invalid
    """
    # Map function names to provider-specific implementations
    function_map = {
        "plan_question": {
            "gemini": plan_question_gemini,
            "huggingface": plan_question_hf,
            "groq": plan_question_groq,
            "claude": plan_question_claude,
        },
        "select_tools": {
            "gemini": select_tools_gemini,
            "huggingface": select_tools_hf,
            "groq": select_tools_groq,
            "claude": select_tools_claude,
        },
        "synthesize_answer": {
            "gemini": synthesize_answer_gemini,
            "huggingface": synthesize_answer_hf,
            "groq": synthesize_answer_groq,
            "claude": synthesize_answer_claude,
        },
    }

    if function_name not in function_map:
        raise ValueError(f"Unknown function name: {function_name}")

    if provider not in function_map[function_name]:
        raise ValueError(
            f"Unknown provider: {provider}. Valid options: gemini, huggingface, groq, claude"
        )

    return function_map[function_name][provider]


def _call_with_fallback(function_name: str, *args, **kwargs) -> Any:
    """
    Call LLM function with configured provider.

    NOTE: Fallback mechanism has been archived to reduce complexity.
    Only the primary provider is used. If it fails, the error is raised directly.

    Args:
        function_name: Base function name ("plan_question", "select_tools", "synthesize_answer")
        *args, **kwargs: Arguments to pass to the provider-specific function

    Returns:
        Result from LLM call

    Raises:
        Exception: If primary provider fails
    """
    # Read config at runtime for UI flexibility
    primary_provider = os.getenv("LLM_PROVIDER", "gemini").lower()

    # ============================================================================
    # ARCHIVED: Fallback mechanism removed to reduce complexity
    # Original fallback code was at: dev/dev_260112_02_fallback_archived.md
    # To restore: Check git history or archived dev file
    # ============================================================================

    # Try primary provider only (no fallback)
    try:
        primary_func = _get_provider_function(function_name, primary_provider)
        logger.info(f"[{function_name}] Using provider: {primary_provider}")
        return retry_with_backoff(lambda: primary_func(*args, **kwargs))
    except Exception as primary_error:
        logger.error(f"[{function_name}] Provider {primary_provider} failed: {primary_error}")
        raise Exception(
            f"{function_name} failed with {primary_provider}: {primary_error}"
        )


# ============================================================================
# Client Initialization
# ============================================================================


def create_claude_client() -> Anthropic:
    """Initialize Anthropic client with API key from environment."""
    api_key = os.getenv("ANTHROPIC_API_KEY")
    if not api_key:
        raise ValueError("ANTHROPIC_API_KEY environment variable not set")

    logger.info(f"Initializing Anthropic client with model: {CLAUDE_MODEL}")
    return Anthropic(api_key=api_key)


def create_gemini_client():
    """Initialize Gemini client with API key from environment."""
    api_key = os.getenv("GOOGLE_API_KEY")
    if not api_key:
        raise ValueError("GOOGLE_API_KEY environment variable not set")

    genai.configure(api_key=api_key)
    logger.info(f"Initializing Gemini client with model: {GEMINI_MODEL}")
    return genai.GenerativeModel(GEMINI_MODEL)


def create_hf_client() -> InferenceClient:
    """Initialize HuggingFace Inference API client with token from environment."""
    hf_token = os.getenv("HF_TOKEN")
    if not hf_token:
        raise ValueError("HF_TOKEN environment variable not set")

    logger.info(f"Initializing HuggingFace Inference client with model: {HF_MODEL}")
    return InferenceClient(model=HF_MODEL, token=hf_token)


def create_groq_client() -> Groq:
    """Initialize Groq client with API key from environment."""
    api_key = os.getenv("GROQ_API_KEY")
    if not api_key:
        raise ValueError("GROQ_API_KEY environment variable not set")

    logger.info(f"Initializing Groq client with model: {GROQ_MODEL}")
    return Groq(api_key=api_key)


# ============================================================================
# Planning Functions - Claude Implementation
# ============================================================================


def plan_question_claude(
    question: str,
    available_tools: Dict[str, Dict],
    file_paths: Optional[List[str]] = None,
) -> str:
    """Analyze question and generate execution plan using Claude."""
    client = create_claude_client()

    # Format tool information
    tool_descriptions = []
    for name, info in available_tools.items():
        tool_descriptions.append(
            f"- {name}: {info['description']} (Category: {info['category']})"
        )
    tools_text = "\n".join(tool_descriptions)

    # File context
    file_context = ""
    if file_paths:
        file_context = f"\n\nAvailable files:\n" + "\n".join(
            [f"- {fp}" for fp in file_paths]
        )

    # Prompt for planning
    system_prompt = """You are a planning agent for answering complex questions.

Your task is to analyze the question and create a step-by-step execution plan.

Consider:
1. What information is needed to answer the question?
2. Which tools can provide that information?
3. In what order should tools be executed?
4. What parameters need to be extracted from the question?

Generate a concise plan with numbered steps."""

    user_prompt = f"""Question: {question}{file_context}

Available tools:
{tools_text}

Create an execution plan to answer this question. Format as numbered steps."""

    logger.info(f"[plan_question_claude] Calling Claude for planning")

    response = client.messages.create(
        model=CLAUDE_MODEL,
        max_tokens=MAX_TOKENS,
        temperature=TEMPERATURE,
        system=system_prompt,
        messages=[{"role": "user", "content": user_prompt}],
    )

    plan = response.content[0].text
    logger.info(f"[plan_question_claude] Generated plan ({len(plan)} chars)")

    return plan


# ============================================================================
# Planning Functions - Gemini Implementation
# ============================================================================


def plan_question_gemini(
    question: str,
    available_tools: Dict[str, Dict],
    file_paths: Optional[List[str]] = None,
) -> str:
    """Analyze question and generate execution plan using Gemini."""
    model = create_gemini_client()

    # Format tool information
    tool_descriptions = []
    for name, info in available_tools.items():
        tool_descriptions.append(
            f"- {name}: {info['description']} (Category: {info['category']})"
        )
    tools_text = "\n".join(tool_descriptions)

    # File context
    file_context = ""
    if file_paths:
        file_context = f"\n\nAvailable files:\n" + "\n".join(
            [f"- {fp}" for fp in file_paths]
        )

    # Combined prompt (Gemini doesn't use separate system/user like Claude)
    prompt = f"""You are a planning agent for answering complex questions.

Your task is to analyze the question and create a step-by-step execution plan.

Consider:
1. What information is needed to answer the question?
2. Which tools can provide that information?
3. In what order should tools be executed?
4. What parameters need to be extracted from the question?

Generate a concise plan with numbered steps.

Question: {question}{file_context}

Available tools:
{tools_text}

Create an execution plan to answer this question. Format as numbered steps."""

    logger.info(f"[plan_question_gemini] Calling Gemini for planning")

    response = model.generate_content(
        prompt,
        generation_config=genai.types.GenerationConfig(
            temperature=TEMPERATURE, max_output_tokens=MAX_TOKENS
        ),
    )

    plan = response.text
    logger.info(f"[plan_question_gemini] Generated plan ({len(plan)} chars)")

    return plan


# ============================================================================
# Planning Functions - HuggingFace Implementation
# ============================================================================


def plan_question_hf(
    question: str,
    available_tools: Dict[str, Dict],
    file_paths: Optional[List[str]] = None,
) -> str:
    """Analyze question and generate execution plan using HuggingFace Inference API."""
    client = create_hf_client()

    # Format tool information
    tool_descriptions = []
    for name, info in available_tools.items():
        tool_descriptions.append(
            f"- {name}: {info['description']} (Category: {info['category']})"
        )
    tools_text = "\n".join(tool_descriptions)

    # File context
    file_context = ""
    if file_paths:
        file_context = f"\n\nAvailable files:\n" + "\n".join(
            [f"- {fp}" for fp in file_paths]
        )

    # System message for Qwen 2.5 (supports system/user format)
    system_prompt = """You are a planning agent for answering complex questions.

Your task is to analyze the question and create a step-by-step execution plan.

Consider:
1. What information is needed to answer the question?
2. Which tools can provide that information?
3. In what order should tools be executed?
4. What parameters need to be extracted from the question?

Generate a concise plan with numbered steps."""

    user_prompt = f"""Question: {question}{file_context}

Available tools:
{tools_text}

Create an execution plan to answer this question. Format as numbered steps."""

    logger.info(f"[plan_question_hf] Calling HuggingFace ({HF_MODEL}) for planning")

    # HuggingFace Inference API chat completion
    messages = [
        {"role": "system", "content": system_prompt},
        {"role": "user", "content": user_prompt},
    ]

    response = client.chat_completion(
        messages=messages, max_tokens=MAX_TOKENS, temperature=TEMPERATURE
    )

    plan = response.choices[0].message.content
    logger.info(f"[plan_question_hf] Generated plan ({len(plan)} chars)")

    return plan


# ============================================================================
# Planning Functions - Groq Implementation
# ============================================================================


def plan_question_groq(
    question: str,
    available_tools: Dict[str, Dict],
    file_paths: Optional[List[str]] = None,
) -> str:
    """Analyze question and generate execution plan using Groq."""
    client = create_groq_client()

    # Format tool information
    tool_descriptions = []
    for name, info in available_tools.items():
        tool_descriptions.append(
            f"- {name}: {info['description']} (Category: {info['category']})"
        )
    tools_text = "\n".join(tool_descriptions)

    # File context
    file_context = ""
    if file_paths:
        file_context = f"\n\nAvailable files:\n" + "\n".join(
            [f"- {fp}" for fp in file_paths]
        )

    # System message for Llama 3.1 (supports system/user format)
    system_prompt = """You are a planning agent for answering complex questions.

Your task is to analyze the question and create a step-by-step execution plan.

Consider:
1. What information is needed to answer the question?
2. Which tools can provide that information?
3. In what order should tools be executed?
4. What parameters need to be extracted from the question?

Generate a concise plan with numbered steps."""

    user_prompt = f"""Question: {question}{file_context}

Available tools:
{tools_text}

Create an execution plan to answer this question. Format as numbered steps."""

    logger.info(f"[plan_question_groq] Calling Groq ({GROQ_MODEL}) for planning")

    # Groq uses OpenAI-compatible API
    messages = [
        {"role": "system", "content": system_prompt},
        {"role": "user", "content": user_prompt},
    ]

    response = client.chat.completions.create(
        model=GROQ_MODEL,
        messages=messages,
        max_tokens=MAX_TOKENS,
        temperature=TEMPERATURE,
    )

    plan = response.choices[0].message.content
    logger.info(f"[plan_question_groq] Generated plan ({len(plan)} chars)")

    return plan


# ============================================================================
# Unified Planning Function with Fallback Chain
# ============================================================================


def plan_question(
    question: str,
    available_tools: Dict[str, Dict],
    file_paths: Optional[List[str]] = None,
) -> str:
    """
    Analyze question and generate execution plan using LLM.

    Uses LLM_PROVIDER config to select which provider to use.
    If ENABLE_LLM_FALLBACK=true, falls back to other providers on failure.
    Each provider call wrapped with retry logic (3 attempts with exponential backoff).

    Args:
        question: GAIA question text
        available_tools: Tool registry (name -> {description, category, parameters})
        file_paths: Optional list of file paths for file-based questions

    Returns:
        Execution plan as structured text
    """
    return _call_with_fallback("plan_question", question, available_tools, file_paths)


# ============================================================================
# Tool Selection - Claude Implementation
# ============================================================================


def select_tools_claude(
    question: str, plan: str, available_tools: Dict[str, Dict], file_paths: Optional[List[str]] = None
) -> List[Dict[str, Any]]:
    """Use Claude function calling to select tools and extract parameters."""
    client = create_claude_client()

    # Convert tool registry to Claude function calling format
    tool_schemas = []
    for name, info in available_tools.items():
        tool_schemas.append(
            {
                "name": name,
                "description": info["description"],
                "input_schema": {
                    "type": "object",
                    "properties": info.get("parameters", {}),
                    "required": info.get("required_params", []),
                },
            }
        )

    # File context for tool selection
    file_context = ""
    if file_paths:
        file_context = f"""

IMPORTANT: These files are available for this question:
{chr(10).join(f"- {fp}" for fp in file_paths)}

When selecting tools, use the ACTUAL file paths listed above. Do NOT use placeholder paths like "<provided_path>" or "path_to_chess_image.jpg".
For vision tools with images: vision(image_path="<actual_file_path>")
For file parsing tools: parse_file(file_path="<actual_file_path>")"""

    system_prompt = f"""You are a tool selection expert. Based on the question and execution plan, select appropriate tools with correct parameters.

Few-shot examples:
- "How many albums did The Beatles release?" β†’ web_search(query="Beatles discography number of albums")
- "What is 25 * 37 + 100?" β†’ calculator(expression="25 * 37 + 100")
- "Analyze the image at example.com/pic.jpg" β†’ vision(image_path="example.com/pic.jpg")
- "What's in the uploaded Excel file?" β†’ parse_file(file_path="actual_file.xlsx")

Execute the plan step by step. Extract correct parameters from the question.
Use actual file paths when files are provided.{file_context}

Plan:
{plan}"""

    user_prompt = f"""Question: {question}

Select and call the tools needed according to the plan. Use exact parameter names from tool schemas."""

    logger.info(
        f"[select_tools_claude] Calling Claude with function calling for {len(tool_schemas)} tools"
    )

    response = client.messages.create(
        model=CLAUDE_MODEL,
        max_tokens=MAX_TOKENS,
        temperature=TEMPERATURE,
        system=system_prompt,
        messages=[{"role": "user", "content": user_prompt}],
        tools=tool_schemas,
    )

    # Extract tool calls from response
    tool_calls = []
    for content_block in response.content:
        if content_block.type == "tool_use":
            tool_calls.append(
                {
                    "tool": content_block.name,
                    "params": content_block.input,
                    "id": content_block.id,
                }
            )

    logger.info(f"[select_tools_claude] Claude selected {len(tool_calls)} tool(s)")

    return tool_calls


# ============================================================================
# Tool Selection - Gemini Implementation
# ============================================================================


def select_tools_gemini(
    question: str, plan: str, available_tools: Dict[str, Dict], file_paths: Optional[List[str]] = None
) -> List[Dict[str, Any]]:
    """Use Gemini function calling to select tools and extract parameters."""
    model = create_gemini_client()

    # Convert tool registry to Gemini function calling format
    tools = []
    for name, info in available_tools.items():
        tools.append(
            genai.protos.Tool(
                function_declarations=[
                    genai.protos.FunctionDeclaration(
                        name=name,
                        description=info["description"],
                        parameters=genai.protos.Schema(
                            type=genai.protos.Type.OBJECT,
                            properties={
                                param_name: genai.protos.Schema(
                                    type=genai.protos.Type.STRING,
                                    description=param_info.get("description", ""),
                                )
                                for param_name, param_info in info.get(
                                    "parameters", {}
                                ).items()
                            },
                            required=info.get("required_params", []),
                        ),
                    )
                ]
            )
        )

    # File context for tool selection
    file_context = ""
    if file_paths:
        file_context = f"""

IMPORTANT: These files are available for this question:
{chr(10).join(f"- {fp}" for fp in file_paths)}

When selecting tools, use the ACTUAL file paths listed above. Do NOT use placeholder paths like "<provided_path>" or "path_to_chess_image.jpg".
For vision tools with images: vision(image_path="<actual_file_path>")
For file parsing tools: parse_file(file_path="<actual_file_path>")"""

    prompt = f"""You are a tool selection expert. Based on the question and execution plan, select appropriate tools with correct parameters.

Few-shot examples:
- "How many albums did The Beatles release?" β†’ web_search(query="Beatles discography number of albums")
- "What is 25 * 37 + 100?" β†’ calculator(expression="25 * 37 + 100")
- "Analyze the image at example.com/pic.jpg" β†’ vision(image_path="example.com/pic.jpg")
- "What's in the uploaded Excel file?" β†’ parse_file(file_path="actual_file.xlsx")

Execute the plan step by step. Extract correct parameters from the question.
Use actual file paths when files are provided.{file_context}

Plan:
{plan}

Question: {question}

Select and call the tools needed according to the plan. Use exact parameter names from tool schemas."""

    logger.info(
        f"[select_tools_gemini] Calling Gemini with function calling for {len(available_tools)} tools"
    )

    response = model.generate_content(
        prompt,
        tools=tools,
        generation_config=genai.types.GenerationConfig(
            temperature=TEMPERATURE, max_output_tokens=MAX_TOKENS
        ),
    )

    # Extract tool calls from response
    tool_calls = []
    for part in response.parts:
        if hasattr(part, "function_call") and part.function_call:
            fc = part.function_call
            tool_calls.append(
                {
                    "tool": fc.name,
                    "params": dict(fc.args),
                    "id": f"gemini_{len(tool_calls)}",
                }
            )

    logger.info(f"[select_tools_gemini] Gemini selected {len(tool_calls)} tool(s)")

    return tool_calls


# ============================================================================
# Tool Selection - HuggingFace Implementation
# ============================================================================


def select_tools_hf(
    question: str, plan: str, available_tools: Dict[str, Dict], file_paths: Optional[List[str]] = None
) -> List[Dict[str, Any]]:
    """Use HuggingFace Inference API with function calling to select tools and extract parameters."""
    client = create_hf_client()

    # Convert tool registry to OpenAI-compatible tool schema (HF uses same format)
    tools = []
    for name, info in available_tools.items():
        tool_schema = {
            "type": "function",
            "function": {
                "name": name,
                "description": info["description"],
                "parameters": {
                    "type": "object",
                    "properties": {},
                    "required": info.get("required_params", []),
                },
            },
        }

        # Add parameter schemas
        for param_name, param_info in info.get("parameters", {}).items():
            tool_schema["function"]["parameters"]["properties"][param_name] = {
                "type": param_info.get("type", "string"),
                "description": param_info.get("description", ""),
            }

        tools.append(tool_schema)

    # File context for tool selection
    file_context = ""
    if file_paths:
        file_context = f"""

IMPORTANT: These files are available for this question:
{chr(10).join(f"- {fp}" for fp in file_paths)}

When selecting tools, use the ACTUAL file paths listed above. Do NOT use placeholder paths like "<provided_path>" or "path_to_chess_image.jpg".
For vision tools with images: vision(image_path="<actual_file_path>")
For file parsing tools: parse_file(file_path="<actual_file_path>")"""

    system_prompt = f"""You are a tool selection expert. Based on the question and execution plan, select appropriate tools with correct parameters.

Few-shot examples:
- "How many albums did The Beatles release?" β†’ web_search(query="Beatles discography number of albums")
- "What is 25 * 37 + 100?" β†’ calculator(expression="25 * 37 + 100")
- "Analyze the image at example.com/pic.jpg" β†’ vision(image_path="example.com/pic.jpg")
- "What's in the uploaded Excel file?" β†’ parse_file(file_path="actual_file.xlsx")

Execute the plan step by step. Extract correct parameters from the question.
Use actual file paths when files are provided.{file_context}

Plan:
{plan}"""

    user_prompt = f"""Question: {question}

Select and call the tools needed according to the plan. Use exact parameter names from tool schemas."""

    logger.info(
        f"[select_tools_hf] Calling HuggingFace with function calling for {len(tools)} tools, file_paths={file_paths}"
    )

    messages = [
        {"role": "system", "content": system_prompt},
        {"role": "user", "content": user_prompt},
    ]

    # HuggingFace Inference API with tools parameter
    response = client.chat_completion(
        messages=messages, tools=tools, max_tokens=MAX_TOKENS, temperature=TEMPERATURE
    )

    # Extract tool calls from response
    tool_calls = []
    if (
        hasattr(response.choices[0].message, "tool_calls")
        and response.choices[0].message.tool_calls
    ):
        for tool_call in response.choices[0].message.tool_calls:
            import json

            tool_calls.append(
                {
                    "tool": tool_call.function.name,
                    "params": json.loads(tool_call.function.arguments),
                    "id": tool_call.id,
                }
            )

    logger.info(f"[select_tools_hf] HuggingFace selected {len(tool_calls)} tool(s)")

    return tool_calls


# ============================================================================
# Tool Selection - Groq Implementation
# ============================================================================


def select_tools_groq(
    question: str, plan: str, available_tools: Dict[str, Dict], file_paths: Optional[List[str]] = None
) -> List[Dict[str, Any]]:
    """Use Groq with function calling to select tools and extract parameters."""
    client = create_groq_client()

    # Convert tool registry to OpenAI-compatible tool schema (Groq uses same format)
    tools = []
    for name, info in available_tools.items():
        tool_schema = {
            "type": "function",
            "function": {
                "name": name,
                "description": info["description"],
                "parameters": {
                    "type": "object",
                    "properties": {},
                    "required": info.get("required_params", []),
                },
            },
        }

        # Add parameter schemas
        for param_name, param_info in info.get("parameters", {}).items():
            tool_schema["function"]["parameters"]["properties"][param_name] = {
                "type": param_info.get("type", "string"),
                "description": param_info.get("description", ""),
            }

        tools.append(tool_schema)

    # File context for tool selection
    file_context = ""
    if file_paths:
        file_context = f"""

IMPORTANT: These files are available for this question:
{chr(10).join(f"- {fp}" for fp in file_paths)}

When selecting tools, use the ACTUAL file paths listed above. Do NOT use placeholder paths like "<provided_path>" or "path_to_chess_image.jpg".
For vision tools with images: vision(image_path="<actual_file_path>")
For file parsing tools: parse_file(file_path="<actual_file_path>")"""

    system_prompt = f"""You are a tool selection expert. Based on the question and execution plan, select appropriate tools with correct parameters.

Few-shot examples:
- "How many albums did The Beatles release?" β†’ web_search(query="Beatles discography number of albums")
- "What is 25 * 37 + 100?" β†’ calculator(expression="25 * 37 + 100")
- "Analyze the image at example.com/pic.jpg" β†’ vision(image_path="example.com/pic.jpg")
- "What's in the uploaded Excel file?" β†’ parse_file(file_path="actual_file.xlsx")

Execute the plan step by step. Extract correct parameters from the question.
Use actual file paths when files are provided.{file_context}

Plan:
{plan}"""

    user_prompt = f"""Question: {question}

Select and call the tools needed according to the plan. Use exact parameter names from tool schemas."""

    logger.info(
        f"[select_tools_groq] Calling Groq with function calling for {len(tools)} tools"
    )

    messages = [
        {"role": "system", "content": system_prompt},
        {"role": "user", "content": user_prompt},
    ]

    # Groq function calling
    response = client.chat.completions.create(
        model=GROQ_MODEL,
        messages=messages,
        tools=tools,
        max_tokens=MAX_TOKENS,
        temperature=TEMPERATURE,
    )

    # Extract tool calls from response
    tool_calls = []
    if (
        hasattr(response.choices[0].message, "tool_calls")
        and response.choices[0].message.tool_calls
    ):
        for tool_call in response.choices[0].message.tool_calls:
            import json

            tool_calls.append(
                {
                    "tool": tool_call.function.name,
                    "params": json.loads(tool_call.function.arguments),
                    "id": tool_call.id,
                }
            )

    logger.info(f"[select_tools_groq] Groq selected {len(tool_calls)} tool(s)")

    return tool_calls


# ============================================================================
# Unified Tool Selection with Fallback Chain
# ============================================================================


def select_tools_with_function_calling(
    question: str, plan: str, available_tools: Dict[str, Dict], file_paths: Optional[List[str]] = None
) -> List[Dict[str, Any]]:
    """
    Use LLM function calling to dynamically select tools and extract parameters.

    Uses LLM_PROVIDER config to select which provider to use.
    If ENABLE_LLM_FALLBACK=true, falls back to other providers on failure.
    Each provider call wrapped with retry logic (3 attempts with exponential backoff).

    Args:
        question: GAIA question text
        plan: Execution plan from planning phase
        available_tools: Tool registry
        file_paths: Optional list of downloaded file paths for file-based questions

    Returns:
        List of tool calls with extracted parameters
    """
    return _call_with_fallback("select_tools", question, plan, available_tools, file_paths)


# ============================================================================
# Answer Synthesis - Claude Implementation
# ============================================================================


def synthesize_answer_claude(question: str, evidence: List[str]) -> str:
    """Synthesize factoid answer from evidence using Claude."""
    client = create_claude_client()

    # Format evidence
    evidence_text = "\n\n".join(
        [f"Evidence {i + 1}:\n{e}" for i, e in enumerate(evidence)]
    )

    system_prompt = """You are an answer synthesis agent for the GAIA benchmark.

Your task is to extract a factoid answer from the provided evidence.

CRITICAL - Response format (two parts):
1. **REASONING** - Show your step-by-step thought process:
   - What information is in the evidence?
   - What is the question asking for?
   - How do you extract the answer from the evidence?
   - Any ambiguities or uncertainties?

2. **FINAL ANSWER** - The factoid answer only:
   - A number, a few words, or a comma-separated list
   - No explanations, just the answer
   - If evidence is insufficient, state "Unable to answer"

Response format:
REASONING: [Your step-by-step thought process here]
FINAL ANSWER: [The factoid answer]

Examples:
REASONING: The evidence mentions the population of Tokyo is 13.9 million. The question asks for the city with highest population. Tokyo is listed as the highest.
FINAL ANSWER: Tokyo

REASONING: The transcript mentions "giant petrel", "emperor", and "adelie" (with typo "deli"). These are three different bird species present in the same scene.
FINAL ANSWER: 3
"""

    user_prompt = f"""Question: {question}

{evidence_text}

Extract the factoid answer from the evidence above. Return only the factoid, nothing else."""

    logger.info(f"[synthesize_answer_claude] Calling Claude for answer synthesis")

    response = client.messages.create(
        model=CLAUDE_MODEL,
        max_tokens=256,  # Factoid answers are short
        temperature=TEMPERATURE,
        system=system_prompt,
        messages=[{"role": "user", "content": user_prompt}],
    )

    answer = response.content[0].text.strip()
    logger.info(f"[synthesize_answer_claude] Generated answer: {answer}")

    return answer


# ============================================================================
# Answer Synthesis - Gemini Implementation
# ============================================================================


def synthesize_answer_gemini(question: str, evidence: List[str]) -> str:
    """Synthesize factoid answer from evidence using Gemini."""
    model = create_gemini_client()

    # Format evidence
    evidence_text = "\n\n".join(
        [f"Evidence {i + 1}:\n{e}" for i, e in enumerate(evidence)]
    )

    prompt = f"""You are an answer synthesis agent for the GAIA benchmark.

Your task is to extract a factoid answer from the provided evidence.

CRITICAL - Answer format requirements:
1. Answers must be factoids: a number, a few words, or a comma-separated list
2. Be concise - no explanations, just the answer
3. If evidence conflicts, evaluate source credibility and recency
4. If evidence is insufficient, state "Unable to answer"

Examples of good factoid answers:
- "42"
- "Paris"
- "Albert Einstein"
- "red, blue, green"
- "1969-07-20"

Examples of bad answers (too verbose):
- "The answer is 42 because..."
- "Based on the evidence, it appears that..."

Question: {question}

{evidence_text}

Extract the factoid answer from the evidence above. Return only the factoid, nothing else."""

    logger.info(f"[synthesize_answer_gemini] Calling Gemini for answer synthesis")

    response = model.generate_content(
        prompt,
        generation_config=genai.types.GenerationConfig(
            temperature=TEMPERATURE,
            max_output_tokens=256,  # Factoid answers are short
        ),
    )

    answer = response.text.strip()
    logger.info(f"[synthesize_answer_gemini] Generated answer: {answer}")

    return answer


# ============================================================================
# Answer Synthesis - HuggingFace Implementation
# ============================================================================


def synthesize_answer_hf(question: str, evidence: List[str]) -> str:
    """Synthesize factoid answer from evidence using HuggingFace Inference API."""
    global _SYSTEM_PROMPT_WRITTEN

    client = create_hf_client()

    # Format evidence
    evidence_text = "\n\n".join(
        [f"Evidence {i + 1}:\n{e}" for i, e in enumerate(evidence)]
    )

    system_prompt = """You are an answer synthesis agent for the GAIA benchmark.

Your task is to extract a factoid answer from the provided evidence.

CRITICAL - Response format (two parts):
1. **REASONING** - Show your step-by-step thought process:
   - What information is in the evidence?
   - What is the question asking for?
   - How do you extract the answer from the evidence?
   - Any ambiguities or uncertainties?

2. **FINAL ANSWER** - The factoid answer only:
   - A number, a few words, or a comma-separated list
   - No explanations, just the answer
   - If evidence is insufficient, state "Unable to answer"

Response format:
REASONING: [Your step-by-step thought process here]
FINAL ANSWER: [The factoid answer]

Examples:
REASONING: The evidence mentions the population of Tokyo is 13.9 million. The question asks for the city with highest population. Tokyo is listed as the highest.
FINAL ANSWER: Tokyo

REASONING: The transcript mentions "giant petrel", "emperor", and "adelie" (with typo "deli"). These are three different bird species present in the same scene.
FINAL ANSWER: 3
"""

    user_prompt = f"""Question: {question}

{evidence_text}

Extract the factoid answer from the evidence above. Return only the factoid, nothing else."""

    # ============================================================================
    # BUFFER QUESTION CONTEXT - Write complete block atomically after response
    # ============================================================================
    context_file = get_session_log_file()
    question_timestamp = datetime.datetime.now().isoformat()

    # Build question header (include system prompt only on first question)
    system_prompt_section = ""
    if not _SYSTEM_PROMPT_WRITTEN:
        system_prompt_section = f"""

## System Prompt (static - used for all questions)

```text
{system_prompt}
```
"""
        _SYSTEM_PROMPT_WRITTEN = True

    question_header = f"""
## Question [{question_timestamp}]

**Question:** {question}
**Evidence items:** {len(evidence)}
{system_prompt_section}

### Evidence & Prompt

```text
{user_prompt}
```
"""

    messages = [
        {"role": "system", "content": system_prompt},
        {"role": "user", "content": user_prompt},
    ]

    response = client.chat_completion(
        messages=messages,
        max_tokens=1024,  # Increased for CoT reasoning
        temperature=TEMPERATURE,
    )

    full_response = response.choices[0].message.content.strip()

    # Extract FINAL ANSWER from response (format: "REASONING: ...\nFINAL ANSWER: ...")
    if "FINAL ANSWER:" in full_response:
        parts = full_response.split("FINAL ANSWER:")
        answer = parts[-1].strip()
        reasoning = parts[0].replace("REASONING:", "").strip()
    else:
        # Fallback if LLM doesn't follow format
        answer = full_response
        reasoning = "No reasoning provided (format not followed)"

    logger.info(f"[synthesize_answer_hf] Answer: {answer}")

    # ============================================================================
    # WRITE COMPLETE QUESTION BLOCK ATOMICALLY (header + response + end)
    # ============================================================================
    complete_block = f"""{question_header}

### LLM Response

```text
{full_response}
```

**Extracted Answer:** `{answer}`

"""

    with open(context_file, "a", encoding="utf-8") as f:
        f.write(complete_block)

    return answer


# ============================================================================
# Answer Synthesis - Groq Implementation
# ============================================================================


def synthesize_answer_groq(question: str, evidence: List[str]) -> str:
    """Synthesize factoid answer from evidence using Groq."""
    client = create_groq_client()

    # Format evidence
    evidence_text = "\n\n".join(
        [f"Evidence {i + 1}:\n{e}" for i, e in enumerate(evidence)]
    )

    system_prompt = """You are an answer synthesis agent for the GAIA benchmark.

Your task is to extract a factoid answer from the provided evidence.

CRITICAL - Response format (two parts):
1. **REASONING** - Show your step-by-step thought process:
   - What information is in the evidence?
   - What is the question asking for?
   - How do you extract the answer from the evidence?
   - Any ambiguities or uncertainties?

2. **FINAL ANSWER** - The factoid answer only:
   - A number, a few words, or a comma-separated list
   - No explanations, just the answer
   - If evidence is insufficient, state "Unable to answer"

Response format:
REASONING: [Your step-by-step thought process here]
FINAL ANSWER: [The factoid answer]

Examples:
REASONING: The evidence mentions the population of Tokyo is 13.9 million. The question asks for the city with highest population. Tokyo is listed as the highest.
FINAL ANSWER: Tokyo

REASONING: The transcript mentions "giant petrel", "emperor", and "adelie" (with typo "deli"). These are three different bird species present in the same scene.
FINAL ANSWER: 3
"""

    user_prompt = f"""Question: {question}

{evidence_text}

Extract the factoid answer from the evidence above. Return only the factoid, nothing else."""

    logger.info(f"[synthesize_answer_groq] Calling Groq for answer synthesis")

    messages = [
        {"role": "system", "content": system_prompt},
        {"role": "user", "content": user_prompt},
    ]

    response = client.chat.completions.create(
        model=GROQ_MODEL,
        messages=messages,
        max_tokens=256,  # Factoid answers are short
        temperature=TEMPERATURE,
    )

    answer = response.choices[0].message.content.strip()
    logger.info(f"[synthesize_answer_groq] Generated answer: {answer}")

    return answer


# ============================================================================
# Unified Answer Synthesis with Fallback Chain
# ============================================================================


def synthesize_answer(question: str, evidence: List[str]) -> str:
    """
    Synthesize factoid answer from collected evidence using LLM.

    Uses LLM_PROVIDER config to select which provider to use.
    If ENABLE_LLM_FALLBACK=true, falls back to other providers on failure.
    Each provider call wrapped with retry logic (3 attempts with exponential backoff).

    Args:
        question: Original GAIA question
        evidence: List of evidence strings from tool executions

    Returns:
        Factoid answer string
    """
    return _call_with_fallback("synthesize_answer", question, evidence)


# ============================================================================
# Conflict Resolution Functions
# ============================================================================


def resolve_conflicts(evidence: List[str]) -> Dict[str, Any]:
    """
    Detect and resolve conflicts in evidence using LLM reasoning.

    Optional function for advanced conflict handling.
    Currently integrated into synthesize_answer().
    Uses same Gemini primary, Claude fallback pattern.

    Args:
        evidence: List of evidence strings that may conflict

    Returns:
        Dictionary with conflict analysis
    """
    try:
        # Try Gemini first
        model = create_gemini_client()
        evidence_text = "\n\n".join(
            [f"Evidence {i + 1}:\n{e}" for i, e in enumerate(evidence)]
        )

        prompt = f"""You are a conflict detection agent.

Analyze the provided evidence and identify any contradictions or conflicts.

Evaluate:
1. Are there contradictory facts?
2. Which sources are more credible?
3. Which information is more recent?
4. How should conflicts be resolved?

Analyze this evidence for conflicts:

{evidence_text}

Respond in JSON format:
{{
    "has_conflicts": true/false,
    "conflicts": ["description of conflict 1", ...],
    "resolution": "recommended resolution strategy"
}}"""

        logger.info(f"[resolve_conflicts] Analyzing with Gemini")

        response = model.generate_content(prompt)

        result = {"has_conflicts": False, "conflicts": [], "resolution": response.text}

        return result

    except Exception as gemini_error:
        logger.warning(
            f"[resolve_conflicts] Gemini failed: {gemini_error}, trying Claude"
        )

        # Fallback to Claude
        client = create_claude_client()
        evidence_text = "\n\n".join(
            [f"Evidence {i + 1}:\n{e}" for i, e in enumerate(evidence)]
        )

        system_prompt = """You are a conflict detection agent.

Analyze the provided evidence and identify any contradictions or conflicts.

Evaluate:
1. Are there contradictory facts?
2. Which sources are more credible?
3. Which information is more recent?
4. How should conflicts be resolved?"""

        user_prompt = f"""Analyze this evidence for conflicts:

{evidence_text}

Respond in JSON format:
{{
    "has_conflicts": true/false,
    "conflicts": ["description of conflict 1", ...],
    "resolution": "recommended resolution strategy"
}}"""

        response = client.messages.create(
            model=CLAUDE_MODEL,
            max_tokens=MAX_TOKENS,
            temperature=TEMPERATURE,
            system=system_prompt,
            messages=[{"role": "user", "content": user_prompt}],
        )

        result = {
            "has_conflicts": False,
            "conflicts": [],
            "resolution": response.content[0].text,
        }

        return result