Spaces:
Sleeping
Sleeping
Update app.py
Browse files
app.py
CHANGED
|
@@ -1,194 +1,191 @@
|
|
| 1 |
-
import os
|
| 2 |
import gradio as gr
|
| 3 |
import requests
|
| 4 |
-
|
| 5 |
-
|
| 6 |
-
|
| 7 |
-
|
| 8 |
-
from
|
| 9 |
-
|
| 10 |
-
|
| 11 |
-
|
| 12 |
-
# ------
|
| 13 |
-
|
| 14 |
-
# The base URL for the GAIA benchmark API
|
| 15 |
GAIA_API_URL = "https://agents-course-unit4-scoring.hf.space"
|
|
|
|
|
|
|
| 16 |
|
| 17 |
-
#
|
| 18 |
-
# This link is submitted to the benchmark for verification and reproducibility.
|
| 19 |
-
AGENT_CODE_LINK = "https://huggingface.co/spaces/YOUR_USERNAME/YOUR_SPACE_NAME"
|
| 20 |
-
|
| 21 |
-
# -----------------------------------------------------------------------------
|
| 22 |
-
# UI Content and Styling
|
| 23 |
-
# -----------------------------------------------------------------------------
|
| 24 |
|
| 25 |
-
|
| 26 |
-
|
| 27 |
-
|
| 28 |
-
|
| 29 |
-
|
| 30 |
-
|
| 31 |
-
|
| 32 |
-
|
| 33 |
-
|
| 34 |
-
|
| 35 |
-
|
| 36 |
-
|
| 37 |
-
|
| 38 |
-
|
| 39 |
-
# Markdown content for the UI description
|
| 40 |
-
UI_DESCRIPTION = """
|
| 41 |
-
# GAIA Benchmark Evaluation Agent
|
| 42 |
-
This Gradio application runs a multi-tool AI agent designed to solve the GAIA (General AI Assistants) benchmark.
|
| 43 |
|
| 44 |
-
|
| 45 |
-
|
| 46 |
-
|
| 47 |
-
|
| 48 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 49 |
|
| 50 |
-
|
| 51 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 52 |
|
| 53 |
-
# ------
|
| 54 |
-
# Core Application Logic
|
| 55 |
-
# -----------------------------------------------------------------------------
|
| 56 |
|
| 57 |
-
def run_and_submit_all(
|
| 58 |
"""
|
| 59 |
-
|
| 60 |
-
|
| 61 |
-
2. Runs the agent on each question.
|
| 62 |
-
3. Submits the answers and returns the final score.
|
| 63 |
-
|
| 64 |
-
This function is a generator, yielding status updates to the UI for a responsive experience.
|
| 65 |
"""
|
| 66 |
-
|
| 67 |
-
|
| 68 |
-
if not profile:
|
| 69 |
-
yield "Error: You must be logged in with your Hugging Face account to submit. Please use the login button at the top."
|
| 70 |
return
|
| 71 |
|
| 72 |
-
|
| 73 |
-
yield f"✅ Logged in as **{username}**. Starting evaluation..."
|
| 74 |
-
|
| 75 |
-
# Step 2: Fetch all questions from the GAIA API
|
| 76 |
try:
|
| 77 |
yield "Fetching questions from the GAIA API..."
|
| 78 |
-
response = requests.get(
|
|
|
|
|
|
|
|
|
|
|
|
|
| 79 |
response.raise_for_status()
|
| 80 |
-
questions = response.json()
|
| 81 |
-
yield f"
|
| 82 |
except requests.exceptions.RequestException as e:
|
| 83 |
-
|
| 84 |
-
|
| 85 |
-
except (KeyError, ValueError):
|
| 86 |
-
yield "❌ Error: The API response for questions is not in the expected JSON format."
|
| 87 |
return
|
| 88 |
|
| 89 |
-
|
| 90 |
-
|
| 91 |
-
|
| 92 |
-
|
| 93 |
-
|
| 94 |
-
|
| 95 |
-
question_text = task["question"]
|
| 96 |
|
| 97 |
-
|
| 98 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 99 |
try:
|
| 100 |
-
|
| 101 |
-
|
| 102 |
-
|
| 103 |
-
# **CORRECTED PAYLOAD STRUCTURE**
|
| 104 |
-
# Each answer must be a dictionary with 'task_id' and 'submitted_answer' keys.
|
| 105 |
-
answers.append({"task_id": task_id, "submitted_answer": submitted_answer})
|
| 106 |
-
|
| 107 |
-
yield f"➡️ Agent answered: **{submitted_answer}**"
|
| 108 |
except Exception as e:
|
| 109 |
-
yield f"
|
| 110 |
-
|
| 111 |
-
answers.append({"task_id": task_id, "submitted_answer": "AGENT_ERROR"})
|
| 112 |
-
continue
|
| 113 |
-
|
| 114 |
-
# Step 4: Submit all collected answers to the API
|
| 115 |
-
submission_payload = {
|
| 116 |
-
"username": username,
|
| 117 |
-
"answers": answers,
|
| 118 |
-
"code_link": AGENT_CODE_LINK,
|
| 119 |
-
}
|
| 120 |
-
|
| 121 |
-
yield "\n---\n🚀 All questions processed. Submitting answers to the leaderboard..."
|
| 122 |
-
try:
|
| 123 |
-
response = requests.post(f"{GAIA_API_URL}/submit", json=submission_payload)
|
| 124 |
-
response.raise_for_status()
|
| 125 |
-
result = response.json()
|
| 126 |
-
|
| 127 |
-
# Display the final score and results using Markdown for rich formatting
|
| 128 |
-
final_score = result.get("final_score")
|
| 129 |
-
score_breakdown = result.get("score_breakdown", {})
|
| 130 |
-
|
| 131 |
-
result_text = "## 🏆 Submission Successful! 🏆\n\n"
|
| 132 |
-
if final_score is not None:
|
| 133 |
-
result_text += f"**Final Score:** {final_score:.2f}%\n\n"
|
| 134 |
-
else:
|
| 135 |
-
result_text += "**Final Score:** Not available\n\n"
|
| 136 |
-
|
| 137 |
-
result_text += "**Score Breakdown by Level:**\n"
|
| 138 |
-
if score_breakdown:
|
| 139 |
-
for level, score in score_breakdown.items():
|
| 140 |
-
result_text += f"- **Level {level}:** {score:.2f}%\n"
|
| 141 |
-
else:
|
| 142 |
-
result_text += "- No breakdown available.\n"
|
| 143 |
-
|
| 144 |
-
yield result_text
|
| 145 |
-
|
| 146 |
-
except requests.exceptions.RequestException as e:
|
| 147 |
-
error_text = f"❌ Error submitting answers: {e}."
|
| 148 |
-
# Provide detailed error from API response if available
|
| 149 |
-
if 'response' in locals() and hasattr(response, 'text'):
|
| 150 |
-
error_text += f" API Response: `{response.text}`"
|
| 151 |
-
yield error_text
|
| 152 |
-
except Exception as e:
|
| 153 |
-
yield f"❌ An unexpected error occurred during submission: {e}"
|
| 154 |
-
|
| 155 |
|
| 156 |
-
#
|
| 157 |
-
|
| 158 |
-
|
| 159 |
-
|
| 160 |
-
|
| 161 |
-
|
| 162 |
-
|
| 163 |
-
|
| 164 |
-
|
| 165 |
-
|
| 166 |
-
|
| 167 |
-
|
| 168 |
-
|
| 169 |
-
|
| 170 |
-
|
| 171 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 172 |
|
| 173 |
-
|
| 174 |
-
|
| 175 |
-
|
| 176 |
-
|
| 177 |
-
|
| 178 |
-
|
| 179 |
-
|
| 180 |
-
value="Click the run button to start the evaluation process.",
|
| 181 |
-
rtl=False
|
| 182 |
-
)
|
| 183 |
|
| 184 |
-
|
| 185 |
-
# As per Gradio best practices, no `inputs` are specified. Gradio automatically
|
| 186 |
-
# passes the OAuth profile because of the `profile: gr.OAuthProfile | None`
|
| 187 |
-
# type hint in the `run_and_submit_all` function signature.
|
| 188 |
-
run_button.click(
|
| 189 |
fn=run_and_submit_all,
|
| 190 |
-
|
| 191 |
-
|
| 192 |
)
|
| 193 |
|
| 194 |
if __name__ == "__main__":
|
|
|
|
|
|
|
| 1 |
import gradio as gr
|
| 2 |
import requests
|
| 3 |
+
import os
|
| 4 |
+
import json
|
| 5 |
+
from langchain_openai import ChatOpenAI
|
| 6 |
+
from langchain.agents import AgentExecutor, create_openai_tools_agent
|
| 7 |
+
from langchain_community.tools.tavily_search import TavilySearchResults
|
| 8 |
+
from langchain_core.prompts import ChatPromptTemplate
|
| 9 |
+
from langchain_core.tools import tool
|
| 10 |
+
|
| 11 |
+
# --- Constants ---
|
|
|
|
|
|
|
| 12 |
GAIA_API_URL = "https://agents-course-unit4-scoring.hf.space"
|
| 13 |
+
TAVILY_API_KEY = os.environ.get("TAVILY_API_KEY")
|
| 14 |
+
OPENAI_API_KEY = os.environ.get("OPENAI_API_KEY")
|
| 15 |
|
| 16 |
+
# --- Tool Definitions ---
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 17 |
|
| 18 |
+
@tool
|
| 19 |
+
def read_file(file_name: str) -> str:
|
| 20 |
+
"""
|
| 21 |
+
Reads the contents of a specified file and returns it as a string.
|
| 22 |
+
Use this tool to inspect the content of files provided by the user.
|
| 23 |
+
"""
|
| 24 |
+
try:
|
| 25 |
+
with open(file_name, "r", encoding="utf-8") as f:
|
| 26 |
+
return f.read()
|
| 27 |
+
except FileNotFoundError:
|
| 28 |
+
return f"Error: File '{file_name}' not found."
|
| 29 |
+
except Exception as e:
|
| 30 |
+
return f"An error occurred while reading the file: {e}"
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 31 |
|
| 32 |
+
@tool
|
| 33 |
+
def write_file(file_name: str, content: str) -> str:
|
| 34 |
+
"""
|
| 35 |
+
Writes the given content to a specified file.
|
| 36 |
+
This will overwrite the file if it already exists.
|
| 37 |
+
"""
|
| 38 |
+
try:
|
| 39 |
+
with open(file_name, "w", encoding="utf-8") as f:
|
| 40 |
+
f.write(content)
|
| 41 |
+
return f"Successfully wrote to {file_name}."
|
| 42 |
+
except Exception as e:
|
| 43 |
+
return f"An error occurred while writing to the file: {e}"
|
| 44 |
|
| 45 |
+
@tool
|
| 46 |
+
def list_files(directory: str = '.') -> list[str]:
|
| 47 |
+
"""
|
| 48 |
+
Lists all files and directories in a given directory.
|
| 49 |
+
Defaults to the current directory.
|
| 50 |
+
"""
|
| 51 |
+
try:
|
| 52 |
+
return os.listdir(directory)
|
| 53 |
+
except FileNotFoundError:
|
| 54 |
+
return [f"Error: Directory '{directory}' not found."]
|
| 55 |
+
except Exception as e:
|
| 56 |
+
return [f"An error occurred: {e}"]
|
| 57 |
+
|
| 58 |
+
# --- Agent Initialization ---
|
| 59 |
+
|
| 60 |
+
AGENT_PROMPT = ChatPromptTemplate.from_messages(
|
| 61 |
+
[
|
| 62 |
+
("system", "You are a helpful assistant designed to solve complex tasks. You have access to a variety of tools. When a file is provided, it will be saved in the current directory. Use the file-system tools to inspect and use it."),
|
| 63 |
+
("human", "{input}"),
|
| 64 |
+
("placeholder", "{agent_scratchpad}"),
|
| 65 |
+
]
|
| 66 |
+
)
|
| 67 |
+
|
| 68 |
+
def initialize_agent(llm, tools):
|
| 69 |
+
"""Initializes and returns an agent executor."""
|
| 70 |
+
agent = create_openai_tools_agent(llm, tools, AGENT_PROMPT)
|
| 71 |
+
agent_executor = AgentExecutor(
|
| 72 |
+
agent=agent,
|
| 73 |
+
tools=tools,
|
| 74 |
+
verbose=True,
|
| 75 |
+
)
|
| 76 |
+
return agent_executor
|
| 77 |
|
| 78 |
+
# --- Core Logic ---
|
|
|
|
|
|
|
| 79 |
|
| 80 |
+
def run_and_submit_all(uploaded_file_path=None):
|
| 81 |
"""
|
| 82 |
+
Fetches all questions from the GAIA API, runs the agent on each,
|
| 83 |
+
and submits the answers.
|
|
|
|
|
|
|
|
|
|
|
|
|
| 84 |
"""
|
| 85 |
+
if not OPENAI_API_KEY or not TAVILY_API_KEY:
|
| 86 |
+
yield "Error: API keys (OPENAI_API_KEY, TAVILY_API_KEY) are not set. Please configure them as environment variables."
|
|
|
|
|
|
|
| 87 |
return
|
| 88 |
|
| 89 |
+
# Fetch questions from the API with robust error handling
|
|
|
|
|
|
|
|
|
|
| 90 |
try:
|
| 91 |
yield "Fetching questions from the GAIA API..."
|
| 92 |
+
response = requests.get(
|
| 93 |
+
f"{GAIA_API_URL}/questions",
|
| 94 |
+
timeout=30 # Set a 30-second timeout for the request
|
| 95 |
+
)
|
| 96 |
+
# Raise an exception for bad status codes (4xx or 5xx)
|
| 97 |
response.raise_for_status()
|
| 98 |
+
questions = response.json()
|
| 99 |
+
yield f"Successfully fetched {len(questions)} questions."
|
| 100 |
except requests.exceptions.RequestException as e:
|
| 101 |
+
# Handle network errors, timeouts, and bad HTTP responses
|
| 102 |
+
yield f"Error fetching questions from API: {e}"
|
|
|
|
|
|
|
| 103 |
return
|
| 104 |
|
| 105 |
+
llm = ChatOpenAI(model="gpt-4o", temperature=0, api_key=OPENAI_API_KEY)
|
| 106 |
+
|
| 107 |
+
# Prepare tools
|
| 108 |
+
base_tools = [TavilySearchResults(max_results=3, api_key=TAVILY_API_KEY)]
|
| 109 |
+
file_tools = [read_file, write_file, list_files]
|
| 110 |
+
all_tools = base_tools + file_tools
|
|
|
|
| 111 |
|
| 112 |
+
agent_executor = initialize_agent(llm, all_tools)
|
| 113 |
|
| 114 |
+
# Process each task
|
| 115 |
+
for i, task in enumerate(questions):
|
| 116 |
+
task_id = task["task_id"]
|
| 117 |
+
question = task["question"]
|
| 118 |
+
file_name = task.get("file_name")
|
| 119 |
+
|
| 120 |
+
yield f"--- Starting Task {i+1}/{len(questions)} (ID: {task_id}) ---"
|
| 121 |
+
yield f"Question: {question}"
|
| 122 |
+
|
| 123 |
+
# If the task has an associated file, download it
|
| 124 |
+
if file_name:
|
| 125 |
+
try:
|
| 126 |
+
yield f"Downloading file: {file_name}..."
|
| 127 |
+
file_response = requests.get(f"{GAIA_API_URL}/files/{file_name}")
|
| 128 |
+
file_response.raise_for_status()
|
| 129 |
+
with open(file_name, "wb") as f:
|
| 130 |
+
f.write(file_response.content)
|
| 131 |
+
yield f"File '{file_name}' downloaded successfully."
|
| 132 |
+
except requests.exceptions.RequestException as e:
|
| 133 |
+
yield f"Error downloading file {file_name}: {e}"
|
| 134 |
+
# Optionally skip this task or try to answer without the file
|
| 135 |
+
continue
|
| 136 |
+
|
| 137 |
+
# Run agent
|
| 138 |
try:
|
| 139 |
+
response = agent_executor.invoke({"input": question})
|
| 140 |
+
answer = response["output"]
|
| 141 |
+
yield f"Agent generated answer: {answer}"
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 142 |
except Exception as e:
|
| 143 |
+
yield f"An error occurred while running the agent: {e}"
|
| 144 |
+
answer = f"Error processing the question: {e}"
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 145 |
|
| 146 |
+
# Submit answer
|
| 147 |
+
try:
|
| 148 |
+
yield "Submitting answer..."
|
| 149 |
+
submission_response = requests.post(
|
| 150 |
+
f"{GAIA_API_URL}/submission",
|
| 151 |
+
json={"task_id": task_id, "answer": answer},
|
| 152 |
+
)
|
| 153 |
+
submission_response.raise_for_status()
|
| 154 |
+
result = submission_response.json()
|
| 155 |
+
yield f"Submission result: {result['message']}"
|
| 156 |
+
except requests.exceptions.RequestException as e:
|
| 157 |
+
yield f"Error submitting answer for task {task_id}: {e}"
|
| 158 |
+
|
| 159 |
+
# Clean up downloaded file
|
| 160 |
+
if file_name and os.path.exists(file_name):
|
| 161 |
+
os.remove(file_name)
|
| 162 |
+
yield f"Cleaned up file: {file_name}"
|
| 163 |
+
|
| 164 |
+
yield "\n--- All tasks completed! ---"
|
| 165 |
+
|
| 166 |
+
|
| 167 |
+
# --- Gradio Interface ---
|
| 168 |
+
|
| 169 |
+
with gr.Blocks() as demo:
|
| 170 |
+
gr.Markdown("# GAIA Benchmark Agent Runner")
|
| 171 |
+
gr.Markdown(
|
| 172 |
+
"This application runs a LangChain agent against all questions from the GAIA benchmark API, "
|
| 173 |
+
"and submits the answers for evaluation. \n\n"
|
| 174 |
+
"**Important:** Ensure your `OPENAI_API_KEY` and `TAVILY_API_KEY` are set as environment variables before launching."
|
| 175 |
+
)
|
| 176 |
|
| 177 |
+
start_button = gr.Button("Run and Submit All Tasks", variant="primary")
|
| 178 |
+
output_textbox = gr.Textbox(
|
| 179 |
+
label="Progress and Logs",
|
| 180 |
+
lines=20,
|
| 181 |
+
autoscroll=True,
|
| 182 |
+
interactive=False
|
| 183 |
+
)
|
|
|
|
|
|
|
|
|
|
| 184 |
|
| 185 |
+
start_button.click(
|
|
|
|
|
|
|
|
|
|
|
|
|
| 186 |
fn=run_and_submit_all,
|
| 187 |
+
inputs=[],
|
| 188 |
+
outputs=[output_textbox]
|
| 189 |
)
|
| 190 |
|
| 191 |
if __name__ == "__main__":
|