Spaces:
Sleeping
Sleeping
Upload app.py
Browse files
app.py
CHANGED
|
@@ -1,127 +1,106 @@
|
|
| 1 |
-
import
|
| 2 |
-
import gradio as gr
|
| 3 |
-
import requests
|
| 4 |
-
import pandas as pd
|
| 5 |
-
#from smolagents import Agent, tool
|
| 6 |
-
from duckduckgo_search import DDGS
|
| 7 |
-
from transformers import pipeline
|
| 8 |
-
|
| 9 |
-
# --- Tool Definitions ---
|
| 10 |
-
from tools.search_tool import web_search
|
| 11 |
-
from tools.citation_tool import cite
|
| 12 |
-
from tools.summarizer_tool import summarize
|
| 13 |
-
from tools.math_tool import python
|
| 14 |
-
from tools.fallback_tool import fallback
|
| 15 |
-
|
| 16 |
-
class BasicAgent:
|
| 17 |
-
def __init__(self):
|
| 18 |
-
pass
|
| 19 |
-
|
| 20 |
-
def __call__(self, question: str) -> str:
|
| 21 |
-
question_lower = question.lower()
|
| 22 |
-
|
| 23 |
-
try:
|
| 24 |
-
if any(keyword in question_lower for keyword in ["latest", "news", "who", "what", "where", "when"]):
|
| 25 |
-
return web_search(question)
|
| 26 |
-
elif any(keyword in question_lower for keyword in ["summarize", "summary", "explain"]):
|
| 27 |
-
return summarize(question)
|
| 28 |
-
elif any(char.isdigit() for char in question) and any(op in question for op in ["+", "-", "*", "/"]):
|
| 29 |
-
return python(question)
|
| 30 |
-
elif "|||" in question:
|
| 31 |
-
return cite(question)
|
| 32 |
-
else:
|
| 33 |
-
return fallback(question)
|
| 34 |
-
except Exception as e:
|
| 35 |
-
return f"Error during processing: {str(e)}"
|
| 36 |
-
|
| 37 |
-
|
| 38 |
-
|
| 39 |
-
|
| 40 |
-
|
| 41 |
-
|
| 42 |
-
# --- Evaluation Logic ---
|
| 43 |
-
DEFAULT_API_URL = "https://agents-course-unit4-scoring.hf.space"
|
| 44 |
|
| 45 |
-
|
| 46 |
-
|
| 47 |
-
if profile:
|
| 48 |
-
username = profile.username
|
| 49 |
-
else:
|
| 50 |
-
return "Please Login to Hugging Face with the button.", None
|
| 51 |
-
|
| 52 |
-
api_url = DEFAULT_API_URL
|
| 53 |
-
questions_url = f"{api_url}/questions"
|
| 54 |
-
submit_url = f"{api_url}/submit"
|
| 55 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 56 |
try:
|
| 57 |
-
|
| 58 |
-
|
| 59 |
-
|
| 60 |
-
|
| 61 |
-
|
| 62 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 63 |
try:
|
| 64 |
-
|
| 65 |
-
|
| 66 |
-
questions_data = response.json()
|
| 67 |
except Exception as e:
|
| 68 |
-
return f"Error
|
| 69 |
|
| 70 |
-
|
| 71 |
-
|
|
|
|
|
|
|
|
|
|
| 72 |
|
| 73 |
-
|
| 74 |
-
|
| 75 |
-
question_text = item.get("question")
|
| 76 |
-
if not task_id or question_text is None:
|
| 77 |
-
continue
|
| 78 |
-
try:
|
| 79 |
-
submitted_answer = agent(question_text)
|
| 80 |
-
answers_payload.append({"task_id": task_id, "submitted_answer": submitted_answer})
|
| 81 |
-
results_log.append({"Task ID": task_id, "Question": question_text, "Submitted Answer": submitted_answer})
|
| 82 |
-
except Exception as e:
|
| 83 |
-
results_log.append({"Task ID": task_id, "Question": question_text, "Submitted Answer": f"AGENT ERROR: {e}"})
|
| 84 |
|
| 85 |
-
|
| 86 |
-
|
|
|
|
|
|
|
| 87 |
|
| 88 |
-
|
| 89 |
-
|
| 90 |
-
|
| 91 |
-
|
| 92 |
-
}
|
| 93 |
|
| 94 |
-
|
| 95 |
-
|
| 96 |
-
|
| 97 |
-
|
| 98 |
-
final_status = (
|
| 99 |
-
f"Submission Successful!\n"
|
| 100 |
-
f"User: {result_data.get('username')}\n"
|
| 101 |
-
f"Overall Score: {result_data.get('score', 'N/A')}% "
|
| 102 |
-
f"({result_data.get('correct_count', '?')}/{result_data.get('total_attempted', '?')} correct)\n"
|
| 103 |
-
f"Message: {result_data.get('message', 'No message received.')}"
|
| 104 |
-
)
|
| 105 |
-
results_df = pd.DataFrame(results_log)
|
| 106 |
-
return final_status, results_df
|
| 107 |
-
except Exception as e:
|
| 108 |
-
return f"Submission Failed: {e}", pd.DataFrame(results_log)
|
| 109 |
|
| 110 |
-
#
|
| 111 |
-
|
| 112 |
-
|
| 113 |
-
|
| 114 |
-
|
| 115 |
-
|
| 116 |
-
|
| 117 |
-
""")
|
| 118 |
|
| 119 |
-
|
| 120 |
-
|
| 121 |
-
status_output = gr.Textbox(label="Run Status / Submission Result", lines=5, interactive=False)
|
| 122 |
-
results_table = gr.DataFrame(label="Questions and Agent Answers", wrap=True)
|
| 123 |
|
| 124 |
-
|
|
|
|
| 125 |
|
|
|
|
| 126 |
if __name__ == "__main__":
|
| 127 |
-
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from smolagents import tool
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 2 |
|
| 3 |
+
# TOOL 1: Wikipedia-based Search Tool
|
| 4 |
+
from duckduckgo_search import DDGS
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 5 |
|
| 6 |
+
@tool
|
| 7 |
+
def web_search(query: str) -> str:
|
| 8 |
+
"""
|
| 9 |
+
Searches for up-to-date facts, biased toward Wikipedia for accuracy.
|
| 10 |
+
|
| 11 |
+
Args:
|
| 12 |
+
query (str): The user's factual question.
|
| 13 |
+
|
| 14 |
+
Returns:
|
| 15 |
+
str: Best matching fact and URL.
|
| 16 |
+
"""
|
| 17 |
+
refined = f"{query} site:en.wikipedia.org"
|
| 18 |
+
with DDGS() as ddgs:
|
| 19 |
+
results = ddgs.text(refined)
|
| 20 |
+
for r in results[:5]:
|
| 21 |
+
if "wikipedia.org" in r["href"].lower():
|
| 22 |
+
snippet = r.get("body") or r.get("content") or r.get("snippet", "")
|
| 23 |
+
if snippet:
|
| 24 |
+
return f"{snippet}\n\nSource: [{r['href']}]({r['href']})"
|
| 25 |
+
return "Could not find a direct answer from Wikipedia."
|
| 26 |
+
|
| 27 |
+
# TOOL 2: Citation Tool
|
| 28 |
+
@tool
|
| 29 |
+
def cite(input: str) -> str:
|
| 30 |
+
"""
|
| 31 |
+
Formats a response and URL into a markdown citation.
|
| 32 |
+
|
| 33 |
+
Args:
|
| 34 |
+
input (str): A string like 'answer ||| source-url'.
|
| 35 |
+
|
| 36 |
+
Returns:
|
| 37 |
+
str: Answer followed by markdown citation.
|
| 38 |
+
"""
|
| 39 |
try:
|
| 40 |
+
answer, url = input.split("|||")
|
| 41 |
+
return f"{answer.strip()}\n\nSource: [{url.strip()}]({url.strip()})"
|
| 42 |
+
except:
|
| 43 |
+
return "Could not format citation."
|
| 44 |
+
|
| 45 |
+
# TOOL 3: Math Eval
|
| 46 |
+
@tool
|
| 47 |
+
def python(code: str) -> str:
|
| 48 |
+
"""
|
| 49 |
+
Evaluates math expressions using Python sandboxed eval.
|
| 50 |
+
|
| 51 |
+
Args:
|
| 52 |
+
code (str): A math expression or calculation.
|
| 53 |
+
|
| 54 |
+
Returns:
|
| 55 |
+
str: The result or error.
|
| 56 |
+
"""
|
| 57 |
try:
|
| 58 |
+
result = str(eval(code, {"__builtins__": {}}))
|
| 59 |
+
return f"Answer: {result}"
|
|
|
|
| 60 |
except Exception as e:
|
| 61 |
+
return f"Error: {str(e)}"
|
| 62 |
|
| 63 |
+
# TOOL 4: Fallback
|
| 64 |
+
@tool
|
| 65 |
+
def fallback(_: str) -> str:
|
| 66 |
+
"""
|
| 67 |
+
Handles unclear or unanswerable queries politely.
|
| 68 |
|
| 69 |
+
Args:
|
| 70 |
+
_ (str): Unused.
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 71 |
|
| 72 |
+
Returns:
|
| 73 |
+
str: A polite fallback message.
|
| 74 |
+
"""
|
| 75 |
+
return "Sorry, I couldn't confidently answer that. Could you rephrase?"
|
| 76 |
|
| 77 |
+
# MAIN AGENT
|
| 78 |
+
class BasicAgent:
|
| 79 |
+
def __call__(self, question: str) -> str:
|
| 80 |
+
q = question.lower()
|
|
|
|
| 81 |
|
| 82 |
+
try:
|
| 83 |
+
# Wikipedia-focused factual lookups
|
| 84 |
+
if any(x in q for x in ["who", "what", "when", "where", "how many", "how much", "did", "which", "name"]):
|
| 85 |
+
return web_search(question)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 86 |
|
| 87 |
+
# Inline citation formatting
|
| 88 |
+
elif "|||" in q:
|
| 89 |
+
return cite(question)
|
| 90 |
+
|
| 91 |
+
# Math evaluation
|
| 92 |
+
elif any(op in q for op in ["+", "-", "*", "/"]):
|
| 93 |
+
return python(question)
|
|
|
|
| 94 |
|
| 95 |
+
# Default catch-all
|
| 96 |
+
return fallback(question)
|
|
|
|
|
|
|
| 97 |
|
| 98 |
+
except Exception as e:
|
| 99 |
+
return f"Agent error: {str(e)}"
|
| 100 |
|
| 101 |
+
# CLI test loop
|
| 102 |
if __name__ == "__main__":
|
| 103 |
+
agent = BasicAgent()
|
| 104 |
+
while True:
|
| 105 |
+
q = input("Ask GAIA: ")
|
| 106 |
+
print(agent(q))
|