File size: 23,257 Bytes
2db8573
10e9b7d
2db8573
0557a16
e7531c4
 
10e9b7d
3c4371f
2db8573
c08f4ef
f953341
 
 
7585561
 
 
f953341
c29231a
2348b3b
 
 
 
 
8f44ac3
c29231a
2348b3b
f8bcd4c
e7531c4
 
2db8573
4a48ae7
e7531c4
ca746c3
d59f015
e80aab9
3db6293
e80aab9
2db8573
d868033
d59f015
2db8573
e7e8f66
e7531c4
2c4372e
e7531c4
 
 
 
a76fad9
 
 
 
 
 
 
05a498f
68d5475
ad8315c
3845494
a76fad9
 
 
 
 
 
 
6647079
 
95edf61
a76fad9
d1e9c01
a76fad9
e7531c4
e7e8f66
 
 
7585561
a465c33
e7e8f66
2348b3b
0557a16
3023bae
8f44ac3
d1e9c01
e7e8f66
 
 
 
4968835
e7e8f66
 
f747f57
d4f92d3
c29231a
8f44ac3
d1e9c01
c29231a
e7e8f66
65c1e6d
e7e8f66
 
f747f57
 
c29231a
a30a657
d1e9c01
e7e8f66
 
 
d4f92d3
c29231a
bd14aba
 
c29231a
 
8f44ac3
a944500
bd14aba
e7e8f66
 
 
c29231a
e7e8f66
 
f747f57
a465c33
f747f57
e7e8f66
 
 
f747f57
a465c33
e7e8f66
 
0557a16
3023bae
8f44ac3
d1e9c01
e7e8f66
 
0557a16
e7e8f66
bd14aba
7585561
 
 
2348b3b
 
13ded9e
 
 
e7e8f66
f747f57
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
0557a16
c69e5e1
0557a16
 
 
 
 
e7e8f66
8f44ac3
9f197ec
f953341
090d793
 
 
 
 
 
 
 
 
 
 
 
 
 
 
941a7a5
f953341
8e46c39
7585561
e69f0ff
090d793
e69f0ff
 
8e46c39
 
 
 
 
 
 
 
 
 
f953341
 
 
 
7585561
f953341
090d793
f953341
 
 
 
 
 
 
 
a0753ba
f953341
8f44ac3
 
d1e9c01
 
 
7585561
d1e9c01
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
c29231a
f22398a
f8bcd4c
 
f22398a
c29231a
8f44ac3
c08f4ef
 
c29231a
 
 
a465c33
c29231a
 
 
 
e94d38d
 
 
f567e8a
e94d38d
 
 
 
 
 
 
 
 
 
 
c29231a
 
 
 
3023bae
c29231a
 
4021bf3
d4f92d3
 
75e3006
c29231a
a6791cd
95edf61
a6791cd
 
d1e9c01
 
d4f92d3
 
 
 
c29231a
8f44ac3
d1e9c01
d4f92d3
 
 
 
 
 
 
 
 
 
c29231a
 
 
 
 
 
8f44ac3
c29231a
 
 
 
 
 
 
8f44ac3
 
 
 
 
 
d1e9c01
 
 
 
 
 
 
d4f92d3
 
 
c29231a
 
 
8f44ac3
d4f92d3
 
2db8573
 
31243f4
 
 
 
7d65c66
2db8573
3c4371f
7e4a06b
2db8573
3c4371f
7e4a06b
3c4371f
7d65c66
3c4371f
7e4a06b
31243f4
 
e80aab9
b177367
31243f4
 
 
3c4371f
31243f4
b177367
36ed51a
c1fd3d2
3c4371f
7d65c66
31243f4
4a48ae7
eccf8e4
31243f4
7d65c66
31243f4
 
2db8573
 
31243f4
3c4371f
2db8573
4a48ae7
 
2db8573
4a48ae7
 
 
7d65c66
31243f4
 
e80aab9
b177367
7d65c66
 
3c4371f
a1a612c
31243f4
 
 
 
 
 
090d793
2db8573
 
 
 
 
 
 
 
 
 
31243f4
2db8573
 
 
 
 
 
 
 
31243f4
 
3c4371f
31243f4
 
2db8573
 
 
 
 
 
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
2db8573
 
 
7d65c66
 
e80aab9
2db8573
e80aab9
 
2db8573
7d65c66
3c4371f
2db8573
7d65c66
3c4371f
 
7d65c66
3c4371f
7d65c66
 
2db8573
7d65c66
 
2db8573
 
 
7d65c66
2db8573
 
 
7d65c66
2db8573
3c4371f
31243f4
8851a45
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
import inspect
import os

import re
from typing import Any, Dict, List, Optional, TypedDict

import gradio as gr
import pandas as pd
import requests

import wikipedia
import wikipediaapi
from bs4 import BeautifulSoup
from langchain_community.retrievers import WikipediaRetriever
from langchain_community.tools import DuckDuckGoSearchRun, WikipediaQueryRun
from langchain_community.utilities import WikipediaAPIWrapper

from langchain_core import messages
from langchain_core.messages import (
    BaseMessage,
    ChatMessage,
    HumanMessage,
    SystemMessage,
    ToolCall,
    ToolMessage,
)
from langchain_google_community.search import GoogleSearchAPIWrapper
from langchain_openai import ChatOpenAI
from langgraph.graph import END, START, StateGraph


hf_token = os.getenv("OPENAI_API_KEY")

# (Keep Constants as is)
# --- Constants ---
DEFAULT_API_URL = "https://agents-course-unit4-scoring.hf.space"


# --- Basic Agent Definition  ---
# ----- THIS IS WERE YOU CAN BUILD WHAT YOU WANT ------

PROMPT = """
You are a general AI assistant. I will ask you a question.
Report your thoughts,always use at least 2 sources to double check your answer, and finish your answer with the following template: 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.
If you are asked for a number, don't use comma to write your number neither use units such as $ or percent sign unless specified otherwise.
If you are asked for a string, don't use articles, neither abbreviations (e.g. for cities), and write the digits in plain text unless specified otherwise.
If you are asked for a comma separated list, apply the above rules depending of whether the element to be put in the list is a number or a string.

Use the following process to answer the question:
1. Analyze and Plan:
Extract ALL Parameters Identify search terms, URLs, code, file paths
Plan Steps: Break down the problem into logical steps required to reach the final answer
2. Delegate Strategically
For each step, choose the best  Agent Tool. Call the tool with a single string argument `request` containing ALL information the specialist needs
Available Tools: `DuckDuckGoSearchAgent`, `CodeExecutorAgent`, `WikipediaAgent`
- For wikipedia searches, **strongly prefer** `WikipediaAgent` formatting the query like WikipediaAgent(`request`='search query'), if duckduckgosearchagent is not providing the exact information but its response can be used to refine a wikipedia query, try doing that as well
- For general web searches, **strongly prefer** `DuckDuckGoSearchAgent` formatting the query like DuckDuckGoSearchAgent(`request`='search query') where search query is very specific
- For standard Python code execution, **strongly prefer** `CodeExecutorAgent` formatting the query like  CodeExecutorAgent(`request`='python code')

3. Synthesize Results:
Combine the information obtained from the specialist agents
Perform any final reasoning or calculation steps needed based on the collected data
Double-check that the synthesized answer directly addresses the original question and respects ALL specific formatting or content details requested (e.g., rounding, order, units IF asked for).\n"

4. Format Output:
Last sentence should of your response shoule either:
- start **EXACTLY** with `FINAL ANSWER: ` followed by the answer.
- OR start **EXACTLY** with `TOOL: ` followed by the tool name and the request to the tool, example `TOOL: DuckDuckGoSearchAgent(request='search query')`

Before answering reread the question and make sure you are answering the exact question asked.
"""


class AnswerState(TypedDict):
    question: str
    task_id: str
    attempt: int
    answer: Optional[str]
    messages: List[BaseMessage]
    is_final_answer: bool
    search_request: Optional[str]
    wiki_request: Optional[str]
    python_request: Optional[str]


class BasicAgent:
    def __init__(self):
        self.model = ChatOpenAI(model="gpt-4o", temperature=0.0)
        self.graph = StateGraph(AnswerState)
        self.graph.add_node("log_question", self.log_question)
        self.graph.add_node("get_attachment", self.get_attachment)
        self.graph.add_node("invoke_model", self.invoke_model)
        self.graph.add_node("web_search", self.web_search)
        self.graph.add_node("wiki_search", self.wiki_search)
        self.graph.add_node("python_exec", self.python_exec)
        self.graph.add_node("decide", self.decide)
        self.graph.add_node("final_answer", self.final_answer)
        self.graph.add_node("exceeded_attempts", self.exceeded_attempts)

        self.graph.add_edge(START, "log_question")
        self.graph.add_edge("log_question", "get_attachment")
        self.graph.add_edge("get_attachment", "invoke_model")
        self.graph.add_edge("web_search", "invoke_model")
        self.graph.add_edge("wiki_search", "invoke_model")
        self.graph.add_edge("python_exec", "invoke_model")

        # Add conditional edges
        self.graph.add_conditional_edges(
            "invoke_model",
            self.decide,
            {
                "FINAL_ANSWER": "final_answer",
                "EXCEEDED_ATTEMPTS": "exceeded_attempts",
                "WEB_SEARCH": "web_search",
                "WIKI_SEARCH": "wiki_search",
                "PYTHON_EXEC": "python_exec",
            },
        )

        self.graph.add_edge("final_answer", END)
        self.graph.add_edge("exceeded_attempts", END)
        self.compiled_graph = self.graph.compile()

    def __call__(self, task_id: str, question: str) -> str:

        print(f"Agent received question (first 50 chars) {task_id}: {question[:50]}...")
        res = self.compiled_graph.invoke(
            {
                "question": question,
                "task_id": task_id,
                "attempt": 0,
                "answer": None,
                "messages": [],
                "is_final_answer": False,
                "search_request": None,
                "wiki_request": None,
                "python_request": None,
            }
        )
        return res.get("answer", "N/A")

    def log_question(self, state: AnswerState) -> Dict[str, Any]:
        print(
            f"[log_question] Agent received question {state['task_id']}: {state['question']}..."
        )
        state["messages"] = [SystemMessage(content=PROMPT)]
        state["messages"].append(HumanMessage(content="Question: " + state["question"]))
        return {
            "messages": state["messages"],
        }

    def get_attachment(self, state: AnswerState) -> Dict[str, Any]:
        print(f"[get_attachment] getting attachment for: {state['task_id']}...")
        api_url = DEFAULT_API_URL
        file_url = f"{api_url}/files/{state['task_id']}"

        try:
            response = requests.get(file_url, timeout=15)
            response.raise_for_status()
            data = response.text
            state["messages"].append(HumanMessage(content="Attachment: " + data))
            return {
                "messages": state["messages"],
            }

        except Exception as e:
            print(f"An unexpected error occurred fetching attachment: {e}")
            return {}

    def final_answer(self, state: AnswerState) -> Dict[str, Any]:
        print(f"[final_answer] Agent returning answer: {state['answer']}")
        answer = state["answer"] if state["answer"] else "I don't know"
        return {
            "answer": answer,
            "is_final_answer": True,
        }

    def wiki_search(self, state: AnswerState) -> Dict[str, Any]:
        print("[wiki_search] Searching for: " + str(state["wiki_request"]))

        # wikipedia.set_lang("en")
        # page_titles = wikipedia.search(state["wiki_request"], results=1)
        # print("[wiki_search] Fetching the whole page")
        # wiki = wikipediaapi.Wikipedia(language="en", user_agent="gaia_example")
        # page = wiki.page(page_titles[0])
        # if page.exists():
        #     html_url = f"https://en.wikipedia.org/wiki/{page.title.replace(' ', '_')}"
        #     html = requests.get(html_url).text
        #     soup = BeautifulSoup(html, "html.parser")
        #     state["messages"].append(
        #         ChatMessage(
        #             role="user", content="WikipediaAgent tool results are: " + str(html)
        #         )
        #     )
        #     return {"messages": state["messages"]}

        print("[wiki_search] Fetching the page via wikiRetriever")
        wiki_tool = WikipediaRetriever(
            wiki_client=wikipedia,
            top_k_results=1,
            doc_content_chars_max=50000,
            load_all_available_meta=True,
        )
        results = wiki_tool.invoke(str(state["wiki_request"]))
        if results:
            print(f"Wiki results: {results[0].page_content}")
            state["messages"].append(
                ChatMessage(
                    role="user",
                    content="WikipediaAgent tool results are: "
                    + results[0].page_content,
                )
            )
            return {"messages": state["messages"]}

        print("[wiki_search] Fetching the page via WikipediaAPIWrapper")
        wiki_tool = WikipediaAPIWrapper(
            wiki_client=wikipedia,
            top_k_results=1,
            doc_content_chars_max=50000,
            load_all_available_meta=True,
        )
        results = wiki_tool.run(str(state["wiki_request"]))
        print(f"Wiki results: {results}")
        state["messages"].append(
            ChatMessage(
                role="user",
                content="WikipediaAgent tool results are: " + results,
            )
        )
        return {"messages": state["messages"]}

    def python_exec(self, state: AnswerState) -> Dict[str, Any]:
        print("[python_exec] Executing: " + str(state["python_request"]))
        import contextlib
        import io

        # Redirect stdout to capture output
        output = io.StringIO()
        sandbox_globals = {}
        sandbox_locals = {}

        with contextlib.redirect_stdout(output):
            exec(str(state["python_request"]), sandbox_globals, sandbox_locals)

        res = output.getvalue()
        print(f"Python results: {res}")
        state["messages"].append(
            ChatMessage(
                role="user",
                content="CodeExecutorAgent tool results are: " + res,
            )
        )
        return {"messages": state["messages"]}

    def web_search(self, state: AnswerState) -> Dict[str, Any]:
        print("[web_search] Searching for: " + str(state["search_request"]))
        search_tool = GoogleSearchAPIWrapper()
        results = search_tool.run(str(state["search_request"]))
        print(f"Search results: {results}")
        state["messages"].append(
            ChatMessage(
                role="user",
                content="DuckDuckGoSearchAgent tool results are: " + results,
            )
        )
        return {"messages": state["messages"]}

    def exceeded_attempts(self, state: AnswerState) -> Dict[str, Any]:
        print(
            f"[exceeded_attempts] Exceeded max number of attempts ({state['attempt']})."
        )
        state["messages"].append(
            ChatMessage(
                role="user",
                content="Based on the information provided and your internal knowledge, please provide a final answer, no tool calls allowed.",
            )
        )
        response = self.model.invoke(state["messages"])
        if "FINAL ANSWER:" in response.content:
            answer = response.text().split("FINAL ANSWER:")[-1].strip()
            print(f"Agent final answer: {answer}")

            return {
                "answer": answer,
                "is_final_answer": True,
            }
        return {
            "answer": "Exceeded max number of attempts.",
            "is_final_answer": False,
        }

    def decide(self, state: AnswerState) -> str:
        print("[parse_response] parsing last chat response")

        if state["is_final_answer"]:
            return "FINAL_ANSWER"
        elif state["attempt"] > 4:
            return "EXCEEDED_ATTEMPTS"
        elif state["search_request"]:
            return "WEB_SEARCH"
        elif state["wiki_request"]:
            return "WIKI_SEARCH"
        elif state["python_request"]:
            return "PYTHON_EXEC"
        return "FINAL_ANSWER"

    def invoke_model(self, state: AnswerState) -> Dict[str, Any]:
        print("[invoke_model] Agent trying to answer")
        state["search_request"] = None
        state["wiki_request"] = None
        state["python_request"] = None

        response = self.model.invoke(state["messages"])
        print(f"Agent response: {response.content}")
        state["messages"].append(
            ChatMessage(
                role="assistant",
                content=response.content,
            )
        )

        if "FINAL ANSWER:" in response.content:
            answer = response.text().split("FINAL ANSWER:")[-1].strip()
            print(f"Agent final answer: {answer}")
            print(f"Agent returning answer: {state['answer']}")
            state["answer"] = answer
            state["is_final_answer"] = True
        elif "TOOL: DuckDuckGoSearchAgent" in response.content:
            request_full = (
                response.text().split("TOOL: DuckDuckGoSearchAgent(")[-1].strip(")")
            )
            print(f"Tool invocation request: {request_full}")
            request = request_full.split("request=")[-1].strip("'")
            print(f"Search request: {request}")
            state["search_request"] = request
        elif "TOOL: WikipediaAgent" in response.content:
            request_full = response.text().split("TOOL: WikipediaAgent(")[-1].strip(")")
            print(f"Tool invocation request: {request_full}")
            request = request_full.split("request=")[-1].strip("'")
            print(f"Wiki request: {request}")
            state["wiki_request"] = request

        elif "TOOL: CodeExecutorAgent" in response.content:
            request_full = response.text().split("TOOL: WikipediaAgent(")[-1].strip(")")
            print(f"Tool invocation request: {request_full}")
            request = request_full.split("request=")[-1].strip("'")
            print(f"Python request: {request}")
            state["python_request"] = request
        return {
            "messages": state["messages"],
            "attempt": state.get("attempt", 0) + 1,
            "answer": state["answer"],
            "is_final_answer": state["is_final_answer"],
            "search_request": state["search_request"],
            "wiki_request": state["wiki_request"],
        }


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. Instantiate Agent ( modify this part to create your agent)
    try:
        agent = BasicAgent()
    except Exception as e:
        print(f"Error instantiating agent: {e}")
        return f"Error initializing agent: {e}", None
    # In the case of an app running as a hugging Face space, this link points toward your codebase ( usefull for others so please keep it public)
    agent_code = f"https://huggingface.co/spaces/{space_id}/tree/main"
    print(agent_code)

    # 2. Fetch Questions
    print(f"Fetching questions from: {questions_url}")
    response = None
    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.JSONDecodeError as e:
        print(f"Error decoding JSON response from questions endpoint: {e}")
        if response:
            print(f"Response text: {response.text[:500]}")
        return f"Error decoding server response for questions: {e}", None
    except requests.exceptions.RequestException as e:
        print(f"Error fetching questions: {e}")
        return f"Error fetching 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
    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(task_id, 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)

    # 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=True)