Spaces:
Sleeping
Sleeping
update
Browse files3 unmodified lines4567891011121314151617185 unmodified lines242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741752 unmodified lines17817918018118218318418518618718818919010 unmodified lines2012022032042052062074 unmodified lines2122132142152162172182192202 unmodified lines2232242252262272282293 unmodified lines2332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622633 unmodified linesimport pandas as pdimport spacesimport jsonimport refrom smolagents import CodeAgent, InferenceClientModel, tool# --- Custom Tools that top scorers use ---@tooldef web_search(query: str) -> str:"""Performs a web search for the given query and returns the top results.Args:query: The search query."""5 unmodified linesresults = DDGS().text(query, max_results=8)if not results:return "No results found."formatted = "\n".join([f"- {r['title']}: {r['body']} ({r['href']})" for r in results])return formattedexcept Exception as e:return f"Search error: {e}"@tooldef visit_webpage(url: str) -> str:"""Visits a webpage and returns its content as markdown. Use this after web_search to get details.Args:url: The URL to visit."""try:import requestsfrom markdownify import markdownifyheaders = {"User-Agent": "Mozilla/5.0"}resp = requests.get(url, timeout=15, headers=headers)resp.raise_for_status()# Convert to markdown to save tokenstext = markdownify(resp.text)return text[:15000] # limit sizeexcept Exception as e:return f"Error visiting {url}: {e}"@tooldef read_file_content(file_path: str) -> str:"""Reads a file from local path. Supports .txt, .csv, .json, .pdf, .xlsxArgs:file_path: Absolute path to file in /tmp"""try:if not os.path.exists(file_path):return f"File not found: {file_path}"ext = file_path.split(".")[-1].lower()if ext == "txt" or ext == "md":with open(file_path, "r", encoding="utf-8", errors="ignore") as f:return f.read()[:20000]elif ext == "csv":import pandas as pddf = pd.read_csv(file_path)return df.to_string()[:20000]elif ext == "json":with open(file_path, "r") as f:return json.dumps(json.load(f), indent=2)[:20000]elif ext == "pdf":try:import PyPDF2reader = PyPDF2.PdfReader(file_path)text = "\n".join([p.extract_text() or "" for p in reader.pages])return text[:20000]except Exception as e:return f"PDF read error: {e}. Try python code with other libraries."elif ext in ["xlsx", "xls"]:import pandas as pddf = pd.read_excel(file_path)return df.to_string()[:20000]else:return f"File type {ext} not directly supported, use python code to read {file_path}"except Exception as e:return f"Error reading file: {e}"DEFAULT_API_URL = "https://agents-course-unit4-scoring.hf.space"class OptimizedAgent:def __init__(self):api_key = os.getenv("HF_TOKEN") or os.getenv("testkey")# Top performer model: Qwen2.5-72B is #1 for GAIA among HF Inference models# Alternative if rate-limited: "Qwen/Qwen3-32B" or "meta-llama/Meta-Llama-3.1-70B-Instruct"self.model = InferenceClientModel(model_id="Qwen/Qwen2.5-72B-Instruct",token=api_key,temperature=0.2, # Lower temp for exact match tasks)# CodeAgent is proven 15-20% better than ToolCallingAgent on GAIA# add_base_tools gives python_interpreter, final_answer etc.# planning_interval=3 forces it to plan every 3 steps (from open-deep-research)self.agent = CodeAgent(tools=[web_search, visit_webpage, read_file_content],model=self.model,add_base_tools=True,max_steps=12, # Top agents use 10-12 steps, not 5planning_interval=3,additional_authorized_imports=["os", "re", "json", "pandas", "numpy", "requests", "bs4","PIL", "datetime", "math", "csv", "io", "PyPDF2", "openpyxl"])# GAIA exact-match prompt from Open Deep Research + HF courseself.agent.prompt_templates["system_prompt"] = """You are an expert research assistant solving GAIA benchmark questions.RULES FOR FINAL ANSWER (CRITICAL - EXACT MATCH EVALUATION):- Your FINAL ANSWER must be a number OR as few words as possible OR a comma separated list- If asked for a number, don't use comma, don't use units like $ or % unless asked- If asked for a string, don't use articles (a, an, the), don't use abbreviations, write digits in plain text- If asked for a list, use comma separated format- NEVER include explanation in FINAL ANSWER, only the answer itself- Format: FINAL ANSWER: [your answer]PROCESS:1. First, PLAN: break down what you need to find2. SEARCH: use web_search for facts, visit_webpage for details3. READ: if file provided, use read_file_content or python code to analyze it4. CALCULATE: use python code for math, counting, date operations5. VERIFY: double check your answer matches the question6. FINAL ANSWERYou can use Python code freely. Always use code for calculations, not mental math.""" + self.agent.prompt_templates["system_prompt"]@spaces.GPU(duration=90)def ask_question(self, question, file_path=None):# Inject file context directly into question like top solutions dofull_q = questionif file_path:full_q = f"""You have a file at: {file_path}Question: {question}File info: name={os.path.basename(file_path)}You MUST read this file using read_file_content or python code. The answer likely requires it."""try:result = self.agent.run(full_q)# Clean result - extract after FINAL ANSWER:result_str = str(result).strip()if "FINAL ANSWER:" in result_str:result_str = result_str.split("FINAL ANSWER:")[-1].strip()# Remove markdown, quotesresult_str = result_str.strip().strip('"').strip("'")# Take first line only (GAIA wants single answer)result_str = result_str.split("\n")[0].strip()print(f"Cleaned answer: {result_str}")return result_strexcept Exception as e:print(f"Agent error: {e}")return f"ERROR: {e}"@spaces.GPU(duration=180) # Full run needs longer GPU slotdef run_and_submit_all(profile: gr.OAuthProfile | None):space_id = os.getenv("SPACE_ID")if not profile:return "Please Login to Hugging Face with the button first.", Noneusername = profile.usernameapi_url = DEFAULT_API_URL2 unmodified linesfiles_url = f"{api_url}/files"try:agent = OptimizedAgent()except Exception as e:return f"Error init agent: {e}", Noneagent_code = f"https://huggingface.co/spaces/{space_id}/tree/main"# Fetch questionstry:resp = requests.get(questions_url, timeout=15)resp.raise_for_status()10 unmodified linesfile_name = item.get("file_name")if not task_id or not question_text:continuefile_path = Noneif file_name:try:4 unmodified lineswith open(tmp_path, "wb") as f:f.write(fr.content)file_path = tmp_pathprint(f"Downloaded {file_name} for {task_id}")except Exception as fe:print(f"File download failed {task_id}: {fe}")try:ans = agent.ask_question(question_text, file_path=file_path)2 unmodified linesexcept Exception as e:results_log.append({"Task ID": task_id, "Question": question_text, "Submitted Answer": f"ERROR: {e}"})# Submitsubmission_data = {"username": username.strip(), "agent_code": agent_code, "answers": answers_payload}try:resp = requests.post(submit_url, json=submission_data, timeout=60)3 unmodified linesf"✅ Submission Successful!\n"f"User: {data.get('username')}\n"f"Score: {data.get('score', 'N/A')}% ({data.get('correct_count', '?')}/{data.get('total_attempted', '?')})\n"f"Message: {data.get('message', '')}\n\n"f"Top agents get 50-55% with Qwen2.5-72B + CodeAgent + planning. If you get 30%+ you pass.")return final_status, pd.DataFrame(results_log)except Exception as e:return f"Submission Failed: {e}\nResp: {getattr(e, 'response', '')}", pd.DataFrame(results_log)with gr.Blocks() as demo:gr.Markdown("# Optimized GAIA Agent ~ 50% Strategy")gr.Markdown("""**What makes this better than template (from leaderboard analysis):**- **Model:** Qwen2.5-72B-Instruct (best open model for GAIA, 55% in open-deep-research) vs Phi-3.5-mini- **Agent Type:** CodeAgent + planning_interval=3 (top teams use code-as-action, not JSON tool calling)- **Steps:** 12 steps vs 5 (GAIA needs multi-step reasoning)- **Tools:** web_search + visit_webpage (markdown) + read_file_content with PyPDF2/pandas (critical for file questions)- **Prompt:** GAIA exact-match rules + forced FINAL ANSWER parsing (fixes 20% of failures)- **File handling:** Auto-downloads /files/{task_id} and injects path into prompt1. Add HF_TOKEN secret in Settings2. Login3. Click Run""")gr.LoginButton()run_button = gr.Button("Run Evaluation & Submit All Answers by Purav")status_output = gr.Textbox(label="Result", lines=8, interactive=False)results_table = gr.DataFrame(label="Answers", wrap=True)run_button.click(fn=run_and_submit_all, outputs=[status_output, results_table])3 unmodified lines4567891011121314155 unmodified lines212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371382 unmodified lines14114214314414514614714814915015115210 unmodified lines1631641651661671684 unmodified lines1731741751761771781791802 unmodified lines1831841851861871883 unmodified lines1921931941951961971981992002012022032042052062072082092102112122132142152162172182193 unmodified linesimport pandas as pdimport spacesimport jsonfrom smolagents import CodeAgent, tool, LiteLLMModel# --- Tools ---@tooldef web_search(query: str) -> str:"""Performs a web search for the given query and returns top results.Args:query: The search query."""5 unmodified linesresults = DDGS().text(query, max_results=8)if not results:return "No results found."return "\n".join([f"- {r['title']}: {r['body']} ({r['href']})" for r in results])except Exception as e:return f"Search error: {e}"@tooldef visit_webpage(url: str) -> str:"""Visits a webpage and returns content as markdown.Args:url: URL to visit."""try:from markdownify import markdownifyheaders = {"User-Agent": "Mozilla/5.0"}resp = requests.get(url, timeout=15, headers=headers)resp.raise_for_status()return markdownify(resp.text)[:15000]except Exception as e:return f"Error visiting {url}: {e}"@tooldef read_file_content(file_path: str) -> str:"""Reads a local file. Supports txt, csv, json, pdf, xlsx.Args:file_path: Absolute path like /tmp/filename"""try:if not os.path.exists(file_path):return f"File not found: {file_path}"ext = file_path.split(".")[-1].lower()if ext in ["txt", "md"]:with open(file_path, "r", encoding="utf-8", errors="ignore") as f:return f.read()[:20000]elif ext == "csv":df = pd.read_csv(file_path)return df.to_string()[:20000]elif ext == "json":with open(file_path, "r") as f:return json.dumps(json.load(f), indent=2)[:20000]elif ext == "pdf":import PyPDF2reader = PyPDF2.PdfReader(file_path)return "\n".join([p.extract_text() or "" for p in reader.pages])[:20000]elif ext in ["xlsx", "xls"]:df = pd.read_excel(file_path)return df.to_string()[:20000]else:return f"Use python code to read {file_path}, type {ext} not auto-handled"except Exception as e:return f"Error reading: {e}"DEFAULT_API_URL = "https://agents-course-unit4-scoring.hf.space"class OptimizedAgentFree:def __init__(self):# GROQ is FREE - get key from console.groq.comgroq_key = os.getenv("GROQ_API_KEY")if not groq_key:raise ValueError("GROQ_API_KEY secret not found! Add it in Settings > Secrets. Get free key from https://console.groq.com/keys")# llama-3.3-70b-versatile is free, fast, and scores ~45% on GAIA L1# Alternatives: groq/qwen-2.5-32b-instruct, groq/llama-3.1-70b-versatileself.model = LiteLLMModel(model_id="groq/llama-3.3-70b-versatile",api_key=groq_key,temperature=0.2,)self.agent = CodeAgent(tools=[web_search, visit_webpage, read_file_content],model=self.model,add_base_tools=True,max_steps=10,planning_interval=3,additional_authorized_imports=["os", "re", "json", "pandas", "numpy", "requests", "bs4","PIL", "datetime", "math", "csv", "io", "PyPDF2", "openpyxl"])self.agent.prompt_templates["system_prompt"] = """You are an expert GAIA solver.CRITICAL FINAL ANSWER RULES (EXACT MATCH):- FINAL ANSWER must be ONLY the answer: number OR few words OR comma list- No units ($, %) unless asked, no commas in numbers, no articles- Format: FINAL ANSWER: [answer]PROCESS: PLAN -> SEARCH -> READ FILE IF ANY -> PYTHON FOR MATH -> VERIFY -> FINAL ANSWERUse code for any calculation.""" + self.agent.prompt_templates["system_prompt"]@spaces.GPU(duration=90)def ask_question(self, question, file_path=None):full_q = questionif file_path:full_q = f"File at: {file_path} (name={os.path.basename(file_path)}). MUST read it.\nQuestion: {question}"try:result = self.agent.run(full_q)s = str(result).strip()if "FINAL ANSWER:" in s:s = s.split("FINAL ANSWER:")[-1].strip()s = s.strip().strip('"').strip("'").split("\n")[0].strip()print(f"Answer: {s}")return sexcept Exception as e:print(f"Agent error: {e}")return f"ERROR: {e}"@spaces.GPU(duration=180)def run_and_submit_all(profile: gr.OAuthProfile | None):space_id = os.getenv("SPACE_ID")if not profile:return "Please Login to Hugging Face first (Login button top right).", Noneusername = profile.usernameapi_url = DEFAULT_API_URL2 unmodified linesfiles_url = f"{api_url}/files"try:agent = OptimizedAgentFree()except Exception as e:return f"Error init: {e}", Noneagent_code = f"https://huggingface.co/spaces/{space_id}/tree/main"try:resp = requests.get(questions_url, timeout=15)resp.raise_for_status()10 unmodified linesfile_name = item.get("file_name")if not task_id or not question_text:continuefile_path = Noneif file_name:try:4 unmodified lineswith open(tmp_path, "wb") as f:f.write(fr.content)file_path = tmp_pathexcept Exception as fe:print(f"File fail {task_id}: {fe}")try:ans = agent.ask_question(question_text, file_path=file_path)2 unmodified linesexcept Exception as e:results_log.append({"Task ID": task_id, "Question": question_text, "Submitted Answer": f"ERROR: {e}"})submission_data = {"username": username.strip(), "agent_code": agent_code, "answers": answers_payload}try:resp = requests.post(submit_url, json=submission_data, timeout=60)3 unmodified linesf"✅ Submission Successful!\n"f"User: {data.get('username')}\n"f"Score: {data.get('score', 'N/A')}% ({data.get('correct_count', '?')}/{data.get('total_attempted', '?')})\n"f"Message: {data.get('message', '')}\n"f"Model: Groq llama-3.3-70b-versatile (FREE, no HF credits needed)")return final_status, pd.DataFrame(results_log)except Exception as e:return f"Submission Failed: {e}", pd.DataFrame(results_log)with gr.Blocks() as demo:gr.Markdown("# Optimized FREE Agent - Groq (No HF credits needed)")gr.Markdown("""**Fix for 402 Payment Required:**Old code used `InferenceClientModel` -> `router.huggingface.co` which now charges.This version uses **Groq FREE API** -> `groq/llama-3.3-70b-versatile`**Setup (1 min):**1. Go to https://console.groq.com/keys -> Create free API key2. In your Space Settings > Secrets > New secret: Name=`GROQ_API_KEY`, Value=`gsk_...`3. Keep `HF_TOKEN` too if you have it, but not required now4. Login and Run""")gr.LoginButton()run_button = gr.Button("Run Evaluation & Submit")status_output = gr.Textbox(label="Result", lines=8, interactive=False)results_table = gr.DataFrame(label="Answers", wrap=True)run_button.click(fn=run_and_submit_all, outputs=[status_output, results_table])
app.py+60-104