Update app.py
Browse files
app.py
CHANGED
|
@@ -1,196 +1,226 @@
|
|
| 1 |
import os
|
| 2 |
import gradio as gr
|
| 3 |
import requests
|
| 4 |
-
import inspect
|
| 5 |
import pandas as pd
|
| 6 |
-
|
| 7 |
-
|
| 8 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 9 |
DEFAULT_API_URL = "https://agents-course-unit4-scoring.hf.space"
|
| 10 |
-
|
| 11 |
-
|
| 12 |
-
# -
|
| 13 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 14 |
def __init__(self):
|
| 15 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 16 |
def __call__(self, question: str) -> str:
|
| 17 |
-
print(f"Agent received question (first 50 chars): {question[:50]}...")
|
| 18 |
-
fixed_answer = "This is a default answer."
|
| 19 |
-
print(f"Agent returning fixed answer: {fixed_answer}")
|
| 20 |
-
return fixed_answer
|
| 21 |
-
|
| 22 |
-
def run_and_submit_all( profile: gr.OAuthProfile | None):
|
| 23 |
-
"""
|
| 24 |
-
Fetches all questions, runs the BasicAgent on them, submits all answers,
|
| 25 |
-
and displays the results.
|
| 26 |
-
"""
|
| 27 |
-
# --- Determine HF Space Runtime URL and Repo URL ---
|
| 28 |
-
space_id = os.getenv("SPACE_ID") # Get the SPACE_ID for sending link to the code
|
| 29 |
-
|
| 30 |
-
if profile:
|
| 31 |
-
username= f"{profile.username}"
|
| 32 |
-
print(f"User logged in: {username}")
|
| 33 |
-
else:
|
| 34 |
-
print("User not logged in.")
|
| 35 |
-
return "Please Login to Hugging Face with the button.", None
|
| 36 |
-
|
| 37 |
-
api_url = DEFAULT_API_URL
|
| 38 |
-
questions_url = f"{api_url}/questions"
|
| 39 |
-
submit_url = f"{api_url}/submit"
|
| 40 |
-
|
| 41 |
-
# 1. Instantiate Agent ( modify this part to create your agent)
|
| 42 |
-
try:
|
| 43 |
-
agent = BasicAgent()
|
| 44 |
-
except Exception as e:
|
| 45 |
-
print(f"Error instantiating agent: {e}")
|
| 46 |
-
return f"Error initializing agent: {e}", None
|
| 47 |
-
# 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)
|
| 48 |
-
agent_code = f"https://huggingface.co/spaces/{space_id}/tree/main"
|
| 49 |
-
print(agent_code)
|
| 50 |
-
|
| 51 |
-
# 2. Fetch Questions
|
| 52 |
-
print(f"Fetching questions from: {questions_url}")
|
| 53 |
-
try:
|
| 54 |
-
response = requests.get(questions_url, timeout=15)
|
| 55 |
-
response.raise_for_status()
|
| 56 |
-
questions_data = response.json()
|
| 57 |
-
if not questions_data:
|
| 58 |
-
print("Fetched questions list is empty.")
|
| 59 |
-
return "Fetched questions list is empty or invalid format.", None
|
| 60 |
-
print(f"Fetched {len(questions_data)} questions.")
|
| 61 |
-
except requests.exceptions.RequestException as e:
|
| 62 |
-
print(f"Error fetching questions: {e}")
|
| 63 |
-
return f"Error fetching questions: {e}", None
|
| 64 |
-
except requests.exceptions.JSONDecodeError as e:
|
| 65 |
-
print(f"Error decoding JSON response from questions endpoint: {e}")
|
| 66 |
-
print(f"Response text: {response.text[:500]}")
|
| 67 |
-
return f"Error decoding server response for questions: {e}", None
|
| 68 |
-
except Exception as e:
|
| 69 |
-
print(f"An unexpected error occurred fetching questions: {e}")
|
| 70 |
-
return f"An unexpected error occurred fetching questions: {e}", None
|
| 71 |
-
|
| 72 |
-
# 3. Run your Agent
|
| 73 |
-
results_log = []
|
| 74 |
-
answers_payload = []
|
| 75 |
-
print(f"Running agent on {len(questions_data)} questions...")
|
| 76 |
-
for item in questions_data:
|
| 77 |
-
task_id = item.get("task_id")
|
| 78 |
-
question_text = item.get("question")
|
| 79 |
-
if not task_id or question_text is None:
|
| 80 |
-
print(f"Skipping item with missing task_id or question: {item}")
|
| 81 |
-
continue
|
| 82 |
try:
|
| 83 |
-
|
| 84 |
-
|
| 85 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 86 |
except Exception as e:
|
| 87 |
-
|
| 88 |
-
results_log.append({"Task ID": task_id, "Question": question_text, "Submitted Answer": f"AGENT ERROR: {e}"})
|
| 89 |
|
| 90 |
-
|
| 91 |
-
|
| 92 |
-
return
|
| 93 |
|
| 94 |
-
|
| 95 |
-
|
| 96 |
-
|
| 97 |
-
|
|
|
|
| 98 |
|
| 99 |
-
# 5. Submit
|
| 100 |
-
print(f"Submitting {len(answers_payload)} answers to: {submit_url}")
|
| 101 |
try:
|
| 102 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 103 |
response.raise_for_status()
|
| 104 |
-
|
| 105 |
-
|
| 106 |
-
f"Submission Successful!\n"
|
| 107 |
-
f"User: {result_data.get('username')}\n"
|
| 108 |
-
f"Overall Score: {result_data.get('score', 'N/A')}% "
|
| 109 |
-
f"({result_data.get('correct_count', '?')}/{result_data.get('total_attempted', '?')} correct)\n"
|
| 110 |
-
f"Message: {result_data.get('message', 'No message received.')}"
|
| 111 |
-
)
|
| 112 |
-
print("Submission successful.")
|
| 113 |
-
results_df = pd.DataFrame(results_log)
|
| 114 |
-
return final_status, results_df
|
| 115 |
-
except requests.exceptions.HTTPError as e:
|
| 116 |
-
error_detail = f"Server responded with status {e.response.status_code}."
|
| 117 |
-
try:
|
| 118 |
-
error_json = e.response.json()
|
| 119 |
-
error_detail += f" Detail: {error_json.get('detail', e.response.text)}"
|
| 120 |
-
except requests.exceptions.JSONDecodeError:
|
| 121 |
-
error_detail += f" Response: {e.response.text[:500]}"
|
| 122 |
-
status_message = f"Submission Failed: {error_detail}"
|
| 123 |
-
print(status_message)
|
| 124 |
-
results_df = pd.DataFrame(results_log)
|
| 125 |
-
return status_message, results_df
|
| 126 |
-
except requests.exceptions.Timeout:
|
| 127 |
-
status_message = "Submission Failed: The request timed out."
|
| 128 |
-
print(status_message)
|
| 129 |
-
results_df = pd.DataFrame(results_log)
|
| 130 |
-
return status_message, results_df
|
| 131 |
-
except requests.exceptions.RequestException as e:
|
| 132 |
-
status_message = f"Submission Failed: Network error - {e}"
|
| 133 |
-
print(status_message)
|
| 134 |
-
results_df = pd.DataFrame(results_log)
|
| 135 |
-
return status_message, results_df
|
| 136 |
except Exception as e:
|
| 137 |
-
|
| 138 |
-
print(status_message)
|
| 139 |
-
results_df = pd.DataFrame(results_log)
|
| 140 |
-
return status_message, results_df
|
| 141 |
|
| 142 |
-
|
| 143 |
-
# --- Build Gradio Interface using Blocks ---
|
| 144 |
with gr.Blocks() as demo:
|
| 145 |
-
gr.Markdown("#
|
| 146 |
-
gr.Markdown(
|
| 147 |
-
"""
|
| 148 |
-
**Instructions:**
|
| 149 |
-
|
| 150 |
-
1. Please clone this space, then modify the code to define your agent's logic, the tools, the necessary packages, etc ...
|
| 151 |
-
2. Log in to your Hugging Face account using the button below. This uses your HF username for submission.
|
| 152 |
-
3. Click 'Run Evaluation & Submit All Answers' to fetch questions, run your agent, submit answers, and see the score.
|
| 153 |
-
|
| 154 |
-
---
|
| 155 |
-
**Disclaimers:**
|
| 156 |
-
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).
|
| 157 |
-
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.
|
| 158 |
-
"""
|
| 159 |
-
)
|
| 160 |
-
|
| 161 |
gr.LoginButton()
|
| 162 |
-
|
| 163 |
-
|
| 164 |
-
|
| 165 |
-
|
| 166 |
-
|
| 167 |
-
results_table = gr.DataFrame(label="Questions and Agent Answers", wrap=True)
|
| 168 |
-
|
| 169 |
-
run_button.click(
|
| 170 |
fn=run_and_submit_all,
|
| 171 |
-
outputs=[
|
| 172 |
)
|
| 173 |
|
| 174 |
if __name__ == "__main__":
|
| 175 |
-
|
| 176 |
-
# Check for SPACE_HOST and SPACE_ID at startup for information
|
| 177 |
-
space_host_startup = os.getenv("SPACE_HOST")
|
| 178 |
-
space_id_startup = os.getenv("SPACE_ID") # Get SPACE_ID at startup
|
| 179 |
-
|
| 180 |
-
if space_host_startup:
|
| 181 |
-
print(f"✅ SPACE_HOST found: {space_host_startup}")
|
| 182 |
-
print(f" Runtime URL should be: https://{space_host_startup}.hf.space")
|
| 183 |
-
else:
|
| 184 |
-
print("ℹ️ SPACE_HOST environment variable not found (running locally?).")
|
| 185 |
-
|
| 186 |
-
if space_id_startup: # Print repo URLs if SPACE_ID is found
|
| 187 |
-
print(f"✅ SPACE_ID found: {space_id_startup}")
|
| 188 |
-
print(f" Repo URL: https://huggingface.co/spaces/{space_id_startup}")
|
| 189 |
-
print(f" Repo Tree URL: https://huggingface.co/spaces/{space_id_startup}/tree/main")
|
| 190 |
-
else:
|
| 191 |
-
print("ℹ️ SPACE_ID environment variable not found (running locally?). Repo URL cannot be determined.")
|
| 192 |
-
|
| 193 |
-
print("-"*(60 + len(" App Starting ")) + "\n")
|
| 194 |
-
|
| 195 |
-
print("Launching Gradio Interface for Basic Agent Evaluation...")
|
| 196 |
-
demo.launch(debug=True, share=False)
|
|
|
|
| 1 |
import os
|
| 2 |
import gradio as gr
|
| 3 |
import requests
|
|
|
|
| 4 |
import pandas as pd
|
| 5 |
+
import re
|
| 6 |
+
import tempfile
|
| 7 |
+
import pytesseract
|
| 8 |
+
from PIL import Image
|
| 9 |
+
from typing import Dict, List, Optional, TypedDict, Annotated
|
| 10 |
+
from langgraph.graph import StateGraph, END
|
| 11 |
+
from langgraph.checkpoint.memory import MemorySaver
|
| 12 |
+
from langchain_core.messages import HumanMessage, SystemMessage, AnyMessage
|
| 13 |
+
from langchain_openai import ChatOpenAI
|
| 14 |
+
from langgraph.prebuilt import ToolNode, tools_condition
|
| 15 |
+
from langchain_community.tools.tavily_search import TavilySearchResults
|
| 16 |
+
from youtube_transcript_api import YouTubeTranscriptApi
|
| 17 |
+
import yt_dlp
|
| 18 |
+
import cv2
|
| 19 |
+
import numpy as np
|
| 20 |
+
import speech_recognition as sr
|
| 21 |
+
|
| 22 |
+
# ================ Configuración Global ================
|
| 23 |
DEFAULT_API_URL = "https://agents-course-unit4-scoring.hf.space"
|
| 24 |
+
SYSTEM_PROMPT = SYSTEM_PROMPT = """You are a precision research assistant for the GAIA benchmark. Your mission is EXTREME ACCURACY.
|
| 25 |
+
CRITICAL ANSWER FORMAT RULES:
|
| 26 |
+
# - ALWAYS end with: FINAL ANSWER: [answer]
|
| 27 |
+
# - READ THE QUESTION CAREFULLY - answer EXACTLY what is asked for, nothing more, nothing less
|
| 28 |
+
SPECIFIC FORMATTING BY QUESTION TYPE:
|
| 29 |
+
# - Numbers: ONLY the number, no units, no text
|
| 30 |
+
# Example: "FINAL ANSWER: 2" NOT "FINAL ANSWER: 2 albums"
|
| 31 |
+
# - First name only: ONLY the first name
|
| 32 |
+
# Example: If person is "John Smith" → "FINAL ANSWER: John"
|
| 33 |
+
# - Country codes, IOC codes, abbreviations, symbols: ONLY the code/abbreviation, no country name or brackets
|
| 34 |
+
# Example: If asked for IOC country code → "FINAL ANSWER: PHI" NOT "FINAL ANSWER: PHILIPPINES [PHI]"
|
| 35 |
+
# - When asked for a specific type of identifier (code, abbreviation, symbol):
|
| 36 |
+
# Give ONLY that identifier, strip all explanatory text, brackets, or full names
|
| 37 |
+
# - Lists/Sets: Exactly as requested format
|
| 38 |
+
# Example: "FINAL ANSWER: a, b, d, e" (comma-separated, alphabetical order)
|
| 39 |
+
CRITICAL TOOL SELECTION:
|
| 40 |
+
# - Wikipedia questions → wikipedia_tool ONLY
|
| 41 |
+
# - File questions → file_analyzer_tool FIRST to inspect contents, then reason based on structure
|
| 42 |
+
# - Current events → web_search_tool ONLY
|
| 43 |
+
# - Mathematical analysis/calculations → wolfram_alpha_tool or python_repl_tool ONLY
|
| 44 |
+
# - Tables, matrices, systematic checking → python_repl_tool ONLY
|
| 45 |
+
FOR MATHEMATICAL PROBLEMS:
|
| 46 |
+
# ALWAYS use python_repl_tool when:
|
| 47 |
+
# - Analyzing mathematical tables or matrices
|
| 48 |
+
# - Checking properties like commutativity, associativity
|
| 49 |
+
# - Systematic verification of mathematical statements
|
| 50 |
+
# - Complex calculations that need precision
|
| 51 |
+
# - ANY problem involving tables, sets, or systematic checking
|
| 52 |
+
MATHEMATICAL ANALYSIS PROCESS:
|
| 53 |
+
# 1. Use python_repl_tool to parse data systematically
|
| 54 |
+
# 2. Write code to check ALL cases (don't rely on manual inspection)
|
| 55 |
+
# 3. Collect results programmatically
|
| 56 |
+
# 4. Verify your logic with multiple approaches
|
| 57 |
+
# 5. Format answer exactly as requested
|
| 58 |
+
# Example for commutativity checking:
|
| 59 |
+
# - Parse the operation table into a data structure
|
| 60 |
+
# - Check ALL pairs (x,y) to see if x*y = y*x
|
| 61 |
+
# - Collect ALL elements involved in ANY counter-example
|
| 62 |
+
# - Return in requested format (e.g., comma-separated, alphabetical)
|
| 63 |
+
FILE HANDLING:
|
| 64 |
+
# - You HAVE the ability to read and analyze uploaded files
|
| 65 |
+
# - ALWAYS use file_analyzer_tool when questions mention files
|
| 66 |
+
# - The tool automatically finds and analyzes Excel, CSV, images, and audio files
|
| 67 |
+
# - For Excel/CSV: Returns columns, data types, sample rows, and numeric totals
|
| 68 |
+
# - NEVER say "I can't access files" - you CAN access them via file_analyzer_tool
|
| 69 |
+
# - Example: "The attached Excel file..." → Use file_analyzer_tool immediately
|
| 70 |
+
SPECIAL CASES TO HANDLE:
|
| 71 |
+
# - If the question appears reversed or encoded, decode it first.
|
| 72 |
+
# - If the question includes an instruction (e.g., "write the opposite of..."), follow the instruction precisely.
|
| 73 |
+
# - DO NOT repeat or paraphrase the question in your answer.
|
| 74 |
+
# - NEVER answer with the full sentence unless explicitly asked to.
|
| 75 |
+
# - If the decoded question asks for a word, give ONLY the word, in the required format.
|
| 76 |
+
REASONING PROCESS:
|
| 77 |
+
# 1. Carefully read what the question is asking for
|
| 78 |
+
# 2. Identify if it needs systematic/mathematical analysis
|
| 79 |
+
# 3. Use appropriate tool (python_repl_tool for math problems)
|
| 80 |
+
# 4. Extract ONLY the specific part requested
|
| 81 |
+
# 5. Format according to the rules above
|
| 82 |
+
# 6. For file questions:
|
| 83 |
+
# a. First use file_analyzer_tool to inspect column names, types, and sample data
|
| 84 |
+
# b. Identify relevant columns based on the question
|
| 85 |
+
# c. Reason using the data (e.g., by counting, filtering, or identifying patterns)
|
| 86 |
+
# d. Only use python_repl_tool if additional computation is necessary
|
| 87 |
+
# 7. If the Wikipedia tool is used but fails to provide an answer (no relevant entry or content), automatically attempt a web search using the same query or a refined version of it
|
| 88 |
+
"""
|
| 89 |
+
|
| 90 |
+
# ================ Clase del Agente ================
|
| 91 |
+
class GaiaAgent:
|
| 92 |
def __init__(self):
|
| 93 |
+
self.tools = self._initialize_tools()
|
| 94 |
+
self.agent_runner = self._create_agent_runner()
|
| 95 |
+
self.recognizer = sr.Recognizer()
|
| 96 |
+
|
| 97 |
+
def _initialize_tools(self):
|
| 98 |
+
return [
|
| 99 |
+
self.wikipedia_tool,
|
| 100 |
+
self.youtube_transcript_tool,
|
| 101 |
+
self.file_analyzer_tool,
|
| 102 |
+
self.web_search_tool
|
| 103 |
+
]
|
| 104 |
+
|
| 105 |
+
def _create_agent_runner(self):
|
| 106 |
+
llm = ChatOpenAI(model="gpt-4-turbo", temperature=0.0)
|
| 107 |
+
model_with_tools = llm.bind_tools(self.tools)
|
| 108 |
+
|
| 109 |
+
def agent_node(state):
|
| 110 |
+
messages = state['messages']
|
| 111 |
+
if not messages or not isinstance(messages[0], SystemMessage):
|
| 112 |
+
messages = [SystemMessage(content=SYSTEM_PROMPT)] + messages
|
| 113 |
+
|
| 114 |
+
response = model_with_tools.invoke(messages)
|
| 115 |
+
return {"messages": [response]}
|
| 116 |
+
|
| 117 |
+
tool_node = ToolNode(self.tools)
|
| 118 |
+
|
| 119 |
+
builder = StateGraph(AgentState)
|
| 120 |
+
builder.add_node("agent", agent_node)
|
| 121 |
+
builder.add_node("tools", tool_node)
|
| 122 |
+
builder.add_edge("tools", "agent")
|
| 123 |
+
builder.add_conditional_edges("agent", tools_condition, {"tools": "tools", END: END})
|
| 124 |
+
|
| 125 |
+
return builder.compile(checkpointer=MemorySaver())
|
| 126 |
+
|
| 127 |
+
# ================ Herramientas ================
|
| 128 |
+
def wikipedia_tool(self, query: str) -> str:
|
| 129 |
+
try:
|
| 130 |
+
import wikipedia
|
| 131 |
+
wikipedia.set_lang("en")
|
| 132 |
+
return wikipedia.summary(query, sentences=3)
|
| 133 |
+
except Exception as e:
|
| 134 |
+
return f"Wikipedia error: {str(e)}"
|
| 135 |
+
|
| 136 |
+
def youtube_transcript_tool(self, url: str, question: str) -> str:
|
| 137 |
+
try:
|
| 138 |
+
video_id = re.findall(r'(?:v=|\/)([0-9A-Za-z_-]{11})', url)[0]
|
| 139 |
+
transcript = YouTubeTranscriptApi.get_transcript(video_id)
|
| 140 |
+
return " ".join([entry['text'] for entry in transcript[:5]])
|
| 141 |
+
except Exception as e:
|
| 142 |
+
return f"Transcript error: {str(e)}"
|
| 143 |
+
|
| 144 |
+
def file_analyzer_tool(self, file_description: str = "") -> str:
|
| 145 |
+
try:
|
| 146 |
+
img = Image.open("temp_file.png")
|
| 147 |
+
text = pytesseract.image_to_string(img)
|
| 148 |
+
return f"OCR Text: {text[:500]}..." if text else "No text found"
|
| 149 |
+
except:
|
| 150 |
+
return "File analysis not available"
|
| 151 |
+
|
| 152 |
+
def web_search_tool(self, query: str) -> str:
|
| 153 |
+
try:
|
| 154 |
+
tavily = TavilySearchResults(max_results=3)
|
| 155 |
+
results = tavily.invoke(query)
|
| 156 |
+
return "\n".join([f"{res['title']}: {res['content']}" for res in results])
|
| 157 |
+
except Exception as e:
|
| 158 |
+
return f"Search error: {str(e)}"
|
| 159 |
+
|
| 160 |
+
# ================ Procesamiento Principal ================
|
| 161 |
def __call__(self, question: str) -> str:
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 162 |
try:
|
| 163 |
+
events = self.agent_runner.stream(
|
| 164 |
+
{"messages": [HumanMessage(content=question)]},
|
| 165 |
+
config={"configurable": {"thread_id": "gaia_thread"}},
|
| 166 |
+
stream_mode="values"
|
| 167 |
+
)
|
| 168 |
+
|
| 169 |
+
for event in events:
|
| 170 |
+
if event['messages']:
|
| 171 |
+
last_msg = event['messages'][-1]
|
| 172 |
+
if hasattr(last_msg, 'content'):
|
| 173 |
+
return self._extract_final_answer(last_msg.content)
|
| 174 |
+
return "No answer generated"
|
| 175 |
except Exception as e:
|
| 176 |
+
return f"Agent Error: {str(e)}"
|
|
|
|
| 177 |
|
| 178 |
+
def _extract_final_answer(self, text: str) -> str:
|
| 179 |
+
match = re.search(r"FINAL ANSWER:\s*(.*)", text, re.IGNORECASE)
|
| 180 |
+
return match.group(1).strip() if match else text.split("\n")[-1].strip()
|
| 181 |
|
| 182 |
+
# ================ Integración con Gradio ================
|
| 183 |
+
def run_and_submit_all(profile: gr.OAuthProfile | None):
|
| 184 |
+
space_id = os.getenv("SPACE_ID")
|
| 185 |
+
if not profile:
|
| 186 |
+
return "Please login with Hugging Face account", None
|
| 187 |
|
|
|
|
|
|
|
| 188 |
try:
|
| 189 |
+
agent = GaiaAgent()
|
| 190 |
+
questions = requests.get(f"{DEFAULT_API_URL}/questions").json()
|
| 191 |
+
|
| 192 |
+
answers = []
|
| 193 |
+
results_log = []
|
| 194 |
+
for item in questions:
|
| 195 |
+
answer = agent(item['question'])
|
| 196 |
+
answers.append({"task_id": item['task_id'], "submitted_answer": answer})
|
| 197 |
+
results_log.append({"Task": item['task_id'], "Answer": answer})
|
| 198 |
+
|
| 199 |
+
submission_data = {
|
| 200 |
+
"username": profile.username,
|
| 201 |
+
"agent_code": f"https://huggingface.co/spaces/{space_id}",
|
| 202 |
+
"answers": answers
|
| 203 |
+
}
|
| 204 |
+
|
| 205 |
+
response = requests.post(f"{DEFAULT_API_URL}/submit", json=submission_data)
|
| 206 |
response.raise_for_status()
|
| 207 |
+
|
| 208 |
+
return f"Success! Score: {response.json().get('score', 0)}", pd.DataFrame(results_log)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 209 |
except Exception as e:
|
| 210 |
+
return f"Error: {str(e)}", pd.DataFrame()
|
|
|
|
|
|
|
|
|
|
| 211 |
|
| 212 |
+
# ================ Interfaz de Usuario ================
|
|
|
|
| 213 |
with gr.Blocks() as demo:
|
| 214 |
+
gr.Markdown("# GAIA Agent - Hugging Face")
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 215 |
gr.LoginButton()
|
| 216 |
+
run_btn = gr.Button("Run Evaluation")
|
| 217 |
+
status = gr.Textbox(label="Status")
|
| 218 |
+
results = gr.DataFrame(label="Results")
|
| 219 |
+
|
| 220 |
+
run_btn.click(
|
|
|
|
|
|
|
|
|
|
| 221 |
fn=run_and_submit_all,
|
| 222 |
+
outputs=[status, results]
|
| 223 |
)
|
| 224 |
|
| 225 |
if __name__ == "__main__":
|
| 226 |
+
demo.launch(debug=True)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|