File size: 23,283 Bytes
10e9b7d
57072d8
 
05240d7
57072d8
05240d7
57072d8
 
10e9b7d
eccf8e4
3c4371f
57072d8
 
 
 
 
 
 
 
 
 
10e9b7d
3db6293
e80aab9
57072d8
 
 
 
 
 
 
 
 
 
 
 
05240d7
57072d8
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
05240d7
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
57072d8
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
05240d7
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
57072d8
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
05240d7
57072d8
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
05240d7
 
57072d8
 
 
 
 
 
 
 
 
 
 
05240d7
 
57072d8
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
31243f4
 
57072d8
 
31243f4
57072d8
31243f4
57072d8
4021bf3
57072d8
 
 
 
 
 
 
 
 
 
 
 
 
 
 
05240d7
 
57072d8
 
 
 
 
 
 
 
 
 
 
3c4371f
7e4a06b
57072d8
3c4371f
7e4a06b
3c4371f
7d65c66
3c4371f
7e4a06b
31243f4
 
e80aab9
31243f4
 
 
3c4371f
31243f4
57072d8
 
 
 
 
 
c1fd3d2
3c4371f
31243f4
eccf8e4
31243f4
7d65c66
31243f4
57072d8
31243f4
57072d8
 
 
31243f4
e80aab9
31243f4
 
57072d8
 
 
7d65c66
31243f4
 
e80aab9
7d65c66
 
57072d8
3c4371f
31243f4
 
 
57072d8
31243f4
 
 
57072d8
31243f4
7d65c66
57072d8
 
 
 
 
 
 
 
 
 
31243f4
57072d8
 
 
 
 
 
 
 
31243f4
 
3c4371f
31243f4
 
57072d8
 
 
 
 
 
 
 
 
31243f4
e80aab9
31243f4
e80aab9
7d65c66
e80aab9
 
57072d8
31243f4
e80aab9
 
3c4371f
 
 
e80aab9
57072d8
e80aab9
31243f4
 
57072d8
e80aab9
3c4371f
e80aab9
 
3c4371f
57072d8
7d65c66
57072d8
3c4371f
31243f4
7d65c66
31243f4
57072d8
3c4371f
 
 
 
 
57072d8
e80aab9
31243f4
 
 
 
57072d8
7d65c66
31243f4
 
 
 
e80aab9
 
 
31243f4
0ee0419
e514fd7
 
57072d8
 
 
e514fd7
 
57072d8
e514fd7
e80aab9
 
7e4a06b
e80aab9
31243f4
e80aab9
57072d8
 
 
 
 
7d65c66
e80aab9
31243f4
 
57072d8
e80aab9
 
57072d8
e80aab9
57072d8
 
3c4371f
57072d8
7d65c66
3c4371f
 
7d65c66
3c4371f
7d65c66
 
57072d8
7d65c66
 
 
 
 
 
57072d8
31243f4
05240d7
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
import os
import json
import ast
import re
import operator as op
from pathlib import Path
from typing import TypedDict, Annotated, Dict, List

import gradio as gr
import requests
import pandas as pd
from dotenv import load_dotenv
from tavily import TavilyClient

from langchain.tools import tool
from langchain_openai import ChatOpenAI
from langchain_core.messages import SystemMessage, HumanMessage, AnyMessage, RemoveMessage
from langgraph.graph.message import add_messages, REMOVE_ALL_MESSAGES
from langgraph.graph import START, END, StateGraph
from langgraph.prebuilt import ToolNode


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

load_dotenv()

OPENAI_API_KEY = os.getenv("OPENAI_API_KEY")
TAVILY_API_KEY = os.getenv("TAVILY_API_KEY")

if not OPENAI_API_KEY:
    raise ValueError("OPENAI_API_KEY is missing")

if not TAVILY_API_KEY:
    raise ValueError("TAVILY_API_KEY is missing")

tavily_client = TavilyClient(TAVILY_API_KEY)
WORKSPACE_ROOT = Path(__file__).resolve().parent


class GaiaState(TypedDict):
    original_question: str
    subquestions: List[str]
    current_subquestion_index: int
    subanswers: Dict[str, str]
    final_answer: str
    messages: Annotated[list[AnyMessage], add_messages]


_ALLOWED_OPERATORS = {
    ast.Add: op.add,
    ast.Sub: op.sub,
    ast.Mult: op.mul,
    ast.Div: op.truediv,
    ast.USub: op.neg,
    ast.UAdd: op.pos,
}


def _safe_eval(node):
    if isinstance(node, ast.Expression):
        return _safe_eval(node.body)
    if isinstance(node, ast.Constant):
        if isinstance(node.value, (int, float)):
            return node.value
        raise ValueError("Only numeric constants are allowed")
    if isinstance(node, ast.Num):
        return node.n
    if isinstance(node, ast.BinOp):
        if type(node.op) not in _ALLOWED_OPERATORS:
            raise ValueError("Unsupported operation")
        left = _safe_eval(node.left)
        right = _safe_eval(node.right)
        if isinstance(node.op, ast.Div) and right == 0:
            raise ValueError("Division by zero")
        return _ALLOWED_OPERATORS[type(node.op)](left, right)
    if isinstance(node, ast.UnaryOp):
        if type(node.op) not in _ALLOWED_OPERATORS:
            raise ValueError("Unsupported unary operation")
        operand = _safe_eval(node.operand)
        return _ALLOWED_OPERATORS[type(node.op)](operand)
    raise ValueError("Invalid expression")


def _truncate_text(value: str, max_chars: int = 6000) -> str:
    if len(value) <= max_chars:
        return value
    return value[:max_chars] + "\n...[truncated]..."


def _extract_json_block(text: str):
    text = text.strip()
    if text.startswith("```"):
        text = re.sub(r"^```(?:json)?\s*", "", text)
        text = re.sub(r"\s*```$", "", text)
    match = re.search(r"\{.*\}", text, re.DOTALL)
    if match:
        return json.loads(match.group(0))
    return json.loads(text)


def _resolve_workspace_path(path_str: str) -> Path:
    candidate = Path(path_str).expanduser()
    if not candidate.is_absolute():
        candidate = (WORKSPACE_ROOT / candidate).resolve()
    else:
        candidate = candidate.resolve()
    if WORKSPACE_ROOT not in candidate.parents and candidate != WORKSPACE_ROOT:
        raise ValueError("Path must be inside the workspace")
    return candidate


@tool
def calculator(expression: str) -> str:
    """
    Evaluate a mathematical expression safely.
    Supports numbers, parentheses, +, -, *, /, and unary +/-.
    Returns the result as a string.
    """
    try:
        parsed = ast.parse(expression, mode="eval")
        result = _safe_eval(parsed)
        if isinstance(result, float) and result.is_integer():
            result = int(result)
        return str(result)
    except Exception as e:
        return f"Error: {e}"


@tool
def web_search(query: str) -> str:
    """
    Search the web for up-to-date information relevant to a question.
    Returns top search results with titles, URLs, and snippets.
    """
    try:
        search_response = tavily_client.search(query, max_results=5)
        results = search_response.get("results", [])

        if not results:
            return f"No search results found for query: {query}"

        formatted_results = [f"Search query: {query}", "", "Top results:"]

        for i, result in enumerate(results, start=1):
            title = result.get("title", "No title")
            url = result.get("url", "No URL")
            content = result.get("content", "No snippet available")
            formatted_results.append(
                f"{i}. {title}\nURL: {url}\nSnippet: {content}\n"
            )

        return "\n".join(formatted_results)
    except Exception as e:
        return f"Web search error: {e}"


@tool
def list_local_files() -> str:
    """
    List local files in the workspace so you can inspect attachments such as Excel, CSV, JSON, or text files.
    """
    allowed_suffixes = {
        ".xlsx", ".xls", ".csv", ".tsv", ".json", ".txt", ".md",
        ".pdf", ".png", ".jpg", ".jpeg", ".parquet"
    }
    files = []
    for path in WORKSPACE_ROOT.rglob("*"):
        if path.is_file() and path.suffix.lower() in allowed_suffixes:
            try:
                relative_path = path.relative_to(WORKSPACE_ROOT)
            except ValueError:
                relative_path = path
            files.append(str(relative_path))
    if not files:
        return "No supported local files found in the workspace."
    return "Local files:\n" + "\n".join(sorted(files))


@tool
def read_local_file(path: str) -> str:
    """
    Read a local file from the workspace. Supports text, JSON, CSV/TSV, and Excel files.
    For spreadsheets, this returns sheet names, preview rows, column names, and numeric column sums when possible.
    """
    try:
        resolved_path = _resolve_workspace_path(path)
        if not resolved_path.exists():
            return f"File not found: {path}"

        suffix = resolved_path.suffix.lower()

        if suffix in {".txt", ".md", ".json"}:
            content = resolved_path.read_text(encoding="utf-8", errors="replace")
            if suffix == ".json":
                try:
                    parsed = json.loads(content)
                    content = json.dumps(parsed, indent=2, ensure_ascii=True)
                except Exception:
                    pass
            return _truncate_text(content)

        if suffix in {".csv", ".tsv"}:
            sep = "\t" if suffix == ".tsv" else ","
            df = pd.read_csv(resolved_path, sep=sep)
            summary = [
                f"File: {resolved_path.name}",
                f"Columns: {', '.join(str(col) for col in df.columns)}",
                f"Rows: {len(df)}",
                "",
                "Preview:",
                df.head(20).to_csv(index=False),
            ]
            numeric_df = df.select_dtypes(include="number")
            if not numeric_df.empty:
                summary.extend(
                    [
                        "",
                        "Numeric column sums:",
                        numeric_df.sum(numeric_only=True).to_string(),
                    ]
                )
            return _truncate_text("\n".join(summary))

        if suffix in {".xlsx", ".xls"}:
            excel_file = pd.ExcelFile(resolved_path)
            output_parts = [f"File: {resolved_path.name}", f"Sheets: {', '.join(excel_file.sheet_names)}"]
            for sheet_name in excel_file.sheet_names[:5]:
                df = excel_file.parse(sheet_name)
                output_parts.extend(
                    [
                        "",
                        f"Sheet: {sheet_name}",
                        f"Columns: {', '.join(str(col) for col in df.columns)}",
                        f"Rows: {len(df)}",
                        "Preview:",
                        df.head(20).to_csv(index=False),
                    ]
                )
                numeric_df = df.select_dtypes(include="number")
                if not numeric_df.empty:
                    output_parts.extend(
                        [
                            "Numeric column sums:",
                            numeric_df.sum(numeric_only=True).to_string(),
                        ]
                    )
            return _truncate_text("\n".join(output_parts))

        return f"Unsupported file type for reading: {suffix}"
    except Exception as e:
        return f"File read error: {e}"


tools = [web_search, calculator, list_local_files, read_local_file]
tool_node = ToolNode(tools)


def get_model(temperature: float = 0):
    return ChatOpenAI(
        model="gpt-4.1-mini",
        temperature=temperature,
        api_key=OPENAI_API_KEY,
    )


def planner(state: GaiaState):
    model = get_model()

    prompt = """You are an expert problem decomposition agent.
Your job is to analyze a question and decide whether it should be decomposed into smaller subquestions.
Rules:
1. If the question is simple and can be answered directly, return a single subquestion equal to the original question.
2. If the question requires multiple reasoning steps, break it into clear atomic subquestions.
3. Each subquestion should be answerable independently using tools such as web search or calculation.
4. Do NOT answer the question yourself.
5. Only produce subquestions needed to solve the problem.
Output format (JSON only):
{
  "subquestions": [
    "subquestion 1",
    "subquestion 2"
  ]
}
Do not include explanations.
Do not include text outside the JSON."""

    messages = [
        SystemMessage(content=prompt),
        HumanMessage(content=state["original_question"]),
    ]

    response = model.invoke(messages)

    subquestions = []
    try:
        content = response.content if isinstance(response.content, str) else str(response.content)
        parsed = _extract_json_block(content)
        subquestions = parsed.get("subquestions", [])
    except Exception:
        subquestions = []

    if not isinstance(subquestions, list) or not subquestions:
        subquestions = [state["original_question"]]

    subquestions = [str(q).strip() for q in subquestions if str(q).strip()]

    if not subquestions:
        subquestions = [state["original_question"]]

    return {
        "subquestions": subquestions,
        "current_subquestion_index": 0,
    }


def answer_subquestion(state: GaiaState):
    current_index = state["current_subquestion_index"]
    current_subquestion = state["subquestions"][current_index]

    solver_model = get_model().bind_tools(tools)

    if not state["messages"]:
        prompt = """You are a research assistant solving a complex question.
You may use tools when necessary to obtain information or perform calculations.
Use tools when:
- the answer requires up-to-date information
- the answer requires external data
- the answer requires arithmetic computation
- the answer depends on a local attachment such as an Excel, CSV, JSON, or text file
When local files may be relevant, first use list_local_files and then read_local_file.
If you already know the answer with high confidence, answer directly.
Be concise and accurate."""

        messages = [
            SystemMessage(content=prompt),
            HumanMessage(content=current_subquestion),
        ]
    else:
        messages = state["messages"]

    response = solver_model.invoke(messages)
    if not state["messages"]:
        return {"messages": messages + [response]}
    return {"messages": [response]}


def route_after_llm(state: GaiaState):
    last_message = state["messages"][-1]
    if getattr(last_message, "tool_calls", None):
        return "tools"
    return "store_subanswer"


def store_subanswer(state: GaiaState):
    current_index = state["current_subquestion_index"]
    next_index = current_index + 1
    current_subquestion = state["subquestions"][current_index]
    last_message = state["messages"][-1]

    answer_text = last_message.content
    if isinstance(answer_text, list):
        answer_text = " ".join(str(x) for x in answer_text)
    else:
        answer_text = str(answer_text)

    updated_subanswers = dict(state["subanswers"])
    updated_subanswers[current_subquestion] = answer_text.strip()

    return {
        "current_subquestion_index": next_index,
        "subanswers": updated_subanswers,
        "messages": [RemoveMessage(id=REMOVE_ALL_MESSAGES)],
    }


def route_subquestion_loop(state: GaiaState):
    if state["current_subquestion_index"] < len(state["subquestions"]):
        return "answer_subquestion"
    return "final_answer"


def final_answer(state: GaiaState):
    model = get_model()

    prompt = """You are a general AI assistant. I will give you an original question and a set of subquestions with their answers. You must formulate one final answer based only on that information.
Finish your answer with the following template exactly:
FINAL ANSWER: [YOUR FINAL ANSWER]
YOUR FINAL ANSWER should be:
- a number, OR
- as few words as possible, OR
- a comma separated list of numbers and/or strings
Rules:
- If asked for a number, do not use commas in the number and do not use units unless explicitly requested.
- If asked for a string, do not use articles and do not use abbreviations unless explicitly requested.
- If asked for a comma separated list, apply the same rules to each element.
- Do not add anything after FINAL ANSWER."""

    question_answer = ""
    for question, answer in state["subanswers"].items():
        question_answer += f"Question: {question}\nAnswer: {answer}\n\n"

    user_content = (
        f"Original question: {state['original_question']}\n\n"
        f"Subquestion answers:\n{question_answer}"
    )

    messages = [
        SystemMessage(content=prompt),
        HumanMessage(content=user_content),
    ]

    response = model.invoke(messages)

    content = response.content
    if isinstance(content, list):
        content = " ".join(str(x) for x in content)
    else:
        content = str(content)

    return {"final_answer": content.strip()}


def build_graph():
    builder = StateGraph(GaiaState)

    builder.add_node("planner", planner)
    builder.add_node("answer_subquestion", answer_subquestion)
    builder.add_node("tools", tool_node)
    builder.add_node("store_subanswer", store_subanswer)
    builder.add_node("final_answer", final_answer)

    builder.add_edge(START, "planner")
    builder.add_edge("planner", "answer_subquestion")
    builder.add_edge("tools", "answer_subquestion")
    builder.add_edge("final_answer", END)

    builder.add_conditional_edges(
        "answer_subquestion",
        route_after_llm,
        {
            "tools": "tools",
            "store_subanswer": "store_subanswer",
        },
    )

    builder.add_conditional_edges(
        "store_subanswer",
        route_subquestion_loop,
        {
            "answer_subquestion": "answer_subquestion",
            "final_answer": "final_answer",
        },
    )

    return builder.compile()


class BasicAgent:
    def __init__(self):
        print("Initializing BasicAgent...")
        self.graph = build_graph()
        print("BasicAgent initialized.")

    def __call__(self, question: str) -> str:
        print(f"Agent received question (first 100 chars): {question[:100]}")

        initial_state: GaiaState = {
            "original_question": question,
            "subquestions": [],
            "current_subquestion_index": 0,
            "subanswers": {},
            "final_answer": "",
            "messages": [],
        }

        result = self.graph.invoke(initial_state)
        answer = str(result.get("final_answer", "")).strip()

        if "FINAL ANSWER:" in answer:
            answer = answer.split("FINAL ANSWER:", 1)[1].strip()

        answer = answer.splitlines()[0].strip()

        answer = answer.strip().strip('"').strip("'")

        if not answer:
            answer = "Unable to determine answer"

        print(f"Agent returning answer: {answer}")
        return answer


def run_and_submit_all(profile: gr.OAuthProfile | None):
    space_id = os.getenv("SPACE_ID")

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

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

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

    if space_id:
        agent_code = f"https://huggingface.co/spaces/{space_id}/tree/main"
    else:
        agent_code = ""

    print(agent_code)

    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 ValueError as e:
        print(f"Error decoding JSON response from questions endpoint: {e}")
        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

    results_log = []
    answers_payload = []

    print(f"Running agent on {len(questions_data)} questions...")
    for item in questions_data:
        task_id = item.get("task_id")
        question_text = item.get("question")

        if not task_id or question_text is None:
            print(f"Skipping item with missing task_id or question: {item}")
            continue

        try:
            submitted_answer = agent(question_text)
            answers_payload.append(
                {"task_id": task_id, "submitted_answer": submitted_answer}
            )
            results_log.append(
                {
                    "Task ID": task_id,
                    "Question": question_text,
                    "Submitted Answer": submitted_answer,
                }
            )
        except Exception as e:
            print(f"Error running agent on task {task_id}: {e}")
            results_log.append(
                {
                    "Task ID": task_id,
                    "Question": question_text,
                    "Submitted Answer": f"AGENT ERROR: {e}",
                }
            )

    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)

    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)

    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 ValueError:
            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


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.
        """
    )

    gr.LoginButton()

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

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

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


if __name__ == "__main__":
    print("\n" + "-" * 30 + " App Starting " + "-" * 30)

    space_host_startup = os.getenv("SPACE_HOST")
    space_id_startup = os.getenv("SPACE_ID")

    if space_host_startup:
        print(f"✅ SPACE_HOST found: {space_host_startup}")
        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(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)