File size: 30,682 Bytes
10e9b7d
980ab20
84ffff4
3dead3c
cc5fac8
84ffff4
 
 
 
10e9b7d
eccf8e4
3c4371f
980ab20
 
 
 
5a5431a
980ab20
 
 
a0b70c8
980ab20
 
 
 
a0b70c8
980ab20
 
a1457c3
 
 
a0b70c8
 
 
 
 
 
 
 
 
 
a1457c3
 
980ab20
 
 
 
 
 
 
 
 
84ffff4
980ab20
 
 
84ffff4
e193ac9
 
a0b70c8
 
 
980ab20
 
 
a0b70c8
 
 
980ab20
 
 
 
 
 
747c5d8
 
980ab20
f578464
a0b70c8
980ab20
a0b70c8
47cc8ce
980ab20
 
 
a0b70c8
f578464
a0b70c8
f578464
 
 
 
a0b70c8
 
 
 
 
 
 
 
980ab20
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
747c5d8
980ab20
747c5d8
980ab20
17b5176
 
 
 
 
 
980ab20
a0b70c8
 
17b5176
980ab20
a0b70c8
980ab20
 
17b5176
980ab20
 
 
 
17b5176
980ab20
747c5d8
980ab20
 
a0b70c8
 
 
747c5d8
 
 
a0b70c8
747c5d8
980ab20
 
747c5d8
2ea61e0
a0b70c8
 
 
 
17b5176
 
 
 
 
 
 
 
 
 
2ea61e0
 
 
a0b70c8
17b5176
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
980ab20
a0b70c8
 
747c5d8
a0b70c8
 
747c5d8
 
a0b70c8
e193ac9
a0b70c8
 
e193ac9
 
a0b70c8
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
980ab20
a0b70c8
980ab20
 
 
 
17b5176
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
980ab20
a0b70c8
 
 
2ea61e0
ccd2ac6
a0b70c8
 
 
 
 
 
 
 
 
 
ccd2ac6
 
 
980ab20
 
ccd2ac6
980ab20
 
 
 
 
ccd2ac6
 
 
17b5176
e193ac9
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
17b5176
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
ccd2ac6
980ab20
 
 
 
 
 
 
 
 
 
a1b1643
980ab20
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
a0b70c8
f578464
a0b70c8
 
f578464
a0b70c8
f578464
 
 
 
a0b70c8
 
 
 
 
 
 
 
980ab20
 
747c5d8
 
980ab20
747c5d8
 
 
 
 
 
980ab20
 
3dead3c
980ab20
a1b1643
980ab20
6a6ba12
 
41a2285
 
386ab84
41a2285
6a6ba12
 
3dead3c
 
980ab20
3dead3c
 
 
 
 
 
 
 
 
 
 
 
cc5fac8
3dead3c
 
a0b70c8
3dead3c
 
 
 
 
a0b70c8
 
 
 
 
 
a585bcc
a1457c3
 
a0b70c8
 
 
 
 
 
a1457c3
 
 
386ab84
a0b70c8
 
386ab84
e8675f6
a585bcc
a0b70c8
 
 
 
 
 
 
a1457c3
a0b70c8
 
 
cc5fac8
b90251f
31243f4
 
 
 
7d65c66
b177367
3c4371f
7e4a06b
1ca9f65
3c4371f
7e4a06b
3c4371f
7d65c66
3c4371f
7e4a06b
31243f4
 
e80aab9
cc5fac8
36ed51a
c1fd3d2
3c4371f
7d65c66
31243f4
eccf8e4
31243f4
7d65c66
31243f4
 
3c4371f
 
31243f4
e80aab9
31243f4
 
3c4371f
 
7d65c66
3c4371f
7d65c66
31243f4
 
e80aab9
cc5fac8
7d65c66
 
cc5fac8
 
 
 
980ab20
cc5fac8
 
 
3dead3c
cc5fac8
 
 
 
 
 
 
3dead3c
cc5fac8
 
 
 
 
 
3dead3c
7d65c66
31243f4
 
3c4371f
31243f4
 
b177367
7d65c66
3c4371f
31243f4
e80aab9
7d65c66
31243f4
e80aab9
7d65c66
e80aab9
 
31243f4
e80aab9
 
3c4371f
 
 
e80aab9
 
31243f4
 
e80aab9
3c4371f
e80aab9
 
3c4371f
e80aab9
7d65c66
3c4371f
31243f4
7d65c66
31243f4
3c4371f
 
 
 
 
e80aab9
31243f4
 
 
 
7d65c66
31243f4
 
 
 
e80aab9
 
 
 
31243f4
0ee0419
e514fd7
 
81917a3
e514fd7
 
 
 
 
 
 
e80aab9
 
7e4a06b
e80aab9
31243f4
e80aab9
9088b99
7d65c66
 
e80aab9
31243f4
 
 
e80aab9
 
 
3c4371f
7d65c66
3c4371f
7d65c66
 
3c4371f
 
7d65c66
3c4371f
7d65c66
 
 
 
 
 
 
 
 
3c4371f
 
31243f4
3c4371f
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
import os
import re
import sys
import time
import concurrent.futures
# Force UTF-8 output on Windows to avoid charmap crashes with Unicode characters
if sys.platform == "win32":
    sys.stdout.reconfigure(encoding="utf-8", errors="replace")
    sys.stderr.reconfigure(encoding="utf-8", errors="replace")
import gradio as gr
import requests
import pandas as pd
from typing import Literal, TypedDict, get_args
from langchain_core.messages import HumanMessage, SystemMessage
from langchain_openai import ChatOpenAI
from langgraph.graph import END, StateGraph
from config import DEFAULT_API_URL, HF_TOKEN, GROQ_API_KEY, OPENROUTER_API_KEY, get_prompt
from tools import (
    web_search,
    wikipedia_search,
    visit_webpage,
    get_youtube_transcript,
    describe_image,
    transcribe_audio,
    run_python_file,
    read_task_file,
)

# ---------------------------------------------------------------------------
# Model fallback chain (primary → backup → last-resort)
# ---------------------------------------------------------------------------
# Use OpenRouter for the main reasoning model (better quality) and Groq for routing (fast)
GROQ_MODELS = [
    {"model_id": "llama-3.3-70b-versatile"},
    {"model_id": "llama-3.1-8b-instant"},
]

OPENROUTER_MODELS = [
    {"model_id": "google/gemini-2.0-flash-001"},
    {"model_id": "qwen/qwen-2.5-72b-instruct"},
    {"model_id": "meta-llama/llama-3.3-70b-instruct"},
]

_LABELS = Literal[
    "python_script",
    "image",
    "audio",
    "other_ext",
    "youtube",
    "research",
    "logic"
]

def _download_task_file(task_id: str, api_url: str = DEFAULT_API_URL) -> tuple[bytes, str]:
    """Download a file attached to a GAIA task."""
    url = f"{api_url}/files/{task_id}"
    try:
        headers = {"Authorization": f"Bearer {HF_TOKEN}"}
        resp = requests.get(url, headers=headers, timeout=30)
    except requests.exceptions.RequestException as e:
        print(f"[DEBUG] Download error for {task_id}: {e}")
        return b"", ""
    if resp.status_code != 200:
        print(f"[DEBUG] GET {url}{resp.status_code}")
        return b"", ""
    ctype = resp.headers.get("content-type", "").lower()
    print(f"[DEBUG] Downloaded file for {task_id}: {len(resp.content)} bytes, type={ctype}")
    return resp.content, ctype

class AgentState(TypedDict):
    question: str
    label: str
    context: str
    answer: str
    task_id: str | None
    file_name: str | None


MAX_WORKERS = 1        # sequential to stay within rate limits
QUESTION_TIMEOUT = 300  # seconds before a single question is abandoned
_exhausted_models: set[str] = set()

# --------------------------------------------------------------------------- #
#                         NODES  (LangGraph  functions)                        #
# --------------------------------------------------------------------------- #
# Router uses Groq (fast, cheap)
_llm_router = ChatOpenAI(
    model=GROQ_MODELS[0]["model_id"],
    base_url="https://api.groq.com/openai/v1",
    api_key=GROQ_API_KEY,
    timeout=60,
)

# Reasoning uses OpenRouter (higher quality)
_llm_answer = ChatOpenAI(
    model=OPENROUTER_MODELS[0]["model_id"],
    base_url="https://openrouter.ai/api/v1",
    api_key=OPENROUTER_API_KEY,
    timeout=120,
)

def route_question(state: AgentState) -> AgentState:
    """Label the task so we know which toolchain to invoke."""
    question = state["question"]

    label_values = set(get_args(_LABELS))
    prompt = get_prompt(
        prompt_key="router",
        question=question,
        labels=", ".join(repr(v) for v in label_values),
    )
    resp = _llm_router.invoke(prompt).content.strip().lower()
    state["label"] = resp if resp in label_values else "logic"
    return state

def call_tools(state: AgentState) -> AgentState:
    question, label, task_id = state["question"], state["label"], state["task_id"]
    file_name = state.get("file_name") or ""

    matched_obj = re.search(r"https?://\S+", question)

    # ---- attachment: try download when task has a file or label suggests one -----
    should_try_file = bool(task_id and file_name)
    if not should_try_file and task_id and label in ("python_script", "image", "audio", "other_ext"):
        should_try_file = True  # label says there's a file — try anyway

    if should_try_file:
        blob, ctype = _download_task_file(api_url=DEFAULT_API_URL, task_id=task_id)
        if blob:
            print(f"[DEBUG] attachment type={ctype}, size={len(blob)} bytes")
            if "python" in ctype or file_name.endswith(".py") or (label == "python_script" and "text" in ctype):
                print("[DEBUG] Working with a Python attachment file")
                state["answer"] = run_python_file.invoke({"code": blob.decode("utf-8", errors="replace")})
                state["label"] = "python_script"
                return state
            if "audio" in ctype or any(file_name.endswith(ext) for ext in [".mp3", ".wav", ".m4a", ".flac"]) or (label == "audio" and "octet" in ctype):
                print("[DEBUG] Working with an audio attachment file")
                state["context"] = transcribe_audio.invoke({"audio_bytes": blob})
                state["label"] = "audio"
                return state
            if "image" in ctype or any(file_name.endswith(ext) for ext in [".png", ".jpg", ".jpeg", ".gif", ".webp"]) or (label == "image" and "octet" in ctype):
                print("[DEBUG] Working with an image attachment file")
                state["answer"] = describe_image.invoke({"img_bytes": blob, "question": question})
                state["label"] = "image"
                return state
            # Excel / CSV / PDF / other binary
            print("[DEBUG] Working with a data file attachment")
            state["context"] = read_task_file.invoke({"xls_bytes": blob})
            state["label"] = "other_ext"
            return state

    # ---- label-based routing (when no file was fetched) ----------
    if label == "youtube":
        print("[TOOL] youtube_transcript")
        if matched_obj:
            url = re.sub(r'[.,;:!?")\]]+$', '', matched_obj.group(0))
            print(f"[TOOL] fetching transcript for: {url}")
            transcript = get_youtube_transcript.invoke({"video_url": url})
            if transcript and transcript != "TRANSCRIPT_UNAVAILABLE":
                state["context"] = transcript
            else:
                # Fallback: search web using the actual question (more informative than URL alone)
                print("[TOOL] Transcript unavailable — searching web for video content")
                search_json = web_search.invoke({"query": question[:150]})
                search_json2 = web_search.invoke({"query": f"youtube video {url}"})
                context_parts = [f"TRANSCRIPT_UNAVAILABLE for {url}."]
                if search_json and search_json != "No search results found.":
                    context_parts.append(f"Question-based search:\n{search_json}")
                if search_json2 and search_json2 != "No search results found.":
                    context_parts.append(f"Video search:\n{search_json2}")
                state["context"] = "\n\n".join(context_parts)
        else:
            print("[TOOL] youtube label but no URL found — falling back to web search")
            state["context"] = web_search.invoke({"query": question})

    elif label in ("image", "audio", "python_script", "other_ext"):
        # File was expected but unavailable — fall back to web research
        print(f"[TOOL] File unavailable for '{label}' question — falling back to web search")
        search_json = web_search.invoke({"query": question[:150]})
        wiki_text = wikipedia_search.invoke({"query": question[:100]})
        context_parts = ["NOTE: The attached file for this question was not available. Answer based on web research."]
        if search_json and search_json != "No search results found.":
            context_parts.append(f"Web search:\n{search_json}")
            try:
                import json as _json
                hits = _json.loads(search_json)
                for hit in hits[:2]:
                    link = hit.get("link", "")
                    if link:
                        page_content = visit_webpage.invoke({"url": link})
                        if page_content and "Could not fetch" not in page_content:
                            context_parts.append(f"Page ({link}):\n{page_content[:12000]}")
            except Exception:
                pass
        if wiki_text and "No Wikipedia results found" not in wiki_text:
            context_parts.append(f"Wikipedia:\n{wiki_text}")
        state["context"] = "\n\n".join(context_parts)

    elif label == "research":
        print("[TOOL] research — multi-step search")
        # Step 1: Generate a focused search query
        search_query_prompt = (
            "Write a short, precise search query (max 10 words) to answer this question. "
            "Include key proper nouns, dates, and specific terms. "
            "Output ONLY the query, nothing else.\n\nQuestion: " + question
        )
        focused_query = _llm_router.invoke(search_query_prompt).content.strip().strip('"').strip("'")
        print(f"[TOOL] search query: {focused_query}")

        # Step 2: Run web search + Wikipedia in parallel
        search_json = web_search.invoke({"query": focused_query})
        wiki_text = wikipedia_search.invoke({"query": focused_query})

        context_parts = []

        # Step 3: Visit top search result URLs to get full page content
        if search_json and search_json != "No search results found.":
            context_parts.append(f"WEB SEARCH RESULTS:\n{search_json}")
            try:
                import json as _json
                hits = _json.loads(search_json)
                # Visit top 2 result URLs for detailed content
                visited = 0
                for hit in hits[:4]:
                    link = hit.get("link", "")
                    if link and visited < 2:
                        page_content = visit_webpage.invoke({"url": link})
                        if page_content and "Could not fetch" not in page_content:
                            context_parts.append(f"\nPAGE CONTENT ({link}):\n{page_content[:15000]}")
                            visited += 1
            except Exception as e:
                print(f"[TOOL] Error visiting search results: {e}")

        if wiki_text and "No Wikipedia results found" not in wiki_text and "failed" not in wiki_text.lower():
            context_parts.append(f"\nWIKIPEDIA:\n{wiki_text}")

        # Step 4: If initial results are thin, try an alternative query
        if not context_parts or all("No " in p or "error" in p.lower() for p in context_parts):
            print("[TOOL] Initial search thin — trying alternative query")
            alt_query = focused_query.replace('"', '').replace("'", "")
            if alt_query != focused_query:
                alt_results = web_search.invoke({"query": alt_query})
                if alt_results and alt_results != "No search results found.":
                    context_parts.append(f"\nALTERNATIVE SEARCH:\n{alt_results}")

        state["context"] = "\n\n".join(context_parts) if context_parts else "No information found from web search or Wikipedia."

    else:
        # Logic / pure reasoning — no search needed
        print("[TOOL] reasoning only (no search)")
        state["context"] = ""
    return state


def _do_research(question: str, query: str | None = None) -> str:
    """Run a research search and return combined context string."""
    import json as _json
    if not query:
        query = question[:120]
    search_json = web_search.invoke({"query": query})
    context_parts = []
    if search_json and search_json != "No search results found.":
        context_parts.append(f"Search results:\n{search_json}")
        try:
            hits = _json.loads(search_json)
            for hit in hits[:2]:
                link = hit.get("link", "")
                if link:
                    page_content = visit_webpage.invoke({"url": link})
                    if page_content and "Could not fetch" not in page_content:
                        context_parts.append(f"Page ({link}):\n{page_content[:12000]}")
        except Exception:
            pass
    return "\n\n".join(context_parts)

def synthesize_response(state: AgentState) -> AgentState:
    # If a tool produced a direct final answer (python execution), skip reasoning
    if state.get("answer") and state["label"] == "python_script":
        print(f"[SYNTHESIZE] skipped — python output: {state['answer'][:200]}")
        return state

    # For image: the vision model already answered, but wrap it through reasoning
    # to extract the precise answer from the description
    if state.get("answer") and state["label"] == "image":
        state["context"] = f"VISION MODEL OUTPUT:\n{state['answer']}"
        state["answer"] = ""  # clear so reasoning runs

    # For other_ext with context (file data), make sure reasoning runs
    if state["label"] == "other_ext" and state.get("context") and not state.get("answer"):
        pass  # context is set, reasoning will run below

    # Pass 1: chain-of-thought reasoning
    reasoning_prompt = [
        SystemMessage(content=get_prompt("reasoning_system")),
        HumanMessage(
            content=get_prompt(
                prompt_key="reasoning_user",
                question=state["question"],
                context=state["context"],
            )
        ),
    ]
    reasoning = _llm_answer.invoke(reasoning_prompt).content.strip()
    print(f"\n[REASONING]\n{reasoning}\n")

    # Try to extract FINAL ANSWER directly from reasoning text
    fa_match = re.search(r"FINAL ANSWER:\s*(.+)", reasoning, re.IGNORECASE)
    if fa_match:
        answer = fa_match.group(1).strip().split('\n')[0].strip()
    elif reasoning.strip():
        extract_prompt = [
            SystemMessage(content=get_prompt("extract_system")),
            HumanMessage(
                content=get_prompt(
                    prompt_key="extract_user",
                    reasoning=reasoning,
                )
            ),
        ]
        answer = _llm_answer.invoke(extract_prompt).content.strip()
    else:
        answer = "ERROR: no reasoning produced"

    # --- SECOND PASS: if answer is vague/uncertain, do more research and retry ---
    _bad = any(w in answer.lower() for w in ["cannot", "unable", "not determine", "no answer", "not possible"])
    if _bad and state["label"] in ("research", "image", "audio", "python_script", "other_ext", "youtube"):
        print(f"[SYNTHESIZE] Answer '{answer[:60]}' is uncertain — doing second research pass")
        # Generate a more targeted query from the first reasoning
        refine_prompt = (
            "Based on this question and partial reasoning, write a very specific search query "
            "(max 12 words) that would find the EXACT missing fact. "
            "Output ONLY the query.\n\n"
            f"Question: {state['question']}\n"
            f"Partial reasoning: {reasoning[:500]}"
        )
        try:
            refined_query = _llm_router.invoke(refine_prompt).content.strip().strip('"').strip("'")
            print(f"[TOOL] second-pass query: {refined_query}")
            extra_context = _do_research(state["question"], refined_query)
            if extra_context:
                combined_context = state["context"] + "\n\nADDITIONAL RESEARCH:\n" + extra_context
                reasoning_prompt2 = [
                    SystemMessage(content=get_prompt("reasoning_system")),
                    HumanMessage(
                        content=get_prompt(
                            prompt_key="reasoning_user",
                            question=state["question"],
                            context=combined_context,
                        )
                    ),
                ]
                reasoning2 = _llm_answer.invoke(reasoning_prompt2).content.strip()
                print(f"\n[REASONING PASS 2]\n{reasoning2}\n")
                fa_match2 = re.search(r"FINAL ANSWER:\s*(.+)", reasoning2, re.IGNORECASE)
                if fa_match2:
                    answer2 = fa_match2.group(1).strip().split('\n')[0].strip()
                    _still_bad = any(w in answer2.lower() for w in ["cannot", "unable", "not determine"])
                    if not _still_bad:
                        answer = answer2
        except Exception as e:
            print(f"[SYNTHESIZE] Second pass error: {e}")

    state["answer"] = answer
    return state

def format_output(state: AgentState) -> AgentState:
    txt = re.sub(r"^(final answer:?\s*)", "", state["answer"], flags=re.I).strip()

    # If question demands a single token (first name / one word), enforce it
    if any(kw in state["question"].lower() for kw in ["first name", "single word"]):
        txt = txt.split(" ")[0]

    state["answer"] = txt.rstrip(".")
    print(f"[FINAL ANSWER] {state['answer']}\n" + "-" * 60)
    return state

# --------------------------------------------------------------------------- #
#                              BUILD  THE  GRAPH                              #
# --------------------------------------------------------------------------- #
def build_graph() -> StateGraph:
    g = StateGraph(AgentState)
    g.set_entry_point("route_question")

    g.add_node("route_question", route_question)
    g.add_node("invoke_tools", call_tools)
    g.add_node("synthesize_response", synthesize_response)
    g.add_node("format_output", format_output)

    g.add_edge("route_question", "invoke_tools")
    g.add_edge("invoke_tools", "synthesize_response")
    g.add_edge("synthesize_response", "format_output")
    g.add_edge("format_output", END)

    return g.compile()

class LGAgent:
    """Callable wrapper used by run_and_submit_all."""

    def __init__(self, model_id: str | None = None, answer_model_id: str | None = None) -> None:
        global _llm_router, _llm_answer
        # Router: fast Groq model
        router_mid = model_id or GROQ_MODELS[0]["model_id"]
        _llm_router = ChatOpenAI(
            model=router_mid,
            base_url="https://api.groq.com/openai/v1",
            api_key=GROQ_API_KEY,
            timeout=60,
        )
        # Answering: higher quality OpenRouter model
        answer_mid = answer_model_id or OPENROUTER_MODELS[0]["model_id"]
        _llm_answer = ChatOpenAI(
            model=answer_mid,
            base_url="https://openrouter.ai/api/v1",
            api_key=OPENROUTER_API_KEY,
            timeout=120,
        )
        self.graph = build_graph()

    def __call__(self, question: str, task_id: str | None = None, file_name: str | None = None) -> str:
        try:
            state: AgentState = {
                "question": question,
                "label": "general",
                "context": "",
                "answer": "",
                "task_id": task_id,
                "file_name": file_name,
            }
            final = self.graph.invoke(state)

            route = final["label"]
            print(f"[ROUTE] '{route}' | Q: {question[:80]}")
            return final["answer"]
        except Exception as e:
            print("Agent error:", e)
            msg = str(e)
            # Re-raise rate-limit errors so _answer_question can fall back to the next model
            if "rate_limit_exceeded" in msg or "429" in msg or "413" in msg or "Request too large" in msg or "model_decommissioned" in msg or "decommissioned" in msg:
                raise
            return f"AGENT ERROR: {e}"

def _parse_retry_after(error_msg: str) -> float:
    """Parse the suggested wait time (seconds) from a Groq 429 error message."""
    m = re.search(r'try again in (?:(\d+)m)?(\d+(?:\.\d+)?)s', error_msg)
    if m:
        return float(m.group(1) or 0) * 60 + float(m.group(2))
    return 65.0  # safe default

def _to_str(val) -> str:
    """Ensure the submitted answer is always a plain string."""
    if isinstance(val, str):
        return val
    if isinstance(val, list):
        parts = [item.get("text", "") if isinstance(item, dict) else str(item) for item in val]
        return " ".join(parts).strip() or "ERROR: empty response"
    return str(val)


def _answer_question(item: dict) -> str:
    """Instantiate a fresh agent and answer one question, retrying on errors."""
    question_text = item["question"]
    task_id = item.get("task_id", "")
    file_name = item.get("file_name") or ""

    augmented_question = question_text

    # Try each OpenRouter answer model with Groq router
    for answer_cfg in OPENROUTER_MODELS:
        answer_model_id = answer_cfg["model_id"]
        if answer_model_id in _exhausted_models:
            print(f"[{answer_model_id}] Skipped (previously rate-limited)")
            continue
        for attempt in range(2):
            try:
                result = LGAgent(
                    model_id=GROQ_MODELS[0]["model_id"],
                    answer_model_id=answer_model_id,
                )(augmented_question, task_id=task_id, file_name=file_name)
                # Pause between questions to respect rate limits
                time.sleep(3)
                return result
            except Exception as e:
                msg = str(e)
                if "model_decommissioned" in msg or "decommissioned" in msg:
                    _exhausted_models.add(answer_model_id)
                    print(f"[{answer_model_id}] Model decommissioned — skipping permanently")
                    break
                if "rate_limit_exceeded" in msg or "429" in msg or "413" in msg or "Request too large" in msg:
                    if "on tokens per day" in msg or "TPD" in msg:
                        _exhausted_models.add(answer_model_id)
                        print(f"[{answer_model_id}] Daily token limit hit — skipping for remaining questions")
                        break
                    wait = _parse_retry_after(msg)
                    print(f"[{answer_model_id}] Rate limited — waiting {wait:.0f}s then retry")
                    time.sleep(min(wait, 30))
                    continue
                else:
                    print(f"[{answer_model_id}] Error: {msg[:200]}")
                    break  # try next model
    return "AGENT ERROR: all models exhausted"

def run_and_submit_all( profile: gr.OAuthProfile | None):
    """
    Fetches all questions, runs the BasicAgent on them, submits all answers,
    and displays the results.
    """
    # --- Determine HF Space Runtime URL and Repo URL ---
    space_id = os.getenv("SPACE_ID") # Get the SPACE_ID for sending link to the code

    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. Agent is instantiated per-question inside _answer_question for parallel execution
    agent_code = f"https://huggingface.co/spaces/{space_id}/tree/main"
    print(agent_code)

    # 2. Fetch Questions
    print(f"Fetching questions from: {questions_url}")
    try:
        response = requests.get(questions_url, timeout=15)
        response.raise_for_status()
        questions_data = response.json()
        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.")
    except requests.exceptions.RequestException as e:
        print(f"Error fetching questions: {e}")
        return f"Error fetching questions: {e}", None
    except requests.exceptions.JSONDecodeError as e:
         print(f"Error decoding JSON response from questions endpoint: {e}")
         print(f"Response text: {response.text[:500]}")
         return f"Error decoding server response for questions: {e}", None
    except Exception as e:
        print(f"An unexpected error occurred fetching questions: {e}")
        return f"An unexpected error occurred fetching questions: {e}", None

    # 3. Run your Agent (parallel)
    results_log = []
    answers_payload = []
    valid_items = [
        item for item in questions_data
        if item.get("task_id") and item.get("question") is not None
    ]
    print(f"Running agent on {len(valid_items)} questions")

    with concurrent.futures.ThreadPoolExecutor(max_workers=MAX_WORKERS) as executor:
        future_to_item = {
            executor.submit(_answer_question, item): item
            for item in valid_items
        }
        for future in concurrent.futures.as_completed(future_to_item):
            item = future_to_item[future]
            task_id = item["task_id"]
            question_text = item["question"]
            try:
                submitted_answer = _to_str(future.result(timeout=QUESTION_TIMEOUT))
            except concurrent.futures.TimeoutError:
                print(f"Timeout on task {task_id}")
                submitted_answer = "TIMEOUT"
            except Exception as e:
                print(f"Error running agent on task {task_id}: {e}")
                submitted_answer = f"AGENT ERROR: {e}"
            answers_payload.append({"task_id": task_id, "submitted_answer": _to_str(submitted_answer)})
            results_log.append({"Task ID": task_id, "Question": question_text, "Submitted Answer": submitted_answer})

    if not answers_payload:
        print("Agent did not produce any answers to submit.")
        return "Agent did not produce any answers to submit.", pd.DataFrame(results_log)

    # 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}")
    try:
        response = requests.post(submit_url, json=submission_data, timeout=60)
        response.raise_for_status()
        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.")
        results_df = pd.DataFrame(results_log)
        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)
        results_df = pd.DataFrame(results_log)
        return status_message, results_df
    except requests.exceptions.Timeout:
        status_message = "Submission Failed: The request timed out."
        print(status_message)
        results_df = pd.DataFrame(results_log)
        return status_message, results_df
    except requests.exceptions.RequestException as e:
        status_message = f"Submission Failed: Network error - {e}"
        print(status_message)
        results_df = pd.DataFrame(results_log)
        return status_message, results_df
    except Exception as e:
        status_message = f"An unexpected error occurred during submission: {e}"
        print(status_message)
        results_df = pd.DataFrame(results_log)
        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)
    # Removed max_rows=10 from DataFrame constructor
    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)
    # Check for SPACE_HOST and SPACE_ID at startup for information
    space_host_startup = os.getenv("SPACE_HOST")
    space_id_startup = os.getenv("SPACE_ID") # Get SPACE_ID at startup

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

    if space_id_startup: # Print repo URLs if SPACE_ID is found
        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.launch(debug=True, share=False)