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 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
from __future__ import annotations

import ast
import base64
import json
import math
import operator
import os
import re
import shutil
import subprocess
import sys
import tempfile
from io import BytesIO
from pathlib import Path
from typing import Annotated, Literal
from urllib.parse import parse_qs, urlparse

import chess
import chess.engine
import cv2
import pandas as pd
import requests
import yt_dlp
from bs4 import BeautifulSoup
from ddgs import DDGS
from langchain_core.messages import (
    AIMessage,
    AnyMessage,
    HumanMessage,
    SystemMessage,
    ToolMessage,
)
from langchain_core.tools import tool
from langchain_openai import ChatOpenAI
from langgraph.graph import END, START, StateGraph
from langgraph.graph.message import add_messages
from langgraph.prebuilt import ToolNode
from openai import OpenAI, RateLimitError
from PIL import Image as PILImage
from PIL import ImageOps
from pypdf import PdfReader
from typing_extensions import NotRequired, TypedDict
from youtube_transcript_api import YouTubeTranscriptApi


# -----------------------------------------------------------------------------
# Model configuration
# -----------------------------------------------------------------------------

OPENAI_API_KEY = os.getenv("OPENAI_API_KEY", "").strip()

if not OPENAI_API_KEY:
    raise RuntimeError(
        "OPENAI_API_KEY is missing. Add it under the Hugging Face "
        "Space Settings > Variables and secrets > Secrets."
    )

TEXT_MODEL = os.getenv("TEXT_MODEL", "gpt-4.1").strip()
VISION_MODEL = os.getenv("VISION_MODEL", "gpt-4.1").strip()
AUDIO_MODEL = os.getenv("AUDIO_MODEL", "gpt-4o-mini-transcribe").strip()
OPENAI_TIMEOUT = float(os.getenv("OPENAI_TIMEOUT", "240"))
OPENAI_MAX_RETRIES = int(os.getenv("OPENAI_MAX_RETRIES", "3"))

llm = ChatOpenAI(
    model=TEXT_MODEL,
    api_key=OPENAI_API_KEY,
    temperature=0,
    max_tokens=1200,
    timeout=OPENAI_TIMEOUT,
    max_retries=OPENAI_MAX_RETRIES,
)

vision_llm = ChatOpenAI(
    model=VISION_MODEL,
    api_key=OPENAI_API_KEY,
    temperature=0,
    max_tokens=1400,
    timeout=OPENAI_TIMEOUT,
    max_retries=OPENAI_MAX_RETRIES,
)

vision_llm_chess = vision_llm

openai_client = OpenAI(
    api_key=OPENAI_API_KEY,
    timeout=OPENAI_TIMEOUT,
    max_retries=OPENAI_MAX_RETRIES,
)

print(
    "OpenAI models configured:",
    {
        "text": TEXT_MODEL,
        "vision": VISION_MODEL,
        "audio": AUDIO_MODEL,
    },
)


# -----------------------------------------------------------------------------
# General tools
# -----------------------------------------------------------------------------

@tool("web_search")
def web_search_tool(query: str) -> str:
    """Search the public web and return concise titles, URLs, and snippets."""

    query = query.strip()
    if not query:
        return "ERROR: Search query is empty."

    try:
        raw_results = list(
            DDGS().text(
                query,
                max_results=4,
            )
        )

        results = []
        for item in raw_results:
            if not isinstance(item, dict):
                continue

            title = str(item.get("title", "")).strip()
            url = str(
                item.get("href")
                or item.get("url")
                or ""
            ).strip()
            snippet = str(
                item.get("body")
                or item.get("snippet")
                or ""
            ).strip()

            if title or url or snippet:
                results.append(
                    {
                        "title": title,
                        "url": url,
                        "snippet": snippet,
                    }
                )

        if not results:
            return "ERROR: Web search returned no results."

        return json.dumps(
            results,
            ensure_ascii=False,
        )

    except Exception as error:
        return (
            "ERROR: Web search failed: "
            f"{type(error).__name__}: {error}"
        )


@tool("read_webpage")
def read_webpage(url: str) -> str:
    """Read visible text from a public webpage."""

    if not url.startswith(("http://", "https://")):
        return "ERROR: URL must begin with http:// or https://."

    try:
        response = requests.get(
            url,
            timeout=30,
            headers={
                "User-Agent": (
                    "Mozilla/5.0 (compatible; GAIAResearchAgent/1.0)"
                )
            },
        )
        response.raise_for_status()

        soup = BeautifulSoup(response.text, "html.parser")

        for element in soup(
            ["script", "style", "nav", "footer", "header", "noscript", "svg"]
        ):
            element.decompose()

        lines = [
            line.strip()
            for line in soup.get_text(separator="\n", strip=True).splitlines()
            if line.strip()
        ]

        # Remove only consecutive duplicate lines. Global de-duplication can
        # destroy repeated rows in tables.
        cleaned_lines: list[str] = []
        for line in lines:
            if not cleaned_lines or line != cleaned_lines[-1]:
                cleaned_lines.append(line)

        cleaned_text = "\n".join(cleaned_lines)
        normalized = cleaned_text.lower()

        blocked_phrases = (
            "checking your browser",
            "access denied",
            "enable javascript",
            "captcha",
        )

        if len(cleaned_text) < 100 or any(
            phrase in normalized for phrase in blocked_phrases
        ):
            return "ERROR: The webpage was blocked or contained no usable text."

        return cleaned_text[:9000]

    except requests.RequestException as error:
        return f"ERROR: Could not read webpage: {type(error).__name__}: {error}"


WIKIPEDIA_API_URL = "https://en.wikipedia.org/w/api.php"
WIKIPEDIA_HEADERS = {
    "User-Agent": "GAIA-LangGraph-Agent/1.0 (educational benchmark project)"
}


@tool("wikipedia_search")
def wikipedia_search(
    query: str,
    as_of_date: str = "2022-12-31",
) -> str:
    """
    Search English Wikipedia and return the best page's content from the
    latest revision on or before as_of_date.
    """

    try:
        search_response = requests.get(
            WIKIPEDIA_API_URL,
            params={
                "action": "query",
                "list": "search",
                "srsearch": query,
                "srlimit": 5,
                "format": "json",
                "formatversion": 2,
            },
            headers=WIKIPEDIA_HEADERS,
            timeout=30,
        )
        search_response.raise_for_status()
        results = search_response.json().get("query", {}).get("search", [])

        if not results:
            return "ERROR: No English Wikipedia page matched the query."

        query_words = set(re.findall(r"[a-z0-9]+", query.lower()))

        def score(item: dict) -> tuple[int, int]:
            title = str(item.get("title", ""))
            title_words = set(re.findall(r"[a-z0-9]+", title.lower()))
            exact = int(title.lower() == query.lower().strip())
            overlap = len(query_words & title_words)
            return exact, overlap

        page_title = max(results, key=score)["title"]

        revision_response = requests.get(
            WIKIPEDIA_API_URL,
            params={
                "action": "query",
                "prop": "revisions",
                "titles": page_title,
                "rvstart": f"{as_of_date}T23:59:59Z",
                "rvdir": "older",
                "rvlimit": 1,
                "rvprop": "ids|timestamp",
                "format": "json",
                "formatversion": 2,
            },
            headers=WIKIPEDIA_HEADERS,
            timeout=30,
        )
        revision_response.raise_for_status()
        pages = revision_response.json().get("query", {}).get("pages", [])
        revisions = pages[0].get("revisions", []) if pages else []

        if not revisions:
            return f"ERROR: No revision was found on or before {as_of_date}."

        revision_id = revisions[0]["revid"]
        revision_timestamp = revisions[0]["timestamp"]

        page_response = requests.get(
            WIKIPEDIA_API_URL,
            params={
                "action": "parse",
                "oldid": revision_id,
                "prop": "text",
                "format": "json",
                "formatversion": 2,
            },
            headers=WIKIPEDIA_HEADERS,
            timeout=30,
        )
        page_response.raise_for_status()
        html = page_response.json().get("parse", {}).get("text", "")

        if not html:
            return "ERROR: Wikipedia returned no page content."

        soup = BeautifulSoup(html, "html.parser")
        for element in soup.select(
            "script, style, sup.reference, .mw-editsection, .navbox, "
            ".vertical-navbox, .metadata"
        ):
            element.decompose()

        blocks: list[str] = []
        for element in soup.select("h2, h3, h4, p, li, tr"):
            text = " ".join(element.stripped_strings)
            if text:
                blocks.append(text)

        return json.dumps(
            {
                "title": page_title,
                "revision_timestamp": revision_timestamp,
                "content": "\n".join(blocks)[:18000],
            },
            ensure_ascii=False,
        )

    except Exception as error:
        return f"ERROR: Wikipedia lookup failed: {type(error).__name__}: {error}"


BINARY_OPERATORS = {
    ast.Add: operator.add,
    ast.Sub: operator.sub,
    ast.Mult: operator.mul,
    ast.Div: operator.truediv,
    ast.Pow: operator.pow,
    ast.Mod: operator.mod,
}
UNARY_OPERATORS = {ast.UAdd: operator.pos, ast.USub: operator.neg}


def _evaluate_math_node(node):
    if isinstance(node, ast.Expression):
        return _evaluate_math_node(node.body)
    if isinstance(node, ast.Constant):
        if not isinstance(node.value, (int, float)):
            raise ValueError("Only numbers are allowed.")
        return node.value
    if isinstance(node, ast.BinOp):
        operation_type = type(node.op)
        if operation_type not in BINARY_OPERATORS:
            raise ValueError(f"Unsupported operation: {operation_type.__name__}")
        left = _evaluate_math_node(node.left)
        right = _evaluate_math_node(node.right)
        if operation_type is ast.Pow and abs(right) > 100:
            raise ValueError("Exponent is too large.")
        return BINARY_OPERATORS[operation_type](left, right)
    if isinstance(node, ast.UnaryOp):
        operation_type = type(node.op)
        if operation_type not in UNARY_OPERATORS:
            raise ValueError("Unsupported unary operation.")
        return UNARY_OPERATORS[operation_type](_evaluate_math_node(node.operand))
    raise ValueError("Expression contains an unsupported element.")


@tool("calculator")
def calculator(expression: str) -> str:
    """Evaluate arithmetic using +, -, *, /, %, **, and parentheses."""

    if len(expression) > 200:
        return "ERROR: Calculator expression is too long."

    try:
        parsed = ast.parse(expression, mode="eval")
        return str(_evaluate_math_node(parsed))
    except Exception as error:
        return f"ERROR: Calculator failed: {type(error).__name__}: {error}"


@tool("python_executor")
def python_executor(code: str) -> str:
    """Execute short Python code for deterministic data processing."""

    if not code.strip():
        return "ERROR: No Python code was provided."
    if len(code) > 10000:
        return "ERROR: Python code is too long."

    try:
        with tempfile.TemporaryDirectory() as directory:
            completed = subprocess.run(
                [sys.executable, "-I", "-c", code],
                cwd=directory,
                capture_output=True,
                text=True,
                timeout=20,
            )

        if completed.returncode != 0:
            return f"ERROR: Python execution failed:\n{completed.stderr[:4000]}"

        output = completed.stdout.strip()
        if not output:
            return "ERROR: Python ran but printed no output."
        return output[:10000]

    except subprocess.TimeoutExpired:
        return "ERROR: Python execution exceeded 20 seconds."
    except Exception as error:
        return f"ERROR: Python execution failed: {type(error).__name__}: {error}"


# -----------------------------------------------------------------------------
# YouTube transcript tool
# -----------------------------------------------------------------------------


def extract_youtube_video_id(url: str) -> str:
    parsed_url = urlparse(url.strip())
    hostname = (parsed_url.hostname or "").lower().removeprefix("www.")
    video_id = ""

    if hostname == "youtu.be":
        video_id = parsed_url.path.strip("/").split("/")[0]
    elif hostname in {"youtube.com", "m.youtube.com", "music.youtube.com"}:
        if parsed_url.path == "/watch":
            video_id = parse_qs(parsed_url.query).get("v", [""])[0]
        elif parsed_url.path.startswith(("/shorts/", "/embed/", "/live/")):
            parts = parsed_url.path.strip("/").split("/")
            if len(parts) >= 2:
                video_id = parts[1]

    if not re.fullmatch(r"[A-Za-z0-9_-]{11}", video_id):
        raise ValueError("Could not extract a valid YouTube video ID.")
    return video_id


def format_video_timestamp(seconds: float) -> str:
    total_seconds = int(seconds)
    minutes, seconds = divmod(total_seconds, 60)
    hours, minutes = divmod(minutes, 60)
    if hours:
        return f"{hours:02d}:{minutes:02d}:{seconds:02d}"
    return f"{minutes:02d}:{seconds:02d}"


@tool("youtube_transcript")
def youtube_transcript(url: str, languages: str = "en") -> str:
    """Retrieve timestamped captions for dialogue or spoken-answer questions."""

    try:
        video_id = extract_youtube_video_id(url)
        language_codes = [x.strip() for x in languages.split(",") if x.strip()]
        transcript = YouTubeTranscriptApi().fetch(
            video_id,
            languages=language_codes or ["en"],
        )

        lines = [f"VIDEO ID: {video_id}", "TRANSCRIPT:"]
        for snippet in transcript:
            text = " ".join(snippet.text.split())
            if text:
                lines.append(f"[{format_video_timestamp(snippet.start)}] {text}")

        result = "\n".join(lines)
        return result[:18000] if result else "ERROR: No transcript was returned."

    except Exception as error:
        return f"ERROR: Transcript retrieval failed: {type(error).__name__}: {error}"


# -----------------------------------------------------------------------------
# Generic visual YouTube tool
# -----------------------------------------------------------------------------

VIDEO_MAX_FRAMES = int(os.getenv("VIDEO_MAX_FRAMES", "24"))
VIDEO_BATCH_SIZE = int(os.getenv("VIDEO_BATCH_SIZE", "8"))
VIDEO_MAX_IMAGE_SIDE = 768
VIDEO_JPEG_QUALITY = 82


def _remove_partial_video_files(output_directory: Path) -> None:
    for file_path in output_directory.glob("video.*"):
        try:
            file_path.unlink()
        except OSError:
            pass


def _find_downloaded_video(output_directory: Path) -> Path | None:
    ignored = {".part", ".ytdl", ".json", ".description"}
    files = [
        path
        for path in output_directory.glob("video.*")
        if path.is_file() and path.suffix not in ignored and path.stat().st_size > 0
    ]
    return max(files, key=lambda path: path.stat().st_size) if files else None


def download_youtube_video(url: str, output_directory: Path) -> Path:
    """Download a public YouTube video, trying several player clients."""

    output_directory.mkdir(parents=True, exist_ok=True)
    base_options = {
        "format": "best[ext=mp4][height<=480]/best[height<=480]/best",
        "outtmpl": str(output_directory / "video.%(ext)s"),
        "noplaylist": True,
        "quiet": True,
        "no_warnings": True,
        "force_ipv4": True,
        "retries": 2,
        "fragment_retries": 2,
        "socket_timeout": 30,
        "overwrites": True,
    }

    attempts = [
        ["default", "tv_simply"],
        ["web_safari", "tv_simply"],
    ]
    errors: list[str] = []

    for clients in attempts:
        _remove_partial_video_files(output_directory)
        options = dict(base_options)
        options["extractor_args"] = {"youtube": {"player_client": clients}}

        try:
            with yt_dlp.YoutubeDL(options) as downloader:
                downloader.download([url])
            downloaded = _find_downloaded_video(output_directory)
            if downloaded:
                return downloaded
        except Exception as error:
            errors.append(f"{clients}: {type(error).__name__}: {error}")

    raise RuntimeError("All YouTube download attempts failed: " + " | ".join(errors))


def resize_video_frame(frame, maximum_side: int = VIDEO_MAX_IMAGE_SIDE):
    height, width = frame.shape[:2]
    longest = max(width, height)
    if longest <= maximum_side:
        return frame
    scale = maximum_side / longest
    return cv2.resize(
        frame,
        (max(1, int(width * scale)), max(1, int(height * scale))),
        interpolation=cv2.INTER_AREA,
    )


def sample_video_frames(
    video_path: Path,
    maximum_frames: int = VIDEO_MAX_FRAMES,
) -> list[dict]:
    capture = cv2.VideoCapture(str(video_path))

    try:
        if not capture.isOpened():
            raise ValueError("OpenCV could not open the video.")

        fps = float(capture.get(cv2.CAP_PROP_FPS))
        frame_count = float(capture.get(cv2.CAP_PROP_FRAME_COUNT))
        if fps <= 0 or frame_count <= 0:
            raise ValueError("Could not determine video duration.")

        duration = frame_count / fps
        sample_count = min(maximum_frames, max(12, math.ceil(duration)))
        final_timestamp = max(duration - 0.05, 0.0)
        timestamps = [
            index * final_timestamp / max(sample_count - 1, 1)
            for index in range(sample_count)
        ]

        sampled: list[dict] = []
        for timestamp in timestamps:
            capture.set(cv2.CAP_PROP_POS_MSEC, timestamp * 1000)
            success, frame = capture.read()
            if not success:
                continue
            frame = resize_video_frame(frame)
            encoded_success, encoded = cv2.imencode(
                ".jpg",
                frame,
                [int(cv2.IMWRITE_JPEG_QUALITY), VIDEO_JPEG_QUALITY],
            )
            if not encoded_success:
                continue
            sampled.append(
                {
                    "timestamp_seconds": round(timestamp, 3),
                    "image_base64": base64.b64encode(encoded.tobytes()).decode(),
                }
            )
        return sampled
    finally:
        capture.release()


def _model_content_to_text(content) -> str:
    if isinstance(content, str):
        return content.strip()
    if isinstance(content, list):
        return "\n".join(
            str(block.get("text", ""))
            for block in content
            if isinstance(block, dict) and block.get("text")
        ).strip()
    return str(content).strip()


def _extract_json_object(text: str) -> dict:
    start = text.find("{")
    end = text.rfind("}")
    if start == -1 or end <= start:
        raise ValueError("The model did not return a JSON object.")
    return json.loads(text[start : end + 1])


def _safe_float(value, default=None):
    try:
        return float(value)
    except (TypeError, ValueError):
        return default


def analyze_video_frame_batch(
    frame_batch: list[dict],
    question: str,
) -> list[dict]:
    prompt = f"""
Analyze each labeled frame independently for the original visual question.

ORIGINAL QUESTION:
{question}

For every frame:
1. Decide whether it contains relevant visible evidence.
2. Describe only what is visibly present.
3. Never combine counts or objects across timestamps.
4. For a count question, put the value supported by that frame in numeric_value.
5. For an identification, color, text, object, person, animal, action, place,
   or event question, put the possible answer in candidate_answer.
6. Use null when the frame does not support a value.
7. Be conservative when evidence is unclear.

Return JSON only:
{{
  "frames": [
    {{
      "frame_label": "FRAME 1",
      "relevant": true,
      "observation": "visible evidence",
      "candidate_answer": null,
      "numeric_value": null,
      "confidence": 0.0
    }}
  ]
}}
""".strip()

    content: list[dict] = [{"type": "text", "text": prompt}]
    for index, frame in enumerate(frame_batch, start=1):
        content.append(
            {
                "type": "text",
                "text": f"FRAME {index}{frame['timestamp_seconds']:.2f} seconds",
            }
        )
        content.append(
            {
                "type": "image_url",
                "image_url": {
                    "url": "data:image/jpeg;base64," + frame["image_base64"]
                },
            }
        )

    response = vision_llm.invoke([HumanMessage(content=content)])
    parsed = _extract_json_object(_model_content_to_text(response.content))
    returned = {
        item.get("frame_label"): item
        for item in parsed.get("frames", [])
        if isinstance(item, dict)
    }

    observations: list[dict] = []
    for index, frame in enumerate(frame_batch, start=1):
        result = returned.get(f"FRAME {index}", {})
        observations.append(
            {
                "timestamp_seconds": frame["timestamp_seconds"],
                "relevant": bool(result.get("relevant", False)),
                "observation": str(result.get("observation", "")).strip(),
                "candidate_answer": result.get("candidate_answer"),
                "numeric_value": _safe_float(result.get("numeric_value")),
                "confidence": _safe_float(result.get("confidence"), 0.0),
            }
        )
    return observations


def synthesize_video_answer(question: str, observations: list[dict]) -> dict:
    relevant = [item for item in observations if item.get("relevant")]
    if not relevant:
        return {"answer": "Unknown", "evidence_timestamps": [], "confidence": 0.0}

    prompt = f"""
Answer the original question using only these timestamped visual observations.

ORIGINAL QUESTION:
{question}

OBSERVATIONS:
{json.dumps(relevant[:60], ensure_ascii=False)}

Rules:
- For highest/maximum/most simultaneously, use the largest value from one timestamp.
- For lowest/minimum, use the smallest value from one timestamp.
- For first, use the earliest relevant timestamp.
- For last, use the latest relevant timestamp.
- Do not add values across timestamps.
- Return Unknown when evidence is insufficient.

Return JSON only:
{{"answer": "concise answer", "evidence_timestamps": [0.0], "confidence": 0.0}}
""".strip()

    response = vision_llm.invoke([HumanMessage(content=prompt)])
    result = _extract_json_object(_model_content_to_text(response.content))
    return {
        "answer": str(result.get("answer", "Unknown")).strip(),
        "evidence_timestamps": result.get("evidence_timestamps", []),
        "confidence": _safe_float(result.get("confidence"), 0.0),
    }


@tool("youtube_visual_analysis")
def youtube_visual_analysis(url: str, question: str) -> str:
    """Analyze objects, counts, text, colors, actions, and events visible in video."""

    try:
        with tempfile.TemporaryDirectory() as directory:
            video_path = download_youtube_video(url, Path(directory))
            sampled_frames = sample_video_frames(video_path, VIDEO_MAX_FRAMES)
            if not sampled_frames:
                return json.dumps({"error": "No video frames could be extracted."})

            observations: list[dict] = []
            batch_errors: list[str] = []
            completed_batches = 0

            for batch_start in range(0, len(sampled_frames), VIDEO_BATCH_SIZE):
                batch_number = batch_start // VIDEO_BATCH_SIZE + 1
                batch = sampled_frames[batch_start : batch_start + VIDEO_BATCH_SIZE]
                try:
                    observations.extend(analyze_video_frame_batch(batch, question))
                    completed_batches += 1
                except RateLimitError as error:
                    return json.dumps(
                        {
                            "error": "Vision-model API rate limit reached.",
                            "stage": f"frame-analysis batch {batch_number}",
                            "provider_message": str(error),
                        },
                        ensure_ascii=False,
                    )
                except Exception as error:
                    batch_errors.append(
                        f"Batch {batch_number}: {type(error).__name__}: {error}"
                    )

            if not observations:
                return json.dumps(
                    {
                        "error": "No video frames were successfully analyzed.",
                        "batch_errors": batch_errors,
                    },
                    ensure_ascii=False,
                )

            normalized = question.lower()
            numeric = [
                item
                for item in observations
                if item.get("relevant") and item.get("numeric_value") is not None
            ]
            final_result = None

            if numeric and any(
                phrase in normalized
                for phrase in (
                    "highest number",
                    "maximum number",
                    "largest number",
                    "most simultaneously",
                )
            ):
                best = max(numeric, key=lambda item: item["numeric_value"])
                value = best["numeric_value"]
                value = int(value) if float(value).is_integer() else value
                final_result = {
                    "answer": str(value),
                    "evidence_timestamps": [best["timestamp_seconds"]],
                    "confidence": best.get("confidence", 0.0),
                }
            elif numeric and any(
                phrase in normalized
                for phrase in ("lowest number", "minimum number", "smallest number")
            ):
                best = min(numeric, key=lambda item: item["numeric_value"])
                value = best["numeric_value"]
                value = int(value) if float(value).is_integer() else value
                final_result = {
                    "answer": str(value),
                    "evidence_timestamps": [best["timestamp_seconds"]],
                    "confidence": best.get("confidence", 0.0),
                }

            if final_result is None:
                final_result = synthesize_video_answer(question, observations)

            return json.dumps(
                {
                    **final_result,
                    "frames_analyzed": len(observations),
                    "frames_sampled": len(sampled_frames),
                    "batches_completed": completed_batches,
                    "batch_errors": batch_errors,
                },
                ensure_ascii=False,
            )

    except RateLimitError as error:
        return json.dumps(
            {
                "error": "Vision-model API rate limit reached.",
                "provider_message": str(error),
            }
        )
    except Exception as error:
        return json.dumps(
            {
                "error": (
                    "YouTube visual analysis failed: "
                    f"{type(error).__name__}: {error}"
                )
            },
            ensure_ascii=False,
        )


# -----------------------------------------------------------------------------
# Agent state and attachment routing
# -----------------------------------------------------------------------------

RouteType = Literal[
    "reasoning",
    "audio",
    "image",
    "chess",
    "spreadsheet",
    "python_file",
    "pdf",
]


class AgentState(TypedDict):
    question: str
    messages: Annotated[list[AnyMessage], add_messages]
    route: NotRequired[RouteType]
    input_file: NotRequired[str]
    attachment_content: NotRequired[str]
    final_answer: NotRequired[str]
    error: NotRequired[str]


AUDIO_EXTENSIONS = {".mp3", ".wav", ".m4a", ".flac", ".ogg"}
IMAGE_EXTENSIONS = {".png", ".jpg", ".jpeg", ".webp", ".bmp"}
SPREADSHEET_EXTENSIONS = {".csv", ".xlsx", ".xls", ".xlsm"}


def router_node(state: AgentState) -> dict:
    question = state["question"].lower()
    input_file = state.get("input_file")

    if not input_file:
        return {"route": "reasoning"}

    extension = Path(input_file).suffix.lower()
    if extension in AUDIO_EXTENSIONS:
        return {"route": "audio"}
    if extension in IMAGE_EXTENSIONS:
        chess_keywords = (
            "chess",
            "black's turn",
            "white's turn",
            "algebraic notation",
            "checkmate",
        )
        return {
            "route": "chess" if any(x in question for x in chess_keywords) else "image"
        }
    if extension in SPREADSHEET_EXTENSIONS:
        return {"route": "spreadsheet"}
    if extension == ".py":
        return {"route": "python_file"}
    if extension == ".pdf":
        return {"route": "pdf"}
    return {"route": "reasoning"}


def choose_route(state: AgentState) -> RouteType:
    return state.get("route", "reasoning")


# -----------------------------------------------------------------------------
# Image helpers and nodes
# -----------------------------------------------------------------------------

MAX_IMAGE_SIDE = 768
JPEG_QUALITY = 85


def prepare_image_for_vlm(file_path: Path) -> tuple[str, str, tuple[int, int]]:
    with PILImage.open(file_path) as image:
        image = ImageOps.exif_transpose(image)

        if image.mode in ("RGBA", "LA"):
            background = PILImage.new("RGB", image.size, "white")
            background.paste(image.convert("RGB"), mask=image.getchannel("A"))
            image = background
        elif image.mode == "P" and "transparency" in image.info:
            image = image.convert("RGBA")
            background = PILImage.new("RGB", image.size, "white")
            background.paste(image.convert("RGB"), mask=image.getchannel("A"))
            image = background
        else:
            image = image.convert("RGB")

        image.thumbnail((MAX_IMAGE_SIDE, MAX_IMAGE_SIDE), PILImage.Resampling.LANCZOS)
        resized_size = image.size
        buffer = BytesIO()
        image.save(buffer, format="JPEG", quality=JPEG_QUALITY, optimize=True)
        image_base64 = base64.b64encode(buffer.getvalue()).decode()

    return image_base64, "image/jpeg", resized_size


def image_node(state: AgentState) -> dict:
    input_file = state.get("input_file")
    if not input_file:
        return {"error": "No image file was supplied."}

    file_path = Path(input_file)
    try:
        image_base64, mime_type, resized_size = prepare_image_for_vlm(file_path)
        question = state.get("question", "Describe the image.").strip()
        prompt = f"""
Analyze the attached image for the original question.

ORIGINAL QUESTION:
{question}

Extract only relevant visible evidence, including readable text, numbers,
symbols, labels, objects, positions, tables, and chart values. Do not invent
unclear details and do not use outside knowledge.
""".strip()
        response = vision_llm.invoke(
            [
                HumanMessage(
                    content=[
                        {"type": "text", "text": prompt},
                        {
                            "type": "image_url",
                            "image_url": {
                                "url": f"data:{mime_type};base64,{image_base64}"
                            },
                        },
                    ]
                )
            ]
        )
        analysis = _model_content_to_text(response.content)
        if not analysis:
            raise ValueError("The vision model returned no image analysis.")
        return {
            "attachment_content": (
                "IMAGE ANALYSIS\n\n"
                f"FILE NAME: {file_path.name}\n"
                f"RESIZED DIMENSIONS: {resized_size[0]} x {resized_size[1]}\n\n"
                f"VISUAL CONTENT:\n{analysis}"
            )
        }
    except Exception as error:
        message = f"Image analysis failed: {type(error).__name__}: {error}"
        return {"attachment_content": message, "error": message}


# -----------------------------------------------------------------------------
# Audio node
# -----------------------------------------------------------------------------


def audio_node(state: AgentState) -> dict:
    input_file = state.get("input_file")
    if not input_file:
        return {"error": "No audio file was supplied."}

    file_path = Path(input_file)

    try:
        with file_path.open("rb") as audio_file:
            transcription = openai_client.audio.transcriptions.create(
                model=AUDIO_MODEL,
                file=audio_file,
                language="en",
                prompt=(
                    "Transcribe accurately. Preserve names, numbers, page "
                    "numbers, ingredient names, and punctuation."
                ),
                response_format="text",
            )

        if isinstance(transcription, str):
            transcript = transcription.strip()
        else:
            transcript = str(
                getattr(transcription, "text", "")
            ).strip()

        if not transcript:
            raise ValueError("The transcription API returned no text.")

        return {
            "attachment_content": (
                "AUDIO TRANSCRIPTION\n\n"
                f"FILE NAME: {file_path.name}\n"
                f"TRANSCRIPTION MODEL: {AUDIO_MODEL}\n\n"
                f"TRANSCRIPT:\n{transcript}"
            )
        }

    except RateLimitError as error:
        message = (
            "Audio transcription failed because the OpenAI rate limit "
            f"was reached: {error}"
        )
        return {"attachment_content": message, "error": message}

    except Exception as error:
        message = (
            "Audio transcription failed: "
            f"{type(error).__name__}: {error}"
        )
        return {"attachment_content": message, "error": message}


# -----------------------------------------------------------------------------
# Chess node
# -----------------------------------------------------------------------------

def find_stockfish() -> str | None:
    candidates = [
        os.getenv("STOCKFISH_PATH", "").strip(),
        shutil.which("stockfish"),
        "/usr/games/stockfish",
        "/usr/local/bin/stockfish",
        "/usr/bin/stockfish",
    ]

    for candidate in candidates:
        if candidate and Path(candidate).is_file():
            return candidate

    return None


STOCKFISH_PATH = find_stockfish()


def detect_side_from_question(question: str):
    normalized = question.lower().replace("’", "'")
    if any(x in normalized for x in ("black to move", "black's turn", "move for black")):
        return chess.BLACK
    if any(x in normalized for x in ("white to move", "white's turn", "move for white")):
        return chess.WHITE
    return None


def chess_node(state: AgentState) -> dict:
    input_file = state.get("input_file")
    if not input_file:
        return {"error": "No chess image was supplied."}
    if not STOCKFISH_PATH:
        message = "Stockfish is not installed."
        return {"attachment_content": message, "error": message}

    file_path = Path(input_file)
    question = state.get("question", "").strip()

    try:
        image_base64, mime_type, resized_size = prepare_image_for_vlm(file_path)
        explicit_turn = detect_side_from_question(question)
        turn_instruction = (
            "Set side_to_move to black."
            if explicit_turn == chess.BLACK
            else "Set side_to_move to white."
            if explicit_turn == chess.WHITE
            else "Determine the side to move from the image."
        )

        prompt = f"""
Reconstruct the attached chessboard exactly.

ORIGINAL QUESTION:
{question}

Inspect all 64 squares and board labels. Do not calculate a move.
{turn_instruction}

Return JSON only:
{{
  "white_pieces": ["Kg1"],
  "black_pieces": ["Kg8"],
  "fen": "complete FEN",
  "side_to_move": "black or white",
  "orientation": "black or white",
  "confidence": 0.0
}}
""".strip()

        response = vision_llm_chess.invoke(
            [
                HumanMessage(
                    content=[
                        {"type": "text", "text": prompt},
                        {
                            "type": "image_url",
                            "image_url": {
                                "url": f"data:{mime_type};base64,{image_base64}"
                            },
                        },
                    ]
                )
            ]
        )
        result = _extract_json_object(_model_content_to_text(response.content))
        fen = str(result.get("fen", "")).strip()
        if not fen:
            raise ValueError("The vision model did not return a FEN.")

        board = chess.Board(fen)
        if explicit_turn is not None:
            board.turn = explicit_turn
            fen = board.fen()
        if not board.is_valid() or board.is_game_over():
            raise ValueError(f"Invalid or finished reconstructed position: {fen}")

        engine = chess.engine.SimpleEngine.popen_uci(STOCKFISH_PATH, timeout=30.0)
        try:
            engine_result = engine.play(board, chess.engine.Limit(depth=18))
            if engine_result.move is None:
                raise ValueError("Stockfish did not return a move.")
            san = board.san(engine_result.move)
            uci = engine_result.move.uci()
        finally:
            engine.quit()

        return {
            "attachment_content": (
                "CHESS POSITION ANALYSIS\n\n"
                f"FILE NAME: {file_path.name}\n"
                f"IMAGE DIMENSIONS: {resized_size[0]} x {resized_size[1]}\n"
                f"FEN: {fen}\n"
                f"BEST MOVE IN SAN: {san}\n"
                f"BEST MOVE IN UCI: {uci}\n"
            )
        }
    except Exception as error:
        message = f"Chess processing failed: {type(error).__name__}: {error}"
        return {"attachment_content": message, "error": message}


# -----------------------------------------------------------------------------
# Spreadsheet, Python, and PDF nodes
# -----------------------------------------------------------------------------


def _clean_dataframe(dataframe: pd.DataFrame) -> pd.DataFrame:
    cleaned = dataframe.copy().replace(r"^\s*$", pd.NA, regex=True)
    return cleaned.dropna(axis=0, how="all").dropna(axis=1, how="all")


def _dataframe_to_text(sheet_name: str, dataframe: pd.DataFrame) -> str:
    dataframe = _clean_dataframe(dataframe)
    rows, columns = dataframe.shape
    section = [
        f"SHEET NAME: {sheet_name}",
        f"ROWS: {rows}",
        f"COLUMNS: {columns}",
        "COLUMN NAMES: " + " | ".join(str(x) for x in dataframe.columns),
        "SHEET DATA:",
        dataframe.to_csv(index=False, na_rep=""),
    ]

    numeric = dataframe.apply(pd.to_numeric, errors="coerce")
    totals = numeric.sum(min_count=1).dropna()
    if not totals.empty:
        section.append("NUMERIC COLUMN TOTALS:")
        for column, total in totals.items():
            section.append(f"{column}: {total}")

    return "\n".join(section)


def spreadsheet_node(state: AgentState) -> dict:
    input_file = state.get("input_file")
    if not input_file:
        return {"error": "No spreadsheet file was supplied."}

    file_path = Path(input_file)
    try:
        if file_path.suffix.lower() == ".csv":
            sheets = {"CSV": pd.read_csv(file_path, dtype=object, keep_default_na=False)}
        else:
            sheets = pd.read_excel(
                file_path,
                sheet_name=None,
                dtype=object,
                keep_default_na=False,
            )

        content = "\n\n".join(
            _dataframe_to_text(name, frame) for name, frame in sheets.items()
        )
        return {
            "attachment_content": (
                "SPREADSHEET INFORMATION\n\n"
                f"FILE NAME: {file_path.name}\n\n{content[:30000]}"
            )
        }
    except Exception as error:
        message = f"Spreadsheet processing failed: {type(error).__name__}: {error}"
        return {"attachment_content": message, "error": message}


def python_file_node(state: AgentState) -> dict:
    input_file = state.get("input_file")
    if not input_file:
        return {"error": "No Python file was supplied."}

    file_path = Path(input_file)
    try:
        try:
            source = file_path.read_text(encoding="utf-8")
        except UnicodeDecodeError:
            source = file_path.read_text(encoding="latin-1")

        tree = ast.parse(source)
        functions = sorted(
            {
                node.name
                for node in ast.walk(tree)
                if isinstance(node, (ast.FunctionDef, ast.AsyncFunctionDef))
            }
        )
        classes = sorted(
            {node.name for node in ast.walk(tree) if isinstance(node, ast.ClassDef)}
        )

        return {
            "attachment_content": (
                "PYTHON FILE INFORMATION\n\n"
                f"FILE NAME: {file_path.name}\n"
                f"FUNCTIONS: {', '.join(functions) or 'None'}\n"
                f"CLASSES: {', '.join(classes) or 'None'}\n\n"
                "ANALYSIS INSTRUCTION: Trace execution from __main__ to the final "
                "printed value. Follow loops, recursion, exceptions, generators, "
                "returns, mutations, and stopping conditions.\n\n"
                f"SOURCE CODE:\n{source[:30000]}"
            )
        }
    except Exception as error:
        message = f"Python file processing failed: {type(error).__name__}: {error}"
        return {"attachment_content": message, "error": message}


def pdf_node(state: AgentState) -> dict:
    input_file = state.get("input_file")
    if not input_file:
        return {"error": "No PDF file was supplied."}

    file_path = Path(input_file)
    try:
        reader = PdfReader(str(file_path))
        pages: list[str] = []
        for page_number, page in enumerate(reader.pages[:50], start=1):
            try:
                text = page.extract_text(extraction_mode="layout") or ""
            except TypeError:
                text = page.extract_text() or ""
            pages.append(f"--- PAGE {page_number} ---\n{text.strip()}")

        full_text = "\n\n".join(pages)
        if not full_text.strip():
            raise ValueError("No text could be extracted from the PDF.")
        return {
            "attachment_content": (
                "PDF INFORMATION\n\n"
                f"FILE NAME: {file_path.name}\n"
                f"TOTAL PAGES: {len(reader.pages)}\n\n"
                f"PDF CONTENT:\n{full_text[:15000]}"
            )
        }
    except Exception as error:
        message = f"PDF processing failed: {type(error).__name__}: {error}"
        return {"attachment_content": message, "error": message}


# -----------------------------------------------------------------------------
# Reasoning and graph
# -----------------------------------------------------------------------------

GENERAL_TOOLS = [
    web_search_tool,
    wikipedia_search,
    read_webpage,
    calculator,
    python_executor,
    youtube_transcript,
    youtube_visual_analysis,
]

WIKIPEDIA_TOOLS = [wikipedia_search, calculator, python_executor]

llm_with_tools = llm.bind_tools(GENERAL_TOOLS)
wikipedia_llm_with_tools = llm.bind_tools(WIKIPEDIA_TOOLS)
tool_node = ToolNode(GENERAL_TOOLS, handle_tool_errors=True)

MAX_TOOL_RESULTS = 6

GAIA_REASONING_PROMPT = """
You are solving a GAIA benchmark question. Use direct reasoning and the
minimum necessary tool calls.

1. Return exactly one block: <answer>YOUR ANSWER</answer>. Put no text outside it.
2. Follow exact formatting: number, name, IOC code, comma-separated list,
   alphabetical order, decimals, capitalization, punctuation, or chess SAN.
3. Solve reversed text, wordplay, simple logic, and short transformations
   directly without tools.
4. Treat attachment content as the primary source and preserve exact values.
5. For web research, use focused web_search and open a relevant result with
   read_webpage. Do not answer from snippets or blocked pages.
6. When the question mentions Wikipedia, use wikipedia_search with the main
   topic. For a latest-2022 request use as_of_date=2022-12-31. Do not switch to
   general web search unless the Wikipedia tool returns an error.
7. Use youtube_transcript for speech, dialogue, quotations, and what someone
   said. Use youtube_visual_analysis for visible objects, animals, people,
   colors, text, actions, counts, timestamps, and simultaneous events.
8. After a successful YouTube tool result, use its evidence instead of a web
   guess. Never add counts from different timestamps for a simultaneous count.
9. Use calculator for arithmetic and python_executor for sorting, filtering,
   counting, tables, comparisons, and multi-step verification.
10. For attached Python code, trace the actual entry point and final printed
    output through recursion, loops, exceptions, generators, and returns.
11. When attachment content contains BEST MOVE IN SAN, copy it exactly.
12. For counting and list questions, identify every qualifying record, apply
    every condition, verify dates/categories, then count or sort.
13. Never invent an answer because a tool failed. Avoid repeating the same
    failing call. Once evidence is sufficient, stop using tools.
14. Before answering, verify exact question, conditions, ordering, spelling,
    capitalization, symbols, units, and decimal places.
""".strip()


def reasoning_node(state: AgentState) -> dict:
    question = state["question"].strip()
    attachment_content = state.get("attachment_content", "").strip()
    messages = list(state.get("messages", []))
    if not messages:
        messages = [HumanMessage(content=question)]

    tool_result_count = sum(isinstance(message, ToolMessage) for message in messages)
    system_content = f"{GAIA_REASONING_PROMPT}\n\nORIGINAL QUESTION:\n{question}"
    if attachment_content:
        system_content += (
            "\n\nCONTENT EXTRACTED FROM THE ATTACHMENT:\n" + attachment_content
        )

    if tool_result_count >= MAX_TOOL_RESULTS:
        system_content += (
            "\n\nThe tool-use budget is exhausted. Do not call another tool. "
            "Use the reliable evidence already available and return the answer now."
        )
        selected_model = llm
    elif "wikipedia" in question.lower():
        selected_model = wikipedia_llm_with_tools
    else:
        selected_model = llm_with_tools

    response = selected_model.invoke(
        [SystemMessage(content=system_content), *messages]
    )
    return {"messages": [response]}


def content_to_text(content) -> str:
    return _model_content_to_text(content)


def final_answer_formatter(state: AgentState) -> dict:
    for message in reversed(state.get("messages", [])):
        if not isinstance(message, AIMessage) or getattr(message, "tool_calls", None):
            continue
        text = content_to_text(message.content)
        if not text:
            continue
        tagged = re.search(
            r"<answer>\s*(.*?)\s*</answer>",
            text,
            flags=re.IGNORECASE | re.DOTALL,
        )
        answer = tagged.group(1).strip() if tagged else text
        answer = re.sub(
            r"^(final\s+answer|answer|result)\s*:\s*",
            "",
            answer,
            flags=re.IGNORECASE,
        )
        answer = re.sub(r"</?answer>", "", answer, flags=re.IGNORECASE)
        return {"final_answer": answer.strip("` \n")}

    return {"final_answer": "", "error": "No completed AI answer was found."}


def route_after_processor(state: AgentState) -> Literal["reason", "stop"]:
    return "stop" if state.get("error") else "reason"


def route_after_reasoning(
    state: AgentState,
) -> Literal["use_tools", "format_answer"]:
    last_message = state["messages"][-1]
    return "use_tools" if getattr(last_message, "tool_calls", None) else "format_answer"


graph_builder = StateGraph(AgentState)
graph_builder.add_node("router", router_node)
graph_builder.add_node("audio_node", audio_node)
graph_builder.add_node("image_node", image_node)
graph_builder.add_node("chess_node", chess_node)
graph_builder.add_node("spreadsheet_node", spreadsheet_node)
graph_builder.add_node("python_file_node", python_file_node)
graph_builder.add_node("pdf_node", pdf_node)
graph_builder.add_node("reasoning_node", reasoning_node)
graph_builder.add_node("tools", tool_node)
graph_builder.add_node("final_answer_formatter", final_answer_formatter)

graph_builder.add_edge(START, "router")
graph_builder.add_conditional_edges(
    "router",
    choose_route,
    {
        "reasoning": "reasoning_node",
        "audio": "audio_node",
        "image": "image_node",
        "chess": "chess_node",
        "spreadsheet": "spreadsheet_node",
        "python_file": "python_file_node",
        "pdf": "pdf_node",
    },
)

for processor in (
    "audio_node",
    "image_node",
    "chess_node",
    "spreadsheet_node",
    "python_file_node",
    "pdf_node",
):
    graph_builder.add_conditional_edges(
        processor,
        route_after_processor,
        {"reason": "reasoning_node", "stop": END},
    )

graph_builder.add_conditional_edges(
    "reasoning_node",
    route_after_reasoning,
    {"use_tools": "tools", "format_answer": "final_answer_formatter"},
)
graph_builder.add_edge("tools", "reasoning_node")
graph_builder.add_edge("final_answer_formatter", END)

gaia_graph = graph_builder.compile()


def clean_answer(answer: str) -> str:
    answer = str(answer or "").strip()
    match = re.search(
        r"<answer>\s*(.*?)\s*</answer>",
        answer,
        flags=re.IGNORECASE | re.DOTALL,
    )
    if match:
        answer = match.group(1).strip()
    return re.sub(
        r"^(final\s+answer|answer|result)\s*:\s*",
        "",
        answer,
        flags=re.IGNORECASE,
    ).strip()


class GaiaAgent:
    """Wrapper called by app.py and the local dry-run script."""

    def __init__(self):
        self.graph = gaia_graph

    def health_check(self) -> dict:
        """Make one small paid request to validate the configured text model."""

        response = llm.invoke(
            [HumanMessage(content="Return exactly the word OK and nothing else.")]
        )
        text = _model_content_to_text(response.content).strip()

        return {
            "text_model": TEXT_MODEL,
            "vision_model": VISION_MODEL,
            "audio_model": AUDIO_MODEL,
            "text_response": text,
            "stockfish_available": bool(STOCKFISH_PATH),
            "ffmpeg_available": bool(shutil.which("ffmpeg")),
        }

    def __call__(
        self,
        question: str,
        input_file: str | None = None,
    ) -> str:
        state: AgentState = {"question": question, "messages": []}
        if input_file:
            state["input_file"] = input_file

        result = self.graph.invoke(state, config={"recursion_limit": 25})
        answer = clean_answer(result.get("final_answer", ""))
        if not answer:
            print("Agent returned no answer. Error:", result.get("error", ""))
        return answer