Spaces:
Sleeping
Sleeping
update
Browse files
app.py
CHANGED
|
@@ -4,15 +4,12 @@ import requests
|
|
| 4 |
import pandas as pd
|
| 5 |
import spaces
|
| 6 |
import json
|
| 7 |
-
import
|
| 8 |
-
from smolagents import CodeAgent, InferenceClientModel, tool
|
| 9 |
-
|
| 10 |
-
# --- Custom Tools that top scorers use ---
|
| 11 |
|
|
|
|
| 12 |
@tool
|
| 13 |
def web_search(query: str) -> str:
|
| 14 |
-
"""
|
| 15 |
-
Performs a web search for the given query and returns the top results.
|
| 16 |
Args:
|
| 17 |
query: The search query.
|
| 18 |
"""
|
|
@@ -24,152 +21,118 @@ def web_search(query: str) -> str:
|
|
| 24 |
results = DDGS().text(query, max_results=8)
|
| 25 |
if not results:
|
| 26 |
return "No results found."
|
| 27 |
-
|
| 28 |
-
return formatted
|
| 29 |
except Exception as e:
|
| 30 |
return f"Search error: {e}"
|
| 31 |
|
| 32 |
@tool
|
| 33 |
def visit_webpage(url: str) -> str:
|
| 34 |
-
"""
|
| 35 |
-
Visits a webpage and returns its content as markdown. Use this after web_search to get details.
|
| 36 |
Args:
|
| 37 |
-
url:
|
| 38 |
"""
|
| 39 |
try:
|
| 40 |
-
import requests
|
| 41 |
from markdownify import markdownify
|
| 42 |
headers = {"User-Agent": "Mozilla/5.0"}
|
| 43 |
resp = requests.get(url, timeout=15, headers=headers)
|
| 44 |
resp.raise_for_status()
|
| 45 |
-
|
| 46 |
-
text = markdownify(resp.text)
|
| 47 |
-
return text[:15000] # limit size
|
| 48 |
except Exception as e:
|
| 49 |
return f"Error visiting {url}: {e}"
|
| 50 |
|
| 51 |
@tool
|
| 52 |
def read_file_content(file_path: str) -> str:
|
| 53 |
-
"""
|
| 54 |
-
Reads a file from local path. Supports .txt, .csv, .json, .pdf, .xlsx
|
| 55 |
Args:
|
| 56 |
-
file_path: Absolute path
|
| 57 |
"""
|
| 58 |
try:
|
| 59 |
if not os.path.exists(file_path):
|
| 60 |
return f"File not found: {file_path}"
|
| 61 |
ext = file_path.split(".")[-1].lower()
|
| 62 |
-
if ext
|
| 63 |
with open(file_path, "r", encoding="utf-8", errors="ignore") as f:
|
| 64 |
return f.read()[:20000]
|
| 65 |
elif ext == "csv":
|
| 66 |
-
import pandas as pd
|
| 67 |
df = pd.read_csv(file_path)
|
| 68 |
return df.to_string()[:20000]
|
| 69 |
elif ext == "json":
|
| 70 |
with open(file_path, "r") as f:
|
| 71 |
return json.dumps(json.load(f), indent=2)[:20000]
|
| 72 |
elif ext == "pdf":
|
| 73 |
-
|
| 74 |
-
|
| 75 |
-
|
| 76 |
-
text = "\n".join([p.extract_text() or "" for p in reader.pages])
|
| 77 |
-
return text[:20000]
|
| 78 |
-
except Exception as e:
|
| 79 |
-
return f"PDF read error: {e}. Try python code with other libraries."
|
| 80 |
elif ext in ["xlsx", "xls"]:
|
| 81 |
-
import pandas as pd
|
| 82 |
df = pd.read_excel(file_path)
|
| 83 |
return df.to_string()[:20000]
|
| 84 |
else:
|
| 85 |
-
return f"
|
| 86 |
except Exception as e:
|
| 87 |
-
return f"Error reading
|
| 88 |
|
| 89 |
DEFAULT_API_URL = "https://agents-course-unit4-scoring.hf.space"
|
| 90 |
|
| 91 |
-
class
|
| 92 |
def __init__(self):
|
| 93 |
-
|
| 94 |
-
|
| 95 |
-
|
| 96 |
-
|
| 97 |
-
|
| 98 |
-
|
| 99 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
| 100 |
)
|
| 101 |
|
| 102 |
-
# CodeAgent is proven 15-20% better than ToolCallingAgent on GAIA
|
| 103 |
-
# add_base_tools gives python_interpreter, final_answer etc.
|
| 104 |
-
# planning_interval=3 forces it to plan every 3 steps (from open-deep-research)
|
| 105 |
self.agent = CodeAgent(
|
| 106 |
tools=[web_search, visit_webpage, read_file_content],
|
| 107 |
model=self.model,
|
| 108 |
add_base_tools=True,
|
| 109 |
-
max_steps=
|
| 110 |
planning_interval=3,
|
| 111 |
additional_authorized_imports=[
|
| 112 |
"os", "re", "json", "pandas", "numpy", "requests", "bs4",
|
| 113 |
"PIL", "datetime", "math", "csv", "io", "PyPDF2", "openpyxl"
|
| 114 |
]
|
| 115 |
)
|
| 116 |
-
|
| 117 |
-
# GAIA exact-match prompt from Open Deep Research + HF course
|
| 118 |
self.agent.prompt_templates["system_prompt"] = """
|
| 119 |
-
You are an expert
|
| 120 |
-
|
| 121 |
-
RULES FOR FINAL ANSWER (CRITICAL - EXACT MATCH EVALUATION):
|
| 122 |
-
- Your FINAL ANSWER must be a number OR as few words as possible OR a comma separated list
|
| 123 |
-
- If asked for a number, don't use comma, don't use units like $ or % unless asked
|
| 124 |
-
- If asked for a string, don't use articles (a, an, the), don't use abbreviations, write digits in plain text
|
| 125 |
-
- If asked for a list, use comma separated format
|
| 126 |
-
- NEVER include explanation in FINAL ANSWER, only the answer itself
|
| 127 |
-
- Format: FINAL ANSWER: [your answer]
|
| 128 |
|
| 129 |
-
|
| 130 |
-
|
| 131 |
-
|
| 132 |
-
|
| 133 |
-
4. CALCULATE: use python code for math, counting, date operations
|
| 134 |
-
5. VERIFY: double check your answer matches the question
|
| 135 |
-
6. FINAL ANSWER
|
| 136 |
|
| 137 |
-
|
|
|
|
| 138 |
""" + self.agent.prompt_templates["system_prompt"]
|
| 139 |
|
| 140 |
@spaces.GPU(duration=90)
|
| 141 |
def ask_question(self, question, file_path=None):
|
| 142 |
-
# Inject file context directly into question like top solutions do
|
| 143 |
full_q = question
|
| 144 |
if file_path:
|
| 145 |
-
full_q = f"
|
| 146 |
-
Question: {question}
|
| 147 |
-
|
| 148 |
-
File info: name={os.path.basename(file_path)}
|
| 149 |
-
You MUST read this file using read_file_content or python code. The answer likely requires it.
|
| 150 |
-
"""
|
| 151 |
try:
|
| 152 |
result = self.agent.run(full_q)
|
| 153 |
-
|
| 154 |
-
|
| 155 |
-
|
| 156 |
-
|
| 157 |
-
|
| 158 |
-
|
| 159 |
-
# Take first line only (GAIA wants single answer)
|
| 160 |
-
result_str = result_str.split("\n")[0].strip()
|
| 161 |
-
print(f"Cleaned answer: {result_str}")
|
| 162 |
-
return result_str
|
| 163 |
except Exception as e:
|
| 164 |
print(f"Agent error: {e}")
|
| 165 |
return f"ERROR: {e}"
|
| 166 |
|
| 167 |
-
|
| 168 |
-
@spaces.GPU(duration=180) # Full run needs longer GPU slot
|
| 169 |
def run_and_submit_all(profile: gr.OAuthProfile | None):
|
| 170 |
space_id = os.getenv("SPACE_ID")
|
| 171 |
if not profile:
|
| 172 |
-
return "Please Login to Hugging Face
|
| 173 |
username = profile.username
|
| 174 |
|
| 175 |
api_url = DEFAULT_API_URL
|
|
@@ -178,13 +141,12 @@ def run_and_submit_all(profile: gr.OAuthProfile | None):
|
|
| 178 |
files_url = f"{api_url}/files"
|
| 179 |
|
| 180 |
try:
|
| 181 |
-
agent =
|
| 182 |
except Exception as e:
|
| 183 |
-
return f"Error init
|
| 184 |
|
| 185 |
agent_code = f"https://huggingface.co/spaces/{space_id}/tree/main"
|
| 186 |
|
| 187 |
-
# Fetch questions
|
| 188 |
try:
|
| 189 |
resp = requests.get(questions_url, timeout=15)
|
| 190 |
resp.raise_for_status()
|
|
@@ -201,7 +163,6 @@ def run_and_submit_all(profile: gr.OAuthProfile | None):
|
|
| 201 |
file_name = item.get("file_name")
|
| 202 |
if not task_id or not question_text:
|
| 203 |
continue
|
| 204 |
-
|
| 205 |
file_path = None
|
| 206 |
if file_name:
|
| 207 |
try:
|
|
@@ -212,9 +173,8 @@ def run_and_submit_all(profile: gr.OAuthProfile | None):
|
|
| 212 |
with open(tmp_path, "wb") as f:
|
| 213 |
f.write(fr.content)
|
| 214 |
file_path = tmp_path
|
| 215 |
-
print(f"Downloaded {file_name} for {task_id}")
|
| 216 |
except Exception as fe:
|
| 217 |
-
print(f"File
|
| 218 |
|
| 219 |
try:
|
| 220 |
ans = agent.ask_question(question_text, file_path=file_path)
|
|
@@ -223,7 +183,6 @@ def run_and_submit_all(profile: gr.OAuthProfile | None):
|
|
| 223 |
except Exception as e:
|
| 224 |
results_log.append({"Task ID": task_id, "Question": question_text, "Submitted Answer": f"ERROR: {e}"})
|
| 225 |
|
| 226 |
-
# Submit
|
| 227 |
submission_data = {"username": username.strip(), "agent_code": agent_code, "answers": answers_payload}
|
| 228 |
try:
|
| 229 |
resp = requests.post(submit_url, json=submission_data, timeout=60)
|
|
@@ -233,31 +192,28 @@ def run_and_submit_all(profile: gr.OAuthProfile | None):
|
|
| 233 |
f"✅ Submission Successful!\n"
|
| 234 |
f"User: {data.get('username')}\n"
|
| 235 |
f"Score: {data.get('score', 'N/A')}% ({data.get('correct_count', '?')}/{data.get('total_attempted', '?')})\n"
|
| 236 |
-
f"Message: {data.get('message', '')}\n
|
| 237 |
-
f"
|
| 238 |
)
|
| 239 |
return final_status, pd.DataFrame(results_log)
|
| 240 |
except Exception as e:
|
| 241 |
-
return f"Submission Failed: {e}
|
| 242 |
-
|
| 243 |
|
| 244 |
with gr.Blocks() as demo:
|
| 245 |
-
gr.Markdown("# Optimized
|
| 246 |
gr.Markdown("""
|
| 247 |
-
**
|
| 248 |
-
|
| 249 |
-
|
| 250 |
-
- **Steps:** 12 steps vs 5 (GAIA needs multi-step reasoning)
|
| 251 |
-
- **Tools:** web_search + visit_webpage (markdown) + read_file_content with PyPDF2/pandas (critical for file questions)
|
| 252 |
-
- **Prompt:** GAIA exact-match rules + forced FINAL ANSWER parsing (fixes 20% of failures)
|
| 253 |
-
- **File handling:** Auto-downloads /files/{task_id} and injects path into prompt
|
| 254 |
|
| 255 |
-
1
|
| 256 |
-
|
| 257 |
-
|
|
|
|
|
|
|
| 258 |
""")
|
| 259 |
gr.LoginButton()
|
| 260 |
-
run_button = gr.Button("Run Evaluation & Submit
|
| 261 |
status_output = gr.Textbox(label="Result", lines=8, interactive=False)
|
| 262 |
results_table = gr.DataFrame(label="Answers", wrap=True)
|
| 263 |
run_button.click(fn=run_and_submit_all, outputs=[status_output, results_table])
|
|
|
|
| 4 |
import pandas as pd
|
| 5 |
import spaces
|
| 6 |
import json
|
| 7 |
+
from smolagents import CodeAgent, tool, LiteLLMModel
|
|
|
|
|
|
|
|
|
|
| 8 |
|
| 9 |
+
# --- Tools ---
|
| 10 |
@tool
|
| 11 |
def web_search(query: str) -> str:
|
| 12 |
+
"""Performs a web search for the given query and returns top results.
|
|
|
|
| 13 |
Args:
|
| 14 |
query: The search query.
|
| 15 |
"""
|
|
|
|
| 21 |
results = DDGS().text(query, max_results=8)
|
| 22 |
if not results:
|
| 23 |
return "No results found."
|
| 24 |
+
return "\n".join([f"- {r['title']}: {r['body']} ({r['href']})" for r in results])
|
|
|
|
| 25 |
except Exception as e:
|
| 26 |
return f"Search error: {e}"
|
| 27 |
|
| 28 |
@tool
|
| 29 |
def visit_webpage(url: str) -> str:
|
| 30 |
+
"""Visits a webpage and returns content as markdown.
|
|
|
|
| 31 |
Args:
|
| 32 |
+
url: URL to visit.
|
| 33 |
"""
|
| 34 |
try:
|
|
|
|
| 35 |
from markdownify import markdownify
|
| 36 |
headers = {"User-Agent": "Mozilla/5.0"}
|
| 37 |
resp = requests.get(url, timeout=15, headers=headers)
|
| 38 |
resp.raise_for_status()
|
| 39 |
+
return markdownify(resp.text)[:15000]
|
|
|
|
|
|
|
| 40 |
except Exception as e:
|
| 41 |
return f"Error visiting {url}: {e}"
|
| 42 |
|
| 43 |
@tool
|
| 44 |
def read_file_content(file_path: str) -> str:
|
| 45 |
+
"""Reads a local file. Supports txt, csv, json, pdf, xlsx.
|
|
|
|
| 46 |
Args:
|
| 47 |
+
file_path: Absolute path like /tmp/filename
|
| 48 |
"""
|
| 49 |
try:
|
| 50 |
if not os.path.exists(file_path):
|
| 51 |
return f"File not found: {file_path}"
|
| 52 |
ext = file_path.split(".")[-1].lower()
|
| 53 |
+
if ext in ["txt", "md"]:
|
| 54 |
with open(file_path, "r", encoding="utf-8", errors="ignore") as f:
|
| 55 |
return f.read()[:20000]
|
| 56 |
elif ext == "csv":
|
|
|
|
| 57 |
df = pd.read_csv(file_path)
|
| 58 |
return df.to_string()[:20000]
|
| 59 |
elif ext == "json":
|
| 60 |
with open(file_path, "r") as f:
|
| 61 |
return json.dumps(json.load(f), indent=2)[:20000]
|
| 62 |
elif ext == "pdf":
|
| 63 |
+
import PyPDF2
|
| 64 |
+
reader = PyPDF2.PdfReader(file_path)
|
| 65 |
+
return "\n".join([p.extract_text() or "" for p in reader.pages])[:20000]
|
|
|
|
|
|
|
|
|
|
|
|
|
| 66 |
elif ext in ["xlsx", "xls"]:
|
|
|
|
| 67 |
df = pd.read_excel(file_path)
|
| 68 |
return df.to_string()[:20000]
|
| 69 |
else:
|
| 70 |
+
return f"Use python code to read {file_path}, type {ext} not auto-handled"
|
| 71 |
except Exception as e:
|
| 72 |
+
return f"Error reading: {e}"
|
| 73 |
|
| 74 |
DEFAULT_API_URL = "https://agents-course-unit4-scoring.hf.space"
|
| 75 |
|
| 76 |
+
class OptimizedAgentFree:
|
| 77 |
def __init__(self):
|
| 78 |
+
# GROQ is FREE - get key from console.groq.com
|
| 79 |
+
groq_key = os.getenv("GROQ_API_KEY")
|
| 80 |
+
if not groq_key:
|
| 81 |
+
raise ValueError("GROQ_API_KEY secret not found! Add it in Settings > Secrets. Get free key from https://console.groq.com/keys")
|
| 82 |
+
|
| 83 |
+
# llama-3.3-70b-versatile is free, fast, and scores ~45% on GAIA L1
|
| 84 |
+
# Alternatives: groq/qwen-2.5-32b-instruct, groq/llama-3.1-70b-versatile
|
| 85 |
+
self.model = LiteLLMModel(
|
| 86 |
+
model_id="groq/llama-3.3-70b-versatile",
|
| 87 |
+
api_key=groq_key,
|
| 88 |
+
temperature=0.2,
|
| 89 |
)
|
| 90 |
|
|
|
|
|
|
|
|
|
|
| 91 |
self.agent = CodeAgent(
|
| 92 |
tools=[web_search, visit_webpage, read_file_content],
|
| 93 |
model=self.model,
|
| 94 |
add_base_tools=True,
|
| 95 |
+
max_steps=10,
|
| 96 |
planning_interval=3,
|
| 97 |
additional_authorized_imports=[
|
| 98 |
"os", "re", "json", "pandas", "numpy", "requests", "bs4",
|
| 99 |
"PIL", "datetime", "math", "csv", "io", "PyPDF2", "openpyxl"
|
| 100 |
]
|
| 101 |
)
|
|
|
|
|
|
|
| 102 |
self.agent.prompt_templates["system_prompt"] = """
|
| 103 |
+
You are an expert GAIA solver.
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 104 |
|
| 105 |
+
CRITICAL FINAL ANSWER RULES (EXACT MATCH):
|
| 106 |
+
- FINAL ANSWER must be ONLY the answer: number OR few words OR comma list
|
| 107 |
+
- No units ($, %) unless asked, no commas in numbers, no articles
|
| 108 |
+
- Format: FINAL ANSWER: [answer]
|
|
|
|
|
|
|
|
|
|
| 109 |
|
| 110 |
+
PROCESS: PLAN -> SEARCH -> READ FILE IF ANY -> PYTHON FOR MATH -> VERIFY -> FINAL ANSWER
|
| 111 |
+
Use code for any calculation.
|
| 112 |
""" + self.agent.prompt_templates["system_prompt"]
|
| 113 |
|
| 114 |
@spaces.GPU(duration=90)
|
| 115 |
def ask_question(self, question, file_path=None):
|
|
|
|
| 116 |
full_q = question
|
| 117 |
if file_path:
|
| 118 |
+
full_q = f"File at: {file_path} (name={os.path.basename(file_path)}). MUST read it.\nQuestion: {question}"
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 119 |
try:
|
| 120 |
result = self.agent.run(full_q)
|
| 121 |
+
s = str(result).strip()
|
| 122 |
+
if "FINAL ANSWER:" in s:
|
| 123 |
+
s = s.split("FINAL ANSWER:")[-1].strip()
|
| 124 |
+
s = s.strip().strip('"').strip("'").split("\n")[0].strip()
|
| 125 |
+
print(f"Answer: {s}")
|
| 126 |
+
return s
|
|
|
|
|
|
|
|
|
|
|
|
|
| 127 |
except Exception as e:
|
| 128 |
print(f"Agent error: {e}")
|
| 129 |
return f"ERROR: {e}"
|
| 130 |
|
| 131 |
+
@spaces.GPU(duration=180)
|
|
|
|
| 132 |
def run_and_submit_all(profile: gr.OAuthProfile | None):
|
| 133 |
space_id = os.getenv("SPACE_ID")
|
| 134 |
if not profile:
|
| 135 |
+
return "Please Login to Hugging Face first (Login button top right).", None
|
| 136 |
username = profile.username
|
| 137 |
|
| 138 |
api_url = DEFAULT_API_URL
|
|
|
|
| 141 |
files_url = f"{api_url}/files"
|
| 142 |
|
| 143 |
try:
|
| 144 |
+
agent = OptimizedAgentFree()
|
| 145 |
except Exception as e:
|
| 146 |
+
return f"Error init: {e}", None
|
| 147 |
|
| 148 |
agent_code = f"https://huggingface.co/spaces/{space_id}/tree/main"
|
| 149 |
|
|
|
|
| 150 |
try:
|
| 151 |
resp = requests.get(questions_url, timeout=15)
|
| 152 |
resp.raise_for_status()
|
|
|
|
| 163 |
file_name = item.get("file_name")
|
| 164 |
if not task_id or not question_text:
|
| 165 |
continue
|
|
|
|
| 166 |
file_path = None
|
| 167 |
if file_name:
|
| 168 |
try:
|
|
|
|
| 173 |
with open(tmp_path, "wb") as f:
|
| 174 |
f.write(fr.content)
|
| 175 |
file_path = tmp_path
|
|
|
|
| 176 |
except Exception as fe:
|
| 177 |
+
print(f"File fail {task_id}: {fe}")
|
| 178 |
|
| 179 |
try:
|
| 180 |
ans = agent.ask_question(question_text, file_path=file_path)
|
|
|
|
| 183 |
except Exception as e:
|
| 184 |
results_log.append({"Task ID": task_id, "Question": question_text, "Submitted Answer": f"ERROR: {e}"})
|
| 185 |
|
|
|
|
| 186 |
submission_data = {"username": username.strip(), "agent_code": agent_code, "answers": answers_payload}
|
| 187 |
try:
|
| 188 |
resp = requests.post(submit_url, json=submission_data, timeout=60)
|
|
|
|
| 192 |
f"✅ Submission Successful!\n"
|
| 193 |
f"User: {data.get('username')}\n"
|
| 194 |
f"Score: {data.get('score', 'N/A')}% ({data.get('correct_count', '?')}/{data.get('total_attempted', '?')})\n"
|
| 195 |
+
f"Message: {data.get('message', '')}\n"
|
| 196 |
+
f"Model: Groq llama-3.3-70b-versatile (FREE, no HF credits needed)"
|
| 197 |
)
|
| 198 |
return final_status, pd.DataFrame(results_log)
|
| 199 |
except Exception as e:
|
| 200 |
+
return f"Submission Failed: {e}", pd.DataFrame(results_log)
|
|
|
|
| 201 |
|
| 202 |
with gr.Blocks() as demo:
|
| 203 |
+
gr.Markdown("# Optimized FREE Agent - Groq (No HF credits needed)")
|
| 204 |
gr.Markdown("""
|
| 205 |
+
**Fix for 402 Payment Required:**
|
| 206 |
+
Old code used `InferenceClientModel` -> `router.huggingface.co` which now charges.
|
| 207 |
+
This version uses **Groq FREE API** -> `groq/llama-3.3-70b-versatile`
|
|
|
|
|
|
|
|
|
|
|
|
|
| 208 |
|
| 209 |
+
**Setup (1 min):**
|
| 210 |
+
1. Go to https://console.groq.com/keys -> Create free API key
|
| 211 |
+
2. In your Space Settings > Secrets > New secret: Name=`GROQ_API_KEY`, Value=`gsk_...`
|
| 212 |
+
3. Keep `HF_TOKEN` too if you have it, but not required now
|
| 213 |
+
4. Login and Run
|
| 214 |
""")
|
| 215 |
gr.LoginButton()
|
| 216 |
+
run_button = gr.Button("Run Evaluation & Submit")
|
| 217 |
status_output = gr.Textbox(label="Result", lines=8, interactive=False)
|
| 218 |
results_table = gr.DataFrame(label="Answers", wrap=True)
|
| 219 |
run_button.click(fn=run_and_submit_all, outputs=[status_output, results_table])
|