Update app.py
Browse files
app.py
CHANGED
|
@@ -1,14 +1,12 @@
|
|
| 1 |
import os
|
|
|
|
| 2 |
import gradio as gr
|
| 3 |
import requests
|
| 4 |
-
import inspect
|
| 5 |
import pandas as pd
|
| 6 |
-
import re
|
| 7 |
|
| 8 |
-
|
| 9 |
from smolagents import CodeAgent, DuckDuckGoSearchTool, InferenceClientModel
|
| 10 |
|
| 11 |
-
|
| 12 |
# --- Constants ---
|
| 13 |
DEFAULT_API_URL = "https://agents-course-unit4-scoring.hf.space"
|
| 14 |
|
|
@@ -18,20 +16,18 @@ DEFAULT_API_URL = "https://agents-course-unit4-scoring.hf.space"
|
|
| 18 |
# =========================================================
|
| 19 |
def clean_answer(text: str) -> str:
|
| 20 |
"""
|
| 21 |
-
|
| 22 |
-
-
|
| 23 |
-
-
|
| 24 |
-
-
|
| 25 |
-
-
|
| 26 |
-
|
| 27 |
"""
|
| 28 |
-
|
| 29 |
if not text:
|
| 30 |
return ""
|
| 31 |
|
| 32 |
text = str(text).strip()
|
| 33 |
|
| 34 |
-
# Remover frases proibidas
|
| 35 |
patterns_to_remove = [
|
| 36 |
r"(?i)final answer[:\- ]*",
|
| 37 |
r"(?i)answer[:\- ]*",
|
|
@@ -41,25 +37,20 @@ def clean_answer(text: str) -> str:
|
|
| 41 |
for p in patterns_to_remove:
|
| 42 |
text = re.sub(p, "", text).strip()
|
| 43 |
|
| 44 |
-
# Remover quebras de linha
|
| 45 |
text = text.replace("\n", " ").strip()
|
| 46 |
|
| 47 |
-
#
|
| 48 |
-
if len(text) >= 2 and text
|
| 49 |
-
text = text[1:-1].strip()
|
| 50 |
-
if len(text) >= 2 and text.startswith("'") and text.endswith("'"):
|
| 51 |
text = text[1:-1].strip()
|
| 52 |
|
| 53 |
-
# Remover espaços múltiplos
|
| 54 |
text = re.sub(r"\s+", " ", text)
|
| 55 |
|
| 56 |
return text.strip()
|
| 57 |
|
| 58 |
|
| 59 |
# =========================================================
|
| 60 |
-
#
|
| 61 |
# =========================================================
|
| 62 |
-
|
| 63 |
SYSTEM_PROMPT = (
|
| 64 |
"You are an AI agent solving GAIA-style questions.\n"
|
| 65 |
"You have access to a web search tool (DuckDuckGoSearchTool).\n"
|
|
@@ -74,6 +65,9 @@ SYSTEM_PROMPT = (
|
|
| 74 |
)
|
| 75 |
|
| 76 |
|
|
|
|
|
|
|
|
|
|
| 77 |
class BasicAgent:
|
| 78 |
"""
|
| 79 |
Agente smolagents com DuckDuckGoSearchTool,
|
|
@@ -81,60 +75,51 @@ class BasicAgent:
|
|
| 81 |
"""
|
| 82 |
|
| 83 |
def __init__(self):
|
| 84 |
-
print("Initializing
|
| 85 |
|
| 86 |
-
|
|
|
|
|
|
|
|
|
|
| 87 |
|
| 88 |
-
#
|
| 89 |
-
|
| 90 |
-
|
| 91 |
-
|
| 92 |
-
|
| 93 |
-
"When you use search, read the results and extract ONLY the exact required answer.\n"
|
| 94 |
-
"RULES:\n"
|
| 95 |
-
" - Output MUST be a SINGLE short string.\n"
|
| 96 |
-
" - NO explanations.\n"
|
| 97 |
-
" - NO reasoning.\n"
|
| 98 |
-
" - NO multi-sentence output.\n"
|
| 99 |
-
" - NO citations or URLs.\n"
|
| 100 |
-
" - NO extra words.\n"
|
| 101 |
-
"Examples of valid outputs:\n"
|
| 102 |
-
" '2002'\n"
|
| 103 |
-
" '7'\n"
|
| 104 |
-
" 'egalitarian'\n"
|
| 105 |
-
" 'Mercedes Sosa'\n"
|
| 106 |
-
"INVALID OUTPUTS:\n"
|
| 107 |
-
" 'The final answer is 7.'\n"
|
| 108 |
-
" 'According to Wikipedia, the answer is 2002.'\n"
|
| 109 |
-
" 'After checking, I think it is 3.'\n"
|
| 110 |
-
"Your response MUST be only the exact final answer.\n"
|
| 111 |
-
)
|
| 112 |
-
)
|
| 113 |
|
| 114 |
-
#
|
|
|
|
|
|
|
|
|
|
| 115 |
self.agent = CodeAgent(
|
| 116 |
model=self.model,
|
| 117 |
tools=[self.search_tool],
|
| 118 |
-
max_steps=8,
|
| 119 |
)
|
| 120 |
|
| 121 |
def __call__(self, question: str) -> str:
|
| 122 |
-
print(f"
|
| 123 |
try:
|
| 124 |
-
|
| 125 |
-
|
| 126 |
-
"
|
|
|
|
|
|
|
| 127 |
)
|
|
|
|
|
|
|
| 128 |
final = clean_answer(raw)
|
|
|
|
| 129 |
print(f"Final cleaned answer: {final}")
|
| 130 |
return final
|
| 131 |
except Exception as e:
|
| 132 |
-
print(f"Error: {e}")
|
| 133 |
return ""
|
| 134 |
|
| 135 |
|
| 136 |
# =========================================================
|
| 137 |
-
# Runner + submit (mantido do template,
|
| 138 |
# =========================================================
|
| 139 |
def run_and_submit_all(profile: gr.OAuthProfile | None):
|
| 140 |
"""
|
|
@@ -155,22 +140,21 @@ def run_and_submit_all(profile: gr.OAuthProfile | None):
|
|
| 155 |
questions_url = f"{api_url}/questions"
|
| 156 |
submit_url = f"{api_url}/submit"
|
| 157 |
|
| 158 |
-
# 1. Instantiate Agent
|
| 159 |
try:
|
| 160 |
agent = BasicAgent()
|
| 161 |
except Exception as e:
|
| 162 |
print(f"Error instantiating agent: {e}")
|
| 163 |
return f"Error initializing agent: {e}", None
|
| 164 |
|
| 165 |
-
#
|
| 166 |
-
# (useful for others so please keep it public)
|
| 167 |
agent_code = f"https://huggingface.co/spaces/{space_id}/tree/main"
|
| 168 |
print(f"Agent code URL: {agent_code}")
|
| 169 |
|
| 170 |
# 2. Fetch Questions
|
| 171 |
print(f"Fetching questions from: {questions_url}")
|
| 172 |
try:
|
| 173 |
-
response = requests.get(questions_url, timeout=
|
| 174 |
response.raise_for_status()
|
| 175 |
questions_data = response.json()
|
| 176 |
if not questions_data:
|
|
@@ -317,9 +301,8 @@ with gr.Blocks() as demo:
|
|
| 317 |
|
| 318 |
if __name__ == "__main__":
|
| 319 |
print("\n" + "-" * 30 + " App Starting " + "-" * 30)
|
| 320 |
-
# Check for SPACE_HOST and SPACE_ID at startup for information
|
| 321 |
space_host_startup = os.getenv("SPACE_HOST")
|
| 322 |
-
space_id_startup = os.getenv("SPACE_ID")
|
| 323 |
|
| 324 |
if space_host_startup:
|
| 325 |
print(f"✅ SPACE_HOST found: {space_host_startup}")
|
|
@@ -327,7 +310,7 @@ if __name__ == "__main__":
|
|
| 327 |
else:
|
| 328 |
print("ℹ️ SPACE_HOST environment variable not found (running locally?).")
|
| 329 |
|
| 330 |
-
if space_id_startup:
|
| 331 |
print(f"✅ SPACE_ID found: {space_id_startup}")
|
| 332 |
print(f" Repo URL: https://huggingface.co/spaces/{space_id_startup}")
|
| 333 |
print(
|
|
@@ -337,6 +320,5 @@ if __name__ == "__main__":
|
|
| 337 |
print("ℹ️ SPACE_ID environment variable not found (running locally?). Repo URL cannot be determined.")
|
| 338 |
|
| 339 |
print("-" * (60 + len(" App Starting ")) + "\n")
|
| 340 |
-
|
| 341 |
print("Launching Gradio Interface for Basic Agent Evaluation...")
|
| 342 |
-
demo.launch(debug=True, share=False)
|
|
|
|
| 1 |
import os
|
| 2 |
+
import re
|
| 3 |
import gradio as gr
|
| 4 |
import requests
|
|
|
|
| 5 |
import pandas as pd
|
|
|
|
| 6 |
|
| 7 |
+
from huggingface_hub import InferenceClient
|
| 8 |
from smolagents import CodeAgent, DuckDuckGoSearchTool, InferenceClientModel
|
| 9 |
|
|
|
|
| 10 |
# --- Constants ---
|
| 11 |
DEFAULT_API_URL = "https://agents-course-unit4-scoring.hf.space"
|
| 12 |
|
|
|
|
| 16 |
# =========================================================
|
| 17 |
def clean_answer(text: str) -> str:
|
| 18 |
"""
|
| 19 |
+
Limpa a resposta retornada pelo modelo:
|
| 20 |
+
- remove quebras de linha
|
| 21 |
+
- remove 'final answer', 'answer:', etc
|
| 22 |
+
- remove aspas externas
|
| 23 |
+
- normaliza espaços
|
| 24 |
+
NÃO apaga o conteúdo útil.
|
| 25 |
"""
|
|
|
|
| 26 |
if not text:
|
| 27 |
return ""
|
| 28 |
|
| 29 |
text = str(text).strip()
|
| 30 |
|
|
|
|
| 31 |
patterns_to_remove = [
|
| 32 |
r"(?i)final answer[:\- ]*",
|
| 33 |
r"(?i)answer[:\- ]*",
|
|
|
|
| 37 |
for p in patterns_to_remove:
|
| 38 |
text = re.sub(p, "", text).strip()
|
| 39 |
|
|
|
|
| 40 |
text = text.replace("\n", " ").strip()
|
| 41 |
|
| 42 |
+
# aspas externas
|
| 43 |
+
if len(text) >= 2 and text[0] == text[-1] and text[0] in ['"', "'"]:
|
|
|
|
|
|
|
| 44 |
text = text[1:-1].strip()
|
| 45 |
|
|
|
|
| 46 |
text = re.sub(r"\s+", " ", text)
|
| 47 |
|
| 48 |
return text.strip()
|
| 49 |
|
| 50 |
|
| 51 |
# =========================================================
|
| 52 |
+
# Prompt base para o agente
|
| 53 |
# =========================================================
|
|
|
|
| 54 |
SYSTEM_PROMPT = (
|
| 55 |
"You are an AI agent solving GAIA-style questions.\n"
|
| 56 |
"You have access to a web search tool (DuckDuckGoSearchTool).\n"
|
|
|
|
| 65 |
)
|
| 66 |
|
| 67 |
|
| 68 |
+
# =========================================================
|
| 69 |
+
# Basic Agent Definition – usando smolagents
|
| 70 |
+
# =========================================================
|
| 71 |
class BasicAgent:
|
| 72 |
"""
|
| 73 |
Agente smolagents com DuckDuckGoSearchTool,
|
|
|
|
| 75 |
"""
|
| 76 |
|
| 77 |
def __init__(self):
|
| 78 |
+
print("Initializing GAIA agent with web search...")
|
| 79 |
|
| 80 |
+
# ---- Token HF vindo do secret HF_TOKEN ----
|
| 81 |
+
hf_token = os.getenv("HF_TOKEN")
|
| 82 |
+
if not hf_token:
|
| 83 |
+
print("⚠️ HF_TOKEN not found in environment! InferenceClient may fail.")
|
| 84 |
|
| 85 |
+
# Cliente de inferência com token
|
| 86 |
+
client = InferenceClient(token=hf_token) if hf_token else InferenceClient()
|
| 87 |
+
|
| 88 |
+
# Modelo remoto via Inference API
|
| 89 |
+
self.model = InferenceClientModel(client=client)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 90 |
|
| 91 |
+
# Ferramenta de busca
|
| 92 |
+
self.search_tool = DuckDuckGoSearchTool()
|
| 93 |
+
|
| 94 |
+
# CodeAgent com ferramenta de busca
|
| 95 |
self.agent = CodeAgent(
|
| 96 |
model=self.model,
|
| 97 |
tools=[self.search_tool],
|
| 98 |
+
max_steps=8, # permite alguns passos (buscar + refinar)
|
| 99 |
)
|
| 100 |
|
| 101 |
def __call__(self, question: str) -> str:
|
| 102 |
+
print(f"\nProcessing question: {question[:80]}...")
|
| 103 |
try:
|
| 104 |
+
# Prompt completo passado para o agente
|
| 105 |
+
full_prompt = (
|
| 106 |
+
f"{SYSTEM_PROMPT}\n\n"
|
| 107 |
+
f"Question: {question}\n\n"
|
| 108 |
+
"Follow the rules above and return ONLY the exact final answer."
|
| 109 |
)
|
| 110 |
+
|
| 111 |
+
raw = self.agent.run(full_prompt)
|
| 112 |
final = clean_answer(raw)
|
| 113 |
+
print(f"Raw answer: {raw}")
|
| 114 |
print(f"Final cleaned answer: {final}")
|
| 115 |
return final
|
| 116 |
except Exception as e:
|
| 117 |
+
print(f"Error inside BasicAgent.__call__: {e}")
|
| 118 |
return ""
|
| 119 |
|
| 120 |
|
| 121 |
# =========================================================
|
| 122 |
+
# Runner + submit (mantido do template, usando BasicAgent novo)
|
| 123 |
# =========================================================
|
| 124 |
def run_and_submit_all(profile: gr.OAuthProfile | None):
|
| 125 |
"""
|
|
|
|
| 140 |
questions_url = f"{api_url}/questions"
|
| 141 |
submit_url = f"{api_url}/submit"
|
| 142 |
|
| 143 |
+
# 1. Instantiate Agent
|
| 144 |
try:
|
| 145 |
agent = BasicAgent()
|
| 146 |
except Exception as e:
|
| 147 |
print(f"Error instantiating agent: {e}")
|
| 148 |
return f"Error initializing agent: {e}", None
|
| 149 |
|
| 150 |
+
# Link para o código do agente (Space público)
|
|
|
|
| 151 |
agent_code = f"https://huggingface.co/spaces/{space_id}/tree/main"
|
| 152 |
print(f"Agent code URL: {agent_code}")
|
| 153 |
|
| 154 |
# 2. Fetch Questions
|
| 155 |
print(f"Fetching questions from: {questions_url}")
|
| 156 |
try:
|
| 157 |
+
response = requests.get(questions_url, timeout=60) # timeout maior
|
| 158 |
response.raise_for_status()
|
| 159 |
questions_data = response.json()
|
| 160 |
if not questions_data:
|
|
|
|
| 301 |
|
| 302 |
if __name__ == "__main__":
|
| 303 |
print("\n" + "-" * 30 + " App Starting " + "-" * 30)
|
|
|
|
| 304 |
space_host_startup = os.getenv("SPACE_HOST")
|
| 305 |
+
space_id_startup = os.getenv("SPACE_ID")
|
| 306 |
|
| 307 |
if space_host_startup:
|
| 308 |
print(f"✅ SPACE_HOST found: {space_host_startup}")
|
|
|
|
| 310 |
else:
|
| 311 |
print("ℹ️ SPACE_HOST environment variable not found (running locally?).")
|
| 312 |
|
| 313 |
+
if space_id_startup:
|
| 314 |
print(f"✅ SPACE_ID found: {space_id_startup}")
|
| 315 |
print(f" Repo URL: https://huggingface.co/spaces/{space_id_startup}")
|
| 316 |
print(
|
|
|
|
| 320 |
print("ℹ️ SPACE_ID environment variable not found (running locally?). Repo URL cannot be determined.")
|
| 321 |
|
| 322 |
print("-" * (60 + len(" App Starting ")) + "\n")
|
|
|
|
| 323 |
print("Launching Gradio Interface for Basic Agent Evaluation...")
|
| 324 |
+
demo.launch(debug=True, share=False)
|