Spaces:
Runtime error
Runtime error
Download app.py from nick17728/Final_Assignment_Template: direct link, hf CLI and curl.
- Browser
- Download file 31.5 kB
-
https://huggingface.co/spaces/nick17728/Final_Assignment_Template/resolve/main/app.py
- Command line
-
hf download hf://spaces/nick17728/Final_Assignment_Template/app.py
-
curl -L -o app.py https://huggingface.co/spaces/nick17728/Final_Assignment_Template/resolve/main/app.py
31.5 kB
| import os | |
| import gradio as gr | |
| import requests | |
| import inspect | |
| import pandas as pd | |
| import re | |
| import json | |
| import time | |
| import glob | |
| import base64 | |
| import mimetypes | |
| import subprocess | |
| import sys | |
| import tempfile | |
| from typing import TypedDict, Annotated | |
| import numpy as np | |
| from bs4 import BeautifulSoup | |
| from markdownify import markdownify | |
| from ddgs import DDGS | |
| from langchain_core.tools import tool | |
| from langchain_core.messages import AnyMessage, HumanMessage, SystemMessage, ToolMessage | |
| from langchain_ollama import ChatOllama | |
| from langgraph.graph import StateGraph, START | |
| from langgraph.graph.message import add_messages | |
| from langgraph.prebuilt import ToolNode, tools_condition | |
| # (Keep Constants as is) | |
| # --- Constants --- | |
| DEFAULT_API_URL = "https://agents-course-unit4-scoring.hf.space" | |
| # --- Settings (override with environment variables if needed) --- | |
| OLLAMA_MODEL = os.getenv("OLLAMA_MODEL", "qwen3.5:9b") # the agent's brain (tool calling) | |
| VISION_MODEL = os.getenv("VISION_MODEL", "qwen3-vl:8b") # used for images and video frames | |
| OLLAMA_BASE_URL = os.getenv("OLLAMA_BASE_URL", "http://localhost:11434") | |
| NUM_CTX = int(os.getenv("NUM_CTX", "16384")) # raise to 32768 on a big GPU | |
| MAX_TOOL_CALLS = 10 | |
| FILES_DIR = "gaia_files" | |
| llm = ChatOllama(model=OLLAMA_MODEL, base_url=OLLAMA_BASE_URL, temperature=0, num_ctx=NUM_CTX, reasoning=False) | |
| vision_llm = ChatOllama(model=VISION_MODEL, base_url=OLLAMA_BASE_URL, temperature=0, reasoning=False) | |
| # ===================================================================== | |
| # Helpers | |
| # ===================================================================== | |
| def _resolve(path): | |
| """Find the file even if the model passes only its name.""" | |
| if os.path.exists(path): | |
| return path | |
| alt = os.path.join(FILES_DIR, os.path.basename(path)) | |
| return alt if os.path.exists(alt) else path | |
| def _load_audio(path, sr=16000): | |
| """Decode any audio/video file to 16 kHz mono float32 using ffmpeg (avoids PyAV version issues).""" | |
| out = subprocess.run( | |
| ["ffmpeg", "-nostdin", "-i", path, "-f", "s16le", "-ac", "1", "-ar", str(sr), "-"], | |
| capture_output=True, check=True).stdout | |
| return np.frombuffer(out, np.int16).astype(np.float32) / 32768.0 | |
| _whisper = None | |
| def _get_whisper(): | |
| """Load Whisper only when first needed (GPU if available, otherwise CPU).""" | |
| global _whisper | |
| if _whisper is None: | |
| from faster_whisper import WhisperModel | |
| try: | |
| _whisper = WhisperModel("small", device="cuda", compute_type="float16") | |
| except Exception: | |
| _whisper = WhisperModel("small", device="cpu", compute_type="int8") | |
| return _whisper | |
| def _transcribe(path): | |
| segments, _ = _get_whisper().transcribe(_load_audio(path)) | |
| return " ".join(s.text for s in segments) | |
| def _video_id(url): | |
| m = re.search(r"(?:v=|youtu\.be/|shorts/)([\w-]{11})", url) | |
| return m.group(1) if m else url | |
| def _download_youtube(url, kind): | |
| """kind='video' (no audio, <=480p) or 'audio'. Returns the local file path.""" | |
| import yt_dlp | |
| vid = _video_id(url) | |
| os.makedirs("videos", exist_ok=True) | |
| existing = glob.glob(f"videos/{vid}_{kind}.*") | |
| if existing: | |
| return existing[0] | |
| fmt = ("bestvideo[height<=480]/best[height<=480]/best" if kind == "video" | |
| else "bestaudio/best") | |
| opts = {"format": fmt, "outtmpl": f"videos/{vid}_{kind}.%(ext)s", "quiet": True} | |
| with yt_dlp.YoutubeDL(opts) as ydl: | |
| ydl.download([url]) | |
| return glob.glob(f"videos/{vid}_{kind}.*")[0] | |
| # ===================================================================== | |
| # Tools | |
| # ===================================================================== | |
| def web_search(query: str) -> str: | |
| """Search the web. Returns the top results with title, URL and snippet. | |
| Follow up with visit_webpage on the most relevant URL to read the full page.""" | |
| last_error = "" | |
| for backend in ["google", "duckduckgo", "brave", "startpage", "yahoo", "mojeek"]: | |
| try: | |
| results = DDGS().text(query, max_results=6, backend=backend) | |
| if results: | |
| return f"(results from {backend})\n\n" + "\n\n".join( | |
| f"{i}. {r.get('title','')}\nURL: {r.get('href','')}\n{r.get('body','')}" | |
| for i, r in enumerate(results, 1)) | |
| except Exception as e: | |
| last_error = f"{backend}: {str(e)[:150]}" | |
| return f"No results (search failed: {last_error}). Try a different query or the wikipedia tool." | |
| WIKI_API = "https://en.wikipedia.org/w/api.php" | |
| WIKI_HEADERS = {"User-Agent": "AgentsCourseGAIA/1.0 (https://huggingface.co/learn/agents-course)"} | |
| def wikipedia(query: str, find: str = "") -> str: | |
| """Search English Wikipedia and return text from the best matching page. | |
| Pages are long, so use `find` to jump to a section or keyword, | |
| e.g. find="Discography", find="Studio albums", find="Career". | |
| Without `find`, returns the start of the page.""" | |
| try: | |
| s = requests.get(WIKI_API, headers=WIKI_HEADERS, timeout=20, params={ | |
| "action": "query", "list": "search", "srsearch": query, | |
| "srlimit": 3, "format": "json"}).json() | |
| hits = s.get("query", {}).get("search", []) | |
| if not hits: | |
| return f"No Wikipedia page found for: {query}" | |
| title = hits[0]["title"] | |
| p = requests.get(WIKI_API, headers=WIKI_HEADERS, timeout=20, params={ | |
| "action": "query", "prop": "extracts", "explaintext": 1, | |
| "titles": title, "format": "json"}).json() | |
| text = next(iter(p["query"]["pages"].values())).get("extract", "") | |
| others = ", ".join(h["title"] for h in hits[1:]) | |
| header = f"Page: {title} ({len(text)} characters)\n(Other matches: {others})\n\n" | |
| if find: | |
| pos = text.lower().find(find.lower()) | |
| if pos == -1: | |
| return header + f"'{find}' not found on this page. Try another keyword or page." | |
| return header + f"...text from '{find}':\n" + text[pos:pos + 6000] | |
| return header + text[:6000] | |
| except Exception as e: | |
| return f"Wikipedia error: {e}" | |
| def visit_webpage(url: str, find: str = "") -> str: | |
| """Open a web page and return its main text as markdown (tables included). | |
| Long pages are cut, so use `find` to jump to a keyword or section, | |
| e.g. find="Studio albums", find="Discography", find="1977".""" | |
| try: | |
| html = requests.get(url, timeout=25, headers={"User-Agent": "Mozilla/5.0"}).text | |
| soup = BeautifulSoup(html, "html.parser") | |
| for tag in soup(["script", "style", "nav", "header", "footer", "aside", "noscript"]): | |
| tag.decompose() | |
| for sel in [".navbox", ".reflist", ".mw-editsection", "#toc", ".vector-header"]: | |
| for tag in soup.select(sel): | |
| tag.decompose() | |
| main = (soup.select_one("#mw-content-text") or soup.find("main") | |
| or soup.find("article") or soup.body or soup) | |
| text = re.sub(r"\n{3,}", "\n\n", markdownify(str(main))) | |
| header = f"URL: {url} ({len(text)} characters)\n\n" | |
| if find: | |
| pos = text.lower().find(find.lower()) | |
| if pos == -1: | |
| return header + f"'{find}' not found on this page. Try another keyword." | |
| return header + f"...text from '{find}':\n" + text[pos:pos + 7000] | |
| return header + text[:7000] | |
| except Exception as e: | |
| return f"Error opening page: {e}" | |
| def read_file(path: str) -> str: | |
| """Read a local file (Excel, CSV, or text/code) and return its contents as text.""" | |
| path = _resolve(path) | |
| try: | |
| if path.endswith((".xlsx", ".xls")): | |
| sheets = pd.read_excel(path, sheet_name=None) | |
| return "\n\n".join(f"Sheet {n}:\n{df.to_string()}" for n, df in sheets.items())[:6000] | |
| if path.endswith(".csv"): | |
| return pd.read_csv(path).to_string()[:6000] | |
| return open(path, encoding="utf-8", errors="ignore").read()[:6000] | |
| except Exception as e: | |
| return f"Error reading file: {e}" | |
| def run_python(code: str) -> str: | |
| """Run Python code and return what it prints. Use this to execute an attached .py file | |
| (e.g. exec(open(path).read())) or to analyse an Excel/CSV file with pandas. | |
| Always print() the result you need.""" | |
| with tempfile.NamedTemporaryFile("w", suffix=".py", delete=False, encoding="utf-8") as f: | |
| f.write(code) | |
| try: | |
| out = subprocess.run([sys.executable, f.name], capture_output=True, text=True, timeout=60) | |
| return (out.stdout + out.stderr)[-4000:] or "(no output)" | |
| except subprocess.TimeoutExpired: | |
| return "Error: code took longer than 60 seconds" | |
| def calculator(expression: str) -> str: | |
| """Evaluate a math expression, e.g. '(12.5 * 4) / 3'. Use this for any arithmetic.""" | |
| try: | |
| return str(eval(expression, {"__builtins__": {}}, {"round": round, "abs": abs, "min": min, "max": max, "sum": sum})) | |
| except Exception as e: | |
| return f"Error: {e}" | |
| def analyze_image(path: str, question: str) -> str: | |
| """Look at a local image file (png, jpg) and answer a question about it. | |
| Use this for any attached image: describe it, read text from it, or answer a specific question.""" | |
| path = _resolve(path) | |
| try: | |
| mime = mimetypes.guess_type(path)[0] or "image/png" | |
| b64 = base64.b64encode(open(path, "rb").read()).decode() | |
| msg = HumanMessage(content=[ | |
| {"type": "text", "text": question}, | |
| {"type": "image_url", "image_url": {"url": f"data:{mime};base64,{b64}"}}, | |
| ]) | |
| return vision_llm.invoke([msg]).content | |
| except Exception as e: | |
| return f"TOOL FAILED: could not analyse image ({str(e)[:200]}). You have NOT seen this image." | |
| def youtube_transcript(url: str) -> str: | |
| """Get the spoken words of a YouTube video (captions, or transcribed audio if there are no captions). | |
| Use for questions about what someone says.""" | |
| vid = _video_id(url) | |
| try: | |
| from youtube_transcript_api import YouTubeTranscriptApi | |
| try: | |
| data = YouTubeTranscriptApi().fetch(vid) | |
| return "Transcript (captions):\n" + " ".join(s.text for s in data)[:6000] | |
| except AttributeError: | |
| return "Transcript (captions):\n" + " ".join( | |
| s["text"] for s in YouTubeTranscriptApi.get_transcript(vid))[:6000] | |
| except Exception: | |
| pass # no captions, or YouTube blocked the request: try the audio instead | |
| try: | |
| audio = _download_youtube(url, "audio") | |
| return "Transcript (from audio):\n" + _transcribe(audio)[:6000] | |
| except Exception as e: | |
| return (f"TOOL FAILED: could not get the transcript ({str(e)[:200]}). " | |
| "You have NOT heard this video. Do not pretend you have.") | |
| def watch_youtube(url: str, question: str) -> str: | |
| """Look at a YouTube video by sampling frames and asking the vision model about each one. | |
| Use for questions about what is visible in a video (counting, objects, on-screen text).""" | |
| try: | |
| import cv2 | |
| path = _download_youtube(url, "video") | |
| cap = cv2.VideoCapture(path) | |
| total = int(cap.get(cv2.CAP_PROP_FRAME_COUNT)) | |
| if total <= 0: | |
| return "TOOL FAILED: the downloaded video could not be read. You have NOT seen this video." | |
| results = [] | |
| for i in range(1, 9): | |
| cap.set(cv2.CAP_PROP_POS_FRAMES, int(total * i / 9)) | |
| ok, frame = cap.read() | |
| if not ok: | |
| continue | |
| frame_path = f"{path}_frame{i}.jpg" | |
| cv2.imwrite(frame_path, frame) | |
| answer = analyze_image.invoke({"path": frame_path, "question": question}) | |
| results.append(f"Frame {i}/8: {answer}") | |
| cap.release() | |
| return "\n".join(results) or "TOOL FAILED: no frames could be read. You have NOT seen this video." | |
| except Exception as e: | |
| return (f"TOOL FAILED: could not download the video ({str(e)[:200]}). " | |
| "You have NOT seen this video. Do not pretend you have.") | |
| def transcribe_audio(path: str) -> str: | |
| """Transcribe a local audio file (mp3, wav) into text.""" | |
| try: | |
| return "Transcript:\n" + _transcribe(_resolve(path))[:6000] | |
| except Exception as e: | |
| return f"TOOL FAILED: could not transcribe ({str(e)[:200]}). You have NOT heard this audio." | |
| TOOLS = [web_search, wikipedia, visit_webpage, read_file, run_python, calculator, | |
| analyze_image, youtube_transcript, watch_youtube, transcribe_audio] | |
| # ===================================================================== | |
| # Prompts | |
| # ===================================================================== | |
| SYSTEM_PROMPT = """You are a careful research assistant answering GAIA benchmark questions. | |
| Answers are graded by EXACT MATCH, so accuracy and format both matter. | |
| HOW TO WORK | |
| 1. Read the question carefully. If it looks reversed or scrambled, decode it first, then answer what it actually asks. | |
| 2. Decide which tool you need. Never guess facts you can look up. | |
| 3. Use one tool at a time, read the result, then decide the next step. | |
| 4. Do not repeat the same search. If a result is not useful, try a different query or a different tool. | |
| 5. As soon as you have enough information, stop calling tools and give the final answer. | |
| 6. If a tool says TOOL FAILED, you did not get that information. Never claim you saw, heard or read something you did not. | |
| Try another tool or approach; only guess as a last resort. | |
| WHICH TOOL TO USE | |
| - General facts or recent info: web_search, then visit_webpage on the best URL. | |
| - Encyclopedia facts (people, places, history): wikipedia. | |
| - Lists and tables (discographies, rosters, results, statistics): visit_webpage on the en.wikipedia.org page | |
| with find="<section name>", because it keeps tables (the wikipedia tool loses them). | |
| - Pages are long: if the info is not at the start, call the tool again with find="<keyword or section>". | |
| - Attached Excel/CSV/text file: read_file to look at it; run_python with pandas for any totals or filtering. | |
| - Attached Python file: run_python with exec(open(path).read()) to get its real output. | |
| - Attached image: analyze_image with a specific question (e.g. "List every chess piece and its square"). | |
| - Attached audio (.mp3/.wav): transcribe_audio. | |
| - YouTube, what is SAID: youtube_transcript. | |
| - YouTube, what is SHOWN: watch_youtube with a specific question. | |
| - Any arithmetic: calculator or run_python. Never do maths in your head. | |
| FINAL ANSWER RULES | |
| When you are done, reply with ONLY the final answer, nothing else: | |
| - No explanation, no full sentence, no quotes, no "FINAL ANSWER" or "The answer is" prefix. | |
| - Numbers: digits only, no commas, no units (unless the question asks for them). | |
| - Text: as few words as possible, no articles (a, an, the), no abbreviations unless asked. | |
| - Lists: comma-separated, in the order the question asks (alphabetical if it says so). | |
| - Follow any format the question specifies (e.g. decimal places, "surname only", country code). | |
| - If you truly cannot find the answer after trying, give your single best guess, never a refusal.""" | |
| FORCE_FINAL = ("You have used enough tools. Based only on the information above, " | |
| "reply now with ONLY the final answer, following the final answer rules.") | |
| FIX_FORMAT = ("You wrote the tool arguments as plain text, so no tool was run. " | |
| "Call the tool properly using the tool-calling format, or reply with only the final answer.") | |
| FORMAT_PROMPT = """Question: | |
| {question} | |
| Draft answer from a research assistant: | |
| {draft} | |
| Return ONLY the final answer to the question, taken from the draft. Rules: | |
| - No explanation, no sentence, no quotes, no prefix like "Answer:". | |
| - Numbers: digits only, no commas, no units unless the question asks for them. | |
| - Text: as few words as possible, no articles. Lists: comma-separated. | |
| - Follow any format the question asks for. | |
| - If the draft does not contain an actual answer, output exactly: NONE | |
| Output nothing except the answer.""" | |
| IMAGE_EXT = (".png", ".jpg", ".jpeg", ".gif", ".webp") | |
| AUDIO_EXT = (".mp3", ".wav", ".m4a") | |
| # ===================================================================== | |
| # Files, prompt building and answer cleanup | |
| # ===================================================================== | |
| def download_file(api_url: str, task_id: str, file_name: str): | |
| """Download a question's attached file. Tries the course API, then the GAIA dataset | |
| (needs access to gaia-benchmark/GAIA and an HF_TOKEN with read access).""" | |
| if not file_name: | |
| return None | |
| os.makedirs(FILES_DIR, exist_ok=True) | |
| path = os.path.join(FILES_DIR, file_name) | |
| if os.path.exists(path) and os.path.getsize(path) > 0: | |
| return os.path.abspath(path) | |
| for attempt in range(3): | |
| try: | |
| r = requests.get(f"{api_url}/files/{task_id}", timeout=120) | |
| r.raise_for_status() | |
| with open(path, "wb") as f: | |
| f.write(r.content) | |
| return os.path.abspath(path) | |
| except Exception as e: | |
| print(f" try {attempt+1} failed for {file_name}: {e}") | |
| time.sleep(3) | |
| try: | |
| from huggingface_hub import hf_hub_download | |
| return hf_hub_download(repo_id="gaia-benchmark/GAIA", repo_type="dataset", | |
| filename=f"2023/validation/{file_name}", local_dir=FILES_DIR) | |
| except Exception as e: | |
| print(f" !! could not get {file_name} from GAIA dataset either: {e}") | |
| return None | |
| def build_prompt(question: str, local_file: str = None, file_expected: bool = False) -> str: | |
| text = question | |
| if text.strip().startswith(".") and " eht " in text: | |
| text += f"\n\n(The question above is written backwards. Reversed, it reads: {text.strip()[::-1]})" | |
| if re.search(r"youtube\.com|youtu\.be", text): | |
| text += ("\n\n(This question is about a YouTube video. Use youtube_transcript for what is SAID, " | |
| "or watch_youtube for what is SHOWN. Do not rely on web search for the video's content.)") | |
| if file_expected and not local_file: | |
| text += "\n\n(Note: an attached file was expected but could not be downloaded. Give your best guess.)" | |
| f = local_file | |
| if f: | |
| low = f.lower() | |
| if low.endswith(IMAGE_EXT): | |
| text += f"\n\nAttached image path: {f} (use the analyze_image tool)" | |
| elif low.endswith(AUDIO_EXT): | |
| text += f"\n\nAttached audio path: {f} (use the transcribe_audio tool)" | |
| elif low.endswith(".py"): | |
| text += f"\n\nAttached Python file: {f} (use run_python with exec(open(path).read()))" | |
| elif low.endswith((".xlsx", ".xls", ".csv")): | |
| text += f"\n\nAttached spreadsheet: {f} (use read_file, then run_python with pandas for calculations)" | |
| else: | |
| text += f"\n\nAttached file path: {f} (use the read_file tool)" | |
| return text | |
| def clean(answer) -> str: | |
| """Trim a reply down to the bare answer for exact-match grading.""" | |
| text = re.sub(r"</?[a-zA-Z_][\w-]*>", "", str(answer)) | |
| lines = [l.strip() for l in text.strip().split("\n") if l.strip()] | |
| text = lines[-1] if lines else "" | |
| text = re.sub(r"^(the )?(final )?answer( is)?\s*:\s*", "", text, flags=re.I) | |
| text = text.strip().strip('"\'').strip().rstrip(".").strip() | |
| if text.upper() == "NONE": | |
| return "" | |
| if re.match(r"^(i'?m sorry|sorry|i apologi[sz]e|i can'?t|i cannot|i am unable|i'?m unable|without being able" | |
| r"|unfortunately|cannot determine|could you|please (provide|share)|no .* available)", text, re.I): | |
| return "" | |
| return text | |
| def format_answer(question: str, draft) -> str: | |
| """Second pass: turn a long or messy draft into the bare answer.""" | |
| draft = str(draft).strip() | |
| if not draft: | |
| return "" | |
| if len(draft) <= 60 and "\n" not in draft: | |
| return clean(draft) | |
| reply = llm.invoke([HumanMessage(content=FORMAT_PROMPT.format(question=question, draft=draft[-4000:]))]) | |
| return clean(reply.content) | |
| def looks_like_fake_tool_call(msg) -> bool: | |
| if getattr(msg, "tool_calls", None): | |
| return False | |
| text = (msg.content or "").strip() | |
| if not text.startswith("{"): | |
| return False | |
| try: | |
| json.loads(text) | |
| return True | |
| except Exception: | |
| return False | |
| class AgentState(TypedDict): | |
| messages: Annotated[list[AnyMessage], add_messages] | |
| # --- Basic Agent Definition --- | |
| # ----- THIS IS WERE YOU CAN BUILD WHAT YOU WANT ------ | |
| class BasicAgent: | |
| def __init__(self): | |
| llm_with_tools = llm.bind_tools(TOOLS) | |
| def assistant(state: AgentState): | |
| msgs = [SystemMessage(content=SYSTEM_PROMPT)] + state["messages"] | |
| tools_used = sum(isinstance(m, ToolMessage) for m in state["messages"]) | |
| if tools_used >= MAX_TOOL_CALLS: # budget used up: answer without tools | |
| return {"messages": [llm.invoke(msgs + [HumanMessage(content=FORCE_FINAL)])]} | |
| reply = llm_with_tools.invoke(msgs) | |
| for _ in range(2): # fix tool calls written as plain text | |
| if not looks_like_fake_tool_call(reply): | |
| break | |
| msgs = msgs + [reply, HumanMessage(content=FIX_FORMAT)] | |
| reply = llm_with_tools.invoke(msgs) | |
| return {"messages": [reply]} | |
| builder = StateGraph(AgentState) | |
| builder.add_node("assistant", assistant) | |
| builder.add_node("tools", ToolNode(TOOLS, handle_tool_errors=True)) | |
| builder.add_edge(START, "assistant") | |
| builder.add_conditional_edges("assistant", tools_condition) | |
| builder.add_edge("tools", "assistant") | |
| self.graph = builder.compile() | |
| self.recursion_limit = 2 * MAX_TOOL_CALLS + 6 | |
| print(f"BasicAgent initialized (LangGraph + Ollama: {OLLAMA_MODEL}, vision: {VISION_MODEL}).") | |
| def __call__(self, question: str, task_id: str = None, file_name: str = None) -> str: | |
| print(f"Agent received question (first 50 chars): {question[:50]}...") | |
| local_file = download_file(DEFAULT_API_URL, task_id, file_name) if (task_id and file_name) else None | |
| prompt = build_prompt(question, local_file, file_expected=bool(file_name)) | |
| start, final = time.time(), None | |
| for update in self.graph.stream( | |
| {"messages": [HumanMessage(content=prompt)]}, | |
| config={"recursion_limit": self.recursion_limit}, | |
| stream_mode="updates", | |
| ): | |
| for node, data in update.items(): | |
| for m in data["messages"]: | |
| t = f"[{time.time() - start:5.0f}s]" | |
| if getattr(m, "tool_calls", None): | |
| for c in m.tool_calls: | |
| print(t, "CALL ", c["name"], c["args"]) | |
| elif node == "tools": | |
| print(t, "RESULT", m.name, "->", str(m.content)[:150].replace("\n", " ")) | |
| else: | |
| print(t, "ANSWER", repr(str(m.content)[:200])) | |
| final = m | |
| answer = format_answer(question, final.content if final else "") | |
| print(f"Agent returning answer: {answer!r}") | |
| return answer | |
| 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}") | |
| 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 | |
| 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, task_id=task_id, file_name=item.get("file_name")) | |
| 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=False) |