import os import re import json import time import tempfile import traceback from typing import List, Dict, Any, Optional import requests import pandas as pd import gradio as gr import spaces from smolagents import ToolCallingAgent, LiteLLMModel, tool, PythonInterpreterTool # ------------------------------------------------------------------------------------ # CONSTANTS # ------------------------------------------------------------------------------------ DEFAULT_API_URL = "https://agents-course-unit4-scoring.hf.space" QUESTIONS_ENDPOINT = f"{DEFAULT_API_URL}/questions" RANDOM_QUESTION_ENDPOINT = f"{DEFAULT_API_URL}/random-question" FILES_ENDPOINT = f"{DEFAULT_API_URL}/files" SUBMIT_ENDPOINT = f"{DEFAULT_API_URL}/submit" REQUEST_TIMEOUT = 30 GROQ_MODEL_ID = "groq/llama-3.3-70b-versatile" # Retry behaviour for a single agent.run() call. Groq / LiteLLM calls can fail # transiently (rate limits, dropped connections, occasional malformed tool-call # responses); we retry a small, bounded number of times before giving up and # returning an empty answer for that question rather than crashing the app. MAX_AGENT_RETRIES = 3 RETRY_BACKOFF_SECONDS = 4 AGENT_MAX_STEPS = 8 # NOTE ON THE ORIGINAL BUG: # The previous implementation used `CodeAgent`, which expects the LLM to # respond with reasoning followed by a ```py ... ``` / ... block # that the agent then parses out with a regex and executes locally. Groq's # llama-3.3-70b-versatile does not reliably keep emitting that exact block on # every turn -- on later, more complex questions it frequently short-circuits # straight to a plain-text final answer, which breaks CodeAgent's regex-based # parser ("Error in code parsing: regex pattern (.*?) was not # found") and crashes that turn. # # `ToolCallingAgent` sidesteps this entirely: it drives the model via native # structured tool-calling (the same JSON function-calling mechanism Groq's # OpenAI-compatible API exposes), so there is no free-text code block for the # model to "forget" to produce. Python execution is preserved via the # dedicated `PythonInterpreterTool`, which is invoked like any other tool. # ------------------------------------------------------------------------------------ # TOOLS # ------------------------------------------------------------------------------------ @tool def web_search(query: str) -> str: """Performs a web search using DuckDuckGo (via DDGS) and returns the top results. Args: query: The search query string. Returns: A formatted string containing the top search results (title, snippet, url). """ try: from ddgs import DDGS except ImportError: try: from duckduckgo_search import DDGS # fallback if ddgs unavailable except ImportError: return "Search tool unavailable: neither 'ddgs' nor 'duckduckgo_search' is installed." try: results = [] with DDGS() as ddgs: for r in ddgs.text(query, max_results=5): title = r.get("title", "") body = r.get("body", "") href = r.get("href", "") results.append(f"Title: {title}\nSnippet: {body}\nURL: {href}") if not results: return f"No results found for query: {query}" return "\n\n".join(results) except Exception as e: return f"Search failed for query '{query}': {str(e)}" @tool def read_text_file(file_path: str) -> str: """Reads and returns the content of a plain text file. Args: file_path: Local path to the text file. Returns: The text content of the file, truncated if extremely large. """ try: with open(file_path, "r", encoding="utf-8", errors="ignore") as f: content = f.read() if len(content) > 20000: content = content[:20000] + "\n...[truncated]..." return content except Exception as e: return f"Failed to read text file {file_path}: {str(e)}" @tool def read_csv_file(file_path: str) -> str: """Reads a CSV file and returns a textual summary along with the first rows. Args: file_path: Local path to the CSV file. Returns: A string describing the CSV columns, shape, and a preview of the data. """ try: df = pd.read_csv(file_path) summary = f"Columns: {list(df.columns)}\nShape: {df.shape}\n\nPreview:\n{df.head(20).to_string()}" return summary except Exception as e: return f"Failed to read csv file {file_path}: {str(e)}" @tool def read_pdf_file(file_path: str) -> str: """Extracts text content from a PDF file. Args: file_path: Local path to the PDF file. Returns: The extracted text content of the PDF, truncated if very large. """ text_content = "" try: try: import pypdf reader = pypdf.PdfReader(file_path) for page in reader.pages: text_content += page.extract_text() or "" except ImportError: try: from PyPDF2 import PdfReader reader = PdfReader(file_path) for page in reader.pages: text_content += page.extract_text() or "" except ImportError: return "No PDF parsing library available (pypdf/PyPDF2 not installed)." if not text_content.strip(): return "PDF appears to contain no extractable text (may be scanned/image-based)." if len(text_content) > 20000: text_content = text_content[:20000] + "\n...[truncated]..." return text_content except Exception as e: return f"Failed to read pdf file {file_path}: {str(e)}" @tool def describe_image_file(file_path: str) -> str: """Loads an image file and returns basic metadata about it (size, mode, format). Args: file_path: Local path to the image file. Returns: A string describing basic image metadata. Note: this does not perform visual understanding; use it only to confirm the image loaded correctly. """ try: from PIL import Image img = Image.open(file_path) return f"Image loaded. Format: {img.format}, Size: {img.size}, Mode: {img.mode}" except Exception as e: return f"Failed to load image file {file_path}: {str(e)}" SYSTEM_PROMPT = """You are a general AI assistant solving questions from the GAIA benchmark. You have access to tools: a web_search tool, a python_interpreter tool for calculations and data manipulation, and file-reading tools (read_text_file, read_csv_file, read_pdf_file, describe_image_file). Use them to research, calculate, and verify facts before producing your final answer. When a local file path is given in the task, open and read it with the appropriate tool to extract the information you need. STRICT OUTPUT RULES (violating these rules is a failure): - Your final answer (passed to the final_answer tool) must be ONLY the final answer. Nothing else. - Do NOT use markdown formatting (no asterisks, no backticks, no headers, no bullet points). - Do NOT include any explanation, reasoning, or commentary in the final answer. - Do NOT output JSON in the final answer. - Do NOT prefix the final answer with "Final Answer", "Answer:", "The answer is", or anything similar. - Do NOT wrap the answer in quotes unless the quotes are part of the actual answer. - If the question asks for a number, output only the number (no units unless explicitly requested, no commas unless part of the expected format). - If the question asks for a string, output only the string, using the exact capitalization and phrasing requested. - If the question asks for a comma separated list, output exactly that list, comma separated, with no extra text. - If multiple values are requested, output exactly those values in the requested format, nothing more. - Think step by step internally, use tools as needed, but NEVER reveal your reasoning, steps, or tool calls in the final answer. - Your final answer must be as concise as possible while being a fully correct, exact match to what is expected. Remember: call the final_answer tool exactly once, with ONLY the final answer as its argument. """ # ------------------------------------------------------------------------------------ # AGENT # ------------------------------------------------------------------------------------ class GAIAAgent: """ Holds the (heavy, non-picklable) ToolCallingAgent/LiteLLMModel state. This object is built ONCE and cached as a module-level singleton. It is NEVER passed as an argument into a @spaces.GPU-decorated call (that is what previously caused "cannot pickle 'module' object" -- ZeroGPU pickles the call target + arguments to hand off to the GPU worker, and any live tool/model objects cannot be pickled). """ def __init__(self): api_key = os.getenv("GROQ_API_KEY") if not api_key: print("WARNING: GROQ_API_KEY environment variable is not set.") self.model = LiteLLMModel( model_id=GROQ_MODEL_ID, api_key=api_key, temperature=0.0, ) # PythonInterpreterTool replaces CodeAgent's implicit "write and run a # Python snippet" behaviour. It is invoked as an ordinary tool call # (JSON args), so it plays nicely with ToolCallingAgent + Groq, unlike # CodeAgent's free-text block parsing. python_tool = PythonInterpreterTool( authorized_imports=[ "pandas", "numpy", "json", "re", "math", "statistics", "datetime", "itertools", "collections", ] ) self.agent = ToolCallingAgent( tools=[ web_search, read_text_file, read_csv_file, read_pdf_file, describe_image_file, python_tool, ], model=self.model, add_base_tools=False, max_steps=AGENT_MAX_STEPS, ) def _run_agent_once(self, prompt: str) -> str: """Runs the agent a single time. Raises on failure; caller handles retries.""" result = self.agent.run(prompt) return str(result) if result is not None else "" def answer_question(self, question: str, file_path: Optional[str] = None) -> str: """Plain (non-GPU-decorated) instance method that runs the agent. This is called from inside the top-level @spaces.GPU function below, never decorated itself, and never passed across the process boundary. Wraps the actual agent run in a bounded retry loop so that a single transient failure (LLM API hiccup, a malformed tool-call response, etc.) never crashes the whole evaluation run -- it just falls back to an empty answer for that one question after exhausting retries. """ prompt = SYSTEM_PROMPT + "\n\nQuestion:\n" + question if file_path: prompt += f"\n\nA file relevant to this question has been downloaded locally at: {file_path}\n" prompt += "Use the appropriate tool (read_text_file, read_csv_file, read_pdf_file, describe_image_file) or the python_interpreter tool to open and inspect it." last_error: Optional[Exception] = None for attempt in range(1, MAX_AGENT_RETRIES + 1): try: answer = self._run_agent_once(prompt) return clean_answer(answer) except Exception as e: last_error = e print(f"Agent run failed on attempt {attempt}/{MAX_AGENT_RETRIES}: {e}") traceback.print_exc() # Reset the agent's internal memory/step state before retrying # so a partially-corrupted conversation state from the failed # attempt doesn't bleed into the retry. try: self.agent.memory.reset() except Exception: pass if attempt < MAX_AGENT_RETRIES: time.sleep(RETRY_BACKOFF_SECONDS) print(f"All {MAX_AGENT_RETRIES} attempts failed for question. Last error: {last_error}") return "" # Module-level singleton. Built lazily on first use and reused for every # subsequent call. Because it lives as a global (not as an argument or as # `self` inside a @spaces.GPU function), it never needs to be pickled. _agent_singleton: Optional[GAIAAgent] = None def get_agent() -> GAIAAgent: global _agent_singleton if _agent_singleton is None: _agent_singleton = GAIAAgent() return _agent_singleton @spaces.GPU(duration=120) def generate_answer(question: str, file_path: Optional[str] = None) -> str: """ Top-level function decorated with @spaces.GPU -- the official ZeroGPU pattern. Only simple, picklable arguments (str / Optional[str]) go in, and only a simple picklable value (str) comes out. The heavy agent object itself is fetched from the module-level singleton inside the worker, never pickled. """ agent = get_agent() return agent.answer_question(question, file_path) # ------------------------------------------------------------------------------------ # OUTPUT CLEANING # ------------------------------------------------------------------------------------ def clean_answer(raw_answer: str) -> str: if raw_answer is None: return "" answer = str(raw_answer).strip() prefixes_to_strip = [ "final answer:", "final answer", "answer:", "the answer is:", "the answer is", "output:", ] lowered = answer.lower() for prefix in prefixes_to_strip: if lowered.startswith(prefix): answer = answer[len(prefix):].strip() lowered = answer.lower() answer = re.sub(r"^```[a-zA-Z]*\n?", "", answer) answer = re.sub(r"\n?```$", "", answer) answer = answer.strip() answer = re.sub(r"^\*\*(.*)\*\*$", r"\1", answer).strip() answer = re.sub(r"^\*(.*)\*$", r"\1", answer).strip() answer = re.sub(r"^`(.*)`$", r"\1", answer).strip() if len(answer) >= 2 and answer[0] == '"' and answer[-1] == '"': answer = answer[1:-1].strip() if len(answer) >= 2 and answer[0] == "'" and answer[-1] == "'": answer = answer[1:-1].strip() if answer.endswith(".") and not re.match(r"^\d+\.\d*\.?$", answer): if not (len(answer) >= 2 and answer[-2].isdigit()): answer = answer[:-1].strip() answer = " ".join(answer.split()) return answer # ------------------------------------------------------------------------------------ # NETWORK HELPERS # ------------------------------------------------------------------------------------ def fetch_questions() -> List[Dict[str, Any]]: try: resp = requests.get(QUESTIONS_ENDPOINT, timeout=REQUEST_TIMEOUT) resp.raise_for_status() return resp.json() except requests.exceptions.Timeout: raise RuntimeError("Timed out while fetching questions from the scoring API.") except requests.exceptions.RequestException as e: raise RuntimeError(f"Network error while fetching questions: {e}") except json.JSONDecodeError as e: raise RuntimeError(f"Failed to decode questions JSON: {e}") def fetch_random_question() -> Dict[str, Any]: try: resp = requests.get(RANDOM_QUESTION_ENDPOINT, timeout=REQUEST_TIMEOUT) resp.raise_for_status() return resp.json() except requests.exceptions.Timeout: raise RuntimeError("Timed out while fetching a random question.") except requests.exceptions.RequestException as e: raise RuntimeError(f"Network error while fetching random question: {e}") except json.JSONDecodeError as e: raise RuntimeError(f"Failed to decode random question JSON: {e}") def download_task_file(task_id: str) -> Optional[str]: if not task_id: return None try: url = f"{FILES_ENDPOINT}/{task_id}" resp = requests.get(url, timeout=REQUEST_TIMEOUT) if resp.status_code == 404: return None resp.raise_for_status() content_disposition = resp.headers.get("content-disposition", "") filename_match = re.search(r'filename="?([^";]+)"?', content_disposition) if filename_match: filename = filename_match.group(1) else: content_type = resp.headers.get("content-type", "") ext = "" if "pdf" in content_type: ext = ".pdf" elif "csv" in content_type: ext = ".csv" elif "text" in content_type: ext = ".txt" elif "png" in content_type: ext = ".png" elif "jpeg" in content_type or "jpg" in content_type: ext = ".jpg" filename = f"{task_id}{ext}" tmp_dir = tempfile.mkdtemp(prefix="gaia_task_") local_path = os.path.join(tmp_dir, filename) with open(local_path, "wb") as f: f.write(resp.content) print(f"Downloaded file for task {task_id} -> {local_path}") return local_path except requests.exceptions.Timeout: print(f"Timed out while downloading file for task {task_id}.") return None except requests.exceptions.RequestException as e: print(f"Network error while downloading file for task {task_id}: {e}") return None except Exception as e: print(f"Unexpected error while downloading file for task {task_id}: {e}") return None def submit_answers(username: str, agent_code: str, answers: List[Dict[str, str]]) -> Dict[str, Any]: payload = { "username": username, "agent_code": agent_code, "answers": answers, } resp = None try: resp = requests.post(SUBMIT_ENDPOINT, json=payload, timeout=120) resp.raise_for_status() return resp.json() except requests.exceptions.Timeout: raise RuntimeError("Timed out while submitting answers.") except requests.exceptions.HTTPError as e: detail = "" if resp is not None: try: detail = resp.text except Exception: pass raise RuntimeError(f"Submission failed with HTTP error: {e}. Details: {detail}") except requests.exceptions.RequestException as e: raise RuntimeError(f"Network error during submission: {e}") except json.JSONDecodeError as e: raise RuntimeError(f"Failed to decode submission response JSON: {e}") # ------------------------------------------------------------------------------------ # GRADIO CALLBACKS # ------------------------------------------------------------------------------------ def test_random_question(): try: question_data = fetch_random_question() except RuntimeError as e: return f"Error: {e}", "", "", "" task_id = question_data.get("task_id", "N/A") question_text = question_data.get("question", "") print(f"[TEST] Task ID: {task_id}") print(f"[TEST] Question: {question_text}") file_path = None try: file_path = download_task_file(task_id) if file_path: print(f"[TEST] Downloaded file: {file_path}") except Exception as e: print(f"[TEST] File download skipped/failed: {e}") try: answer = generate_answer(question_text, file_path) print(f"[TEST] LLM answer: {answer}") status = "Success" except Exception as e: answer = "" status = f"Agent error: {e}" print(f"[TEST] {status}") traceback.print_exc() return status, str(task_id), question_text, answer def run_and_submit_all(profile: gr.OAuthProfile | None): if profile is None: return "Please log in to Hugging Face using the button above before running the evaluation.", None username = profile.username print(f"User logged in: {username}") space_id = os.getenv("SPACE_ID", "") if space_id: agent_code = f"https://huggingface.co/spaces/{space_id}/tree/main" else: agent_code = "local-run/unknown-space" try: # Warm up / validate the agent singleton before starting the loop. get_agent() except Exception as e: error_msg = f"Failed to initialize agent: {e}" print(error_msg) traceback.print_exc() return error_msg, None try: questions = fetch_questions() except RuntimeError as e: return f"Error fetching questions: {e}", None if not questions: return "No questions were returned by the scoring API.", None print(f"Fetched {len(questions)} questions.") answers_payload = [] results_log = [] for idx, item in enumerate(questions): task_id = item.get("task_id", f"unknown-{idx}") question_text = item.get("question", "") print(f"\n--- Processing task {idx + 1}/{len(questions)}: {task_id} ---") print(f"Question: {question_text}") file_path = None try: file_path = download_task_file(task_id) if file_path: print(f"Downloaded file: {file_path}") except Exception as e: print(f"File download failed for task {task_id}: {e}") # A failure on any single question must never abort the whole batch -- # generate_answer already retries internally, so this except is a # last-resort safety net (e.g. GPU allocation errors). try: answer = generate_answer(question_text, file_path) print(f"LLM answer for {task_id}: {answer}") except Exception as e: print(f"Agent failed on task {task_id}: {e}") traceback.print_exc() answer = "" answers_payload.append({ "task_id": task_id, "submitted_answer": answer, }) results_log.append({ "Task ID": task_id, "Question": question_text, "Submitted Answer": answer, }) if not answers_payload: return "No answers were generated; nothing to submit.", pd.DataFrame(results_log) print(f"\nSubmitting {len(answers_payload)} answers for user '{username}'...") status_msg = "Submission not attempted." try: submission_result = submit_answers(username, agent_code, answers_payload) score = submission_result.get("score", "N/A") correct = submission_result.get("correct_count", submission_result.get("correct", "N/A")) total = submission_result.get("total_attempted", submission_result.get("total", len(answers_payload))) message = submission_result.get("message", "") status_msg = ( f"Submission successful!\n" f"User: {username}\n" f"Score: {score}\n" f"Correct: {correct} / {total}\n" f"{message}" ) print(status_msg) except RuntimeError as e: status_msg = f"Submission failed: {e}" print(status_msg) return status_msg, pd.DataFrame(results_log) # ------------------------------------------------------------------------------------ # GRADIO UI # ------------------------------------------------------------------------------------ with gr.Blocks(title="GAIA Agent - Unit 4 Final Assignment") as demo: gr.Markdown("# GAIA Agent Evaluation Runner") gr.Markdown( "This Space runs a smolagents ToolCallingAgent (Groq `llama-3.3-70b-versatile` via LiteLLM) " "against the GAIA benchmark questions from the Hugging Face Agents Course Unit 4 scoring API. " "Log in with Hugging Face, then either test a single random question or run the full evaluation " "and submit all answers for scoring." ) gr.LoginButton() with gr.Row(): test_button = gr.Button("Test Random Question") run_button = gr.Button("Run Evaluation & Submit All Answers", variant="primary") status_box = gr.Textbox(label="Status", lines=6, interactive=False) with gr.Row(): test_task_id = gr.Textbox(label="Task ID", interactive=False) test_question = gr.Textbox(label="Question", lines=4, interactive=False) test_answer = gr.Textbox(label="Answer", lines=2, interactive=False) results_df = gr.Dataframe(label="Results", wrap=True) test_button.click( fn=test_random_question, inputs=[], outputs=[status_box, test_task_id, test_question, test_answer], ) run_button.click( fn=run_and_submit_all, inputs=[], outputs=[status_box, results_df], ) if __name__ == "__main__": demo.launch(debug=True)