File size: 194,076 Bytes
10e9b7d
 
eccf8e4
7d65c66
3c4371f
1a176ca
71d5860
8180298
 
71d5860
8180298
 
 
 
 
10e9b7d
e80aab9
3db6293
e80aab9
aa3bba6
31243f4
 
 
05114ab
54bbdf0
 
6ee032b
71d5860
6ee032b
 
54bbdf0
87ed5c0
8f38aff
12eeaa0
05114ab
 
 
 
 
ffb02e2
05114ab
 
 
 
 
 
 
 
 
 
 
 
ffb02e2
 
05114ab
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
ffb02e2
12eeaa0
 
 
 
 
 
ffb02e2
12eeaa0
 
5f804b3
12eeaa0
ffb02e2
5f804b3
12eeaa0
7db7108
12eeaa0
 
 
 
 
 
 
 
 
 
ffb02e2
 
 
12eeaa0
762fb0e
 
73f16f4
762fb0e
 
 
 
 
 
 
 
 
 
 
 
 
 
 
ffb02e2
 
 
73f16f4
12eeaa0
762fb0e
 
 
 
 
 
 
 
 
 
05114ab
73f16f4
762fb0e
 
 
 
 
 
 
 
 
 
 
 
 
 
12eeaa0
73f16f4
762fb0e
 
 
 
73f16f4
83d4468
 
 
 
 
345e181
 
83d4468
 
 
 
 
 
 
 
73f16f4
12eeaa0
05114ab
73f16f4
345e181
6ee032b
71d5860
 
 
 
 
 
 
 
 
 
 
 
8f38aff
71d5860
 
 
 
 
 
 
 
 
 
 
 
1294c4f
71d5860
1294c4f
71d5860
 
 
 
284201d
 
 
 
23b9e3b
284201d
23b9e3b
71d5860
aa3bba6
 
284201d
23b9e3b
71d5860
 
92d027e
8180298
71d5860
aa3bba6
23b9e3b
 
 
aa3bba6
6ee032b
 
284201d
23b9e3b
 
 
 
 
 
 
 
 
 
 
 
 
284201d
aa3bba6
23b9e3b
 
 
 
 
 
 
 
 
aa3bba6
 
 
92d027e
 
 
 
 
8f38aff
92d027e
23b9e3b
92d027e
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
71d5860
92d027e
 
8180298
92d027e
 
aa3bba6
 
92d027e
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
23b9e3b
92d027e
 
23b9e3b
92d027e
 
 
 
 
23b9e3b
92d027e
6ee032b
92d027e
 
 
aa3bba6
 
 
 
71d5860
73f16f4
 
54bbdf0
 
23b9e3b
54bbdf0
 
 
23b9e3b
73f16f4
 
57ae274
 
62b30f0
 
5a11b9a
62b30f0
 
 
23b9e3b
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
62b30f0
 
 
 
 
 
 
 
 
 
 
 
73f16f4
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
62b30f0
23b9e3b
62b30f0
 
 
 
 
 
 
 
 
 
 
54bbdf0
23b9e3b
 
 
 
 
 
 
 
 
54bbdf0
23b9e3b
 
73f16f4
23b9e3b
57ae274
23b9e3b
 
57ae274
 
 
 
23b9e3b
57ae274
 
 
 
23b9e3b
57ae274
 
 
 
 
 
 
 
 
23b9e3b
62b30f0
57ae274
62b30f0
57ae274
 
 
 
 
23b9e3b
54bbdf0
 
80f4b19
6ee032b
54bbdf0
ba1b713
 
 
 
 
 
60fd734
ba1b713
 
80f4b19
ba1b713
a294b8e
 
 
 
80f4b19
 
 
 
 
 
 
 
 
 
 
ba1b713
 
8f38aff
60fd734
 
 
 
 
 
 
 
 
 
 
 
 
 
ba1b713
60fd734
 
 
ba1b713
 
a294b8e
 
 
80f4b19
a294b8e
 
 
60fd734
 
 
ba1b713
 
 
 
 
a294b8e
80f4b19
 
 
 
8f38aff
ba1b713
 
80f4b19
 
ba1b713
 
 
80f4b19
ba1b713
 
80f4b19
 
 
ba1b713
 
 
a294b8e
 
60fd734
 
 
ba1b713
80f4b19
 
 
 
 
 
 
 
 
8f38aff
80f4b19
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
ba1b713
a294b8e
aa3bba6
7db7108
bd25c5a
 
54bbdf0
 
ba1b713
54bbdf0
ba1b713
54bbdf0
ba1b713
bd25c5a
ba1b713
 
54bbdf0
ba1b713
5595cc4
3e5afcb
5595cc4
 
 
54bbdf0
bd25c5a
7da00ee
bd25c5a
 
 
 
 
3e5afcb
bd25c5a
 
 
 
60fd734
bd25c5a
7da00ee
60fd734
7da00ee
bd25c5a
 
54bbdf0
 
 
bd25c5a
 
 
54bbdf0
3e5afcb
ba1b713
 
 
 
 
 
 
3e5afcb
 
 
bd25c5a
 
3e5afcb
 
 
 
 
 
bd25c5a
 
 
60fd734
3e5afcb
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
7da00ee
3e5afcb
 
 
 
60fd734
bd25c5a
7da00ee
60fd734
7da00ee
bd25c5a
 
ba1b713
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
118479f
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
3e5afcb
118479f
 
 
39e4ba0
 
 
 
 
 
 
 
 
 
54bbdf0
 
 
51c9782
 
 
 
 
 
 
 
 
960c986
 
6ee032b
960c986
51c9782
 
 
960c986
51c9782
60fd734
51c9782
 
 
 
 
 
 
 
 
60fd734
 
6ee032b
51c9782
 
 
 
960c986
51c9782
60fd734
51c9782
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
6ee032b
aa3bba6
5595cc4
1caf24d
 
 
 
 
 
5595cc4
1d90f9d
 
 
 
 
 
 
 
 
 
6ee032b
54bbdf0
 
 
 
 
 
 
edb1d4c
3b400eb
54bbdf0
 
 
3b400eb
54bbdf0
 
 
3b400eb
54bbdf0
edb1d4c
3b400eb
edb1d4c
 
 
 
3b400eb
edb1d4c
 
 
 
 
 
 
 
 
 
 
3b400eb
edb1d4c
3b400eb
05114ab
 
 
 
 
 
 
 
 
 
 
 
57ae274
edb1d4c
 
3b400eb
05114ab
edb1d4c
3b400eb
8f38aff
05114ab
8f38aff
1622804
05114ab
46f9947
57ae274
aa3bba6
 
 
dadcec9
1622804
5595cc4
aa3bba6
 
1622804
8f38aff
01b1725
8f38aff
 
 
01b1725
39e4ba0
 
 
 
bc6b7ec
ffb02e2
3b400eb
edb1d4c
05114ab
edb1d4c
3b400eb
05114ab
57ae274
b0b4900
01b1725
 
 
 
05114ab
b0b4900
01b1725
 
b0b4900
 
 
 
 
 
 
 
01b1725
 
 
 
8f38aff
18ef9ab
01b1725
 
b0b4900
01b1725
b0b4900
 
 
 
 
 
 
 
 
 
 
 
 
01b1725
 
 
 
 
 
 
 
 
b0b4900
 
 
5145911
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
b0b4900
 
 
 
 
 
 
 
 
 
 
01b1725
 
b0b4900
5145911
3b400eb
57ae274
54bbdf0
aaee519
 
71d5860
23b9e3b
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
a85e151
5595cc4
 
 
 
 
a85e151
 
5595cc4
a85e151
5595cc4
a85e151
 
 
80f4b19
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
a85e151
762fb0e
 
 
 
a85e151
762fb0e
 
 
 
 
 
 
 
 
 
 
 
 
 
 
a85e151
762fb0e
 
 
 
 
 
73f16f4
762fb0e
 
 
 
 
 
 
 
 
 
73f16f4
80f4b19
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
762fb0e
80f4b19
 
 
 
 
 
 
 
 
 
 
 
762fb0e
80f4b19
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
a85e151
762fb0e
 
 
 
 
 
 
 
 
 
 
 
 
80f4b19
762fb0e
 
 
80f4b19
762fb0e
80f4b19
 
 
762fb0e
 
 
 
 
 
 
80f4b19
 
 
 
5595cc4
80f4b19
762fb0e
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1caf24d
762fb0e
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
5595cc4
762fb0e
 
 
 
80f4b19
5b7bb41
762fb0e
 
 
 
80f4b19
762fb0e
18ef9ab
762fb0e
80f4b19
762fb0e
6ee032b
762fb0e
 
 
 
 
 
 
5b7bb41
5595cc4
762fb0e
 
 
 
 
 
 
 
 
80f4b19
762fb0e
 
 
 
9d19ced
 
 
 
762fb0e
8f38aff
762fb0e
 
 
 
 
 
 
 
 
 
 
 
 
 
5b7bb41
762fb0e
 
5b7bb41
762fb0e
 
 
 
 
 
 
 
 
 
9fec2df
762fb0e
 
5595cc4
762fb0e
 
 
5b7bb41
5595cc4
762fb0e
5595cc4
 
762fb0e
 
 
 
 
 
 
 
 
5595cc4
80f4b19
5b7bb41
80f4b19
5b7bb41
 
 
 
80f4b19
 
762fb0e
 
 
aa3bba6
a85e151
 
 
 
 
 
 
1622804
a85e151
 
 
1622804
 
 
 
 
 
 
 
a85e151
1622804
 
a85e151
 
 
 
 
 
 
 
 
 
 
 
 
 
1622804
a85e151
 
 
1622804
a85e151
8f38aff
a85e151
 
 
 
1622804
a85e151
 
762fb0e
9fec2df
a85e151
 
762fb0e
a85e151
 
 
 
762fb0e
a85e151
 
 
762fb0e
 
 
a85e151
6ee032b
1622804
a85e151
 
 
5595cc4
a85e151
5595cc4
a85e151
 
 
6ee032b
5595cc4
a85e151
 
6ee032b
a85e151
 
 
 
 
5595cc4
a85e151
 
 
 
5595cc4
 
 
 
 
 
 
a85e151
5595cc4
 
 
 
a85e151
 
9d19ced
6ee032b
1622804
6ee032b
5595cc4
8f38aff
5595cc4
 
 
 
 
 
 
 
 
 
 
 
 
 
762fb0e
9fec2df
 
 
5595cc4
 
762fb0e
 
 
 
 
5595cc4
 
 
 
762fb0e
 
5595cc4
a85e151
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
80f4b19
 
a85e151
 
1622804
a85e151
aa3bba6
a85e151
 
 
 
 
 
 
8f38aff
a85e151
 
 
 
 
 
f96d740
5595cc4
f96d740
5595cc4
aa3bba6
1622804
 
 
 
aa3bba6
f96d740
aa3bba6
a85e151
 
 
 
 
0862631
aa3bba6
6ee032b
aa3bba6
6ee032b
5595cc4
6ee032b
aa3bba6
 
 
6ee032b
a85e151
 
aa3bba6
6ee032b
5595cc4
aa3bba6
 
f11e723
a85e151
1622804
a85e151
01b1725
 
8f38aff
6ee032b
 
8f38aff
 
 
01b1725
5595cc4
 
 
 
 
8f38aff
5595cc4
 
 
 
 
596ad58
3041415
01b1725
1df3f2d
8f38aff
3041415
5595cc4
 
 
 
 
1df3f2d
01b1725
 
 
 
 
 
8f38aff
01b1725
 
5595cc4
6ee032b
1df3f2d
01b1725
6ee032b
a85e151
1622804
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
53641ed
 
 
 
 
 
 
09d83ba
53641ed
09d83ba
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1622804
 
aa3bba6
5595cc4
75c256e
 
5595cc4
 
53641ed
15afb36
01b1725
15afb36
01b1725
15afb36
53641ed
15afb36
 
8f38aff
 
53641ed
 
 
 
8f38aff
 
53641ed
8f38aff
53641ed
 
5595cc4
53641ed
 
ffb02e2
53641ed
ffb02e2
53641ed
ffb02e2
53641ed
 
ffb02e2
 
 
 
 
 
a85e151
 
 
 
 
6ee032b
a85e151
 
 
9e6a727
 
 
 
a85e151
9e6a727
 
 
a85e151
 
 
5595cc4
f11e723
5595cc4
 
 
 
a85e151
73f16f4
 
60fd734
f931a1a
73f16f4
 
76719c9
01b1725
73f16f4
5ea2343
118479f
 
 
 
 
 
f931a1a
 
 
118479f
 
113a6a5
 
f931a1a
118479f
 
f931a1a
 
 
118479f
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
f931a1a
 
118479f
f931a1a
118479f
f931a1a
 
 
 
 
b1a4aa2
 
 
 
 
 
 
 
 
 
 
5ea2343
60fd734
3abb118
01b1725
f931a1a
3741326
 
f931a1a
42a2874
 
 
 
 
 
 
 
 
f931a1a
 
3741326
f931a1a
b1a4aa2
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
60fd734
b1a4aa2
73f16f4
60fd734
 
9fec2df
73f16f4
60fd734
 
 
 
 
 
73f16f4
9fec2df
73f16f4
 
60fd734
 
73f16f4
3741326
42a2874
9e6a727
a85e151
7a8f9bd
a85e151
 
9e6a727
 
 
8f38aff
c51b8b4
 
 
 
 
8f38aff
7a8f9bd
 
 
 
 
 
 
 
5b0754a
7a8f9bd
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
5b0754a
 
 
7a8f9bd
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
fa378c9
42a2874
fa378c9
 
 
 
 
 
42a2874
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
fa378c9
42a2874
 
 
 
 
 
 
 
 
 
 
 
fa378c9
42a2874
fa378c9
118479f
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
4e480ab
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
5b0754a
4e480ab
 
 
 
5b0754a
 
 
 
fa378c9
5b0754a
 
 
fa378c9
5b0754a
fa378c9
5b0754a
fa378c9
5b0754a
fa378c9
5b0754a
 
fa378c9
5b0754a
 
 
 
6abc8f1
 
5b0754a
 
 
c51b8b4
5b0754a
6abc8f1
118479f
5b0754a
 
6abc8f1
fa378c9
6abc8f1
 
 
 
 
d3725ae
 
 
 
 
 
 
6abc8f1
d3725ae
 
6abc8f1
5b0754a
6a7de67
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
a85e151
 
 
 
 
 
 
 
 
 
34ee0f9
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
9d19ced
eb12a98
34ee0f9
 
 
 
9d19ced
 
 
 
 
 
 
 
34ee0f9
 
 
 
 
a85e151
34ee0f9
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
a85e151
34ee0f9
eb12a98
 
 
 
 
 
 
 
 
468002f
 
34ee0f9
a85e151
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
9e6a727
a85e151
 
73f16f4
a85e151
 
 
 
73f16f4
 
eb12a98
73f16f4
a85e151
73f16f4
 
 
9e6a727
73f16f4
d3725ae
 
 
 
 
 
6abc8f1
 
d3725ae
6abc8f1
 
73f16f4
6abc8f1
 
d3725ae
 
6abc8f1
73f16f4
a85e151
 
b2c7f98
 
 
 
a85e151
 
 
 
 
b0b4900
 
 
 
 
 
d3725ae
 
 
 
 
 
b0b4900
 
d3725ae
b0b4900
 
6abc8f1
6ee032b
 
d3725ae
 
6ee032b
 
b0b4900
a85e151
 
 
 
 
 
 
9e6a727
a85e151
 
9e6a727
5595cc4
 
 
 
 
 
 
 
9e6a727
5595cc4
 
 
 
 
 
 
a85e151
 
 
9951ab3
963db70
1b20cb2
 
a85e151
5595cc4
1b20cb2
1b4ffc4
762fb0e
 
a85e151
1b20cb2
1b4ffc4
762fb0e
 
6ee032b
42a2874
 
 
9951ab3
 
 
42a2874
9951ab3
42a2874
53641ed
60fd734
6ee032b
093dd0d
18ef9ab
832af6a
18ef9ab
 
093dd0d
 
 
 
87ed5c0
268da2e
87ed5c0
a85e151
87ed5c0
3abb118
87ed5c0
832af6a
 
 
7ac6988
b1a4aa2
87ed5c0
b1a4aa2
7ac6988
b1a4aa2
 
7ac6988
b1a4aa2
ffb02e2
87ed5c0
ffb02e2
87ed5c0
6ee032b
01b1725
 
6ee032b
 
a85e151
6ee032b
a85e151
 
2134a67
5595cc4
5ea2343
5595cc4
 
345e181
5595cc4
8f38aff
9951ab3
5595cc4
18ef9ab
 
f11e723
093dd0d
5595cc4
 
 
 
 
 
8f38aff
 
 
 
 
 
 
b1a4aa2
8f38aff
b1a4aa2
 
 
 
 
 
 
 
9951ab3
5595cc4
 
 
 
 
8f38aff
9951ab3
5595cc4
6ee032b
a85e151
dadcec9
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
eb7c372
f11e723
 
dadcec9
f11e723
42a2874
 
 
 
 
 
 
 
 
 
 
f11e723
42a2874
f11e723
42a2874
 
 
 
f11e723
42a2874
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
5595cc4
5a11b9a
 
8f38aff
f11e723
 
5a11b9a
f11e723
8f38aff
5a11b9a
 
f11e723
 
dadcec9
5a11b9a
 
 
 
f11e723
dadcec9
 
e7332f3
dadcec9
 
 
 
 
 
 
 
 
 
 
 
 
 
 
8f38aff
dadcec9
8f38aff
 
3b1d86e
dadcec9
 
 
 
 
 
 
 
 
3b1d86e
8f38aff
dadcec9
f11e723
 
5595cc4
dadcec9
 
 
5595cc4
 
 
a85e151
 
 
 
118479f
 
 
1294c4f
 
 
118479f
1294c4f
 
6abc8f1
1294c4f
6abc8f1
118479f
 
 
c51b8b4
118479f
a85e151
 
1a176ca
 
 
 
bc6b7ec
1a176ca
83d4468
a85e151
 
 
 
 
 
 
 
23b9e3b
a85e151
 
 
 
6ee032b
1a176ca
6ee032b
c84ac75
a85e151
 
 
 
9914586
 
 
a85e151
 
 
 
 
 
73f16f4
 
 
 
 
 
 
 
a85e151
1a176ca
a85e151
9e6a727
1a176ca
23b9e3b
a85e151
 
83d4468
 
01b1725
83d4468
 
 
01b1725
118479f
 
83d4468
 
 
01b1725
83d4468
 
 
 
 
160dfba
 
 
a85e151
 
80f4b19
bc6b7ec
141c26f
 
e493537
 
d25d7c5
e493537
 
 
141c26f
e7820bc
 
 
dadcec9
 
 
 
e7820bc
1caf24d
141c26f
1caf24d
141c26f
 
1caf24d
 
 
141c26f
6abc8f1
 
 
 
 
 
 
4e480ab
 
6abc8f1
 
 
c51b8b4
 
 
 
 
 
 
6abc8f1
 
 
 
 
 
 
 
 
 
 
c51b8b4
118479f
c51b8b4
118479f
 
c51b8b4
118479f
6abc8f1
c51b8b4
 
 
 
 
 
 
 
 
 
6abc8f1
141c26f
5b7bb41
 
 
 
 
 
 
 
1caf24d
 
 
 
 
 
dadcec9
 
 
 
 
 
 
 
5b7bb41
 
 
 
6abc8f1
 
 
 
5b7bb41
 
3741326
dadcec9
6abc8f1
c51b8b4
 
 
 
 
 
6abc8f1
 
5b7bb41
 
3741326
dadcec9
c51b8b4
 
 
 
 
 
141c26f
 
bc6b7ec
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
e493537
a85e151
284201d
5595cc4
83d4468
c51b8b4
83d4468
 
c1761c3
 
 
 
a85e151
83d4468
 
9e6a727
f11e723
60fd734
345e181
73f16f4
60fd734
 
 
284201d
80f4b19
284201d
60fd734
 
 
118479f
284201d
 
 
 
 
 
 
 
 
 
 
 
 
 
118479f
284201d
 
60fd734
 
284201d
 
80f4b19
 
 
 
 
 
 
 
 
 
 
 
 
 
cec12ab
 
 
 
 
 
 
80f4b19
 
 
 
 
 
 
 
 
284201d
80f4b19
 
 
 
cec12ab
 
 
6abc8f1
 
cec12ab
 
284201d
 
118479f
 
 
 
 
 
80f4b19
 
 
 
 
 
 
 
 
dadcec9
 
 
 
 
 
 
80f4b19
dadcec9
 
80f4b19
 
 
 
 
 
 
 
 
4e480ab
 
 
 
 
7a8f9bd
 
 
 
 
118479f
 
7a8f9bd
 
73f16f4
cec12ab
6abc8f1
23b9e3b
 
6abc8f1
1622804
23b9e3b
 
 
 
 
 
6abc8f1
1b4ffc4
 
 
 
 
 
 
 
cec12ab
1b4ffc4
cec12ab
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
118479f
 
1294c4f
118479f
 
 
 
 
 
 
 
cec12ab
c1761c3
60fd734
73f16f4
c1761c3
 
 
 
 
 
 
 
 
 
73f16f4
83d4468
118479f
83d4468
 
 
 
 
 
284201d
83d4468
 
 
 
 
 
 
 
 
 
 
73f16f4
83d4468
 
 
 
aaee519
83d4468
aaee519
284201d
73f16f4
401c115
aaee519
 
 
 
 
83d4468
9d19ced
83d4468
 
 
401c115
83d4468
 
 
 
 
1294c4f
83d4468
401c115
 
 
 
15afb36
 
 
 
 
 
 
 
401c115
 
15afb36
401c115
 
 
c51b8b4
 
 
 
 
 
 
 
 
401c115
c51b8b4
401c115
 
 
 
 
15afb36
401c115
83d4468
 
 
 
 
 
60fd734
83d4468
73f16f4
f11e723
dadcec9
 
eb12a98
 
 
 
f11e723
eb12a98
 
 
 
 
 
 
 
 
 
 
 
 
dadcec9
 
 
c51b8b4
dadcec9
 
 
c51b8b4
dadcec9
 
c51b8b4
963db70
 
83d4468
c51b8b4
 
 
 
 
 
 
 
 
 
83d4468
 
dadcec9
 
 
 
 
762fb0e
 
dadcec9
83d4468
dadcec9
09d83ba
 
 
 
 
 
c51b8b4
dadcec9
c51b8b4
 
 
b0b4900
c51b8b4
 
 
 
 
 
 
80f4b19
83d4468
c1761c3
dadcec9
 
 
 
 
 
83d4468
dadcec9
 
3041415
6ee032b
c1761c3
dadcec9
01b1725
c1761c3
 
01b1725
 
 
 
 
 
 
 
 
dadcec9
 
 
 
 
 
 
 
 
c1761c3
dadcec9
 
 
 
 
 
 
 
 
 
 
 
 
 
c1761c3
dadcec9
01b1725
3041415
dadcec9
 
9d19ced
 
 
 
9876751
 
9d19ced
 
9876751
6ee032b
9876751
dadcec9
9876751
284201d
83d4468
 
 
3041415
c1761c3
83d4468
dadcec9
83d4468
 
a85e151
83d4468
 
6f96f9e
83d4468
 
 
 
 
 
 
 
 
 
80f4b19
83d4468
6f96f9e
 
 
83d4468
 
 
80f4b19
83d4468
 
 
dadcec9
 
 
 
 
 
345e181
a85e151
cec12ab
a85e151
401c115
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
aa3bba6
 
 
 
 
 
 
 
 
a85e151
 
 
 
 
6ee032b
a85e151
 
 
 
 
 
 
 
 
 
 
 
6ee032b
a85e151
 
 
 
 
6ee032b
a85e151
5595cc4
 
a85e151
5595cc4
 
 
a85e151
 
 
 
c1761c3
 
 
a85e151
c1761c3
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
a85e151
6ee032b
a85e151
 
 
 
 
 
 
aa3bba6
a85e151
 
 
 
 
 
 
 
 
aa3bba6
a85e151
 
6abc8f1
 
 
a85e151
6abc8f1
1622804
6abc8f1
 
 
1622804
a85e151
6abc8f1
 
 
 
 
 
 
 
a85e151
aa3bba6
a85e151
 
 
aa3bba6
a85e151
 
 
284201d
a85e151
 
 
aa3bba6
 
 
6f96f9e
 
aa3bba6
6f96f9e
aa3bba6
a85e151
aa3bba6
284201d
aa3bba6
596ad58
284201d
a85e151
8a8ae11
a85e151
8a8ae11
 
a85e151
 
 
596ad58
 
a85e151
c51b8b4
 
 
a85e151
 
87ed5c0
 
 
 
 
 
 
a85e151
 
87ed5c0
a85e151
 
 
 
 
 
 
 
 
 
c1761c3
a85e151
c1761c3
 
 
 
 
 
 
 
 
 
 
 
 
 
 
a85e151
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
e80aab9
 
31243f4
0ee0419
e514fd7
 
 
df67543
 
 
e514fd7
 
 
 
 
 
e80aab9
 
7e4a06b
e80aab9
31243f4
e80aab9
9088b99
7d65c66
e80aab9
31243f4
 
 
e80aab9
 
 
aa3bba6
3c4371f
596ad58
7d65c66
3c4371f
 
596ad58
 
 
 
 
 
 
 
 
 
3c4371f
7d65c66
 
596ad58
7d65c66
9e6a727
 
7d65c66
 
 
aa3bba6
3c4371f
31243f4
c1761c3
8f38aff
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
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
3006
3007
3008
3009
3010
3011
3012
3013
3014
3015
3016
3017
3018
3019
3020
3021
3022
3023
3024
3025
3026
3027
3028
3029
3030
3031
3032
3033
3034
3035
3036
3037
3038
3039
3040
3041
3042
3043
3044
3045
3046
3047
3048
3049
3050
3051
3052
3053
3054
3055
3056
3057
3058
3059
3060
3061
3062
3063
3064
3065
3066
3067
3068
3069
3070
3071
3072
3073
3074
3075
3076
3077
3078
3079
3080
3081
3082
3083
3084
3085
3086
3087
3088
3089
3090
3091
3092
3093
3094
3095
3096
3097
3098
3099
3100
3101
3102
3103
3104
3105
3106
3107
3108
3109
3110
3111
3112
3113
3114
3115
3116
3117
3118
3119
3120
3121
3122
3123
3124
3125
3126
3127
3128
3129
3130
3131
3132
3133
3134
3135
3136
3137
3138
3139
3140
3141
3142
3143
3144
3145
3146
3147
3148
3149
3150
3151
3152
3153
3154
3155
3156
3157
3158
3159
3160
3161
3162
3163
3164
3165
3166
3167
3168
3169
3170
3171
3172
3173
3174
3175
3176
3177
3178
3179
3180
3181
3182
3183
3184
3185
3186
3187
3188
3189
3190
3191
3192
3193
3194
3195
3196
3197
3198
3199
3200
3201
3202
3203
3204
3205
3206
3207
3208
3209
3210
3211
3212
3213
3214
3215
3216
3217
3218
3219
3220
3221
3222
3223
3224
3225
3226
3227
3228
3229
3230
3231
3232
3233
3234
3235
3236
3237
3238
3239
3240
3241
3242
3243
3244
3245
3246
3247
3248
3249
3250
3251
3252
3253
3254
3255
3256
3257
3258
3259
3260
3261
3262
3263
3264
3265
3266
3267
3268
3269
3270
3271
3272
3273
3274
3275
3276
3277
3278
3279
3280
3281
3282
3283
3284
3285
3286
3287
3288
3289
3290
3291
3292
3293
3294
3295
3296
3297
3298
3299
3300
3301
3302
3303
3304
3305
3306
3307
3308
3309
3310
3311
3312
3313
3314
3315
3316
3317
3318
3319
3320
3321
3322
3323
3324
3325
3326
3327
3328
3329
3330
3331
3332
3333
3334
3335
3336
3337
3338
3339
3340
3341
3342
3343
3344
3345
3346
3347
3348
3349
3350
3351
3352
3353
3354
3355
3356
3357
3358
3359
3360
3361
3362
3363
3364
3365
3366
3367
3368
3369
3370
3371
3372
3373
3374
3375
3376
3377
3378
3379
3380
3381
3382
3383
3384
3385
3386
3387
3388
3389
3390
3391
3392
3393
3394
3395
3396
3397
3398
3399
3400
3401
3402
3403
3404
3405
3406
3407
3408
3409
3410
3411
3412
3413
3414
3415
3416
3417
3418
3419
3420
3421
3422
3423
3424
3425
3426
3427
3428
3429
3430
3431
3432
3433
3434
3435
3436
3437
3438
3439
3440
3441
3442
3443
3444
3445
3446
3447
3448
3449
3450
3451
3452
3453
3454
3455
3456
3457
3458
3459
3460
3461
3462
3463
3464
3465
3466
3467
3468
3469
3470
3471
3472
3473
3474
3475
3476
3477
3478
3479
3480
3481
3482
3483
3484
3485
3486
3487
3488
3489
3490
3491
3492
3493
3494
3495
3496
3497
3498
3499
3500
3501
3502
3503
3504
3505
3506
3507
3508
3509
3510
3511
3512
3513
3514
3515
3516
3517
3518
3519
3520
3521
3522
3523
3524
3525
3526
3527
3528
3529
3530
3531
3532
3533
3534
3535
3536
3537
3538
3539
3540
3541
3542
3543
3544
3545
3546
3547
3548
3549
3550
3551
3552
3553
3554
3555
3556
3557
3558
3559
3560
3561
3562
3563
3564
3565
3566
3567
3568
3569
3570
3571
3572
3573
3574
3575
3576
3577
3578
3579
3580
3581
3582
3583
3584
3585
3586
3587
3588
3589
3590
3591
3592
3593
3594
3595
3596
3597
3598
3599
3600
3601
3602
3603
3604
3605
3606
3607
3608
3609
3610
3611
3612
3613
3614
3615
3616
3617
3618
3619
3620
3621
3622
3623
3624
3625
3626
3627
3628
3629
3630
3631
3632
3633
3634
3635
3636
3637
3638
3639
3640
3641
3642
3643
3644
3645
3646
3647
3648
3649
3650
3651
3652
3653
3654
3655
3656
3657
3658
3659
3660
3661
3662
3663
3664
3665
3666
3667
3668
3669
3670
3671
3672
3673
3674
3675
3676
3677
3678
3679
3680
3681
3682
3683
3684
3685
3686
3687
3688
3689
3690
3691
3692
3693
3694
3695
3696
3697
3698
3699
3700
3701
3702
3703
3704
3705
3706
3707
3708
3709
3710
3711
3712
3713
3714
3715
3716
3717
3718
3719
3720
3721
3722
3723
3724
3725
3726
3727
3728
3729
3730
3731
3732
3733
3734
3735
3736
3737
3738
3739
3740
3741
3742
3743
3744
3745
3746
3747
3748
3749
3750
3751
3752
3753
3754
3755
3756
3757
3758
3759
3760
3761
3762
3763
3764
3765
3766
3767
3768
3769
3770
3771
3772
3773
3774
3775
3776
3777
3778
3779
3780
3781
3782
3783
3784
3785
3786
3787
3788
3789
3790
3791
3792
3793
3794
3795
3796
3797
3798
3799
3800
3801
3802
3803
3804
3805
3806
3807
3808
3809
3810
3811
3812
3813
3814
3815
3816
3817
3818
3819
3820
3821
3822
3823
3824
3825
3826
3827
3828
3829
3830
3831
3832
3833
3834
3835
3836
3837
3838
3839
3840
3841
3842
3843
3844
3845
3846
3847
3848
3849
3850
3851
3852
3853
3854
3855
3856
3857
3858
3859
3860
3861
3862
3863
3864
3865
3866
3867
3868
3869
3870
3871
3872
3873
3874
3875
3876
3877
3878
3879
3880
3881
3882
3883
3884
3885
3886
3887
3888
3889
3890
3891
3892
3893
3894
3895
3896
3897
3898
3899
3900
3901
3902
3903
3904
3905
3906
3907
3908
3909
3910
3911
3912
3913
3914
3915
3916
3917
3918
3919
3920
3921
3922
3923
3924
3925
3926
3927
3928
3929
3930
3931
3932
3933
3934
3935
3936
3937
3938
3939
3940
3941
3942
3943
3944
3945
3946
3947
3948
3949
3950
3951
3952
3953
3954
3955
3956
3957
3958
3959
3960
3961
3962
3963
3964
3965
3966
3967
3968
3969
3970
3971
3972
3973
3974
3975
3976
3977
import os
import gradio as gr
import requests
import inspect
import pandas as pd
import posixpath

try:
    import spaces

    @spaces.GPU
    def _register_zerogpu():
        return None
except ImportError:
    pass

# --- Constants ---
DEFAULT_API_URL = "https://agents-course-unit4-scoring.hf.space"


# --- Basic Agent Definition ---
class BasicAgent:
    def __init__(self):
        import re
        import base64
        import mimetypes
        import threading
        import litellm
        from smolagents import CodeAgent, LiteLLMModel, MultiStepAgent, tool

        litellm.drop_params = True
        litellm.suppress_debug_info = True
        litellm.request_timeout = 25

        provider_env_prefixes = {
            "openrouter": ("OPENROUTER_API_KEY", "OPENROUTER_TOKEN", "OPENROUTER_KEY"),
            "gemini": ("GEMINI_API_KEY", "GOOGLE_API_KEY", "GEMINI_TOKEN", "GOOGLE_GEMINI_API_KEY"),
            "groq": ("GROQ_API_KEY", "GROQ_TOKEN"),
            "huggingface": ("HF_TOKEN", "HUGGINGFACE_API_KEY", "HUGGINGFACEHUB_API_TOKEN", "HUGGINGFACE_TOKEN"),
            "nvidia_nim": ("NVIDIA_API_KEY", "NVIDIA_NIM_API_KEY", "NIM_API_KEY"),
        }
        raw_pools = {p: [] for p in provider_env_prefixes}

        def _classify_token(token: str, default_provider: str) -> str:
            if token.startswith("sk-or-"):
                return "openrouter"
            if token.startswith("AIza"):
                return "gemini"
            if token.startswith("gsk_"):
                return "groq"
            if token.startswith("hf_"):
                return "huggingface"
            if token.startswith("nvapi-"):
                return "nvidia_nim"
            return default_provider

        for raw_name, raw_val in os.environ.items():
            if not raw_val:
                continue
            env_name = raw_name.upper().strip()
            matched_provider = next(
                (
                    prov
                    for prov, prefixes in provider_env_prefixes.items()
                    if any(env_name == pref or env_name.startswith(pref + "_") for pref in prefixes)
                ),
                None,
            )
            if not matched_provider:
                continue
            for part in re.split(r"[\s,;]+", raw_val):
                tok = part.strip(" '\"\n\r\t[]")
                if tok:
                    target_prov = _classify_token(tok, matched_provider)
                    raw_pools[target_prov].append(tok)

        self.provider_key_pools = {
            prov: list(dict.fromkeys(tokens)) for prov, tokens in raw_pools.items()
        }
        self._provider_key_idx = {prov: 0 for prov in self.provider_key_pools}

        openrouter_key = self.provider_key_pools["openrouter"][0] if self.provider_key_pools["openrouter"] else ""
        groq_key = self.provider_key_pools["groq"][0] if self.provider_key_pools["groq"] else ""
        hf_key = self.provider_key_pools["huggingface"][0] if self.provider_key_pools["huggingface"] else ""
        gemini_key = self.provider_key_pools["gemini"][0] if self.provider_key_pools["gemini"] else ""
        nvidia_key = self.provider_key_pools["nvidia_nim"][0] if self.provider_key_pools["nvidia_nim"] else ""

        self.provider_keys = {
            "openrouter": openrouter_key,
            "groq": groq_key,
            "huggingface": hf_key,
            "gemini": gemini_key,
            "nvidia_nim": nvidia_key,
        }
        if not any(self.provider_keys.values()):
            raise ValueError(
                "Missing API key in Space secrets. Add at least one of: "
                "OPENROUTER_API_KEY, GROQ_API_KEY, HF_TOKEN, GEMINI_API_KEY, or NVIDIA_API_KEY."
            )

        self.gemini_key = gemini_key
        if gemini_key:
            os.environ["GEMINI_API_KEY"] = gemini_key
            os.environ["GOOGLE_API_KEY"] = gemini_key
        if openrouter_key:
            os.environ["OPENROUTER_API_KEY"] = openrouter_key
        if groq_key:
            os.environ["GROQ_API_KEY"] = groq_key
        if hf_key:
            os.environ["HF_TOKEN"] = hf_key
            os.environ["HUGGINGFACE_API_KEY"] = hf_key
        if nvidia_key:
            os.environ["NVIDIA_API_KEY"] = nvidia_key
            os.environ["NVIDIA_NIM_API_KEY"] = nvidia_key

        self._state_lock = threading.RLock()

        def _sync_provider_env(provider: str, key: str) -> None:
            with self._state_lock:
                self.provider_keys[provider] = key
                if not key:
                    return
                if provider == "openrouter":
                    os.environ["OPENROUTER_API_KEY"] = key
                elif provider == "groq":
                    os.environ["GROQ_API_KEY"] = key
                elif provider == "huggingface":
                    os.environ["HF_TOKEN"] = key
                    os.environ["HUGGINGFACE_API_KEY"] = key
                elif provider == "gemini":
                    self.gemini_key = key
                    os.environ["GEMINI_API_KEY"] = key
                    os.environ["GOOGLE_API_KEY"] = key
                elif provider == "nvidia_nim":
                    os.environ["NVIDIA_API_KEY"] = key
                    os.environ["NVIDIA_NIM_API_KEY"] = key

        def _get_api_key(model_name: str) -> str | None:
            with self._state_lock:
                provider = model_name.split("/", 1)[0].lower() if "/" in model_name else "gemini"
                pool = self.provider_key_pools.get(provider) or []
                idx = self._provider_key_idx.get(provider, 0)
                if idx < len(pool):
                    key = pool[idx]
                    _sync_provider_env(provider, key)
                    return key
                _sync_provider_env(provider, "")
                return None

        def _rotate_api_key(provider: str, permanent: bool = False) -> bool:
            with self._state_lock:
                pool = self.provider_key_pools.get(provider) or []
                cur_idx = self._provider_key_idx.get(provider, 0)
                if permanent and 0 <= cur_idx < len(pool):
                    pool.pop(cur_idx)
                    next_idx = cur_idx
                else:
                    next_idx = cur_idx + 1
                self._provider_key_idx[provider] = next_idx
                if next_idx < len(pool):
                    _sync_provider_env(provider, pool[next_idx])
                    return True
                _sync_provider_env(provider, "")
                return False

        def _reset_key_indices() -> None:
            with self._state_lock:
                for prov, pool in self.provider_key_pools.items():
                    self._provider_key_idx[prov] = 0
                    _sync_provider_env(prov, pool[0] if pool else "")

        def _tool_timeout(default_timeout: float, min_timeout: float = 4.0) -> float:
            import time

            local_state = getattr(self, "_local_state", None)
            deadline = getattr(local_state, "deadline", None) if local_state is not None else None
            if deadline is None:
                deadline = getattr(self, "_task_deadline", None)
            if deadline is None:
                return default_timeout
            remaining = deadline - time.monotonic()
            if remaining <= 2.5:
                raise RuntimeError("Task time budget exhausted")
            return max(min_timeout, min(default_timeout, remaining - 2.0))

        self._tool_timeout = _tool_timeout
        self._sync_provider_env = _sync_provider_env
        self._get_api_key = _get_api_key
        self._rotate_api_key = _rotate_api_key
        self._reset_key_indices = _reset_key_indices
        self.gemini_flash_models = []

        @tool
        def fetch_url_text(url: str) -> str:
            """Fetches clean plain text from a given URL.
            Args:
                url: The HTTP/HTTPS URL to fetch.
            """
            import re
            from html import unescape

            try:
                response = requests.get(
                    url,
                    timeout=_tool_timeout(15.0),
                    headers={"User-Agent": "Mozilla/5.0"},
                )
                response.raise_for_status()
                raw_html = re.sub(
                    r"(?is)<(script|style|noscript|svg|header|footer|nav).*?>.*?</\1>",
                    " ",
                    response.text,
                )
                plain_text = re.sub(r"(?s)<[^>]+>", " ", raw_html)
                cleaned = re.sub(r"\s+", " ", unescape(plain_text)).strip()
                if not cleaned:
                    return "Empty text response."
                if len(cleaned) <= 45000:
                    return cleaned
                return cleaned[:45000] + "\n...[truncated]..."
            except Exception as e:
                return f"Error fetching URL '{url}': {str(e)}"

        @tool
        def download_task_file(
            task_id: str,
            output_dir: str = "/tmp/gaia_files",
            preferred_filename: str = "",
            file_url: str = "",
        ) -> str:
            """Downloads a task attachment from the course API (or direct URL) and returns the local file path.
            Args:
                task_id: Task identifier from the evaluation dataset.
                output_dir: Local directory where the file should be saved.
                preferred_filename: Optional original attachment filename from the task metadata.
                file_url: Optional direct URL if mentioned in the task prompt.
            """
            import re
            import time
            from urllib.parse import unquote

            clean_id = (task_id or "").strip()
            clean_url = (file_url or "").strip()
            if not clean_id and not clean_url:
                return "Error downloading file: missing task_id and file_url."

            safe_out_dir = (output_dir or "").strip() or "/tmp/gaia_files"
            os.makedirs(safe_out_dir, exist_ok=True)
            safe_pref_name = os.path.basename((preferred_filename or "").strip())

            # Sprawdź najpierw czy plik już istnieje w output_dir lub podkatalogach roboczych
            search_names = [n for n in (safe_pref_name, f"{clean_id}.bin", clean_id) if n]
            for s_name in search_names:
                direct_cand = os.path.join(safe_out_dir, s_name)
                if os.path.isfile(direct_cand) and os.path.getsize(direct_cand) > 0:
                    return direct_cand
            if clean_id:
                for fname in os.listdir(safe_out_dir):
                    f_full = os.path.join(safe_out_dir, fname)
                    if os.path.isfile(f_full) and os.path.getsize(f_full) > 0:
                        if fname.startswith(clean_id) or (safe_pref_name and fname == safe_pref_name):
                            return f_full

            base_url = DEFAULT_API_URL.rstrip("/")
            candidate_urls = []
            if clean_url.startswith(("http://", "https://")):
                candidate_urls.append(clean_url)
            if clean_id:
                candidate_urls.extend([
                    f"{base_url}/files/{clean_id}",
                    f"{base_url}/attachments/{clean_id}",
                    f"{base_url}/tasks/{clean_id}/file",
                ])

            last_err = None
            for url in candidate_urls:
                resp = None
                for attempt in range(3):
                    try:
                        resp = requests.get(
                            url,
                            timeout=(8.0, _tool_timeout(25.0, min_timeout=5.0)),
                            headers={"User-Agent": "Mozilla/5.0"},
                            allow_redirects=True,
                        )
                        if resp.status_code in {429, 502, 503, 504} and attempt < 2:
                            _tool_timeout(4.0, min_timeout=1.0)
                            time.sleep(1.5 * (attempt + 1))
                            continue
                        break
                    except Exception as exc:
                        last_err = exc
                        if "task time budget exhausted" in str(exc).lower():
                            return f"Error downloading file for task '{clean_id}': {str(exc)}"
                        if attempt < 2:
                            try:
                                _tool_timeout(4.0, min_timeout=1.0)
                                time.sleep(1.5 * (attempt + 1))
                                continue
                            except Exception:
                                resp = None
                                break
                        resp = None
                        break

                if resp is None or resp.status_code == 404:
                    continue

                try:
                    resp.raise_for_status()
                except Exception as exc:
                    last_err = exc
                    continue

                if not resp.content:
                    continue

                content_disp = resp.headers.get("Content-Disposition", "")
                filename = safe_pref_name

                if not filename:
                    star_match = re.search(
                        r"filename\*\s*=\s*(?:[A-Za-z0-9_-]+''|\"[A-Za-z0-9_-]+'')?([^\";]+)",
                        content_disp,
                        flags=re.IGNORECASE,
                    )
                    if star_match:
                        raw_star = star_match.group(1).strip().strip('"')
                        if "''" in raw_star:
                            raw_star = raw_star.split("''", 1)[1]
                        filename = os.path.basename(unquote(raw_star))

                if not filename:
                    std_match = re.search(
                        r'filename\s*=\s*"?([^";]+)"?',
                        content_disp,
                        flags=re.IGNORECASE,
                    )
                    if std_match:
                        filename = os.path.basename(unquote(std_match.group(1).strip()))

                if not filename:
                    content_type = resp.headers.get("Content-Type", "").split(";")[0].strip().lower()
                    ext_map = {
                        "text/plain": ".txt",
                        "text/csv": ".csv",
                        "application/json": ".json",
                        "application/pdf": ".pdf",
                        "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet": ".xlsx",
                        "application/vnd.ms-excel": ".xls",
                        "application/zip": ".zip",
                        "image/png": ".png",
                        "image/jpeg": ".jpg",
                        "image/webp": ".webp",
                        "audio/mpeg": ".mp3",
                        "audio/wav": ".wav",
                        "text/x-python": ".py",
                    }
                    ext = ext_map.get(content_type) or mimetypes.guess_extension(content_type) or ".bin"
                    filename = f"{clean_id or 'attachment'}{ext}"

                out_path = os.path.join(safe_out_dir, filename)
                with open(out_path, "wb") as f:
                    f.write(resp.content)
                return out_path

            if last_err is not None:
                return f"Error downloading file for task '{clean_id}': {str(last_err)}"
            return f"No attachment available for task '{clean_id}' (404 Not Found)."

        self._download_task_file = download_task_file

        @tool
        def read_local_file(file_path: str) -> str:
            """Reads text, PDF, DOCX, PPTX, ZIP archive, CSV/JSON, or spreadsheet content from a local file.
            Args:
                file_path: Local path to the downloaded file.
            """
            import json
            import re
            import xml.etree.ElementTree as ET
            import zipfile

            def _read_single(path: str, max_chars: int) -> str:
                f_ext = os.path.splitext(path)[1].lower()
                if f_ext in {".xlsx", ".xlsm", ".xls"}:
                    sheets = pd.read_excel(path, sheet_name=None)
                    if not sheets:
                        return "Empty Excel workbook."
                    parts_out = []
                    for s_name, df in sheets.items():
                        summary = (
                            f"=== Sheet: {s_name} (rows={len(df)}, cols={list(df.columns)}) ===\n"
                            f"{df.to_csv(index=False)}"
                        )
                        parts_out.append(summary)
                    text = "\n\n".join(parts_out)
                elif f_ext == ".csv":
                    df = pd.read_csv(path)
                    text = f"=== CSV (rows={len(df)}, cols={list(df.columns)}) ===\n{df.to_csv(index=False)}"
                elif f_ext == ".json":
                    with open(path, "r", encoding="utf-8", errors="replace") as f:
                        raw_j = f.read()
                    try:
                        parsed_j = json.loads(raw_j)
                        text = json.dumps(parsed_j, ensure_ascii=False, indent=2)
                    except Exception:
                        text = raw_j
                elif f_ext == ".pdf":
                    try:
                        from pypdf import PdfReader

                        reader = PdfReader(path)
                        pages = [
                            f"=== Page {i + 1} ===\n{(p.extract_text() or '').strip()}"
                            for i, p in enumerate(reader.pages)
                        ]
                        text = "\n\n".join(p for p in pages if p.strip()) or "Empty PDF text."
                    except Exception as pdf_exc:
                        return f"Error reading PDF '{path}': {str(pdf_exc)}"
                elif f_ext == ".docx":
                    try:
                        with zipfile.ZipFile(path, "r") as zf:
                            if "word/document.xml" not in zf.namelist():
                                return f"Invalid DOCX archive '{path}': missing word/document.xml."
                            root = ET.fromstring(zf.read("word/document.xml"))
                        paragraphs = []
                        for p_elem in root.iter():
                            if p_elem.tag.endswith("}p"):
                                runs = [
                                    t_elem.text
                                    for t_elem in p_elem.iter()
                                    if t_elem.tag.endswith("}t") and t_elem.text
                                ]
                                line = "".join(runs).strip()
                                if line:
                                    paragraphs.append(line)
                        text = "\n".join(paragraphs) or "Empty DOCX document."
                    except Exception as docx_exc:
                        return f"Error reading DOCX '{path}': {str(docx_exc)}"
                elif f_ext == ".pptx":
                    try:
                        with zipfile.ZipFile(path, "r") as zf:
                            slide_names = [
                                name for name in zf.namelist()
                                if re.fullmatch(r"ppt/slides/slide\d+\.xml", name)
                            ]
                            slide_names.sort(
                                key=lambda n: int(re.search(r"slide(\d+)\.xml$", n).group(1))
                            )
                            slides_out = []
                            for idx, s_name in enumerate(slide_names, start=1):
                                root = ET.fromstring(zf.read(s_name))
                                s_lines = []
                                for p_elem in root.iter():
                                    if p_elem.tag.endswith("}p"):
                                        runs = [
                                            t_elem.text
                                            for t_elem in p_elem.iter()
                                            if t_elem.tag.endswith("}t") and t_elem.text
                                        ]
                                        line = "".join(runs).strip()
                                        if line:
                                            s_lines.append(line)
                                slides_out.append(f"=== Slide {idx} ===\n" + ("\n".join(s_lines) or "(empty)"))
                        text = "\n\n".join(slides_out) or "Empty PPTX presentation."
                    except Exception as pptx_exc:
                        return f"Error reading PPTX '{path}': {str(pptx_exc)}"
                elif f_ext in {".png", ".jpg", ".jpeg", ".webp", ".gif"}:
                    return f"Binary image file '{path}'. Use inspect_image(image_path='{path}', question=...) or analyze_chessboard(image_path='{path}')."
                elif f_ext in {".mp3", ".wav", ".m4a", ".ogg", ".flac"}:
                    return f"Binary audio file '{path}'. Use transcribe_audio(audio_path='{path}', question=...)."
                else:
                    with open(path, "r", encoding="utf-8", errors="replace") as f:
                        text = f.read()

                if len(text) <= max_chars:
                    return text
                half = max_chars // 2
                return text[:half] + "\n...\n" + text[-half:]

            try:
                resolved = file_path
                if not os.path.isfile(resolved):
                    base_name = os.path.basename(file_path or "")
                    for cand_dir in ("/tmp/gaia_files", "."):
                        cand_p = os.path.join(cand_dir, base_name)
                        if base_name and os.path.isfile(cand_p):
                            resolved = cand_p
                            break
                if not os.path.isfile(resolved):
                    return f"File not found: '{file_path}'"

                ext = os.path.splitext(resolved)[1].lower()
                office_zip_exts = {".xlsx", ".xlsm", ".xls", ".docx", ".pptx"}
                if ext == ".zip" or (ext not in office_zip_exts and zipfile.is_zipfile(resolved)):
                    extract_dir = os.path.join(
                        os.path.dirname(resolved),
                        f"extracted_{os.path.basename(resolved)}",
                    )
                    os.makedirs(extract_dir, exist_ok=True)
                    base_extract = os.path.realpath(extract_dir)
                    sections = []
                    with zipfile.ZipFile(resolved, "r") as zf:
                        members = [m for m in zf.namelist() if not m.endswith("/")]
                        sections.append(
                            f"=== ZIP Archive ({len(members)} files) ===\nFiles: {', '.join(members)}"
                        )
                        per_member_cap = max(4000, min(24000, 44000 // max(1, len(members))))
                        for member in members:
                            target_path = os.path.realpath(os.path.join(extract_dir, member))
                            if not (target_path == base_extract or target_path.startswith(base_extract + os.sep)):
                                sections.append(f"=== {member} ===\nSkipped unsafe path.")
                                continue
                            os.makedirs(os.path.dirname(target_path), exist_ok=True)
                            with zf.open(member, "r") as src, open(target_path, "wb") as dst:
                                dst.write(src.read())
                            try:
                                content_str = _read_single(target_path, max_chars=per_member_cap)
                                sections.append(f"=== {member} (extracted to {target_path}) ===\n{content_str}")
                            except Exception as m_exc:
                                sections.append(f"=== {member} (extracted to {target_path}) ===\nRead error: {m_exc}")
                    joined_zip = "\n\n".join(sections)
                    if len(joined_zip) <= 48000:
                        return joined_zip
                    return joined_zip[:24000] + "\n...\n" + joined_zip[-24000:]

                return _read_single(resolved, max_chars=48000)
            except Exception as e:
                return f"Error reading file '{file_path}': {str(e)}"

        self._read_local_file = read_local_file

        @tool
        def web_search(query: str) -> str:
            """Searches the web for a query and returns top results with titles, URLs, and snippets.
            Args:
                query: The search query string.
            """
            from concurrent.futures import ThreadPoolExecutor
            import re
            from html import unescape
            from urllib.parse import parse_qs, unquote, urlparse

            clean_q = (query or "").strip()
            if not clean_q:
                return "Empty search query."

            def _clean_ddg_href(raw_href: str) -> str:
                h = unescape((raw_href or "").strip())
                if h.startswith("//"):
                    h = "https:" + h
                if "duckduckgo.com/l/?" in h or h.startswith("/l/?"):
                    parsed = urlparse(h)
                    uddg = parse_qs(parsed.query).get("uddg")
                    if uddg and uddg[0]:
                        return unquote(uddg[0])
                return h

            results_out = []
            try:
                ddgs_timeout = _tool_timeout(7.0, min_timeout=3.0)

                def _run_ddgs():
                    try:
                        from ddgs import DDGS
                    except ImportError:
                        from duckduckgo_search import DDGS
                    try:
                        client = DDGS(timeout=int(ddgs_timeout))
                    except TypeError:
                        client = DDGS()
                    return client.text(clean_q, max_results=5) or []

                ddgs_pool = ThreadPoolExecutor(max_workers=1)
                ddgs_fut = ddgs_pool.submit(_run_ddgs)
                try:
                    raw_results = ddgs_fut.result(timeout=ddgs_timeout)
                finally:
                    ddgs_pool.shutdown(wait=False, cancel_futures=True)

                for item in raw_results:
                    if not isinstance(item, dict):
                        continue
                    title = str(item.get("title", "")).strip()
                    href = _clean_ddg_href(str(item.get("href", "")))
                    body = str(item.get("body", "")).strip()
                    if title or href or body:
                        results_out.append(f"- {title}\n  URL: {href}\n  Snippet: {body}")
            except Exception as ddgs_exc:
                if "task time budget exhausted" in str(ddgs_exc).lower():
                    return f"Web search aborted: {ddgs_exc}"

            if not results_out:
                try:
                    resp = requests.post(
                        "https://html.duckduckgo.com/html/",
                        data={"q": clean_q},
                        headers={
                            "User-Agent": "Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/124.0.0.0 Safari/537.36",
                            "Accept-Language": "en-US,en;q=0.9",
                        },
                        timeout=_tool_timeout(7.0, min_timeout=3.0),
                    )
                    resp.raise_for_status()
                    link_matches = re.findall(
                        r"(?is)<a\b([^>]*\bclass=['\"][^'\"]*result__a[^'\"]*['\"][^>]*)>(.*?)</a>",
                        resp.text,
                    )
                    snippets = re.findall(
                        r"(?is)<(?:a|div)\b[^>]*\bclass=['\"][^'\"]*result__snippet[^'\"]*['\"][^>]*>(.*?)</(?:a|div)>",
                        resp.text,
                    )
                    for idx, (tag_attrs, raw_title) in enumerate(link_matches[:5]):
                        href_m = re.search(r"\bhref=['\"]([^'\"]+)['\"]", tag_attrs, flags=re.IGNORECASE)
                        href = _clean_ddg_href(href_m.group(1)) if href_m else ""
                        title = re.sub(r"\s+", " ", unescape(re.sub(r"(?s)<[^>]+>", " ", raw_title))).strip()
                        raw_snip = snippets[idx] if idx < len(snippets) else ""
                        snip = re.sub(r"\s+", " ", unescape(re.sub(r"(?s)<[^>]+>", " ", raw_snip))).strip()
                        if title or href or snip:
                            results_out.append(f"- {title}\n  URL: {href}\n  Snippet: {snip}")
                except Exception as html_exc:
                    if "task time budget exhausted" in str(html_exc).lower():
                        return f"Web search aborted: {html_exc}"

            if not results_out:
                try:
                    lite_resp = requests.post(
                        "https://lite.duckduckgo.com/lite/",
                        data={"q": clean_q},
                        headers={
                            "User-Agent": "Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/124.0.0.0 Safari/537.36",
                            "Accept-Language": "en-US,en;q=0.9",
                        },
                        timeout=_tool_timeout(7.0, min_timeout=3.0),
                    )
                    lite_resp.raise_for_status()
                    lite_links = re.findall(
                        r"(?is)<a\b([^>]*\bclass=['\"][^'\"]*result-link[^'\"]*['\"][^>]*)>(.*?)</a>",
                        lite_resp.text,
                    )
                    lite_snippets = re.findall(
                        r"(?is)<td\b[^>]*\bclass=['\"][^'\"]*result-snippet[^'\"]*['\"][^>]*>(.*?)</td>",
                        lite_resp.text,
                    )
                    for idx, (tag_attrs, raw_title) in enumerate(lite_links[:5]):
                        href_m = re.search(r"\bhref=['\"]([^'\"]+)['\"]", tag_attrs, flags=re.IGNORECASE)
                        href = _clean_ddg_href(href_m.group(1)) if href_m else ""
                        title = re.sub(r"\s+", " ", unescape(re.sub(r"(?s)<[^>]+>", " ", raw_title))).strip()
                        raw_snip = lite_snippets[idx] if idx < len(lite_snippets) else ""
                        snip = re.sub(r"\s+", " ", unescape(re.sub(r"(?s)<[^>]+>", " ", raw_snip))).strip()
                        if title or href or snip:
                            results_out.append(f"- {title}\n  URL: {href}\n  Snippet: {snip}")
                except Exception as lite_exc:
                    if "task time budget exhausted" in str(lite_exc).lower():
                        return f"Web search aborted: {lite_exc}"

            if not results_out:
                return f"No web results found for '{clean_q}'. Try search_wikipedia(query) or fetch_url_text(url)."
            return "\n\n".join(results_out)

        wiki_cache = {}

        @tool
        def search_wikipedia(query: str) -> str:
            """Searches English Wikipedia and returns clean plain text (including tables) of the best matching article.
            Args:
                query: Search query or exact Wikipedia article title.
            """
            import re
            import time
            from html import unescape

            headers = {"User-Agent": "HF-Agents-Course-Bot/1.0"}
            api_endpoint = "https://en.wikipedia.org/w/api.php"
            use_2022 = ("2022" in query.lower()) or bool(getattr(self, "_prefer_2022_wiki", False))
            clean_query = re.sub(r"\b2022\b", "", query).strip() or query.strip()
            cache_key = f"{clean_query.lower()}|2022={use_2022}"
            if cache_key in wiki_cache:
                return wiki_cache[cache_key]
            try:
                search_resp = None
                for attempt in range(2):
                    search_resp = requests.get(
                        api_endpoint,
                        params={
                            "action": "query",
                            "list": "search",
                            "srsearch": clean_query,
                            "format": "json",
                            "srlimit": 5,
                        },
                        headers=headers,
                        timeout=_tool_timeout(8.0, min_timeout=2.5),
                    )
                    if search_resp.status_code == 429 and attempt < 1:
                        _tool_timeout(3.0, min_timeout=1.0)
                        time.sleep(0.5)
                        continue
                    break
                search_resp.raise_for_status()
                results = search_resp.json().get("query", {}).get("search", [])
                if not results:
                    out_empty = f"No Wikipedia results for '{query}'."
                    wiki_cache[cache_key] = out_empty
                    return out_empty

                query_norm = clean_query.lower()
                selected = next(
                    (r for r in results if r["title"].strip().lower() == query_norm),
                    results[0],
                )
                title = selected["title"]
                other_titles = [r["title"] for r in results if r["title"] != title]

                rev_id = None
                if use_2022:
                    rev_resp = requests.get(
                        api_endpoint,
                        params={
                            "action": "query",
                            "titles": title,
                            "prop": "revisions",
                            "rvlimit": 1,
                            "rvdir": "older",
                            "rvstart": "2023-01-01T00:00:00Z",
                            "format": "json",
                        },
                        headers=headers,
                        timeout=_tool_timeout(6.0, min_timeout=2.0),
                    )
                    if rev_resp.status_code == 200:
                        pages = rev_resp.json().get("query", {}).get("pages", {})
                        for p_data in pages.values():
                            revs = p_data.get("revisions") or []
                            if revs and revs[0].get("revid"):
                                rev_id = revs[0]["revid"]
                                break

                parse_params = {
                    "action": "parse",
                    "prop": "text",
                    "redirects": 1,
                    "format": "json",
                }
                if rev_id:
                    parse_params["oldid"] = rev_id
                else:
                    parse_params["page"] = title

                parse_resp = None
                for attempt in range(2):
                    parse_resp = requests.get(
                        api_endpoint,
                        params=parse_params,
                        headers=headers,
                        timeout=_tool_timeout(8.0, min_timeout=2.5),
                    )
                    if parse_resp.status_code == 429 and attempt < 1:
                        _tool_timeout(3.0, min_timeout=1.0)
                        time.sleep(0.5)
                        continue
                    break
                parse_resp.raise_for_status()
                parse_data = parse_resp.json().get("parse", {})
                raw_html = parse_data.get("text", {}).get("*", "")
                resolved_title = parse_data.get("title", title)

                if raw_html:
                    cleaned_html = re.sub(
                        r"(?is)<(script|style|noscript|svg).*?>.*?</\1>",
                        " ",
                        raw_html,
                    )
                    cleaned_html = re.sub(r"(?i)</(tr|p|li|h[1-6]|div|br)>", "\n", cleaned_html)
                    cleaned_html = re.sub(r"(?i)</(td|th)>", " | ", cleaned_html)
                    plain_text = unescape(re.sub(r"(?s)<[^>]+>", " ", cleaned_html))
                    lines = [re.sub(r"[ \t]+", " ", ln).strip() for ln in plain_text.splitlines()]
                    text = "\n".join(ln for ln in lines if ln)
                else:
                    text = ""

                body_text = re.split(
                    r"(?im)^(?:references|external links|further reading|notes)\s*$",
                    text,
                    maxsplit=1,
                )[0].strip() or text

                if len(body_text) > 8500:
                    section_match = re.search(
                        r"(?i)\b(?:discography|studio albums|participating national olympic committees|"
                        r"participating nations|recipients|laureates|winners|medal table)\b",
                        body_text,
                    )
                    if section_match:
                        start = max(0, section_match.start() - 250)
                        focus_section = body_text[start:start + 6800]
                        text = body_text[:1400] + "\n...\n" + focus_section
                    else:
                        text = body_text[:4200] + "\n...\n" + body_text[-4200:]
                else:
                    text = body_text
                display_title = resolved_title or title
                header_lines = [f"Wikipedia: {display_title}"]
                if rev_id:
                    header_lines[0] += f" (2022 revision {rev_id})"
                if other_titles:
                    header_lines.append(f"Other search matches: {', '.join(other_titles[:4])}")
                body_out = text if text else "No readable article text found."
                result_str = "\n".join(header_lines) + "\n\n" + body_out
                wiki_cache[cache_key] = result_str
                return result_str
            except Exception as e:
                return f"Wikipedia error for '{query}': {str(e)}"

        @tool
        def ask_web(query: str) -> str:
            """Searches Wikipedia first and falls back to DuckDuckGo web search if needed.
            Args:
                query: Search query string.
            """
            import re
            from html import unescape

            cleaned_query = (query or "").strip()
            if not cleaned_query:
                return "No results."

            try:
                resp = requests.get(
                    "https://en.wikipedia.org/w/api.php",
                    params={"action": "opensearch", "search": cleaned_query, "limit": 3, "format": "json"},
                    headers={"User-Agent": "BasicAgent/1.0"},
                    timeout=_tool_timeout(7.0, min_timeout=2.5),
                )
                resp.raise_for_status()
                data = resp.json()
                titles = data[1] if len(data) > 1 else []
                descs = data[2] if len(data) > 2 else []
                urls = data[3] if len(data) > 3 else []
                wiki_lines = [f"{t}: {d} ({u})" for t, d, u in zip(titles, descs, urls) if t or d]
                if wiki_lines:
                    return "\n".join(wiki_lines)
            except Exception as wiki_exc:
                if "task time budget exhausted" in str(wiki_exc).lower():
                    return "No results."

            try:
                ddg_resp = requests.post(
                    "https://html.duckduckgo.com/html/",
                    data={"q": cleaned_query},
                    headers={"User-Agent": "Mozilla/5.0"},
                    timeout=_tool_timeout(7.0, min_timeout=2.5),
                )
                ddg_resp.raise_for_status()
                matches = re.findall(
                    r'(?is)<a[^>]+class="result__a"[^>]+href="([^"]+)"[^>]*>(.*?)</a>',
                    ddg_resp.text,
                )
                out = []
                for href, raw_title in matches[:3]:
                    title = re.sub(r"\s+", " ", unescape(re.sub(r"(?s)<[^>]+>", " ", raw_title))).strip()
                    if title:
                        out.append(f"{title} ({href})")
                if out:
                    return "\n".join(out)
            except Exception:
                pass

            return "No results."

        def _litellm_route_kwargs(model_name: str, api_key: str) -> dict:
            route = {"model": model_name, "api_key": api_key}
            if model_name.startswith("huggingface/"):
                raw_hf = model_name[len("huggingface/") :]
                route["model"] = f"openai/{raw_hf}"
                route["api_base"] = "https://router.huggingface.co/v1"
            return route

        def _is_daily_quota_exhausted(err_lower: str) -> bool:
            return any(
                marker in err_lower
                for marker in (
                    "free-models-per-day",
                    "rate limit exceeded: free-models-per-day",
                    "daily limit",
                    "quota exceeded",
                )
            )

        @tool
        def inspect_image(image_path: str, question: str) -> str:
            """Analyzes a local image file using a multimodal vision model and answers a specific question about it.
            Args:
                image_path: Local path to the image file (.png, .jpg, .jpeg, .webp).
                question: Specific question or instruction about what to extract from the image.
            """
            import io

            try:
                if not os.path.isfile(image_path):
                    return f"Image file not found: '{image_path}'"

                mime_type, _ = mimetypes.guess_type(image_path)
                if not mime_type or not mime_type.startswith("image/"):
                    mime_type = "image/png"

                with open(image_path, "rb") as f:
                    raw_bytes = f.read()

                payload_bytes = raw_bytes
                if len(raw_bytes) > 3_500_000:
                    try:
                        from PIL import Image

                        img = Image.open(io.BytesIO(raw_bytes))
                        img.thumbnail((1600, 1600))
                        buf = io.BytesIO()
                        save_fmt = "JPEG" if mime_type in ("image/jpeg", "image/jpg") else "PNG"
                        if save_fmt == "JPEG" and img.mode in ("RGBA", "P"):
                            img = img.convert("RGB")
                        img.save(buf, format=save_fmt, optimize=True, quality=85)
                        payload_bytes = buf.getvalue()
                        mime_type = "image/jpeg" if save_fmt == "JPEG" else "image/png"
                    except Exception:
                        payload_bytes = raw_bytes

                b64_data = base64.b64encode(payload_bytes).decode("utf-8")

                vision_tags = (
                    "gemma-3",
                    "gemma-4",
                    "gemini",
                    "vision",
                    "-vl",
                    "scout",
                    "maverick",
                    "pixtral",
                    "qwen2.5-vl",
                    "qwen3-vl",
                )
                vision_candidates = []
                current_model = getattr(self, "model_id", "")
                current_model_low = current_model.lower()

                if current_model and any(tag in current_model_low for tag in vision_tags):
                    vision_candidates.append(current_model)

                if self.provider_keys.get("groq") or self.provider_key_pools.get("groq"):
                    vision_candidates.extend([
                        "groq/meta-llama/llama-4-maverick-17b-128e-instruct",
                        "groq/meta-llama/llama-4-scout-17b-16e-instruct",
                    ])
                
                if self.provider_keys.get("gemini"):
                    vision_candidates.extend(
                        self.gemini_flash_models
                        or [
                            "gemini/gemini-2.5-flash",
                            "gemini/gemini-3-flash-preview",
                            "gemini/gemini-flash-latest",
                        ]
                    )

                if self.provider_keys.get("openrouter"):
                    vision_candidates.extend([
                        "openrouter/google/gemma-4-26b-a4b-it:free",
                        "openrouter/google/gemma-4-31b-it:free",
                        "openrouter/google/gemma-3-27b-it:free",
                    ])
                if self.provider_keys.get("nvidia_nim") or self.provider_key_pools.get("nvidia_nim"):
                    vision_candidates.extend([
                        "nvidia_nim/meta/llama-3.2-90b-vision-instruct",
                        "nvidia_nim/nvidia/nemotron-nano-12b-v2-vl",
                        "nvidia_nim/moonshotai/kimi-k2.5",
                    ])

                for m in getattr(self, "working_models", []):
                    if m not in vision_candidates and any(tag in m.lower() for tag in vision_tags):
                        vision_candidates.append(m)

                unique_vision = list(dict.fromkeys(vision_candidates))
                last_err = None
                rate_limited_providers = set()
                dead_models = getattr(self, "_dead_models", None)
                if dead_models is None:
                    dead_models = set()
                    self._dead_models = dead_models

                for v_model in unique_vision:
                    if v_model in dead_models:
                        continue
                    v_provider = v_model.split("/", 1)[0].lower() if "/" in v_model else "gemini"
                    if v_provider in rate_limited_providers:
                        continue
                    while True:
                        v_key = self._get_api_key(v_model)
                        if not v_key:
                            break
                        try:
                            call_kwargs = _litellm_route_kwargs(v_model, v_key)
                            call_kwargs["num_retries"] = 0
                            call_kwargs["max_retries"] = 0
                            call_kwargs["max_tokens"] = 1024
                            call_kwargs["timeout"] = _tool_timeout(20.0)
                            if v_provider == "openrouter" or (v_provider == "gemini" and "gemma" not in v_model.lower()):
                                call_kwargs["reasoning_effort"] = "low"

                            response = litellm.completion(
                                **call_kwargs,
                                messages=[
                                    {
                                        "role": "user",
                                        "content": [
                                            {"type": "text", "text": question},
                                            {
                                                "type": "image_url",
                                                "image_url": {"url": f"data:{mime_type};base64,{b64_data}"},
                                            },
                                        ],
                                    }
                                ],
                            )
                            msg_content = response.choices[0].message.content
                            if isinstance(msg_content, list):
                                out = "\n".join(
                                    str(p.get("text", "")).strip()
                                    for p in msg_content
                                    if isinstance(p, dict) and p.get("text")
                                ).strip()
                            else:
                                out = (msg_content or "").strip()
                            if out:
                                return out
                            break
                        except Exception as exc:
                            last_err = exc
                            err_low = str(exc).lower()
                            if "task time budget exhausted" in err_low:
                                raise
                            if any(
                                marker in err_low
                                for marker in (
                                    "400",
                                    "badrequesterror",
                                    "reasoning is mandatory",
                                    "cannot be disabled",
                                    "404",
                                    "not found",
                                    "model_not_found",
                                    "decommissioned",
                                    "unsupported",
                                )
                            ):
                                dead_models.add(v_model)
                                break
                            if any(
                                marker in err_low
                                for marker in (
                                    "401",
                                    "402",
                                    "403",
                                    "authentication",
                                    "invalid api key",
                                    "permission_denied",
                                    "insufficient permissions",
                                )
                            ):
                                if hasattr(self, "_rotate_api_key") and self._rotate_api_key(
                                    v_provider, permanent=True
                                ):
                                    continue
                                rate_limited_providers.add(v_provider)
                                break
                            if any(
                                marker in err_low
                                for marker in (
                                    "429",
                                    "rate limit",
                                    "free-models-per-day",
                                    "quota",
                                    "resource_exhausted",
                                )
                            ):
                                if hasattr(self, "_rotate_api_key") and self._rotate_api_key(v_provider):
                                    continue
                                if _is_daily_quota_exhausted(err_low):
                                    rate_limited_providers.add(v_provider)
                                break
                            break

                raise RuntimeError(str(last_err) if last_err else "No vision model available.")
            except Exception as e:
                print(f"[IMAGE ERR] path={image_path}: {type(e).__name__}: {e}", flush=True)
                raise RuntimeError(f"Error inspecting image '{image_path}': {str(e)}") from e

        @tool
        def analyze_chessboard(image_path: str, side_to_move: str = "black") -> str:
            """Extracts a structured chessboard position from an image and evaluates candidate legal moves for the side to move.
            Args:
                image_path: Local path to the chessboard image (.png, .jpg, .jpeg, .webp).
                side_to_move: Side whose turn it is ('black' or 'white').
            """
            chess_prompt = (
                "Carefully examine this chessboard image rank by rank from rank 8 down to rank 1, "
                "and file by file from file 'a' to file 'h' (standard algebraic coordinates where a1 is White's "
                "leftmost square and h8 is Black's leftmost square, regardless of visual rotation—state which rank "
                "is at the bottom of the image).\n"
                "List EVERY piece currently on the board with its exact square:\n"
                "- White pieces (K, Q, R, B, N, P)\n"
                "- Black pieces (k, q, r, b, n, p)\n"
                "Also provide the exact FEN placement string (8 ranks separated by '/') and list all immediate "
                "checks, captures, forks, pins, and mating threats available to "
                f"{(side_to_move or 'black').upper()}, plus the best winning move in Standard Algebraic Notation (SAN)."
            )
            vision_summary = inspect_image(image_path=image_path, question=chess_prompt)

            # Jeśli zainstalowana jest biblioteka python-chess, spróbuj zweryfikować legalne ruchy z podanego FEN-a
            try:
                import re
                import chess

                fen_match = re.search(
                    r"\b([rnbqkprnbqkprnbqkprnbqkprnbqkprnbqkprnbqkp1-8]{1,8}(?:/[rnbqkprnbqkprnbqkprnbqkprnbqkprnbqkprnbqkp1-8]{1,8}){7})\b",
                    vision_summary,
                    flags=re.IGNORECASE,
                )
                if fen_match:
                    raw_placement = fen_match.group(1)
                    turn_char = "b" if (side_to_move or "black").strip().lower().startswith("b") else "w"
                    board = chess.Board(f"{raw_placement} {turn_char} - - 0 1")
                    legal_sans = [board.san(mv) for mv in board.legal_moves]
                    forcing_sans = [
                        board.san(mv)
                        for mv in board.legal_moves
                        if board.gives_check(mv) or board.is_capture(mv)
                    ]
                    return (
                        f"{vision_summary}\n\n"
                        f"[Verified FEN]: {board.fen()}\n"
                        f"[Legal moves count]: {len(legal_sans)}\n"
                        f"[Checks / Captures]: {', '.join(forcing_sans[:25]) or 'none'}\n"
                        f"[All legal SANs]: {', '.join(legal_sans[:40])}"
                    )
            except Exception:
                pass

            return vision_summary
        
        @tool
        def inspect_youtube(
            url: str,
            question: str = "Provide a detailed account of all visual scenes, on-screen text, counts, actions, and spoken audio in this video.",
        ) -> str:
            """Fetches YouTube video metadata, captions/transcripts, and multimodal visual/audio analysis for a given YouTube URL or video ID.
            Args:
                url: YouTube video URL or 11-character video ID.
                question: Specific question or instruction about what to look for or extract from the video.
            """
            import json
            import re
            from html import unescape

            def _extract_json_array_after(source: str, key_marker: str):
                idx = source.find(key_marker)
                if idx == -1:
                    return None
                start = source.find("[", idx + len(key_marker))
                if start == -1:
                    return None
                depth = 0
                in_str = False
                escape = False
                for pos in range(start, len(source)):
                    ch = source[pos]
                    if in_str:
                        if escape:
                            escape = False
                        elif ch == "\\":
                            escape = True
                        elif ch == '"':
                            in_str = False
                        continue
                    if ch == '"':
                        in_str = True
                    elif ch == "[":
                        depth += 1
                    elif ch == "]":
                        depth -= 1
                        if depth == 0:
                            try:
                                return json.loads(source[start : pos + 1])
                            except Exception:
                                return None
                return None

            try:
                raw = (url or "").strip()
                vid_match = re.search(
                    r"(?:v=|/shorts/|/embed/|youtu\.be/)([A-Za-z0-9_-]{11})",
                    raw,
                )
                video_id = vid_match.group(1) if vid_match else (raw if re.fullmatch(r"[A-Za-z0-9_-]{11}", raw) else "")
                if not video_id:
                    return f"Invalid YouTube URL or video ID: '{url}'"

                watch_url = f"https://www.youtube.com/watch?v={video_id}"
                headers = {
                    "User-Agent": "Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/124.0.0.0 Safari/537.36",
                    "Accept-Language": "en-US,en;q=0.9",
                    "Cookie": "SOCS=CAI",
                }
                sections = [f"Video ID: {video_id}", f"URL: {watch_url}"]
                has_title = False
                has_desc = False
                has_transcript = False
                caption_tracks = []

                try:
                    oembed_resp = requests.get(
                        "https://www.youtube.com/oembed",
                        params={"url": watch_url, "format": "json"},
                        headers=headers,
                        timeout=_tool_timeout(8.0, min_timeout=2.0),
                    )
                    if oembed_resp.status_code == 200:
                        oembed = oembed_resp.json()
                        if oembed.get("title"):
                            sections.append(f"Title: {oembed['title']}")
                            has_title = True
                        if oembed.get("author_name"):
                            sections.append(f"Channel: {oembed['author_name']}")
                except Exception as req_exc:
                    if "task time budget exhausted" in str(req_exc).lower():
                        raise

                innertube_clients = [
                    (
                        "ANDROID",
                        "19.09.37",
                        "com.google.android.youtube/19.09.37 (Linux; U; Android 11) gzip",
                    ),
                    (
                        "IOS",
                        "19.29.1",
                        "com.google.ios.youtube/19.29.1 (iPhone16,2; U; CPU iOS 17_5_1 like Mac OS X;)",
                    ),
                ]
                for client_name, client_ver, client_ua in innertube_clients:
                    if has_desc and caption_tracks:
                        break
                    try:
                        player_resp = requests.post(
                            "https://www.youtube.com/youtubei/v1/player",
                            params={"prettyPrint": "false"},
                            headers={
                                "Content-Type": "application/json",
                                "User-Agent": client_ua,
                            },
                            json={
                                "context": {
                                    "client": {
                                        "clientName": client_name,
                                        "clientVersion": client_ver,
                                        "hl": "en",
                                        "gl": "US",
                                    }
                                },
                                "videoId": video_id,
                            },
                            timeout=_tool_timeout(8.0, min_timeout=2.0),
                        )
                        if player_resp.status_code == 200:
                            player_data = player_resp.json()
                            v_details = player_data.get("videoDetails") or {}
                            if not has_title and v_details.get("title"):
                                sections.append(f"Title: {v_details['title']}")
                                has_title = True
                            if not has_desc and v_details.get("shortDescription"):
                                sections.append(f"Description:\n{str(v_details['shortDescription'])[:2000]}")
                                has_desc = True
                            if not caption_tracks:
                                tracks = (
                                    (player_data.get("captions") or {})
                                    .get("playerCaptionsTracklistRenderer", {})
                                    .get("captionTracks")
                                )
                                if isinstance(tracks, list) and tracks:
                                    caption_tracks = tracks
                    except Exception as req_exc:
                        if "task time budget exhausted" in str(req_exc).lower():
                            raise

                if not has_desc or not caption_tracks:
                    try:
                        page_resp = requests.get(
                            watch_url,
                            headers=headers,
                            timeout=_tool_timeout(10.0, min_timeout=2.0),
                        )
                        if page_resp.status_code == 200:
                            html_text = page_resp.text
                            if not has_desc:
                                desc_match = re.search(r'"shortDescription"\s*:\s*"((?:\\.|[^"\\])*)"', html_text)
                                if desc_match:
                                    try:
                                        desc_val = json.loads(f'"{desc_match.group(1)}"')
                                    except Exception:
                                        desc_val = unescape(desc_match.group(1))
                                    sections.append(f"Description:\n{desc_val[:2000]}")
                                    has_desc = True
                            if not caption_tracks:
                                parsed_tracks = _extract_json_array_after(html_text, '"captionTracks"')
                                if isinstance(parsed_tracks, list) and parsed_tracks:
                                    caption_tracks = parsed_tracks
                    except Exception as e:
                        if "task time budget exhausted" in str(e).lower():
                            raise

                if caption_tracks:
                    sorted_tracks = sorted(
                        caption_tracks,
                        key=lambda t: (
                            0 if str(t.get("languageCode", "")).lower().startswith("en") else 1,
                            1 if str(t.get("kind", "")).lower() == "asr" else 0,
                        ),
                    )
                    for tr in sorted_tracks[:3]:
                        base_url = tr.get("baseUrl")
                        if not base_url:
                            continue
                        try:
                            tr_resp = requests.get(
                                unescape(base_url),
                                headers=headers,
                                timeout=_tool_timeout(8.0, min_timeout=2.0),
                            )
                            if tr_resp.status_code == 200 and tr_resp.text:
                                raw_cues = re.findall(r"(?is)<text[^>]*>(.*?)</text>", tr_resp.text)
                                cues = [
                                    re.sub(r"\s+", " ", unescape(re.sub(r"(?s)<[^>]+>", " ", c))).strip()
                                    for c in raw_cues
                                ]
                                transcript = " ".join(c for c in cues if c)
                                if transcript:
                                    lang = tr.get("languageCode", "unknown")
                                    sections.append(f"Transcript ({lang}):\n{transcript[:5000]}")
                                    has_transcript = True
                                    break
                        except Exception as tr_exc:
                            if "task time budget exhausted" in str(tr_exc).lower():
                                raise
                            continue

                visual_markers = (
                    "visual",
                    "scene",
                    "appear",
                    "color",
                    "colour",
                    "wear",
                    "wearing",
                    "shirt",
                    "count",
                    "how many",
                    "bird",
                    "species",
                    "animal",
                    "screen",
                    "shown",
                    "show",
                    "frame",
                    "background",
                    "sign",
                    "logo",
                    "action",
                    "doing",
                    "see",
                    "look",
                    "watch",
                )
                needs_video_analysis = (not has_transcript) or any(
                    marker in (question or "").lower() for marker in visual_markers
                )

                video_analyzed = False
                video_analysis_error = ""
                gemini_pool = self.provider_key_pools.get("gemini") or []
                if gemini_pool and needs_video_analysis:
                    gemini_models = list(
                        dict.fromkeys(
                            [
                                "gemini/gemini-flash-latest",
                                "gemini/gemini-2.5-flash",
                            ]
                            + (self.gemini_flash_models or [])
                        )
                    )[:2]
                    while not video_analyzed:
                        rate_limited_gemini = False
                        for g_model in gemini_models:
                            raw_model = g_model[len("gemini/"):] if g_model.startswith("gemini/") else g_model
                            while True:
                                g_key = self._get_api_key(g_model)
                                if not g_key:
                                    video_analysis_error = "no gemini api key"
                                    break
                                try:
                                    gm_resp = requests.post(
                                        f"https://generativelanguage.googleapis.com/v1beta/models/{raw_model}:generateContent",
                                        params={"key": g_key},
                                        headers={"Content-Type": "application/json"},
                                        json={
                                            "contents": [
                                                {
                                                    "parts": [
                                                        {"file_data": {"file_uri": watch_url}},
                                                        {"text": question},
                                                    ]
                                                }
                                            ],
                                            "generationConfig": {
                                                "maxOutputTokens": 2048,
                                                "thinkingConfig": {"thinkingBudget": 0},
                                            },
                                        },
                                        timeout=_tool_timeout(20.0, min_timeout=4.0),
                                    )
                                    if gm_resp.status_code == 200:
                                        candidates = gm_resp.json().get("candidates") or []
                                        if candidates:
                                            parts = (candidates[0].get("content") or {}).get("parts") or []
                                            analysis_text = "\n".join(
                                                str(p.get("text", "")).strip()
                                                for p in parts
                                                if isinstance(p, dict) and p.get("text")
                                            ).strip()
                                            if analysis_text:
                                                sections.append(f"Multimodal Video Analysis:\n{analysis_text}")
                                                video_analyzed = True
                                                break
                                        video_analysis_error = "gemini returned empty candidate"
                                        break
                                    err_low = gm_resp.text.lower()
                                    video_analysis_error = f"gemini status {gm_resp.status_code}: {gm_resp.text[:200]}"
                                    if gm_resp.status_code in (401, 402, 403):
                                        if hasattr(self, "_rotate_api_key") and self._rotate_api_key(
                                            "gemini", permanent=True
                                        ):
                                            continue
                                        break
                                    if (
                                        gm_resp.status_code == 429
                                        or "quota" in err_low
                                        or "resource_exhausted" in err_low
                                    ):
                                        rate_limited_gemini = True
                                        break
                                    break
                                except Exception as gm_exc:
                                    if "task time budget exhausted" in str(gm_exc).lower():
                                        raise
                                    video_analysis_error = f"gemini exception: {type(gm_exc).__name__}: {gm_exc}"
                                    break
                            if video_analyzed:
                                break

                        if (
                            not video_analyzed
                            and rate_limited_gemini
                            and hasattr(self, "_rotate_api_key")
                            and self._provider_key_idx.get("gemini", 0) + 1 < len(gemini_pool)
                            and self._rotate_api_key("gemini")
                        ):
                            continue
                        break

                if not has_transcript and not video_analyzed:
                    reason = f" ({video_analysis_error})" if video_analysis_error else ""
                    sections.append(
                        "Transcript/Video Analysis Status: unavailable"
                        f"{reason}. "
                        "Use web_search or search_wikipedia with the video title, channel, or quoted dialogue. "
                        "Do NOT guess visual counts from the question alone."
                    )

                return _trim_tool_output("\n\n".join(sections), max_chars=12000)
            except Exception as e:
                return f"Error inspecting YouTube '{url}': {str(e)}"

        @tool
        def transcribe_audio(
            audio_path: str,
            question: str = "Transcribe all spoken words verbatim and answer any question about the audio.",
        ) -> str:
            """Transcribes or analyzes a local audio file (.mp3, .wav, .m4a, .ogg) using available audio/multimodal models.
            Args:
                audio_path: Local path or filename of the downloaded audio file.
                question: Specific transcription or analysis instruction for the audio.
            """
            try:
                resolved_path = audio_path
                if not os.path.isfile(resolved_path):
                    target_name = os.path.basename(audio_path)
                    for root, _, files in os.walk("."):
                        if target_name in files:
                            resolved_path = os.path.join(root, target_name)
                            break
                if not os.path.isfile(resolved_path):
                    return f"Audio file not found: '{audio_path}'"

                ext = os.path.splitext(resolved_path)[1].lower().lstrip(".")
                mime_map = {
                    "mp3": "audio/mp3",
                    "wav": "audio/wav",
                    "m4a": "audio/mp4",
                    "ogg": "audio/ogg",
                    "flac": "audio/flac",
                }
                mime_type = mime_map.get(ext, "audio/mp3")

                while True:
                    groq_key = self._get_api_key("groq/whisper-large-v3-turbo")
                    if not groq_key:
                        break
                    try:
                        with open(resolved_path, "rb") as audio_f:
                            groq_resp = requests.post(
                                "https://api.groq.com/openai/v1/audio/transcriptions",
                                headers={"Authorization": f"Bearer {groq_key}"},
                                files={"file": (os.path.basename(resolved_path), audio_f, mime_type)},
                                data={"model": "whisper-large-v3-turbo", "response_format": "text"},
                                timeout=_tool_timeout(20.0),
                            )
                        if groq_resp.status_code == 200:
                            transcript = groq_resp.text.strip()
                            if transcript:
                                return f"[Whisper Transcript]: {transcript}"
                            break
                        err_body = groq_resp.text.lower()
                        if groq_resp.status_code in (401, 402, 403):
                            if hasattr(self, "_rotate_api_key") and self._rotate_api_key("groq", permanent=True):
                                continue
                            break
                        if groq_resp.status_code == 429 or "quota" in err_body or "resource_exhausted" in err_body:
                            groq_pool = self.provider_key_pools.get("groq") or []
                            if (
                                hasattr(self, "_rotate_api_key")
                                and self._provider_key_idx.get("groq", 0) + 1 < len(groq_pool)
                                and self._rotate_api_key("groq", permanent=False)
                            ):
                                continue
                        break
                    except Exception as groq_exc:
                        if "task time budget exhausted" in str(groq_exc).lower():
                            raise
                        break

                with open(resolved_path, "rb") as f:
                    b64_data = base64.b64encode(f.read()).decode("utf-8")

                audio_models = []
                if getattr(self, "model_id", "").startswith("gemini/"):
                    audio_models.append(self.model_id)
                if self.provider_key_pools.get("gemini"):
                    audio_models.extend(
                        self.gemini_flash_models
                        or [
                            "gemini/gemini-3-flash-preview",
                            "gemini/gemini-flash-latest",
                        ]
                    )
                audio_models = list(dict.fromkeys(audio_models))[:2]

                last_err = None
                while True:
                    rate_limited_gemini = False
                    for a_model in audio_models:
                        raw_model = a_model[len("gemini/"):] if a_model.startswith("gemini/") else a_model
                        while True:
                            a_key = self._get_api_key(a_model)
                            if not a_key:
                                break
                            try:
                                gm_resp = requests.post(
                                    f"https://generativelanguage.googleapis.com/v1beta/models/{raw_model}:generateContent",
                                    params={"key": a_key},
                                    headers={"Content-Type": "application/json"},
                                    json={
                                        "contents": [
                                            {
                                                "parts": [
                                                    {"inline_data": {"mime_type": mime_type, "data": b64_data}},
                                                    {"text": question},
                                                ]
                                            }
                                        ],
                                        "generationConfig": {
                                            "maxOutputTokens": 2048,
                                            "thinkingConfig": {"thinkingBudget": 512},
                                        },
                                    },
                                    timeout=_tool_timeout(30.0),
                                )
                                if gm_resp.status_code == 200:
                                    candidates = gm_resp.json().get("candidates") or []
                                    if candidates:
                                        parts = (candidates[0].get("content") or {}).get("parts") or []
                                        out = "\n".join(
                                            str(p.get("text", "")).strip()
                                            for p in parts
                                            if isinstance(p, dict) and p.get("text")
                                        ).strip()
                                        if out:
                                            return out
                                    break
                                err_low = gm_resp.text.lower()
                                if gm_resp.status_code in (401, 402, 403):
                                    if hasattr(self, "_rotate_api_key") and self._rotate_api_key(
                                        "gemini", permanent=True
                                    ):
                                        continue
                                    break
                                if (
                                    gm_resp.status_code == 429
                                    or "quota" in err_low
                                    or "resource_exhausted" in err_low
                                ):
                                    rate_limited_gemini = True
                                    break
                                break
                            except Exception as exc:
                                if "task time budget exhausted" in str(exc).lower():
                                    raise
                                last_err = exc
                                break

                    gemini_pool = self.provider_key_pools.get("gemini") or []
                    if (
                        rate_limited_gemini
                        and hasattr(self, "_rotate_api_key")
                        and self._provider_key_idx.get("gemini", 0) + 1 < len(gemini_pool)
                        and self._rotate_api_key("gemini")
                    ):
                        continue
                    break

                raise RuntimeError(str(last_err) if last_err else "No audio transcription model available.")
            except Exception as e:
                return f"Error transcribing audio '{audio_path}': {str(e)}"

        self._transcribe_audio = transcribe_audio

        candidate_models = []

        # 1. Gemini Flash jako główny model (najlepsza stabilność z CodeAgent)
        if self.provider_keys.get("gemini"):
            available_api_models = set()
            for g_key in self.provider_key_pools.get("gemini") or [gemini_key]:
                if not g_key:
                    continue
                try:
                    models_resp = requests.get(
                        "https://generativelanguage.googleapis.com/v1beta/models",
                        params={"key": g_key},
                        timeout=15,
                    )
                    if models_resp.status_code == 200:
                        for m in models_resp.json().get("models", []):
                            if "generateContent" in m.get("supportedGenerationMethods", []):
                                raw_name = m.get("name", "")
                                if raw_name.startswith("models/"):
                                    full_id = "gemini/" + raw_name[len("models/"):]
                                    low_id = full_id.lower()
                                    if not any(
                                        bad in low_id
                                        for bad in (
                                            "tts", "image", "imagen", "veo", "embedding",
                                            "aqa", "audio", "robotics", "computer-use",
                                            "deep-research", "omni", "exp", "thinking",
                                            "gemma", "flash-lite",
                                        )
                                    ):
                                        available_api_models.add(full_id)
                        if available_api_models:
                            break
                except Exception as list_exc:
                    print(f"Warning: could not list Gemini models via REST: {list_exc}")

            if available_api_models:
                discovered_flash = sorted(
                    (m for m in available_api_models if "flash" in m.lower()),
                    key=lambda name: (
                        0 if name.lower() == "gemini/gemini-3-flash-preview" else 1,
                        0 if name.lower() == "gemini/gemini-flash-latest" else 1,
                        0 if name.lower() == "gemini/gemini-2.5-flash" else 1,
                        name,
                    ),
                )
                self.gemini_flash_models = (discovered_flash or sorted(available_api_models))[:2]
                candidate_models.extend(self.gemini_flash_models)
            else:
                self.gemini_flash_models = [
                    "gemini/gemini-3-flash-preview",
                    "gemini/gemini-flash-latest",
                ]
                candidate_models.extend(self.gemini_flash_models)
            print(f"[GEMINI MODELS] {self.gemini_flash_models}", flush=True)

        # 2. Groq jako szybki fallback
        if self.provider_keys.get("groq"):
            preferred_groq = [
                "groq/llama-3.3-70b-versatile",
                "groq/moonshotai/kimi-k2-instruct",
                "groq/meta-llama/llama-4-maverick-17b-128e-instruct",
                "groq/meta-llama/llama-4-scout-17b-16e-instruct",
                "groq/qwen/qwen3-32b",
                "groq/qwen/qwen3.8-27b",
                "groq/llama-3.1-8b-instant",
            ]
            live_groq = []
            try:
                groq_resp = requests.get(
                    "https://api.groq.com/openai/v1/models",
                    headers={"Authorization": f"Bearer {self.provider_keys['groq']}"},
                    timeout=10,
                )
                if groq_resp.status_code == 200:
                    for item in groq_resp.json().get("data", []):
                        g_id = str(item.get("id", "")).strip()
                        if g_id and not any(
                            bad in g_id.lower()
                            for bad in (
                                "whisper", "tts", "orpheus", "guard",
                                "safeguard", "embed", "compound", "allam",
                                "gpt-oss",
                            )
                        ):
                            live_groq.append(f"groq/{g_id}")
            except Exception as groq_exc:
                print(f"Warning: could not list Groq models: {groq_exc}")

            print(f"[GROQ LIVE MODELS] {live_groq}", flush=True)
            if live_groq:
                live_set = set(live_groq)
                curated_groq = [m for m in preferred_groq if m in live_set]
                extra_groq = sorted(
                    (m for m in live_groq if m not in curated_groq),
                    key=lambda name: (
                        0 if any(k in name.lower() for k in ("kimi", "70b", "maverick", "scout", "32b", "27b")) else 1,
                        name,
                    ),
                )
                selected_groq = list(dict.fromkeys(curated_groq + extra_groq))[:4]
                candidate_models.extend(selected_groq)
            else:
                candidate_models.extend(preferred_groq[:4])

        # 3. OpenRouter darmowe modele dopiero po Gemini i Groq
        priority_openrouter_models = [
            "openrouter/meta-llama/llama-3.3-70b-instruct:free",
            "openrouter/qwen/qwen3-next-80b-a3b-instruct:free",
            "openrouter/google/gemma-3-27b-it:free",
            "openrouter/mistralai/mistral-small-3.1-24b-instruct:free",
            "openrouter/openrouter/free",
        ]

        if self.provider_keys.get("openrouter"):
            live_free_models = set()
            try:
                or_resp = requests.get(
                    "https://openrouter.ai/api/v1/models",
                    timeout=10,
                    headers={"User-Agent": "HF-Agents-Course-Bot/1.0"},
                )
                if or_resp.status_code == 200:
                    for item in or_resp.json().get("data", []):
                        m_id = str(item.get("id", "")).strip()
                        if m_id == "openrouter/free" or m_id.endswith(":free"):
                            live_free_models.add(f"openrouter/{m_id}")
            except Exception as or_exc:
                print(f"Warning: could not list OpenRouter models: {or_exc}")

            if live_free_models:
                curated_live = [m for m in priority_openrouter_models if m in live_free_models]
                candidate_models.extend(curated_live[:2] or ["openrouter/openrouter/free"])
            else:
                candidate_models.extend(priority_openrouter_models[:2])

        if self.provider_keys.get("huggingface"):
            candidate_models.extend([
                "huggingface/Qwen/Qwen2.5-72B-Instruct",
                "huggingface/meta-llama/Llama-3.3-70B-Instruct",
            ])

        if self.provider_keys.get("nvidia_nim"):
            preferred_nim = [
                "nvidia_nim/nvidia/nemotron-3-ultra-550b-a55b",
                "nvidia_nim/nvidia/llama-3.3-nemotron-super-49b-v1",
                "nvidia_nim/nvidia/llama-3.1-nemotron-70b-instruct",
                "nvidia_nim/qwen/qwen2.5-72b-instruct",
                "nvidia_nim/meta/llama-3.1-70b-instruct",
                "nvidia_nim/mistralai/mistral-large-2-instruct",
            ]
            live_nim = []
            try:
                nim_resp = requests.get(
                    "https://integrate.api.nvidia.com/v1/models",
                    headers={"Authorization": f"Bearer {self.provider_keys['nvidia_nim']}"},
                    timeout=10,
                )
                if nim_resp.status_code == 200:
                    for item in nim_resp.json().get("data", []):
                        n_id = str(item.get("id", "")).strip()
                        if n_id and not any(
                            bad in n_id.lower()
                            for bad in ("embed", "rerank", "guard", "parse", "ocr", "tts", "asr", "riva", "kosmos", "deplot", "paligemma")
                        ):
                            live_nim.append(f"nvidia_nim/{n_id}")
            except Exception as nim_exc:
                print(f"Warning: could not list NVIDIA NIM models: {nim_exc}")

            if live_nim:
                live_nim_set = set(live_nim)
                curated_nim = [m for m in preferred_nim if m in live_nim_set]
                extra_nim = [
                    m for m in live_nim
                    if m not in curated_nim and any(k in m.lower() for k in ("nemotron", "70b", "72b", "large", "qwen", "llama-3.3", "llama-3.1"))
                ]
                candidate_models.extend((curated_nim + extra_nim)[:5])
            else:
                candidate_models.extend(preferred_nim[:4])

        priority_rank = {name: idx for idx, name in enumerate(candidate_models)}

        def _model_priority(model_name: str) -> tuple[int, int, int, tuple[int, int], str]:
            provider = model_name.split("/", 1)[0].lower() if "/" in model_name else "gemini"
            low = model_name.lower()
            key_missing = 0 if self._get_api_key(model_name) else 1

            if provider == "nvidia_nim":
                if "ultra" in low or "550b" in low:
                    sub_rank = 0
                elif "mistral-large" in low:
                    sub_rank = 1
                elif "nemotron" in low and "nano" not in low and "bolt" not in low and "reasoning" not in low:
                    sub_rank = 2
                else:
                    sub_rank = 3
                return (key_missing, 0, sub_rank, (0, 0), model_name)

            if provider == "openrouter":
                sub_rank = priority_rank.get(model_name, len(priority_rank))
                return (key_missing, 1, sub_rank, (0, 0), model_name)

            if provider == "gemini":
                if low == "gemini/gemini-3-flash-preview":
                    return (key_missing, 2, 0, (0, 0), model_name)
                if low == "gemini/gemini-flash-latest":
                    return (key_missing, 2, 1, (0, 0), model_name)
                return (key_missing, 2, 2, (0, 0), model_name)

            if provider == "groq":
                if "llama-3.3-70b" in low or "kimi" in low:
                    sub_rank = 0
                elif "maverick" in low or "scout" in low:
                    sub_rank = 1
                elif "32b" in low or "27b" in low:
                    sub_rank = 2
                else:
                    sub_rank = 3
                return (key_missing, 3, sub_rank, (0, 0), model_name)

            if provider == "huggingface":
                return (key_missing, 4, 0, (0, 0), model_name)

            return (key_missing, 5, 0, (0, 0), model_name)

        self.working_models = sorted(
            dict.fromkeys(candidate_models),
            key=_model_priority,
        )

        if not self.working_models:
            raise RuntimeError("No models available for the configured API keys.")

        sig = inspect.signature(CodeAgent.__init__)
        supports_custom_tags = "code_block_tags" in sig.parameters
        code_open_tag, code_close_tag = ("<code>", "</code>") if supports_custom_tags else ("```py", "```")

        class SafeLiteLLMModel(LiteLLMModel):
            open_tag = code_open_tag
            close_tag = code_close_tag

            def __init__(self, *args, **kwargs):
                super().__init__(*args, **kwargs)
                self._explicit_api_key = kwargs.get("api_key")
                self._explicit_api_base = kwargs.get("api_base")
                self._last_llm_error = None
                if self._explicit_api_key:
                    self.api_key = self._explicit_api_key
                if self._explicit_api_base:
                    self.api_base = self._explicit_api_base

            if hasattr(LiteLLMModel, "generate"):
                def generate(self, *args, **kwargs):
                    from concurrent.futures import ThreadPoolExecutor, TimeoutError as FutureTimeoutError
                    import copy
                    import time

                    litellm.suppress_debug_info = True
                    litellm.num_retries = 0
                    t0 = time.monotonic()

                    def _trim_text_val(val: str, max_len: int) -> str:
                        if len(val) <= max_len:
                            return val
                        half_len = max_len // 2
                        return val[:half_len] + "\n...[trimmed]...\n" + val[-half_len:]

                    def _trim_messages(raw_msgs):
                        if not isinstance(raw_msgs, list):
                            return raw_msgs
                        if len(raw_msgs) > 8:
                            selected = raw_msgs[:2] + raw_msgs[-6:]
                        else:
                            selected = raw_msgs
                        out = []
                        for idx, m in enumerate(selected):
                            max_len = 14000 if idx < 2 else 8500
                            m_copy = copy.copy(m)
                            if isinstance(m_copy, dict):
                                content = m_copy.get("content")
                                if isinstance(content, str) and len(content) > max_len:
                                    m_copy["content"] = _trim_text_val(content, max_len)
                                elif isinstance(content, list):
                                    new_parts = []
                                    for part in content:
                                        if (
                                            isinstance(part, dict)
                                            and isinstance(part.get("text"), str)
                                            and len(part["text"]) > max_len
                                        ):
                                            part_copy = dict(part)
                                            part_copy["text"] = _trim_text_val(part["text"], max_len)
                                            new_parts.append(part_copy)
                                        else:
                                            new_parts.append(part)
                                    m_copy["content"] = new_parts
                            else:
                                content = getattr(m_copy, "content", None)
                                if isinstance(content, str) and len(content) > max_len:
                                    try:
                                        setattr(m_copy, "content", _trim_text_val(content, max_len))
                                    except Exception:
                                        pass
                            out.append(m_copy)
                        return out

                    raw_messages = kwargs.pop("messages", None)
                    if raw_messages is None and len(args) >= 1:
                        raw_messages = args[0]
                    trimmed_messages = _trim_messages(raw_messages)

                    stop_sequences = kwargs.pop("stop_sequences", None)
                    if stop_sequences is None and len(args) >= 2:
                        stop_sequences = args[1]

                    kwargs.pop("response_format", None)
                    kwargs.pop("tools_to_call_from", None)

                    call_kwargs = self._prepare_call_kwargs(dict(kwargs))
                    call_kwargs["num_retries"] = 0
                    call_kwargs["max_retries"] = 0
                    req_timeout = min(
                        float(call_kwargs.get("timeout") or getattr(self, "timeout", None) or 22.0),
                        22.0,
                    )
                    task_deadline = getattr(self, "deadline", None)
                    if task_deadline is not None:
                        remaining = task_deadline - time.monotonic()
                        if remaining <= 1.0:
                            raise RuntimeError("Task time budget exhausted")
                        req_timeout = max(1.0, min(req_timeout, remaining - 0.5))
                        hard_timeout = max(1.5, min(req_timeout + 2.0, remaining))
                    else:
                        hard_timeout = req_timeout + 3.0
                    call_kwargs["timeout"] = req_timeout
                    litellm.request_timeout = req_timeout
                    hard_timeout = req_timeout + 3.0

                    role_map = {
                        "tool-call": "assistant",
                        "tool-response": "user",
                        "tool": "user",
                    }
                    formatted_messages = []
                    for m in trimmed_messages or []:
                        if isinstance(m, dict):
                            raw_role = m.get("role", "user")
                            content_val = m.get("content", "")
                        else:
                            raw_role = getattr(m, "role", "user")
                            content_val = getattr(m, "content", "")
                        role_str = str(getattr(raw_role, "value", raw_role) or "user").lower()
                        role_str = role_map.get(role_str, role_str)
                        if role_str not in {"system", "user", "assistant"}:
                            role_str = "user"
                        if content_val is None:
                            content_val = ""
                        formatted_messages.append({"role": role_str, "content": content_val})

                    if stop_sequences:
                        call_kwargs["stop"] = list(stop_sequences)

                    def _invoke_completion():
                        try:
                            from smolagents.models import ChatMessage
                        except ImportError:
                            from smolagents import ChatMessage

                        response = litellm.completion(
                            model=self.model_id,
                            messages=formatted_messages,
                            **call_kwargs,
                        )
                        choices = (
                            response.get("choices")
                            if isinstance(response, dict)
                            else getattr(response, "choices", None)
                        ) or []
                        first_choice = choices[0] if choices else {}
                        raw_msg = (
                            first_choice.get("message")
                            if isinstance(first_choice, dict)
                            else getattr(first_choice, "message", None)
                        )
                        raw_content = (
                            raw_msg.get("content")
                            if isinstance(raw_msg, dict)
                            else getattr(raw_msg, "content", None)
                        )
                        if isinstance(raw_content, list):
                            content_txt = "\n".join(
                                str(p.get("text", ""))
                                for p in raw_content
                                if isinstance(p, dict) and p.get("text")
                            )
                        else:
                            content_txt = "" if raw_content is None else str(raw_content)

                        if content_txt and stop_sequences:
                            for seq in stop_sequences:
                                if seq and content_txt.endswith(seq):
                                    content_txt = content_txt[: -len(seq)]

                        usage = (
                            response.get("usage")
                            if isinstance(response, dict)
                            else getattr(response, "usage", None)
                        )
                        in_tok = (
                            usage.get("prompt_tokens", 0)
                            if isinstance(usage, dict)
                            else getattr(usage, "prompt_tokens", 0)
                        ) or 0
                        out_tok = (
                            usage.get("completion_tokens", 0)
                            if isinstance(usage, dict)
                            else getattr(usage, "completion_tokens", 0)
                        ) or 0
                        self.last_input_token_count = in_tok
                        self.last_output_token_count = out_tok

                        token_usage_obj = None
                        try:
                            from smolagents.monitoring import TokenUsage

                            token_usage_obj = TokenUsage(input_tokens=in_tok, output_tokens=out_tok)
                        except Exception:
                            pass

                        cm_kwargs = {
                            "role": "assistant",
                            "content": content_txt,
                            "tool_calls": None,
                            "raw": response,
                            "token_usage": token_usage_obj,
                        }
                        cm_sig = inspect.signature(ChatMessage.__init__)
                        return ChatMessage(
                            **{k: v for k, v in cm_kwargs.items() if k != "self" and k in cm_sig.parameters}
                        )

                    executor = ThreadPoolExecutor(max_workers=1)
                    future = executor.submit(_invoke_completion)
                    try:
                        raw_msg = future.result(timeout=hard_timeout)
                        msg = self._validate_message(raw_msg)
                        self._last_llm_error = None
                        return msg
                    except FutureTimeoutError:
                        timeout_exc = TimeoutError(
                            f"LLM call timed out after {hard_timeout:.1f}s for {self.model_id}"
                        )
                        self._last_llm_error = timeout_exc
                        raise timeout_exc
                    except Exception as exc:
                        self._last_llm_error = exc
                        raise
                    finally:
                        executor.shutdown(wait=False, cancel_futures=True)
                        print(f"[LLM] {self.model_id}: {time.monotonic() - t0:.1f}s", flush=True)

            
            @classmethod
            def _sanitize_code_tags(cls, text: str) -> str:
                import ast
                import json
                import re

                open_t = cls.open_tag
                close_t = cls.close_tag

                text = re.sub(r"<think>.*?</think>", "", text, flags=re.DOTALL | re.IGNORECASE).strip()
                text = re.sub(
                    r"(?im)^\s*(?:from\s+(?:tools|download_task_file|read_local_file|web_search|search_wikipedia|fetch_url_text|inspect_image|analyze_chessboard|inspect_youtube|transcribe_audio|ask_web)\s+import\s+.*|import\s+(?:tools|download_task_file|read_local_file|web_search|search_wikipedia|fetch_url_text|inspect_image|analyze_chessboard|inspect_youtube|transcribe_audio|ask_web)\b.*)$",
                    "",
                    text,
                ).strip()

                def _convert_xml_tool_calls(raw: str) -> str | None:
                    qwen_calls = re.findall(
                        r"<tool_call>\s*<function=([A-Za-z_][A-Za-z0-9_]*)>(.*?)</function>\s*</tool_call>",
                        raw,
                        flags=re.DOTALL | re.IGNORECASE,
                    )
                    if qwen_calls:
                        py_lines = []
                        for idx, (fn_name, params_blob) in enumerate(qwen_calls):
                            params = re.findall(
                                r"<parameter=([A-Za-z_][A-Za-z0-9_]*)>(.*?)</parameter>",
                                params_blob,
                                flags=re.DOTALL | re.IGNORECASE,
                            )
                            kwargs_parts = []
                            for p_name, p_val in params:
                                val_clean = p_val.strip()
                                try:
                                    parsed_val = json.loads(val_clean)
                                    kwargs_parts.append(f"{p_name}={repr(parsed_val)}")
                                except Exception:
                                    kwargs_parts.append(f"{p_name}={json.dumps(val_clean, ensure_ascii=False)}")
                            if fn_name in ("python_interpreter", "python", "code"):
                                code_arg = next((v.strip() for k, v in params if k in ("code", "arguments", "script")), "")
                                if code_arg:
                                    py_lines.append(code_arg)
                            else:
                                var_name = f"tool_res_{idx}"
                                py_lines.append(f"{var_name} = {fn_name}({', '.join(kwargs_parts)})")
                                py_lines.append(f"print({var_name})")
                        if py_lines:
                            return "\n".join(py_lines)

                    dsml_blocks = re.findall(
                        r"<[||]DSML[||]\s*invoke\s+name=['\"]([^'\"]+)['\"]\s*>(.*?)</[||]DSML[||]\s*invoke>",
                        raw,
                        flags=re.DOTALL | re.IGNORECASE,
                    )
                    if dsml_blocks:
                        py_lines = []
                        for inv_name, inv_body in dsml_blocks:
                            dsml_params = re.findall(
                                r"<[||]DSML[||]\s*parameter\s+name=['\"]([^'\"]+)['\"][^>]*>(.*?)</[||]DSML[||]\s*parameter>",
                                inv_body,
                                flags=re.DOTALL | re.IGNORECASE,
                            )
                            if inv_name in ("python_interpreter", "python", "code"):
                                code_arg = next((v.strip() for k, v in dsml_params if k in ("arguments", "code", "script")), "")
                                if code_arg:
                                    py_lines.append(code_arg)
                            else:
                                kwargs_parts = [
                                    f"{k}={json.dumps(v.strip(), ensure_ascii=False)}"
                                    for k, v in dsml_params
                                ]
                                py_lines.append(f"print({inv_name}({', '.join(kwargs_parts)}))")
                        if py_lines:
                            return "\n".join(py_lines)
                    return None

                def _guard_unbound_lines(code_str: str) -> str:
                    if not code_str:
                        return code_str
                    try:
                        tree = ast.parse(code_str)
                    except SyntaxError:
                        return code_str

                    def _has_load(node: ast.AST) -> bool:
                        return any(
                            isinstance(n, ast.Name) and n.id == "lines" and isinstance(n.ctx, ast.Load)
                            for n in ast.walk(node)
                        )

                    def _has_store(node: ast.AST) -> bool:
                        return any(
                            isinstance(n, ast.Name) and n.id == "lines" and isinstance(n.ctx, ast.Store)
                            for n in ast.walk(node)
                        )

                    defined = False
                    needs_guard = False
                    for stmt in tree.body:
                        if isinstance(stmt, ast.Assign):
                            if not defined and _has_load(stmt.value):
                                needs_guard = True
                                break
                            if any(_has_store(t) for t in stmt.targets):
                                defined = True
                        elif isinstance(stmt, ast.AnnAssign):
                            if not defined and stmt.value is not None and _has_load(stmt.value):
                                needs_guard = True
                                break
                            if stmt.value is not None and _has_store(stmt.target):
                                defined = True
                        elif isinstance(stmt, ast.AugAssign):
                            if not defined:
                                needs_guard = True
                                break
                        else:
                            if not defined and _has_load(stmt):
                                needs_guard = True
                                break
                            if _has_store(stmt):
                                defined = True

                    return ("lines = []\n" + code_str) if needs_guard else code_str

                def _ensure_observable_output(code_str: str) -> str:
                    clean_code = (code_str or "").strip()
                    if not clean_code or "final_answer(" in clean_code:
                        return clean_code
                    try:
                        tree = ast.parse(clean_code)
                    except SyntaxError:
                        return clean_code
                    if not tree.body:
                        return clean_code
                    last_node = tree.body[-1]
                    if (
                        isinstance(last_node, ast.Assign)
                        and len(last_node.targets) == 1
                        and isinstance(last_node.targets[0], ast.Name)
                    ):
                        var_name = last_node.targets[0].id
                        return f"{clean_code}\nprint({var_name})"
                    return clean_code

                def _convert_json_tool_calls(raw: str) -> str | None:
                    stripped = raw.strip()
                    if not (stripped.startswith("{") or stripped.startswith("[")):
                        return None
                    try:
                        payload = json.loads(stripped)
                    except Exception:
                        return None

                    calls = []
                    if isinstance(payload, dict) and isinstance(payload.get("tool_calls"), list):
                        calls = payload["tool_calls"]
                    elif isinstance(payload, dict) and ("name" in payload or "function" in payload):
                        calls = [payload]
                    elif isinstance(payload, list):
                        calls = payload

                    py_lines = []
                    for idx, item in enumerate(calls):
                        if not isinstance(item, dict):
                            continue
                        fn_obj = item.get("function") if isinstance(item.get("function"), dict) else item
                        fn_name = fn_obj.get("name")
                        fn_args = fn_obj.get("arguments", {})
                        if not fn_name or not isinstance(fn_name, str):
                            continue
                        if isinstance(fn_args, str):
                            try:
                                fn_args = json.loads(fn_args) if fn_args.strip() else {}
                            except Exception:
                                fn_args = {"query": fn_args}
                        if not isinstance(fn_args, dict):
                            continue
                        var_name = f"tool_res_{idx}"
                        py_lines.append(f"{var_name} = {fn_name}(**{json.dumps(fn_args, ensure_ascii=False)})")
                        py_lines.append(f"print({var_name})")
                    return "\n".join(py_lines) if py_lines else None

                def _extract_valid_python(raw: str) -> str:
                    json_converted = _convert_json_tool_calls(raw)
                    if json_converted is not None:
                        return _ensure_observable_output(_guard_unbound_lines(json_converted))

                    converted = _convert_xml_tool_calls(raw)
                    if converted is not None:
                        raw = converted

                    src_lines = []
                    for line in raw.splitlines():
                        stripped = line.lstrip()
                        if re.match(r"^(?:thoughts?|thinking)\s*:", stripped, flags=re.IGNORECASE):
                            src_lines.append("# " + stripped)
                        else:
                            src_lines.append(line)

                    n = len(src_lines)
                    for start in range(n):
                        if not src_lines[start].strip():
                            continue
                        for end in range(n, start, -1):
                            candidate = "\n".join(src_lines[start:end]).strip()
                            if not candidate:
                                continue
                            try:
                                tree = ast.parse(candidate)
                                if not tree.body:
                                    continue
                                if (
                                    len(tree.body) == 1
                                    and isinstance(tree.body[0], ast.Expr)
                                    and isinstance(tree.body[0].value, (ast.Name, ast.Constant, ast.List, ast.Tuple))
                                ):
                                    continue
                                return _ensure_observable_output(_guard_unbound_lines(candidate))
                            except SyntaxError:
                                continue

                    plain = "\n".join(src_lines).strip()
                    fa_match = re.findall(
                        r"(?im)^\s*(?:final\s*answer|answer)\s*:\s*(.+)$",
                        plain,
                    )
                    if fa_match and fa_match[-1].strip():
                        safe_ans = (
                            json.dumps(fa_match[-1].strip(), ensure_ascii=False)
                            .replace("<", "\\u003c")
                            .replace(">", "\\u003e")
                            .replace("```", "\\x60\\x60\\x60")
                        )
                        return f"final_answer({safe_ans})"
                    return (
                        'print("Invalid non-code output. Write valid Python code inside '
                        'the code block calling a tool or final_answer(...).")'
                    )

                tag_blocks = re.findall(
                    rf"{re.escape(open_t)}(.*?){re.escape(close_t)}",
                    text,
                    flags=re.DOTALL | re.IGNORECASE,
                )
                if tag_blocks:
                    non_empty_blocks = [b.strip() for b in tag_blocks if b.strip()]
                    for raw_block in reversed(non_empty_blocks):
                        extracted = _extract_valid_python(raw_block)
                        if "Invalid non-code output." not in extracted:
                            return f"{open_t}\n{extracted}\n{close_t}"
                    if non_empty_blocks:
                        return f"{open_t}\n{_extract_valid_python(non_empty_blocks[-1])}\n{close_t}"

                fenced_blocks = re.findall(
                    r"```(?:py|python)?\s*\n(.*?)```",
                    text,
                    flags=re.DOTALL | re.IGNORECASE,
                )
                if fenced_blocks:
                    non_empty_fenced = [b.strip() for b in fenced_blocks if b.strip()]
                    for raw_block in reversed(non_empty_fenced):
                        extracted = _extract_valid_python(raw_block)
                        if "Invalid non-code output." not in extracted:
                            return f"{open_t}\n{extracted}\n{close_t}"
                    if non_empty_fenced:
                        return f"{open_t}\n{_extract_valid_python(non_empty_fenced[-1])}\n{close_t}"

                return f"{open_t}\n{_extract_valid_python(text)}\n{close_t}"

            @classmethod
            def _validate_message(cls, msg):
                import json
                import re

                if msg is None:
                    raise RuntimeError(
                        "Error in generating model output: empty model response (content=None)"
                    )

                def _extract_text_from_blocks(val) -> str:
                    if val is None:
                        return ""
                    if isinstance(val, str):
                        return val.strip()
                    if isinstance(val, list):
                        parts = []
                        for part in val:
                            if isinstance(part, dict):
                                txt = part.get("text") or part.get("thinking") or part.get("content")
                                if txt:
                                    parts.append(str(txt))
                            else:
                                txt = (
                                    getattr(part, "text", None)
                                    or getattr(part, "thinking", None)
                                    or getattr(part, "content", None)
                                )
                                if txt:
                                    parts.append(str(txt))
                        return "\n".join(parts).strip()
                    return str(val).strip()

                raw_obj = getattr(msg, "raw", None)
                raw_msg = None
                finish_reason = ""

                if raw_obj is not None:
                    choices = raw_obj.get("choices") if isinstance(raw_obj, dict) else getattr(raw_obj, "choices", None)
                    if choices:
                        first_choice = choices[0]
                        finish_reason = str(
                            (
                                first_choice.get("finish_reason")
                                if isinstance(first_choice, dict)
                                else getattr(first_choice, "finish_reason", "")
                            )
                            or ""
                        ).lower()
                        raw_msg = (
                            first_choice.get("message")
                            if isinstance(first_choice, dict)
                            else getattr(first_choice, "message", None)
                        )

                content_str = _extract_text_from_blocks(getattr(msg, "content", None))

                reasoning_sources = [
                    getattr(msg, "reasoning_content", None),
                    getattr(msg, "reasoning", None),
                ]
                if raw_msg is not None:
                    if isinstance(raw_msg, dict):
                        reasoning_sources.extend([
                            raw_msg.get("reasoning_content"),
                            raw_msg.get("reasoning"),
                            raw_msg.get("thinking_blocks"),
                        ])
                    else:
                        reasoning_sources.extend([
                            getattr(raw_msg, "reasoning_content", None),
                            getattr(raw_msg, "reasoning", None),
                            getattr(raw_msg, "thinking_blocks", None),
                        ])

                reasoning_str = next(
                    (txt for src in reasoning_sources if (txt := _extract_text_from_blocks(src))),
                    "",
                )

                tool_calls = getattr(msg, "tool_calls", None)
                if not tool_calls and raw_msg is not None:
                    tool_calls = (
                        raw_msg.get("tool_calls")
                        if isinstance(raw_msg, dict)
                        else getattr(raw_msg, "tool_calls", None)
                    )

                if not content_str and not tool_calls and not reasoning_str and "malformed_function_call" in finish_reason:
                    raise RuntimeError(
                        "Error in generating model output: malformed_function_call with empty content"
                    )

                if not content_str and tool_calls:
                    rendered_calls = []
                    for tc in tool_calls:
                        fn_obj = getattr(tc, "function", None)
                        if fn_obj is None and isinstance(tc, dict):
                            fn_obj = tc.get("function")
                        fn_name = getattr(fn_obj, "name", None) if fn_obj is not None else None
                        if fn_name is None and isinstance(fn_obj, dict):
                            fn_name = fn_obj.get("name")
                        fn_args = getattr(fn_obj, "arguments", None) if fn_obj is not None else None
                        if fn_args is None and isinstance(fn_obj, dict):
                            fn_args = fn_obj.get("arguments")
                        if not fn_name:
                            continue
                        if isinstance(fn_args, str):
                            try:
                                parsed_args = json.loads(fn_args) if fn_args.strip() else {}
                            except Exception:
                                parsed_args = {"query": fn_args}
                        else:
                            parsed_args = fn_args or {}
                        if isinstance(parsed_args, dict):
                            rendered_calls.append(
                                f"print({fn_name}(**{json.dumps(parsed_args, ensure_ascii=False)}))"
                            )
                    if rendered_calls:
                        content_str = f"{cls.open_tag}\n" + "\n".join(rendered_calls) + f"\n{cls.close_tag}"

                if not content_str and reasoning_str:
                    code_matches = re.findall(
                        r"(<code>.*?</code>|```(?:py|python)?\s*\n.*?```)",
                        reasoning_str,
                        flags=re.DOTALL | re.IGNORECASE,
                    )
                    if code_matches:
                        content_str = code_matches[-1].strip()
                    elif re.search(r"\bfinal_answer\s*\(", reasoning_str):
                        content_str = reasoning_str
                    else:
                        fa_matches = re.findall(
                            r"(?im)^\s*(?:final\s*answer|answer)\s*:\s*(.+)$",
                            reasoning_str,
                        )
                        if fa_matches and fa_matches[-1].strip():
                            ans_val = (
                                json.dumps(fa_matches[-1].strip(), ensure_ascii=False)
                                .replace("<", "\\u003c")
                                .replace(">", "\\u003e")
                                .replace("```", "\\x60\\x60\\x60")
                            )
                            content_str = (
                                f"{cls.open_tag}\n"
                                f"final_answer({ans_val})\n"
                                f"{cls.close_tag}"
                            )
                        else:
                            content_str = (
                                f"{cls.open_tag}\n"
                                'print("No Python code block produced. Write valid Python code inside '
                                'the code block to call a tool or final_answer(...).")\n'
                                f"{cls.close_tag}"
                            )

                if not content_str:
                    print(
                        f"[EMPTY] finish_reason={finish_reason!r} raw={repr(raw_obj)[:800]}",
                        flush=True,
                    )
                    raise RuntimeError(
                        "Error in generating model output: empty model response (content=None)"
                    )

                cleaned = cls._sanitize_code_tags(content_str)
                if cls.open_tag not in cleaned and cls.close_tag not in cleaned:
                    fa_direct = re.findall(
                        r"(?im)^\s*(?:final\s*answer|answer)\s*:\s*(.+)$",
                        cleaned,
                    )
                    if fa_direct and fa_direct[-1].strip():
                        ans_val = (
                            json.dumps(fa_direct[-1].strip(), ensure_ascii=False)
                            .replace("<", "\\u003c")
                            .replace(">", "\\u003e")
                            .replace("```", "\\x60\\x60\\x60")
                        )
                        cleaned = (
                            f"{cls.open_tag}\n"
                            f"final_answer({ans_val})\n"
                            f"{cls.close_tag}"
                        )
                    else:
                        cleaned = (
                            f"{cls.open_tag}\n"
                            'print("Invalid non-code output. Write valid Python code inside '
                            'the code block to call a tool or final_answer(...).")\n'
                            f"{cls.close_tag}"
                        )

                if not cleaned.strip():
                    raise RuntimeError(
                        "Error in generating model output: empty model response after sanitization"
                    )

                try:
                    msg.content = cleaned
                    msg.tool_calls = None
                except Exception:
                    pass
                if getattr(msg, "content", None) != cleaned or getattr(msg, "tool_calls", None) is not None:
                    try:
                        from smolagents.models import ChatMessage
                    except ImportError:
                        from smolagents import ChatMessage

                    cm_kwargs = {
                        "role": getattr(msg, "role", "assistant"),
                        "content": cleaned,
                        "tool_calls": None,
                        "raw": getattr(msg, "raw", None),
                        "token_usage": getattr(msg, "token_usage", None),
                    }
                    cm_sig = inspect.signature(ChatMessage.__init__)
                    msg = ChatMessage(
                        **{k: v for k, v in cm_kwargs.items() if k != "self" and k in cm_sig.parameters}
                    )
                return msg

            def _prepare_call_kwargs(self, kwargs: dict) -> dict:
                import time

                key = kwargs.pop("api_key", None) or getattr(self, "_explicit_api_key", None)
                api_base = kwargs.pop("api_base", None) or getattr(self, "_explicit_api_base", None)
                model_name = str(getattr(self, "model_id", "") or "")
                if api_base:
                    self.api_base = api_base
                    kwargs["api_base"] = api_base
                    if isinstance(getattr(self, "kwargs", None), dict):
                        self.kwargs["api_base"] = api_base
                if key:
                    self.api_key = key
                    kwargs["api_key"] = key
                    if isinstance(getattr(self, "kwargs", None), dict):
                        self.kwargs["api_key"] = key

                default_cap = 22.0
                raw_timeout = kwargs.get("timeout") or getattr(self, "timeout", None) or default_cap
                timeout = min(float(raw_timeout), default_cap)
                task_deadline = getattr(self, "deadline", None)
                if task_deadline is not None:
                    remaining = task_deadline - time.monotonic()
                    if remaining <= 2.5:
                        raise RuntimeError("Task time budget exhausted")
                    timeout = max(1.5, min(timeout, remaining - 1.5))

                kwargs["timeout"] = timeout

                if model_name.startswith("gemini/"):
                    if "gemma" not in model_name.lower():
                        kwargs.setdefault("reasoning_effort", "low")
                    else:
                        kwargs.pop("reasoning_effort", None)
                    if "gemini-3" in model_name.lower():
                        kwargs.pop("temperature", None)
                        if isinstance(getattr(self, "kwargs", None), dict):
                            self.kwargs.pop("temperature", None)
                    kwargs["max_tokens"] = 4096
                    if isinstance(getattr(self, "kwargs", None), dict):
                        self.kwargs["max_tokens"] = 4096
                if model_name.startswith("openrouter/"):
                    kwargs["max_tokens"] = 4096
                    if isinstance(getattr(self, "kwargs", None), dict):
                        self.kwargs["max_tokens"] = 4096
                    kwargs.pop("reasoning_effort", None)
                    if isinstance(getattr(self, "kwargs", None), dict):
                        self.kwargs.pop("reasoning_effort", None)
                if model_name.startswith("groq/"):
                    is_qwen3 = "qwen3" in model_name.lower()
                    groq_tokens = 4096 if is_qwen3 else 2048
                    kwargs["max_tokens"] = groq_tokens
                    if isinstance(getattr(self, "kwargs", None), dict):
                        self.kwargs["max_tokens"] = groq_tokens
                    if is_qwen3:
                        kwargs["reasoning_effort"] = "none"
                        kwargs["reasoning_format"] = "hidden"
                if model_name.startswith("nvidia_nim/"):
                    kwargs["max_tokens"] = 4096
                    if isinstance(getattr(self, "kwargs", None), dict):
                        self.kwargs["max_tokens"] = 4096

                kwargs["num_retries"] = 0
                kwargs["max_retries"] = 0
                kwargs.pop("tools", None)
                kwargs.pop("tool_choice", None)
                return kwargs

        self._model_cls = SafeLiteLLMModel

        def _build_model(model_name: str):
            api_key = self._get_api_key(model_name)
            common = {"num_retries": 0, "max_retries": 0, "timeout": 16.0}
            if model_name.startswith("gemini/"):
                kwargs = {
                    "model_id": model_name,
                    "api_key": api_key,
                    "max_tokens": 2048,
                    **common,
                }
                if "gemma" not in model_name.lower():
                    kwargs["reasoning_effort"] = "low"
                if "gemini-3" not in model_name.lower() and "latest" not in model_name.lower():
                    kwargs["temperature"] = 0.1
            elif model_name.startswith("huggingface/"):
                raw_hf = model_name[len("huggingface/"):]
                kwargs = {
                    "model_id": f"openai/{raw_hf}",
                    "api_base": "https://router.huggingface.co/v1",
                    "api_key": api_key,
                    "max_tokens": 2048,
                    **common,
                }
            elif model_name.startswith("groq/") and "qwen3" in model_name.lower():
                kwargs = {
                    "model_id": model_name,
                    "api_key": api_key,
                    "max_tokens": 2048,
                    "reasoning_effort": "none",
                    "reasoning_format": "hidden",
                    **common,
                }
            elif model_name.startswith("nvidia_nim/"):
                kwargs = {
                    "model_id": model_name,
                    "api_key": api_key,
                    "max_tokens": 3072,
                    **common,
                }
            else:
                kwargs = {
                    "model_id": model_name,
                    "api_key": api_key,
                    "max_tokens": 2048,
                    **common,
                }
            return self._model_cls(**kwargs)

        DEAD_MODEL_PATTERNS = (
            "model_not_found",
            "does not exist",
            "decommissioned",
            "no longer supported",
            "is not found for api version",
            "unknown model",
        )

        def _classify_preflight_error(err: Exception) -> str:
            msg = str(err).lower()
            status = getattr(err, "status_code", None)
            if status is None:
                resp = getattr(err, "response", None)
                status = getattr(resp, "status_code", None)

            if status == 404 or any(p in msg for p in DEAD_MODEL_PATTERNS):
                return "DEAD_MODEL"

            if status in (401, 403) or "invalid_api_key" in msg or "permission_denied" in msg:
                return "DEAD_KEY"

            if status == 400 or "unsupported" in msg or "invalid_request_error" in msg:
                return "BAD_REQUEST_PARAM"

            return "TRANSIENT_BUSY"

        def _remove_specific_key(provider: str, bad_key: str) -> None:
            with self._state_lock:
                pool = self.provider_key_pools.get(provider) or []
                if bad_key and bad_key in pool:
                    pool = [k for k in pool if k != bad_key]
                    self.provider_key_pools[provider] = pool
                self._provider_key_idx[provider] = 0
                _sync_provider_env(provider, pool[0] if pool else "")

        def _probe_candidate(model_name: str) -> tuple[str, str, str]:
            import time

            provider = model_name.split("/", 1)[0].lower() if "/" in model_name else "gemini"
            t0 = time.monotonic()
            max_key_attempts = max(1, len(self.provider_key_pools.get(provider) or []))
            tried_keys = set()
            last_short = "no api key"

            for _ in range(max_key_attempts):
                api_key = self._get_api_key(model_name)
                if not api_key or api_key in tried_keys:
                    return (model_name, "DEAD_KEY", last_short)
                tried_keys.add(api_key)

                try:
                    kw = {
                        "model": model_name,
                        "api_key": api_key,
                        "max_tokens": 128,
                        "timeout": 8,
                        "num_retries": 0,
                        "max_retries": 0,
                    }
                    if model_name.startswith("huggingface/"):
                        kw["model"] = "openai/" + model_name[len("huggingface/"):]
                        kw["api_base"] = "https://router.huggingface.co/v1"
                    elif model_name.startswith("gemini/") and "gemma" not in model_name.lower():
                        kw["reasoning_effort"] = "low"
                    elif model_name.startswith("groq/") and "qwen3" in model_name.lower():
                        kw["reasoning_effort"] = "none"
                        kw["reasoning_format"] = "hidden"

                    litellm.completion(
                        **kw,
                        messages=[{"role": "user", "content": "Reply with the single word OK."}],
                    )
                    return (model_name, "OK", f"{time.monotonic() - t0:.1f}s")
                except Exception as exc:
                    status_kind = _classify_preflight_error(exc)
                    last_short = " ".join(f"{type(exc).__name__}: {exc}".split())[:220]
                    if status_kind == "DEAD_KEY":
                        _remove_specific_key(provider, api_key)
                        continue
                    return (model_name, status_kind, last_short)

            return (model_name, "DEAD_KEY", last_short)

        from concurrent.futures import ThreadPoolExecutor, wait as futures_wait

        probe_targets = [m for m in self.working_models if not m.startswith("openrouter/")][:6]
        probe_status = {}
        probe_pool = ThreadPoolExecutor(max_workers=6)
        try:
            probe_futures = [probe_pool.submit(_probe_candidate, m) for m in probe_targets]
            done, _ = futures_wait(probe_futures, timeout=12)
            for fut in done:
                try:
                    p_name, p_state, p_info = fut.result()
                    probe_status[p_name] = p_state
                    print(f"[PREFLIGHT] {p_state:18} {p_name} :: {p_info}", flush=True)
                except Exception:
                    pass
        finally:
            probe_pool.shutdown(wait=False, cancel_futures=True)

        if not hasattr(self, "_dead_models"):
            self._dead_models = set()

        for m_name, st in probe_status.items():
            if st == "DEAD_MODEL":
                self._dead_models.add(m_name)

        # Usuwamy tylko trwałe DEAD_MODEL; reszta (OK, BAD_REQUEST_PARAM, TRANSIENT_BUSY, DEAD_KEY jeśli zostały inne klucze) zostaje
        surviving_models = []
        for m_name in self.working_models:
            if m_name in self._dead_models or probe_status.get(m_name) == "DEAD_MODEL":
                continue
            prov = m_name.split("/", 1)[0].lower() if "/" in m_name else "gemini"
            if not (self.provider_key_pools.get(prov) or []):
                continue
            surviving_models.append(m_name)

        ok_models = [m for m in surviving_models if probe_status.get(m) == "OK"]
        untested_non_or = [
            m for m in surviving_models
            if m not in probe_status and not m.startswith("openrouter/")
        ]
        openrouter_models = [
            m for m in surviving_models
            if m.startswith("openrouter/")
        ]
        degraded_models = [
            m for m in surviving_models
            if probe_status.get(m) in ("BAD_REQUEST_PARAM", "TRANSIENT_BUSY", "DEAD_KEY")
            and m not in ok_models
            and m not in untested_non_or
            and m not in openrouter_models
        ]

        reordered = ok_models + untested_non_or + openrouter_models + degraded_models
        if reordered:
            self.working_models = reordered

        if not self.working_models:
            raise RuntimeError("No models available after preflight.")

        self.model_id = self.working_models[0]
        print(f"Using primary LLM model: {self.model_id} (fallbacks: {self.working_models[1:]})")

        self._build_model = _build_model
        model = self._build_model(self.model_id)

        exact_match_rule = (
            f"Write ONLY valid, executable Python code inside {code_open_tag}...{code_close_tag} at every step. "
            "In intermediate steps, always call print(...) on tool outputs (e.g., `res = search_wikipedia(...); print(res)`) "
            "so you can read the result in the next step—never end a step with a bare assignment without print(...). "
            "NEVER pass raw webpage text, paragraphs, or full tool outputs into `final_answer(...)`. "
            "Always parse/extract the specific answer in Python (using regex, string search, or reasoning in the next step) "
            "before calling `final_answer(exact_value)`. "
            "When you have the final result, call `final_answer(exact_value)` inside the code block, where `exact_value` is ONLY "
            "the exact requested value (a single number, single name/surname, short phrase, or comma-separated list, strictly under 100 characters) "
            "with NO explanations, NO units, NO sentences, and NO 'final answer' prefix. "
            "Match the exact requested granularity: if the question asks for a single item, person, first name, or surname, "
            "pass ONLY that single word/field (e.g., only the surname if asked for 'surname', never a paragraph or full name). "
            "Output a comma-separated list ONLY when multiple items are requested, evaluating every item in the provided list in the requested order. "
            "For chess moves, pass ONLY Standard Algebraic Notation (SAN, e.g., 'Rd5', 'Nf6+', 'O-O') without move numbers or commentary. "
            "For numbers, omit commas ('1500' not '1,500'). "
            "Always define every variable before using it (never reference undefined variables like `lines`), "
            "NEVER import tools (do NOT write `from download_task_file import ...` or `import tools`—all tools are already built-in global functions), "
            "do not import `requests` or `posixpath`, and use `read_local_file(file_path=...)` instead of `open(...)` for local files."
        )

        allowed_funcs = {
            "open": open,
            "os": os,
            "posixpath": posixpath,
            "repr": repr,
        }
        accepted_params = set(sig.parameters) | set(inspect.signature(MultiStepAgent.__init__).parameters)
        agent_kwargs = {
            "tools": [
                web_search,
                search_wikipedia,
                fetch_url_text,
                download_task_file,
                read_local_file,
                inspect_image,
                analyze_chessboard,
                inspect_youtube,
                transcribe_audio,
            ],
            "additional_authorized_imports": [
                "os",
                "posixpath",
                "pathlib",
                "glob",
                "json",
                "csv",
                "pandas",
                "numpy",
                "urllib.request",
                "urllib.parse",
                "urllib.error",
                "html",
                "decimal",
                "fractions",
                "string",
                "re",
                "time",
                "math",
                "cmath",
                "statistics",
                "datetime",
                "collections",
                "itertools",
                "operator",
                "openpyxl",
            ],
            "additional_functions": allowed_funcs,
            "instructions": exact_match_rule,
            "code_block_tags": (code_open_tag, code_close_tag),
            "executor_kwargs": {"additional_functions": allowed_funcs},
            "max_steps": 6,
            "verbosity_level": 0,
        }

        def _create_code_agent(model_instance):
            def _step_guard(step_log, *args, **kwargs):
                llm_err = getattr(model_instance, "_last_llm_error", None)
                if llm_err is not None:
                    raise llm_err
                obs = getattr(step_log, "observations", None)
                if isinstance(obs, str) and len(obs) > 9000:
                    step_log.observations = obs[:4400] + "\n...[trimmed]...\n" + obs[-4400:]

            local_kwargs = dict(agent_kwargs)
            local_kwargs["model"] = model_instance
            local_kwargs["step_callbacks"] = [_step_guard]
            filtered_local = {k: v for k, v in local_kwargs.items() if k in accepted_params}
            return CodeAgent(**filtered_local)

        self._create_code_agent = _create_code_agent
        self.agent = _create_code_agent(model)

        if not hasattr(self, "_build_model") or not hasattr(self, "agent"):
            raise RuntimeError("BasicAgent.__init__ failed to bind _build_model or self.agent.")
        print("CodeAgent initialized with LiteLLMModel.")

    def _clean_exact_match_answer(self, text: str) -> str:
        import ast
        import re

        if text is None:
            return ""

        cleaned = str(text).strip()
        if not cleaned or cleaned.startswith("AGENT ERROR:"):
            return cleaned

        code_match = re.search(r"<code[^>]*>(.*?)</code>", cleaned, flags=re.DOTALL | re.IGNORECASE)
        if code_match:
            cleaned = code_match.group(1).strip()
        else:
            cleaned = re.sub(r"</?code[^>]*>", "", cleaned, flags=re.IGNORECASE).strip()

        cleaned = re.sub(r"^final_answer\s*:\s*", "", cleaned, flags=re.IGNORECASE).strip()

        cleaned = re.sub(
            r'\{\s*["\']tool["\']\s*:\s*["\'][^"\']+["\']\s*,\s*["\']arguments["\']\s*:\s*\{.*?\}\s*\}',
            "",
            cleaned,
            flags=re.DOTALL,
        ).strip()

        cleaned = re.sub(r"(?im)^\s*(?:#\s*)?(?:thought|reasoning|plan)\s*:.*$", "", cleaned).strip()

        tech_error_pattern = re.compile(
            r"(?:invalid non-code output|no python code block produced|"
            r"reached max steps|max steps reached|error in generating|error in execution|"
            r"task time budget exhausted|traceback \(most recent call last\)|"
            r"transcript/video analysis status:\s*unavailable)",
            re.IGNORECASE,
        )
        if '"tool_calls"' in cleaned or re.search(r'^\s*\{\s*["\'](?:id|type|function|name)["\']\s*:', cleaned):
            return ""
        if tech_error_pattern.search(cleaned):
            return ""

        fa_matches = re.findall(
            r"final_answer\s*\(\s*(?:answer\s*=\s*)?([^()]+?)\s*\)",
            cleaned,
            flags=re.DOTALL,
        )
        if fa_matches:
            inner_fa = fa_matches[-1].strip()
            try:
                lit_val = ast.literal_eval(inner_fa)
                if isinstance(lit_val, (list, tuple)):
                    cleaned = ", ".join(str(item).strip() for item in lit_val if str(item).strip())
                elif isinstance(lit_val, (str, int, float, bool)):
                    cleaned = str(lit_val).strip()
                else:
                    return ""
            except Exception:
                return ""

        raw_tool_call_pattern = re.compile(
            r"(?:^|\b)(?:web_search|search_wikipedia|fetch_url_text|"
            r"download_task_file|read_local_file|inspect_image|analyze_chessboard|inspect_youtube|"
            r"transcribe_audio|ask_web|final_answer)\s*\(|"
            r"^\s*print\s*\(|"
            r"^\s*[A-Za-z_][A-Za-z0-9_]*\s*=\s*[A-Za-z_][A-Za-z0-9_.]*\s*\(",
            re.IGNORECASE | re.MULTILINE,
        )
        raw_py_stmt_pattern = re.compile(
            r"^\s*(?:import\s+[A-Za-z_][A-Za-z0-9_.]*|"
            r"from\s+[A-Za-z_][A-Za-z0-9_.]*\s+import\b|"
            r"def\s+[A-Za-z_][A-Za-z0-9_]*\s*\(|"
            r"class\s+[A-Za-z_][A-Za-z0-9_]*\s*[:(]|"
            r"(?:for|while|if|elif|else|try|with)\b.*:\s*$|"
            r"return\b|raise\b)",
            re.MULTILINE,
        )
        if raw_tool_call_pattern.search(cleaned) or raw_py_stmt_pattern.search(cleaned):
            return ""

        arrow_match = re.search(
            r"\b(?:answer|result|output|final\s+answer)\s*->\s*(.+)$",
            cleaned,
            flags=re.IGNORECASE | re.DOTALL,
        )
        if arrow_match:
            tail_part = arrow_match.group(1).strip()
            quoted_match = re.findall(r'"([^"]+)"|\'([^\']+)\'', tail_part)
            if quoted_match:
                last_q = quoted_match[-1]
                cleaned = (last_q[0] or last_q[1]).strip()
            else:
                cleaned = tail_part.strip(" .\"'")

        cleaned = re.sub(
            r"^(?:so\s+the\s+answer\s+is|the\s+answer\s+is|therefore|thus|hence|in\s+conclusion|"
            r"based\s+on\s+the\s+(?:text|article|table|video|search\s+results)|according\s+to\s+the\s+(?:text|article|table|video))\s*[,:\-–—]?\s*",
            "",
            cleaned,
            flags=re.IGNORECASE,
        ).strip()

        junk_pattern = re.compile(
            r"^(?:the wikipedia article|the youtube video|the search results show|this scene is from|"
            r"the page is quite long|the task doesn't have|the download failed|let me try|let me search|"
            r"let me check|now i need to find|i found the|the operation is not commutative|"
            r"the scene occurs|i need to|i should|i will|i can|"
            r"no attachment|no web results|no wikipedia|file not found|image file not found|"
            r"audio file not found|error fetching|error downloading|error reading|"
            r"error inspecting|error transcribing)\b",
            re.IGNORECASE,
        )

        lines = [ln.strip() for ln in cleaned.splitlines() if ln.strip()]
        answer_line = next(
            (
                ln for ln in reversed(lines)
                if not junk_pattern.match(ln)
                and not raw_tool_call_pattern.search(ln)
                and not raw_py_stmt_pattern.search(ln)
            ),
            "",
        )
        if not answer_line:
            return ""

        cleaned = answer_line.strip("`").strip()
        if (
            junk_pattern.match(cleaned)
            or raw_tool_call_pattern.search(cleaned)
            or raw_py_stmt_pattern.search(cleaned)
            or tech_error_pattern.search(cleaned)
        ):
            return ""

        if (
            (cleaned.startswith("[") and cleaned.endswith("]"))
            or (cleaned.startswith("(") and cleaned.endswith(")"))
        ):
            try:
                parsed_seq = ast.literal_eval(cleaned)
                if isinstance(parsed_seq, (list, tuple)):
                    cleaned = ", ".join(
                        str(item).strip() for item in parsed_seq if str(item).strip()
                    )
            except Exception:
                pass

        if len(cleaned) >= 2 and cleaned[0] == cleaned[-1] and cleaned[0] in ('"', "'"):
            cleaned = cleaned[1:-1].strip()

        if (
            cleaned.endswith(".")
            and not cleaned.endswith("...")
            and not re.search(r"(?:^|\b[A-Za-z]\.)[A-Za-z]\.$", cleaned)
            and not re.search(r"\b(?:Mr|Mrs|Ms|Dr|Prof|Sr|Jr|St|Inc|Ltd|Co|vs|etc|e\.g|i\.e)\.$", cleaned)
        ):
            cleaned = cleaned[:-1].strip()

        return cleaned

    def __call__(self, question: str, task_id: str = "", file_name: str = "") -> str:
        import time
        import threading

        if not hasattr(self, "_local_state"):
            self._local_state = threading.local()
        if not hasattr(self, "_dead_models"):
            self._dead_models = set()
        if not hasattr(self, "_model_cooldowns"):
            self._model_cooldowns = {}

        if hasattr(self, "_reset_key_indices"):
            self._reset_key_indices()

        deadline = time.monotonic() + 185.0
        self._local_state.deadline = deadline
        self._task_deadline = deadline

        try:
            prompt = question.strip()
            self._prefer_2022_wiki = "2022" in prompt.lower()
            clean_file_name = (file_name or "").strip()
            tools_map = getattr(getattr(self, "agent", None), "tools", {}) or {}

            if task_id:
                prefetched_path = ""
                if hasattr(self, "_download_task_file"):
                    for _attempt in range(3):
                        try:
                            res_path = self._download_task_file(
                                task_id=task_id,
                                preferred_filename=clean_file_name,
                            )
                            if (
                                isinstance(res_path, str)
                                and not res_path.startswith(("Error ", "No attachment"))
                                and os.path.isfile(res_path)
                            ):
                                prefetched_path = res_path
                                break
                        except Exception as dl_exc:
                            print(f"[DOWNLOAD WARN] task_id={task_id} attempt={_attempt + 1}: {dl_exc}", flush=True)
                        if not clean_file_name and _attempt >= 1:
                            break
                        time.sleep(1.0)

                if prefetched_path:
                    ext = os.path.splitext(prefetched_path)[1].lower()
                    if ext in {".mp3", ".wav", ".m4a", ".ogg", ".flac"}:
                        tool_hint = f"Call transcribe_audio(audio_path='{prefetched_path}', question=...) if more detail is needed."
                        transcribe_fn = getattr(self, "_transcribe_audio", None) or tools_map.get("transcribe_audio")
                        if transcribe_fn is not None:
                            try:
                                tr_preview = transcribe_fn(
                                    audio_path=prefetched_path,
                                    question=question.strip(),
                                )
                                if (
                                    isinstance(tr_preview, str)
                                    and tr_preview.strip()
                                    and not tr_preview.startswith(("Error ", "Audio file not found"))
                                ):
                                    prompt += (
                                        f"\n\nTask ID: {task_id}. Audio transcription:\n"
                                        f"{tr_preview.strip()[:5000]}"
                                    )
                                    prompt += (
                                        "\n\nIMPORTANT for audio tasks: Base your answer ONLY on the transcription above. "
                                        "If it is empty or missing, call transcribe_audio again. "
                                        "Never guess names, numbers, or dates—quote them directly from the transcript."
                                    )
                                    tool_hint = ""
                            except Exception as tr_exc:
                                print(f"[PRE-TRANSCRIBE WARN] task_id={task_id}: {tr_exc}", flush=True)
                        if tool_hint:
                            prompt += (
                                f"\n\nTask ID: {task_id}. The task attachment is downloaded at '{prefetched_path}'. "
                                f"{tool_hint}"
                            )
                    elif ext in {".png", ".jpg", ".jpeg", ".webp", ".gif"}:
                        prompt += (
                            f"\n\nTask ID: {task_id}. The task attachment is downloaded at '{prefetched_path}'. "
                            f"Call inspect_image(image_path='{prefetched_path}', question=...) immediately."
                        )
                        prompt += (
                            "\n\nIMPORTANT for image tasks: Extract ALL visible numbers, labels, and text first. "
                            "For tables/charts, read row/column headers and data cells before answering. "
                            "For chess positions, verify board orientation (a1-h8 coordinates, White vs Black at bottom), "
                            "list exact piece squares and side to move, and answer ONLY with the move in Standard Algebraic Notation (SAN). "
                            "Do not describe the image generally—answer the specific question asked."
                        )
                    else:
                        tool_hint = f"Call read_local_file(file_path='{prefetched_path}') immediately."
                        if ext in {".xlsx", ".xlsm", ".xls", ".csv"}:
                            prompt += (
                                f"\n\nTask ID: {task_id}. The tabular attachment is saved at '{prefetched_path}'. "
                                f"Use pandas (`pd.read_excel('{prefetched_path}', sheet_name=None)` or `pd.read_csv('{prefetched_path}')`) "
                                "to inspect exact sheet names, columns, and compute exact totals/filters."
                            )
                        read_fn = getattr(self, "_read_local_file", None) or tools_map.get("read_local_file")
                        if read_fn is not None:
                            try:
                                file_preview = read_fn(file_path=prefetched_path)
                                if (
                                    isinstance(file_preview, str)
                                    and file_preview.strip()
                                    and not file_preview.startswith(("Error ", "File not found"))
                                ):
                                    clean_preview = file_preview.strip()
                                    if len(clean_preview) > 6000:
                                        clean_preview = (
                                            clean_preview[:3000]
                                            + "\n...[truncated]...\n"
                                            + clean_preview[-3000:]
                                        )
                                    prompt += (
                                        f"\n\nTask ID: {task_id}. Attachment '{prefetched_path}' content:\n"
                                        f"{clean_preview}"
                                    )
                                    tool_hint = ""
                            except Exception as rd_exc:
                                print(f"[PRE-READ WARN] task_id={task_id}: {rd_exc}", flush=True)
                        if tool_hint:
                            prompt += (
                                f"\n\nTask ID: {task_id}. The task attachment is downloaded at '{prefetched_path}'. "
                                f"{tool_hint}"
                            )
                        else:
                            prompt += (
                                f"\nThe file is ALREADY downloaded locally at '{prefetched_path}'. "
                                "Do NOT call download_task_file again. Write Python code directly to compute the answer and call final_answer(...)."
                            )
                else:
                    prompt += f"\n\nTask ID: {task_id}"
                    if clean_file_name:
                        prompt += f" (expected attachment filename: '{clean_file_name}')"
                    prompt += (
                        ". NEVER list or inspect the current working directory ('.' or repo files like app.py/README.md). "
                        "If this task refers to an attached file, spreadsheet, image, audio, or document, "
                        f"call download_task_file(task_id='{task_id}', preferred_filename='{clean_file_name}') first."
                    )

            prompt_lower = prompt.lower()
            if "chess" in prompt_lower or "algebraic notation" in prompt_lower:
                side_hint = "white" if "white's turn" in prompt_lower or "white to move" in prompt_lower else "black"
                img_hint = f"'{prefetched_path}'" if "prefetched_path" in locals() and prefetched_path else "the downloaded image path"
                prompt += (
                    "\n\nIMPORTANT for chess tasks:\n"
                    f"1. Call analyze_chessboard(image_path={img_hint}, side_to_move='{side_hint}') first "
                    "(and if needed, inspect_image with the exact piece list per square from rank 8 to rank 1, file a to h).\n"
                    f"2. In Python, verify the board state and candidate moves for {side_hint.upper()} "
                    "(checks, captures, forks, pins, discovered attacks, and forced mate lines), and pick the winning move.\n"
                    "3. Output ONLY the single move in Standard Algebraic Notation (SAN, e.g. Rd5, Nf6+, Qxd4) "
                    "with NO move numbers ('1...' or '1.') and NO commentary."
                )
            if (
                "|*|" in prompt
                or "commutative" in prompt_lower
                or "commutativity" in prompt_lower
                or "cayley table" in prompt_lower
                or "binary operation" in prompt_lower
                or ("operation" in prompt_lower and "table" in prompt_lower)
            ):
                prompt += (
                    "\n\nIMPORTANT: For binary operation / Cayley table tasks, write Python that builds a dict of dicts, "
                    "then loops over all pairs (x,y) and checks table[x][y] != table[y][x]. "
                    "Collect all elements from pairs where this is true into a set, sort alphabetically, "
                    "and output as comma-separated string. Do NOT use undefined variables."
                )
            if "youtube.com" in prompt or "youtu.be" in prompt or " video" in prompt_lower:
                prompt += (
                    "\n\nIMPORTANT for video tasks: Call inspect_youtube first. "
                    "If it returns 'Transcript/Video Analysis Status: unavailable', do NOT guess. "
                    "Immediately use web_search with the video title/channel or search_wikipedia for the quoted dialogue. "
                    "Answer only from retrieved text, never invent."
                )
            if "between" in prompt_lower and ("album" in prompt_lower or "published" in prompt_lower):
                prompt += (
                    "\n\nIMPORTANT: Extract the Discography/Studio albums table from the Wikipedia text. "
                    "Count entries where the year is >= start_year and <= end_year. "
                    "If the table is not visible in the provided text, call search_wikipedia again with "
                    "the exact article title + ' discography' to get the full section."
                )
            if any(
                k in prompt_lower
                for k in ("first name", "last name", "surname", "ioc", "country code", "recipient")
            ):
                prompt += (
                    "\n\nIMPORTANT for multi-condition & single-field questions: "
                    "Do NOT return a list of candidates before verifying all constraints. "
                    "Check each candidate's attributes via search_wikipedia/web_search, filter down to the single matching entity, "
                    "and extract ONLY the exact requested sub-field (e.g., if 'first name' is asked, output only the given/first name, "
                    "never the full name or a list of names; if 'IOC country code' is asked, verify the exact table numbers first and output only the 3-letter code)."
                )

            blocked_models = set(self._dead_models)
            blocked_providers = set()

            now = time.monotonic()
            all_candidates = list(getattr(self, "working_models", []) or [self.model_id])
            if self.model_id and self.model_id not in all_candidates:
                all_candidates.append(self.model_id)
            models_to_try = [
                m for m in all_candidates
                if m not in self._dead_models and self._model_cooldowns.get(m, 0.0) <= now
            ]
            if not models_to_try:
                models_to_try = [m for m in all_candidates if m not in self._dead_models] or all_candidates

            backoff_rounds = 0

            while time.monotonic() < deadline:
                rate_limited_models = set()
                rate_limited_providers = set()

                for model_name in models_to_try:
                    remaining = deadline - time.monotonic()
                    if remaining <= 6.0:
                        break
                    if not hasattr(self, "_build_model") or not hasattr(self, "_create_code_agent"):
                        return "AGENT ERROR: Agent not initialized."
                    provider = model_name.split("/", 1)[0].lower() if "/" in model_name else "gemini"
                    transient_retries = 0
                    while time.monotonic() < deadline:
                        if (
                            model_name in blocked_models
                            or model_name in rate_limited_models
                            or provider in blocked_providers
                        ):
                            break
                        if not self._get_api_key(model_name):
                            blocked_providers.add(provider)
                            break
                        built_model = None
                        step_t0 = time.monotonic()
                        try:
                            rem_now = deadline - step_t0
                            if rem_now <= 6.0:
                                break
                            call_timeout = max(8.0, min(28.0, rem_now - 2.0))
                            print(
                                f"[TRACE] task_id={task_id} model={model_name} provider={provider} "
                                f"rem={rem_now:.1f}s timeout={call_timeout:.1f}s start",
                                flush=True,
                            )
                            built_model = self._build_model(model_name)
                            built_model.model_id = getattr(built_model, "model_id", model_name)
                            built_model.timeout = call_timeout
                            built_model.deadline = deadline
                            run_agent = self._create_code_agent(built_model)
                            run_agent.max_steps = 7 if rem_now > 60.0 else (5 if rem_now > 25.0 else 4)
                            result = run_agent.run(prompt)
                            raw_result = "" if result is None else str(result).strip()
                            if raw_result.lower().startswith("error in generating"):
                                raise RuntimeError(raw_result)
                            cleaned = self._clean_exact_match_answer(raw_result)
                            if cleaned and len(cleaned) <= 2000 and not cleaned.startswith("AGENT ERROR:"):
                                return cleaned

                            collected_obs = []
                            mem_steps = getattr(getattr(run_agent, "memory", None), "steps", None) or []
                            for st in mem_steps:
                                for attr_name in ("observations", "action_output", "model_output"):
                                    val = getattr(st, attr_name, None)
                                    if val is None:
                                        continue
                                    txt = "\n".join(str(x) for x in val) if isinstance(val, list) else str(val)
                                    txt = txt.strip()
                                    if txt and "Invalid non-code output" not in txt and len(txt) > 10:
                                        collected_obs.append(txt[:4500])

                            if collected_obs or raw_result:
                                context_blob = "\n---\n".join(collected_obs[-4:])
                                if raw_result and "max steps" not in raw_result.lower():
                                    context_blob += f"\n---\nAgent draft: {raw_result[:1500]}"
                                if context_blob.strip():
                                    extract_model = next(
                                        (
                                            m for m in [model_name] + models_to_try
                                            if m not in blocked_models
                                            and m not in rate_limited_models
                                            and (m.split("/", 1)[0].lower() if "/" in m else "gemini") not in blocked_providers
                                        ),
                                        model_name,
                                    )
                                    direct_ans = self._direct_extract_answer(
                                        model_name=extract_model,
                                        question=question.strip(),
                                        evidence=context_blob[:12000],
                                        deadline=deadline,
                                    )
                                    if direct_ans:
                                        print(f"[DIRECT EXTRACT OK] task_id={task_id} ans={direct_ans!r}", flush=True)
                                        return direct_ans
                        except Exception as exc:
                            llm_err = getattr(built_model, "_last_llm_error", None)
                            if llm_err is not None and llm_err is not exc:
                                exc = llm_err
                            err_text = str(exc)
                            err_lower = err_text.lower()
                            print(f"[AGENT ERROR] task_id={task_id} model={model_name}: {err_text}", flush=True)
                            if "task time budget exhausted" in err_lower:
                                break
                            http_status = getattr(exc, "status_code", None)

                            if http_status in (401, 403) or any(
                                marker in err_lower
                                for marker in (
                                    "authentication",
                                    "invalid api key",
                                    "api key not valid",
                                    "permission_denied",
                                    "insufficient permissions",
                                )
                            ):
                                if hasattr(self, "_rotate_api_key") and self._rotate_api_key(
                                    provider, permanent=True
                                ):
                                    continue
                                for m in models_to_try:
                                    if m.startswith(f"{provider}/"):
                                        blocked_models.add(m)
                                blocked_providers.add(provider)
                                break

                            if http_status == 402 or "payment required" in err_lower or "insufficient_quota" in err_lower:
                                if hasattr(self, "_rotate_api_key") and self._rotate_api_key(
                                    provider, permanent=True
                                ):
                                    continue
                                blocked_models.add(model_name)
                                self._dead_models.add(model_name)
                                break

                            is_daily_exhausted = any(
                                marker in err_lower
                                for marker in (
                                    "free-models-per-day",
                                    "perday",
                                    "per_day",
                                    "tokens per day",
                                    "tpd",
                                    "daily limit",
                                )
                            )
                            is_provider_quota = is_daily_exhausted or any(
                                marker in err_lower
                                for marker in (
                                    "quota",
                                    "resource_exhausted",
                                )
                            )
                            is_model_rate_limit = http_status == 429 or any(
                                marker in err_lower
                                for marker in (
                                    "429",
                                    "rate limit exceeded",
                                    "too many requests",
                                )
                            )

                            if is_model_rate_limit and not is_provider_quota and provider == "nvidia_nim":
                                if transient_retries < 2 and (deadline - time.monotonic()) > 15.0:
                                    transient_retries += 1
                                    time.sleep(5.0)
                                    continue

                            if is_provider_quota or is_model_rate_limit:
                                if hasattr(self, "_rotate_api_key") and self._rotate_api_key(
                                    provider, permanent=is_daily_exhausted
                                ):
                                    continue
                                if is_daily_exhausted:
                                    for m in models_to_try:
                                        if m.startswith(f"{provider}/"):
                                            blocked_models.add(m)
                                            self._dead_models.add(m)
                                    blocked_providers.add(provider)
                                    break
                                cooldown_until = time.monotonic() + 20.0
                                rate_limited_models.add(model_name)
                                self._model_cooldowns[model_name] = cooldown_until
                                if is_provider_quota:
                                    rate_limited_providers.add(provider)
                                    for m in models_to_try:
                                        if m.startswith(f"{provider}/"):
                                            rate_limited_models.add(m)
                                            self._model_cooldowns[m] = cooldown_until
                                break

                            if any(marker in err_lower for marker in ("timeout", "timed out")):
                                blocked_models.add(model_name)
                                self._model_cooldowns[model_name] = time.monotonic() + 60.0
                                break

                            is_context_overflow = any(
                                marker in err_lower
                                for marker in (
                                    "context length",
                                    "context_length",
                                    "maximum context",
                                    "too many tokens",
                                    "token limit",
                                    "reduce the length",
                                    "request too large",
                                )
                            )
                            is_hard_dead_model = http_status == 404 or any(
                                marker in err_lower
                                for marker in (
                                    "model_not_found",
                                    "does not exist",
                                    "decommissioned",
                                    "no longer supported",
                                    "is not found for api version",
                                    "unknown model",
                                )
                            )
                            is_bad_request = http_status == 400 or any(
                                marker in err_lower
                                for marker in (
                                    "badrequesterror",
                                    "bad request",
                                    "invalid_request_error",
                                    "reasoning is mandatory",
                                    "cannot be disabled",
                                    "does not support",
                                    "unsupported",
                                )
                            )
                            if is_hard_dead_model or is_bad_request or is_context_overflow:
                                blocked_models.add(model_name)
                                if is_hard_dead_model and not is_context_overflow:
                                    self._dead_models.add(model_name)
                                break

                            if http_status == 503 or any(
                                marker in err_lower
                                for marker in (
                                    "503",
                                    "service unavailable",
                                    "high demand",
                                    "overloaded",
                                )
                            ):
                                blocked_models.add(model_name)
                                self._model_cooldowns[model_name] = time.monotonic() + 60.0
                                break

                            if "connection error" in err_lower:
                                if transient_retries < 1 and (deadline - time.monotonic()) > 10.0:
                                    transient_retries += 1
                                    time.sleep(0.5)
                                    continue
                                blocked_models.add(model_name)
                                self._model_cooldowns[model_name] = time.monotonic() + 60.0
                                break

                            blocked_models.add(model_name)
                            break

                if time.monotonic() >= deadline:
                    break

                rotated_any = False
                if hasattr(self, "_rotate_api_key"):
                    for prov in rate_limited_providers:
                        if prov not in blocked_providers:
                            pool = self.provider_key_pools.get(prov) or []
                            if self._provider_key_idx.get(prov, 0) + 1 < len(pool):
                                if self._rotate_api_key(prov):
                                    rotated_any = True
                if not rotated_any:
                    rem_after_pass = deadline - time.monotonic()
                    if rate_limited_models and backoff_rounds < 2 and rem_after_pass > 18.0:
                        backoff_rounds += 1
                        for prov in rate_limited_providers:
                            if prov not in blocked_providers:
                                pool = self.provider_key_pools.get(prov) or []
                                self._provider_key_idx[prov] = 0
                                if hasattr(self, "_sync_provider_env"):
                                    self._sync_provider_env(prov, pool[0] if pool else "")
                        time.sleep(min(12.0, max(3.0, rem_after_pass - 15.0)))
                        continue
                    break
        finally:
            local_state = getattr(self, "_local_state", None)
            if local_state is not None:
                try:
                    local_state.deadline = None
                except Exception:
                    pass
            self._task_deadline = None

        return ""

    def _direct_extract_answer(self, model_name: str, question: str, evidence: str, deadline: float) -> str:
        import time
        import litellm

        rem = deadline - time.monotonic()
        if rem <= 5.0:
            return ""
        api_key = self._get_api_key(model_name)
        if not api_key:
            return ""
        kw = {"model": model_name, "api_key": api_key}
        if model_name.startswith("huggingface/"):
            kw = {
                "model": "openai/" + model_name[len("huggingface/"):],
                "api_base": "https://router.huggingface.co/v1",
                "api_key": api_key,
            }
        try:
            resp = litellm.completion(
                **kw,
                messages=[
                    {
                        "role": "system",
                        "content": (
                            "Extract ONLY the exact final answer to the user's question from the provided evidence. "
                            "Output ONLY the exact requested value (number, single word/name, SAN chess move, or comma-separated list). "
                            "NO sentences, NO explanations, NO markdown, NO units unless requested."
                        ),
                    },
                    {
                        "role": "user",
                        "content": f"Question:\n{question}\n\nEvidence:\n{evidence}",
                    },
                ],
                max_tokens=256,
                timeout=max(6.0, min(15.0, rem - 2.0)),
                num_retries=0,
                max_retries=0,
            )
            txt = (resp.choices[0].message.content or "").strip()
            cleaned = self._clean_exact_match_answer(txt)
            if cleaned and len(cleaned) <= 300 and not cleaned.startswith("AGENT ERROR:"):
                return cleaned
        except Exception as exc:
            print(f"[DIRECT EXTRACT ERR] model={model_name}: {exc}", flush=True)
        return ""

def _trim_tool_output(text: str, max_chars: int = 4000) -> str:
    if not isinstance(text, str):
        return str(text)
    cleaned = "\n".join(line.strip() for line in text.splitlines() if line.strip())
    if len(cleaned) <= max_chars:
        return cleaned
    return cleaned[:max_chars] + "\n...[truncated]..."


def run_and_submit_all(profile: gr.OAuthProfile | None):
    """
    Fetches all questions, runs the BasicAgent on them, submits all answers,
    and displays the results.
    """
    space_id = os.getenv("SPACE_ID")

    if profile:
        username = f"{profile.username}"
        print(f"User logged in: {username}")
    else:
        print("User not logged in.")
        return "Please Login to Hugging Face with the button.", None

    api_url = DEFAULT_API_URL
    questions_url = f"{api_url}/questions"
    submit_url = f"{api_url}/submit"

    # 1. Instantiate Agent
    try:
        agent = BasicAgent()
    except Exception as e:
        print(f"Error instantiating agent: {e}")
        return f"Error initializing agent: {e}", None

    agent_code = (
        f"https://huggingface.co/spaces/{space_id.strip()}/tree/main"
        if space_id and space_id.strip()
        else (
            (os.getenv("AGENT_CODE_URL") or "").strip()
            or f"https://huggingface.co/spaces/{username.strip()}/Final_Assignment_Template/tree/main"
        )
    )
    print(agent_code)

    # 2. Fetch Questions
    import json
    import time

    print(f"Fetching questions from: {questions_url}")
    questions_cache_path = "/tmp/gaia_questions.json"
    questions_data = None
    last_fetch_exc = None
    for attempt in range(3):
        try:
            response = requests.get(questions_url, timeout=(15, 90))
            if response.status_code in {429, 502, 503, 504} and attempt < 2:
                time.sleep(3 * (attempt + 1))
                continue
            response.raise_for_status()
            questions_data = response.json()
            if questions_data:
                try:
                    with open(questions_cache_path, "w", encoding="utf-8") as f_q:
                        json.dump(questions_data, f_q, ensure_ascii=False)
                except Exception:
                    pass
            break
        except requests.exceptions.RequestException as e:
            last_fetch_exc = e
            if attempt < 2:
                time.sleep(3 * (attempt + 1))
                continue
        except Exception as e:
            last_fetch_exc = e
            break

    if questions_data is None and os.path.isfile(questions_cache_path):
        try:
            with open(questions_cache_path, "r", encoding="utf-8") as f_q:
                questions_data = json.load(f_q)
            print("Loaded questions from local cache after network error.")
        except Exception:
            questions_data = None

    if questions_data is None:
        print(f"Error fetching questions: {last_fetch_exc}")
        return f"Error fetching questions: {last_fetch_exc}", None
    if not questions_data:
        print("Fetched questions list is empty.")
        return "Fetched questions list is empty or invalid format.", None
    print(f"Fetched {len(questions_data)} questions.")

    # 3. Run Agent
    from concurrent.futures import ThreadPoolExecutor, TimeoutError as FutureTimeoutError
    import json
    import time

    results_log = []
    answers_payload = []
    partial_path = "/tmp/gaia_partial_results.json"
    cached_by_task_id = {}
    cached_by_question = {}
    try:
        if os.path.isfile(partial_path):
            with open(partial_path, "r", encoding="utf-8") as f_cache:
                cached_items = json.load(f_cache)
            if isinstance(cached_items, list):
                for c_item in cached_items:
                    if not isinstance(c_item, dict):
                        continue
                    c_tid = c_item.get("Task ID")
                    c_q = c_item.get("Question")
                    c_ans = c_item.get("Submitted Answer")
                    if not isinstance(c_ans, str):
                        continue
                    raw_cached = c_ans.strip()
                    if (
                        not raw_cached
                        or len(raw_cached) > 120
                        or raw_cached.startswith("AGENT ERROR:")
                        or "</code>" in raw_cached.lower()
                        or "without access to" in raw_cached.lower()
                        or "gaia_questions.json" in raw_cached.lower()
                    ):
                        continue
                    clean_cached = agent._clean_exact_match_answer(raw_cached)
                    if not clean_cached or clean_cached.startswith("AGENT ERROR:"):
                        continue
                    if isinstance(c_tid, str) and c_tid.strip():
                        cached_by_task_id[c_tid.strip()] = clean_cached
                    if isinstance(c_q, str) and c_q.strip():
                        cached_by_question[c_q.strip()] = clean_cached
    except Exception:
        cached_by_task_id = {}
        cached_by_question = {}

    print(f"Running agent on {len(questions_data)} questions...")
    ran_fresh_query = False
    for idx, item in enumerate(questions_data):
        task_id = item.get("task_id")
        question_text = item.get("question")
        file_name = str(item.get("file_name") or "").strip()
        if not task_id or question_text is None:
            print(f"Skipping item with missing task_id or question: {item}")
            continue

        clean_tid = str(task_id).strip()
        clean_q = str(question_text).strip()
        force_refresh = os.getenv("FORCE_REFRESH_TASKS", "").strip().lower() in {"1", "true", "yes"}
        if not force_refresh and clean_tid in cached_by_task_id:
            submitted_answer = cached_by_task_id[clean_tid]
        elif not force_refresh and clean_q in cached_by_question:
            submitted_answer = cached_by_question[clean_q]
        else:
            if ran_fresh_query:
                time.sleep(2)
            ran_fresh_query = True
            executor = ThreadPoolExecutor(max_workers=1)
            future = executor.submit(agent, question_text, task_id=task_id, file_name=file_name)
            try:
                submitted_answer = future.result(timeout=210)
            except FutureTimeoutError:
                print(f"Timeout running agent on task {task_id} after 210s.")
                submitted_answer = "AGENT ERROR: Task timed out after 210s."
            except Exception as e:
                print(f"Error running agent on task {task_id}: {e}")
                submitted_answer = f"AGENT ERROR: {e}"
            finally:
                executor.shutdown(wait=False, cancel_futures=True)

        if not isinstance(submitted_answer, str) or not submitted_answer.strip():
            submitted_answer = "AGENT ERROR: Empty answer"

        answers_payload.append({"task_id": task_id, "submitted_answer": submitted_answer})
        results_log.append({"Task ID": task_id, "Question": question_text, "Submitted Answer": submitted_answer})

        valid_to_cache = [
            row for row in results_log
            if isinstance(row.get("Submitted Answer"), str)
            and row["Submitted Answer"].strip()
            and not row["Submitted Answer"].strip().startswith("AGENT ERROR:")
        ]
        try:
            with open(partial_path, "w", encoding="utf-8") as f_part:
                json.dump(valid_to_cache, f_part, ensure_ascii=False, indent=2)
        except Exception:
            pass

    # 4. Prepare Submission
    submission_data = {"username": username.strip(), "agent_code": agent_code, "answers": answers_payload}
    status_update = f"Agent finished. Submitting {len(answers_payload)} answers for user '{username}'..."
    print(status_update)

    # 5. Submit
    print(f"Submitting {len(answers_payload)} answers to: {submit_url}")
    results_df = pd.DataFrame(results_log)
    try:
        response = None
        for attempt in range(3):
            try:
                response = requests.post(submit_url, json=submission_data, timeout=(15, 90))
                if response.status_code in {429, 502, 503, 504} and attempt < 2:
                    time.sleep(3 * (attempt + 1))
                    continue
                response.raise_for_status()
                break
            except (requests.exceptions.Timeout, requests.exceptions.ConnectionError):
                if attempt < 2:
                    time.sleep(3 * (attempt + 1))
                    continue
                raise

        result_data = response.json()
        final_status = (
            f"Submission Successful!\n"
            f"User: {result_data.get('username')}\n"
            f"Overall Score: {result_data.get('score', 'N/A')}% "
            f"({result_data.get('correct_count', '?')}/{result_data.get('total_attempted', '?')} correct)\n"
            f"Message: {result_data.get('message', 'No message received.')}"
        )
        print("Submission successful.")
        return final_status, results_df
    except requests.exceptions.HTTPError as e:
        error_detail = f"Server responded with status {e.response.status_code}."
        try:
            error_json = e.response.json()
            error_detail += f" Detail: {error_json.get('detail', e.response.text)}"
        except requests.exceptions.JSONDecodeError:
            error_detail += f" Response: {e.response.text[:500]}"
        status_message = f"Submission Failed: {error_detail}"
        print(status_message)
        return status_message, results_df
    except requests.exceptions.Timeout:
        status_message = "Submission Failed: The request timed out."
        print(status_message)
        return status_message, results_df
    except requests.exceptions.RequestException as e:
        status_message = f"Submission Failed: Network error - {e}"
        print(status_message)
        return status_message, results_df
    except Exception as e:
        status_message = f"An unexpected error occurred during submission: {e}"
        print(status_message)
        return status_message, results_df


# --- Build Gradio Interface using Blocks ---
with gr.Blocks() as demo:
    gr.Markdown("# Basic Agent Evaluation Runner")
    gr.Markdown(
        """
        **Instructions:**

1.  Please clone this space, then modify the code to define your agent's logic, the tools, the necessary packages, etc ...
2.  Log in to your Hugging Face account using the button below. This uses your HF username for submission.
3.  Click 'Run Evaluation & Submit All Answers' to fetch questions, run your agent, submit answers, and see the score.

        ---
        **Disclaimers:**
        Once clicking on the "submit button, it can take quite some time ( this is the time for the agent to go through all the questions).
        This space provides a basic setup and is intentionally sub-optimal to encourage you to develop your own, more robust solution. For instance for the delay process of the submit button, a solution could be to cache the answers and submit in a seperate action or even to answer the questions in async.
        """
    )

    gr.LoginButton()

    run_button = gr.Button("Run Evaluation & Submit All Answers")

    status_output = gr.Textbox(label="Run Status / Submission Result", lines=5, interactive=False)
    results_table = gr.DataFrame(label="Questions and Agent Answers", wrap=True)

    run_button.click(
        fn=run_and_submit_all,
        outputs=[status_output, results_table]
    )

if __name__ == "__main__":
    print("\n" + "-" * 30 + " App Starting " + "-" * 30)
    space_host_startup = os.getenv("SPACE_HOST")
    space_id_startup = os.getenv("SPACE_ID")

    if space_host_startup:
        print(f"✅ SPACE_HOST found: {space_host_startup}")
        runtime_url = (
            space_host_startup
            if space_host_startup.startswith("http")
            else (
                f"https://{space_host_startup}"
                if space_host_startup.endswith(".hf.space")
                else f"https://{space_host_startup}.hf.space"
            )
        )
        print(f"   Runtime URL should be: {runtime_url}")
    else:
        print("ℹ️  SPACE_HOST environment variable not found (running locally?).")

    if space_id_startup:
        print(f"✅ SPACE_ID found: {space_id_startup}")
        print(f"   Repo URL: https://huggingface.co/spaces/{space_id_startup}")
        print(f"   Repo Tree URL: https://huggingface.co/spaces/{space_id_startup}/tree/main")
    else:
        print("ℹ️  SPACE_ID environment variable not found (running locally?). Repo URL cannot be determined.")

    print("-" * (60 + len(" App Starting ")) + "\n")

    print("Launching Gradio Interface for Basic Agent Evaluation...")
    demo.queue()
    demo.launch(debug=True, share=False, ssr_mode=False)