Spaces:
Sleeping
Sleeping
Qscar KIM commited on
Commit ยท
e45db2e
1
Parent(s): 56ac7c7
update codes
Browse files
app.py
CHANGED
|
@@ -3,54 +3,130 @@ import gradio as gr
|
|
| 3 |
import requests
|
| 4 |
import inspect
|
| 5 |
import pandas as pd
|
|
|
|
|
|
|
|
|
|
| 6 |
|
| 7 |
-
import
|
| 8 |
-
from smolagents import CodeAgent, InferenceClientModel, TransformersModel, OpenAIModel
|
| 9 |
-
from smolagents import DuckDuckGoSearchTool
|
| 10 |
|
| 11 |
-
|
| 12 |
-
# (Keep Constants as is)
|
| 13 |
# --- Constants ---
|
| 14 |
DEFAULT_API_URL = "https://agents-course-unit4-scoring.hf.space"
|
| 15 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 16 |
# --- Basic Agent Definition ---
|
| 17 |
-
# ----- THIS IS WERE YOU CAN BUILD WHAT YOU WANT ------
|
| 18 |
class BasicAgent:
|
| 19 |
def __init__(self):
|
| 20 |
-
|
| 21 |
-
|
| 22 |
-
|
| 23 |
-
# model = InferenceClientModel(
|
| 24 |
-
# token=hf_token
|
| 25 |
-
# )
|
| 26 |
-
|
| 27 |
-
model = OpenAIModel(
|
| 28 |
-
model_id="deepseek-chat",
|
| 29 |
-
api_base="https://api.deepseek.com",
|
| 30 |
-
api_key=os.getenv("DEEPSEEK_API_KEY"),
|
| 31 |
)
|
|
|
|
|
|
|
| 32 |
|
| 33 |
-
#
|
| 34 |
-
|
| 35 |
-
|
| 36 |
-
|
| 37 |
-
|
| 38 |
-
|
| 39 |
-
model=model,
|
| 40 |
-
add_base_tools=True, # Add any additional base tools
|
| 41 |
-
planning_interval=3 # Enable planning every 3 steps
|
| 42 |
)
|
|
|
|
| 43 |
|
| 44 |
def __call__(self, question: str) -> str:
|
| 45 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 46 |
|
| 47 |
def run_and_submit_all( profile: gr.OAuthProfile | None):
|
| 48 |
-
""
|
| 49 |
-
Fetches all questions, runs the BasicAgent on them, submits all answers,
|
| 50 |
-
and displays the results.
|
| 51 |
-
"""
|
| 52 |
-
# --- Determine HF Space Runtime URL and Repo URL ---
|
| 53 |
-
space_id = os.getenv("SPACE_ID") # Get the SPACE_ID for sending link to the code
|
| 54 |
|
| 55 |
if profile:
|
| 56 |
username= f"{profile.username}"
|
|
@@ -63,17 +139,14 @@ def run_and_submit_all( profile: gr.OAuthProfile | None):
|
|
| 63 |
questions_url = f"{api_url}/questions"
|
| 64 |
submit_url = f"{api_url}/submit"
|
| 65 |
|
| 66 |
-
# 1. Instantiate Agent ( modify this part to create your agent)
|
| 67 |
try:
|
| 68 |
agent = BasicAgent()
|
| 69 |
except Exception as e:
|
| 70 |
print(f"Error instantiating agent: {e}")
|
| 71 |
return f"Error initializing agent: {e}", None
|
| 72 |
-
# 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)
|
| 73 |
agent_code = f"https://huggingface.co/spaces/{space_id}/tree/main"
|
| 74 |
print(agent_code)
|
| 75 |
|
| 76 |
-
# 2. Fetch Questions
|
| 77 |
print(f"Fetching questions from: {questions_url}")
|
| 78 |
try:
|
| 79 |
response = requests.get(questions_url, timeout=15)
|
|
@@ -94,7 +167,6 @@ def run_and_submit_all( profile: gr.OAuthProfile | None):
|
|
| 94 |
print(f"An unexpected error occurred fetching questions: {e}")
|
| 95 |
return f"An unexpected error occurred fetching questions: {e}", None
|
| 96 |
|
| 97 |
-
# 3. Run your Agent
|
| 98 |
results_log = []
|
| 99 |
answers_payload = []
|
| 100 |
print(f"Running agent on {len(questions_data)} questions...")
|
|
@@ -116,12 +188,10 @@ def run_and_submit_all( profile: gr.OAuthProfile | None):
|
|
| 116 |
print("Agent did not produce any answers to submit.")
|
| 117 |
return "Agent did not produce any answers to submit.", pd.DataFrame(results_log)
|
| 118 |
|
| 119 |
-
# 4. Prepare Submission
|
| 120 |
submission_data = {"username": username.strip(), "agent_code": agent_code, "answers": answers_payload}
|
| 121 |
status_update = f"Agent finished. Submitting {len(answers_payload)} answers for user '{username}'..."
|
| 122 |
print(status_update)
|
| 123 |
|
| 124 |
-
# 5. Submit
|
| 125 |
print(f"Submitting {len(answers_payload)} answers to: {submit_url}")
|
| 126 |
try:
|
| 127 |
response = requests.post(submit_url, json=submission_data, timeout=60)
|
|
@@ -164,29 +234,20 @@ def run_and_submit_all( profile: gr.OAuthProfile | None):
|
|
| 164 |
results_df = pd.DataFrame(results_log)
|
| 165 |
return status_message, results_df
|
| 166 |
|
| 167 |
-
|
| 168 |
-
# --- Build Gradio Interface using Blocks ---
|
| 169 |
with gr.Blocks() as demo:
|
| 170 |
gr.Markdown("# Basic Agent Evaluation Runner")
|
| 171 |
gr.Markdown(
|
| 172 |
"""
|
| 173 |
**Instructions:**
|
| 174 |
-
1.
|
| 175 |
-
2.
|
| 176 |
-
3.
|
| 177 |
-
---
|
| 178 |
-
**Disclaimers:**
|
| 179 |
-
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).
|
| 180 |
-
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.
|
| 181 |
"""
|
| 182 |
)
|
| 183 |
|
| 184 |
gr.LoginButton()
|
| 185 |
-
|
| 186 |
run_button = gr.Button("Run Evaluation & Submit All Answers")
|
| 187 |
-
|
| 188 |
status_output = gr.Textbox(label="Run Status / Submission Result", lines=5, interactive=False)
|
| 189 |
-
# Removed max_rows=10 from DataFrame constructor
|
| 190 |
results_table = gr.DataFrame(label="Questions and Agent Answers", wrap=True)
|
| 191 |
|
| 192 |
run_button.click(
|
|
@@ -195,25 +256,4 @@ with gr.Blocks() as demo:
|
|
| 195 |
)
|
| 196 |
|
| 197 |
if __name__ == "__main__":
|
| 198 |
-
print("\n" + "-"*30 + " App Starting " + "-"*30)
|
| 199 |
-
# Check for SPACE_HOST and SPACE_ID at startup for information
|
| 200 |
-
space_host_startup = os.getenv("SPACE_HOST")
|
| 201 |
-
space_id_startup = os.getenv("SPACE_ID") # Get SPACE_ID at startup
|
| 202 |
-
|
| 203 |
-
if space_host_startup:
|
| 204 |
-
print(f"โ
SPACE_HOST found: {space_host_startup}")
|
| 205 |
-
print(f" Runtime URL should be: https://{space_host_startup}.hf.space")
|
| 206 |
-
else:
|
| 207 |
-
print("โน๏ธ SPACE_HOST environment variable not found (running locally?).")
|
| 208 |
-
|
| 209 |
-
if space_id_startup: # Print repo URLs if SPACE_ID is found
|
| 210 |
-
print(f"โ
SPACE_ID found: {space_id_startup}")
|
| 211 |
-
print(f" Repo URL: https://huggingface.co/spaces/{space_id_startup}")
|
| 212 |
-
print(f" Repo Tree URL: https://huggingface.co/spaces/{space_id_startup}/tree/main")
|
| 213 |
-
else:
|
| 214 |
-
print("โน๏ธ SPACE_ID environment variable not found (running locally?). Repo URL cannot be determined.")
|
| 215 |
-
|
| 216 |
-
print("-"*(60 + len(" App Starting ")) + "\n")
|
| 217 |
-
|
| 218 |
-
print("Launching Gradio Interface for Basic Agent Evaluation...")
|
| 219 |
demo.launch(debug=True, share=False)
|
|
|
|
| 3 |
import requests
|
| 4 |
import inspect
|
| 5 |
import pandas as pd
|
| 6 |
+
import time
|
| 7 |
+
import re
|
| 8 |
+
from bs4 import BeautifulSoup
|
| 9 |
|
| 10 |
+
from smolagents import CodeAgent, InferenceClientModel, Tool
|
|
|
|
|
|
|
| 11 |
|
|
|
|
|
|
|
| 12 |
# --- Constants ---
|
| 13 |
DEFAULT_API_URL = "https://agents-course-unit4-scoring.hf.space"
|
| 14 |
|
| 15 |
+
# --- High-Performance Tool 1: ๋ค์ฐจ์ ๊ตฌ์กฐํ ์น ๊ฒ์ ํด ---
|
| 16 |
+
class AdvancedSearchTool(Tool):
|
| 17 |
+
name = "web_search"
|
| 18 |
+
description = "Executes a deep web search via DuckDuckGo HTML architecture and extracts exact URLs and targeted meta-snippets."
|
| 19 |
+
inputs = {"query": {"type": "string", "description": "The precise keyword query to search for"}}
|
| 20 |
+
output_type = "string"
|
| 21 |
+
|
| 22 |
+
def forward(self, query: str) -> str:
|
| 23 |
+
try:
|
| 24 |
+
url = f"https://html.duckduckgo.com/html/?q={requests.utils.quote(query)}"
|
| 25 |
+
headers = {"User-Agent": "Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/120.0.0.0 Safari/537.36"}
|
| 26 |
+
response = requests.get(url, headers=headers, timeout=12)
|
| 27 |
+
if response.status_code != 200:
|
| 28 |
+
return f"Search Gateway Error: HTTP {response.status_code}"
|
| 29 |
+
|
| 30 |
+
soup = BeautifulSoup(response.text, "lxml")
|
| 31 |
+
results = []
|
| 32 |
+
for i, item in enumerate(soup.select(".result__body")[:5]):
|
| 33 |
+
title_anchor = item.select_one(".result__title a")
|
| 34 |
+
snippet_div = item.select_one(".result__snippet")
|
| 35 |
+
if title_anchor and snippet_div:
|
| 36 |
+
title = title_anchor.get_text(strip=True)
|
| 37 |
+
link = title_anchor.get("href")
|
| 38 |
+
# ๋ด๋ถ ๋ฆฌ๋ค์ด๋ ํธ URL ์ ์
|
| 39 |
+
if "uddg=" in link:
|
| 40 |
+
link = requests.utils.unquote(link.split("uddg=")[1].split("&")[0])
|
| 41 |
+
snippet = snippet_div.get_text(strip=True)
|
| 42 |
+
results.append(f"[{i+1}] Title: {title}\nURL: {link}\nContext: {snippet}")
|
| 43 |
+
return "\n\n".join(results) if results else "No indexing data found."
|
| 44 |
+
except Exception as e:
|
| 45 |
+
return f"Search Engine Exception: {str(e)}"
|
| 46 |
+
|
| 47 |
+
# --- High-Performance Tool 2: ๋งํฌ๋ค์ด ๋ณํํ ์น ๋ฐ ๋ํ๋จผํธ ํ์ ํด ---
|
| 48 |
+
class DeepPageVisitTool(Tool):
|
| 49 |
+
name = "visit_webpage"
|
| 50 |
+
description = "Visits a specific URL, bypasses layout boilerplate, and converts raw HTML into a dense Markdown/Table format for complex data analysis."
|
| 51 |
+
inputs = {"url": {"type": "string", "description": "The target exact URL to scrape content from"}}
|
| 52 |
+
output_type = "string"
|
| 53 |
+
|
| 54 |
+
def forward(self, url: str) -> str:
|
| 55 |
+
try:
|
| 56 |
+
headers = {"User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/122.0.0.0 Safari/537.36"}
|
| 57 |
+
response = requests.get(url, headers=headers, timeout=15)
|
| 58 |
+
if response.status_code != 200:
|
| 59 |
+
return f"HTTP Access Failure: Status {response.status_code}"
|
| 60 |
+
|
| 61 |
+
soup = BeautifulSoup(response.text, "lxml")
|
| 62 |
+
# ๋
ธ์ด์ฆ ํ๊ทธ ์ ๋ ์ ๊ฑฐ
|
| 63 |
+
for element in soup(["script", "style", "nav", "footer", "header", "aside"]):
|
| 64 |
+
element.extract()
|
| 65 |
+
|
| 66 |
+
# GAIA ํต์ฌ ์งํ์ธ 'ํ ๋ฐ์ดํฐ' ๋ณด์กด ์ฒ๋ฆฌ
|
| 67 |
+
for table in soup.find_all("table"):
|
| 68 |
+
markdown_table = []
|
| 69 |
+
for row in table.find_all("tr"):
|
| 70 |
+
cells = [f" {cell.get_text(strip=True)} " for cell in row.find_all(["td", "th"])]
|
| 71 |
+
markdown_table.append("|" + "|".join(cells) + "|")
|
| 72 |
+
if markdown_table:
|
| 73 |
+
table.replace_with(soup.new_string("\n" + "\n".join(markdown_table) + "\n"))
|
| 74 |
+
|
| 75 |
+
text = soup.get_text(separator="\n")
|
| 76 |
+
text = re.sub(r'\n+', '\n', text).strip()
|
| 77 |
+
return text[:6000] # ์ปจํ
์คํธ ์ํ์น ํ๋ณด
|
| 78 |
+
except Exception as e:
|
| 79 |
+
return f"Page Scraping Exception: {str(e)}"
|
| 80 |
+
|
| 81 |
# --- Basic Agent Definition ---
|
|
|
|
| 82 |
class BasicAgent:
|
| 83 |
def __init__(self):
|
| 84 |
+
self.model = InferenceClientModel(
|
| 85 |
+
model_id="Qwen/Qwen2.5-Coder-32B-Instruct",
|
| 86 |
+
token=os.getenv("HF_TOKEN")
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 87 |
)
|
| 88 |
+
self.search_tool = AdvancedSearchTool()
|
| 89 |
+
self.visit_tool = DeepPageVisitTool()
|
| 90 |
|
| 91 |
+
# ๊ฐ๋๋ ์ผ ๊ฐํ๋ฅผ ์ํด verbosity_level์ ๋์ด๊ณ ๋ณตํฉ ์ฐ์ฐ ์ง์ ํ๋กฌํํธ ํ
ํ๋ฆฟ ์กฐ์
|
| 92 |
+
self.agent = CodeAgent(
|
| 93 |
+
tools=[self.search_tool, self.visit_tool],
|
| 94 |
+
model=self.model,
|
| 95 |
+
max_steps=12,
|
| 96 |
+
verbosity_level=2
|
|
|
|
|
|
|
|
|
|
| 97 |
)
|
| 98 |
+
print("BasicAgent: Guardrail & Self-Correction Engine Loaded.")
|
| 99 |
|
| 100 |
def __call__(self, question: str) -> str:
|
| 101 |
+
print(f"Agent received question (first 50 chars): {question[:50]}...")
|
| 102 |
+
try:
|
| 103 |
+
# ์์ด์ ํธ๊ฐ ๋จ๋ฐ์ฑ ํ๋จ์ ๋ด๋ฆฌ์ง ์๊ณ ๋ช
ํํ ์คํ ๊ณํ(Execution Plan)์ ์ธ์ฐ๋๋ก ๊ฐ์ ํ๋ ์์ง๋์ด๋ง ํ๋กฌํํธ
|
| 104 |
+
structured_prompt = (
|
| 105 |
+
f"You are an expert AI agent solving a GAIA task.\n"
|
| 106 |
+
f"Task: {question}\n\n"
|
| 107 |
+
f"Strict Protocol:\n"
|
| 108 |
+
f"1. Plan: Break down the research and computation into clear sub-tasks.\n"
|
| 109 |
+
f"2. Action: Use your code interpreter or tools to gather and verify facts.\n"
|
| 110 |
+
f"3. Self-Correction: If any code execution fails with a Traceback, analyze the error, rewrite the script, and run it again.\n"
|
| 111 |
+
f"4. Output: Extract the absolute raw answer value (e.g., specific number, name, date) without any markdown formatting wrappers or conversational text. Present this on the very last line."
|
| 112 |
+
)
|
| 113 |
+
|
| 114 |
+
result = self.agent.run(structured_prompt)
|
| 115 |
+
if result is None:
|
| 116 |
+
return "unknown"
|
| 117 |
+
|
| 118 |
+
# ์ ๋ต ์ ์ค ๋ฐฉ์ง๋ฅผ ์ํ ์ต์ข
ํ๊ฒ ํ์ฑ ๊ฐ๋๋ ์ผ ์ฒ๋ฆฌ
|
| 119 |
+
final_output = str(result).strip()
|
| 120 |
+
if "\n" in final_output:
|
| 121 |
+
final_output = final_output.split("\n")[-1].replace("Final Answer:", "").strip()
|
| 122 |
+
return final_output
|
| 123 |
+
|
| 124 |
+
except Exception as e:
|
| 125 |
+
print(f"Critical System Failure during agent execution: {e}")
|
| 126 |
+
return "unknown"
|
| 127 |
|
| 128 |
def run_and_submit_all( profile: gr.OAuthProfile | None):
|
| 129 |
+
space_id = os.getenv("SPACE_ID")
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 130 |
|
| 131 |
if profile:
|
| 132 |
username= f"{profile.username}"
|
|
|
|
| 139 |
questions_url = f"{api_url}/questions"
|
| 140 |
submit_url = f"{api_url}/submit"
|
| 141 |
|
|
|
|
| 142 |
try:
|
| 143 |
agent = BasicAgent()
|
| 144 |
except Exception as e:
|
| 145 |
print(f"Error instantiating agent: {e}")
|
| 146 |
return f"Error initializing agent: {e}", None
|
|
|
|
| 147 |
agent_code = f"https://huggingface.co/spaces/{space_id}/tree/main"
|
| 148 |
print(agent_code)
|
| 149 |
|
|
|
|
| 150 |
print(f"Fetching questions from: {questions_url}")
|
| 151 |
try:
|
| 152 |
response = requests.get(questions_url, timeout=15)
|
|
|
|
| 167 |
print(f"An unexpected error occurred fetching questions: {e}")
|
| 168 |
return f"An unexpected error occurred fetching questions: {e}", None
|
| 169 |
|
|
|
|
| 170 |
results_log = []
|
| 171 |
answers_payload = []
|
| 172 |
print(f"Running agent on {len(questions_data)} questions...")
|
|
|
|
| 188 |
print("Agent did not produce any answers to submit.")
|
| 189 |
return "Agent did not produce any answers to submit.", pd.DataFrame(results_log)
|
| 190 |
|
|
|
|
| 191 |
submission_data = {"username": username.strip(), "agent_code": agent_code, "answers": answers_payload}
|
| 192 |
status_update = f"Agent finished. Submitting {len(answers_payload)} answers for user '{username}'..."
|
| 193 |
print(status_update)
|
| 194 |
|
|
|
|
| 195 |
print(f"Submitting {len(answers_payload)} answers to: {submit_url}")
|
| 196 |
try:
|
| 197 |
response = requests.post(submit_url, json=submission_data, timeout=60)
|
|
|
|
| 234 |
results_df = pd.DataFrame(results_log)
|
| 235 |
return status_message, results_df
|
| 236 |
|
|
|
|
|
|
|
| 237 |
with gr.Blocks() as demo:
|
| 238 |
gr.Markdown("# Basic Agent Evaluation Runner")
|
| 239 |
gr.Markdown(
|
| 240 |
"""
|
| 241 |
**Instructions:**
|
| 242 |
+
1. Please clone this space, then modify the code to define your agent's logic, the tools, the necessary packages, etc ...
|
| 243 |
+
2. Log in to your Hugging Face account using the button below. This uses your HF username for submission.
|
| 244 |
+
3. Click 'Run Evaluation & Submit All Answers' to fetch questions, run your agent, submit answers, and see the score.
|
|
|
|
|
|
|
|
|
|
|
|
|
| 245 |
"""
|
| 246 |
)
|
| 247 |
|
| 248 |
gr.LoginButton()
|
|
|
|
| 249 |
run_button = gr.Button("Run Evaluation & Submit All Answers")
|
|
|
|
| 250 |
status_output = gr.Textbox(label="Run Status / Submission Result", lines=5, interactive=False)
|
|
|
|
| 251 |
results_table = gr.DataFrame(label="Questions and Agent Answers", wrap=True)
|
| 252 |
|
| 253 |
run_button.click(
|
|
|
|
| 256 |
)
|
| 257 |
|
| 258 |
if __name__ == "__main__":
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 259 |
demo.launch(debug=True, share=False)
|