Spaces:
Sleeping
Sleeping
Update app.py
Browse files
app.py
CHANGED
|
@@ -1,209 +1,140 @@
|
|
|
|
|
| 1 |
import gradio as gr
|
| 2 |
import requests
|
| 3 |
-
import os
|
| 4 |
-
import json
|
| 5 |
from huggingface_hub import HfApi
|
| 6 |
-
|
| 7 |
-
from langchain_openai import ChatOpenAI
|
| 8 |
-
from langchain.agents import AgentExecutor, create_openai_tools_agent
|
| 9 |
-
from langchain_community.tools.tavily_search import TavilySearchResults
|
| 10 |
-
from langchain_core.prompts import ChatPromptTemplate
|
| 11 |
-
from langchain_core.tools import tool
|
| 12 |
-
|
| 13 |
-
# Import the solve function from our agent file
|
| 14 |
-
from agent import solve
|
| 15 |
|
| 16 |
# --- Constants ---
|
| 17 |
GAIA_API_URL = "https://agents-course-unit4-scoring.hf.space"
|
| 18 |
-
# The agent itself will handle API key checks internally, but we can do a preliminary check here.
|
| 19 |
-
GROQ_API_KEY = os.environ.get("GROQ_API_KEY")
|
| 20 |
-
TAVILY_API_KEY = os.environ.get("TAVILY_API_KEY")
|
| 21 |
-
OPENAI_API_KEY = os.environ.get("OPENAI_API_KEY")
|
| 22 |
-
|
| 23 |
-
# --- Tool Definitions ---
|
| 24 |
-
|
| 25 |
-
@tool
|
| 26 |
-
def read_file(file_name: str) -> str:
|
| 27 |
-
"""
|
| 28 |
-
Reads the contents of a specified file and returns it as a string.
|
| 29 |
-
Use this tool to inspect the content of files provided by the user.
|
| 30 |
-
"""
|
| 31 |
-
try:
|
| 32 |
-
with open(file_name, "r", encoding="utf-8") as f:
|
| 33 |
-
return f.read()
|
| 34 |
-
except FileNotFoundError:
|
| 35 |
-
return f"Error: File '{file_name}' not found."
|
| 36 |
-
except Exception as e:
|
| 37 |
-
return f"An error occurred while reading the file: {e}"
|
| 38 |
-
|
| 39 |
-
@tool
|
| 40 |
-
def write_file(file_name: str, content: str) -> str:
|
| 41 |
-
"""
|
| 42 |
-
Writes the given content to a specified file.
|
| 43 |
-
This will overwrite the file if it already exists.
|
| 44 |
-
"""
|
| 45 |
-
try:
|
| 46 |
-
with open(file_name, "w", encoding="utf-8") as f:
|
| 47 |
-
f.write(content)
|
| 48 |
-
return f"Successfully wrote to {file_name}."
|
| 49 |
-
except Exception as e:
|
| 50 |
-
return f"An error occurred while writing to the file: {e}"
|
| 51 |
|
| 52 |
-
|
| 53 |
-
def list_files(directory: str = '.') -> list[str]:
|
| 54 |
-
"""
|
| 55 |
-
Lists all files and directories in a given directory.
|
| 56 |
-
Defaults to the current directory.
|
| 57 |
-
"""
|
| 58 |
-
try:
|
| 59 |
-
return os.listdir(directory)
|
| 60 |
-
except FileNotFoundError:
|
| 61 |
-
return [f"Error: Directory '{directory}' not found."]
|
| 62 |
-
except Exception as e:
|
| 63 |
-
return [f"An error occurred: {e}"]
|
| 64 |
-
|
| 65 |
-
# --- Agent Initialization ---
|
| 66 |
-
|
| 67 |
-
AGENT_PROMPT = ChatPromptTemplate.from_messages(
|
| 68 |
-
[
|
| 69 |
-
("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."),
|
| 70 |
-
("human", "{input}"),
|
| 71 |
-
("placeholder", "{agent_scratchpad}"),
|
| 72 |
-
]
|
| 73 |
-
)
|
| 74 |
-
|
| 75 |
-
def initialize_agent(llm, tools):
|
| 76 |
-
"""Initializes and returns an agent executor."""
|
| 77 |
-
agent = create_openai_tools_agent(llm, tools, AGENT_PROMPT)
|
| 78 |
-
agent_executor = AgentExecutor(
|
| 79 |
-
agent=agent,
|
| 80 |
-
tools=tools,
|
| 81 |
-
verbose=True,
|
| 82 |
-
)
|
| 83 |
-
return agent_executor
|
| 84 |
|
| 85 |
-
# ---
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 86 |
|
| 87 |
-
|
|
|
|
|
|
|
|
|
|
| 88 |
"""
|
| 89 |
-
|
| 90 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 91 |
"""
|
|
|
|
| 92 |
if profile is None:
|
| 93 |
-
yield "Error: Please log in with your Hugging Face account first."
|
| 94 |
return
|
| 95 |
|
| 96 |
-
#
|
| 97 |
try:
|
| 98 |
api = HfApi()
|
| 99 |
hf_user = api.whoami(token=profile.token)
|
| 100 |
username = hf_user['name']
|
| 101 |
-
yield f"Authenticated as Hugging Face user: {username}"
|
| 102 |
except Exception as e:
|
| 103 |
-
yield f"Error during Hugging Face authentication: {e}"
|
| 104 |
return
|
| 105 |
-
|
| 106 |
-
# .
|
| 107 |
-
|
| 108 |
-
|
| 109 |
-
if not GROQ_API_KEY or not TAVILY_API_KEY:
|
| 110 |
-
yield "Error: Required API keys (GROQ_API_KEY, TAVILY_API_KEY) are not set. Please configure them as Space secrets."
|
| 111 |
return
|
| 112 |
|
| 113 |
-
# .
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 114 |
|
| 115 |
-
#
|
| 116 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 117 |
|
| 118 |
-
|
| 119 |
-
|
| 120 |
-
|
| 121 |
-
question = task["question"]
|
| 122 |
-
file_name = task.get("file_name")
|
| 123 |
|
| 124 |
-
|
| 125 |
-
yield f"
|
|
|
|
|
|
|
| 126 |
|
| 127 |
-
|
| 128 |
-
|
| 129 |
-
|
| 130 |
-
|
| 131 |
-
file_response = requests.get(f"{GAIA_API_URL}/files/{file_name}")
|
| 132 |
-
file_response.raise_for_status()
|
| 133 |
-
# Save the file in the workspace directory defined in agent.py
|
| 134 |
-
file_path = os.path.join("workspace", file_name)
|
| 135 |
-
os.makedirs("workspace", exist_ok=True)
|
| 136 |
-
with open(file_path, "wb") as f:
|
| 137 |
-
f.write(file_response.content)
|
| 138 |
-
yield f"File '{file_name}' downloaded to workspace. The agent can now access it."
|
| 139 |
-
except requests.exceptions.RequestException as e:
|
| 140 |
-
yield f"Error downloading file {file_name}: {e}"
|
| 141 |
-
continue
|
| 142 |
-
|
| 143 |
-
# Run the imported Groq agent using the solve function
|
| 144 |
-
try:
|
| 145 |
-
yield "Invoking agent..."
|
| 146 |
-
answer = solve(question)
|
| 147 |
-
yield f"Agent generated answer: {answer}"
|
| 148 |
-
except Exception as e:
|
| 149 |
-
yield f"An error occurred while running the agent: {e}"
|
| 150 |
-
answer = f"Error processing the question: {e}"
|
| 151 |
-
|
| 152 |
-
# Submit the answer with the username
|
| 153 |
-
try:
|
| 154 |
-
yield f"Submitting answer for user '{username}'..."
|
| 155 |
-
submission_payload = {
|
| 156 |
-
"task_id": task_id,
|
| 157 |
-
"submitted_answer": answer,
|
| 158 |
-
"username": username
|
| 159 |
-
}
|
| 160 |
-
submission_response = requests.post(
|
| 161 |
-
f"{GAIA_API_URL}/submission",
|
| 162 |
-
json=submission_payload,
|
| 163 |
-
)
|
| 164 |
-
submission_response.raise_for_status()
|
| 165 |
-
result = submission_response.json()
|
| 166 |
-
yield f"Submission result: {result['message']}"
|
| 167 |
-
except requests.exceptions.RequestException as e:
|
| 168 |
-
yield f"Error submitting answer for task {task_id}: {e}"
|
| 169 |
-
|
| 170 |
-
# Clean up the downloaded file
|
| 171 |
-
if file_name:
|
| 172 |
-
cleanup_path = os.path.join("workspace", file_name)
|
| 173 |
-
if os.path.exists(cleanup_path):
|
| 174 |
-
os.remove(cleanup_path)
|
| 175 |
-
yield f"Cleaned up file: {file_name}"
|
| 176 |
-
|
| 177 |
-
yield "\n--- All tasks completed! ---"
|
| 178 |
-
|
| 179 |
-
# --- Gradio Interface ---
|
| 180 |
-
|
| 181 |
-
with gr.Blocks(theme=gr.themes.Soft()) as demo:
|
| 182 |
-
gr.Markdown("# GAIA Benchmark Agent Runner")
|
| 183 |
gr.Markdown(
|
| 184 |
-
"This application runs
|
| 185 |
-
"and
|
| 186 |
-
"**Step 1:** Log in with your Hugging Face account using the button below. \n"
|
| 187 |
-
"**Step 2:** Ensure your `GROQ_API_KEY` and `TAVILY_API_KEY` are set as Space secrets. \n"
|
| 188 |
-
"**Step 3:** Click 'Run and Submit All Tasks' to begin."
|
| 189 |
)
|
| 190 |
-
|
| 191 |
with gr.Row():
|
| 192 |
-
login_button = gr.LoginButton(value="Login with Hugging Face")
|
| 193 |
-
|
| 194 |
-
|
| 195 |
-
|
| 196 |
-
|
| 197 |
-
|
| 198 |
-
|
| 199 |
-
|
| 200 |
-
|
| 201 |
-
|
| 202 |
-
|
| 203 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 204 |
fn=run_and_submit_all,
|
| 205 |
-
inputs=[login_button
|
| 206 |
-
outputs=[output_textbox]
|
| 207 |
)
|
| 208 |
|
| 209 |
if __name__ == "__main__":
|
|
|
|
| 1 |
+
import os
|
| 2 |
import gradio as gr
|
| 3 |
import requests
|
|
|
|
|
|
|
| 4 |
from huggingface_hub import HfApi
|
| 5 |
+
from agent import solve # Import the new OpenAI-based agent solver
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 6 |
|
| 7 |
# --- Constants ---
|
| 8 |
GAIA_API_URL = "https://agents-course-unit4-scoring.hf.space"
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 9 |
|
| 10 |
+
MAX_QUESTIONS = 5 # Limit the number of questions to process in a single run
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 11 |
|
| 12 |
+
# --- Helper Function to Fetch Questions ---
|
| 13 |
+
def get_all_questions():
|
| 14 |
+
"""Fetches all available questions from the GAIA API."""
|
| 15 |
+
response = requests.get(f"{GAIA_API_URL}/api/questions")
|
| 16 |
+
response.raise_for_status()
|
| 17 |
+
return response.json()
|
| 18 |
|
| 19 |
+
# --- Core Application Logic ---
|
| 20 |
+
def run_and_submit_all(
|
| 21 |
+
profile: gr.OAuthProfile | None, openai_api_key: str, tavily_api_key: str
|
| 22 |
+
):
|
| 23 |
"""
|
| 24 |
+
Orchestrates the process of fetching GAIA tasks, running the agent, and submitting results.
|
| 25 |
+
|
| 26 |
+
This function now handles:
|
| 27 |
+
1. User authentication via Hugging Face OAuth.
|
| 28 |
+
2. Securely receiving API keys from the UI.
|
| 29 |
+
3. Setting environment variables for the agent at runtime.
|
| 30 |
+
4. Calling the new OpenAI-based agent from `agent.py`.
|
| 31 |
+
5. Submitting results under the authenticated user's name.
|
| 32 |
"""
|
| 33 |
+
# 1. Validate User Login
|
| 34 |
if profile is None:
|
| 35 |
+
yield "### ❌ Error: Please log in with your Hugging Face account first."
|
| 36 |
return
|
| 37 |
|
| 38 |
+
# 2. **FIX**: Define `username` from the OAuth profile
|
| 39 |
try:
|
| 40 |
api = HfApi()
|
| 41 |
hf_user = api.whoami(token=profile.token)
|
| 42 |
username = hf_user['name']
|
| 43 |
+
yield f"### ✅ Authenticated as Hugging Face user: **{username}**"
|
| 44 |
except Exception as e:
|
| 45 |
+
yield f"### ❌ Error during Hugging Face authentication: {e}"
|
| 46 |
return
|
| 47 |
+
|
| 48 |
+
# 3. Validate API Keys
|
| 49 |
+
if not openai_api_key or not tavily_api_key:
|
| 50 |
+
yield "### ❌ Error: OpenAI and Tavily API keys are required. Please enter them above."
|
|
|
|
|
|
|
| 51 |
return
|
| 52 |
|
| 53 |
+
# 4. Set API Keys as Environment Variables for the Agent
|
| 54 |
+
# This makes the keys available to the `solve` function when it's called.
|
| 55 |
+
os.environ["OPENAI_API_KEY"] = openai_api_key
|
| 56 |
+
os.environ["TAVILY_API_KEY"] = tavily_api_key
|
| 57 |
+
yield "### 🔑 API keys successfully set for this session."
|
| 58 |
+
yield "---"
|
| 59 |
|
| 60 |
+
# 5. Fetch and Process Questions
|
| 61 |
+
try:
|
| 62 |
+
yield "### 📥 Fetching questions from GAIA..."
|
| 63 |
+
questions = get_all_questions()
|
| 64 |
+
tasks = questions.get("questions", [])
|
| 65 |
+
if not tasks:
|
| 66 |
+
yield "### समाप्त No questions available to process."
|
| 67 |
+
return
|
| 68 |
+
|
| 69 |
+
yield f"### 🚀 Found {len(tasks)} questions. Starting agent on the first {MAX_QUESTIONS} tasks..."
|
| 70 |
+
|
| 71 |
+
for i, task in enumerate(tasks[:MAX_QUESTIONS]):
|
| 72 |
+
task_id = task["task_id"]
|
| 73 |
+
question = task["Question"]
|
| 74 |
+
task_prompt = f"Task ID: {task_id}\nQuestion: {question}"
|
| 75 |
+
|
| 76 |
+
yield f"\n\n---"
|
| 77 |
+
yield f"### 🧠 **Task {i+1}/{MAX_QUESTIONS}** (ID: {task_id})"
|
| 78 |
+
yield f"> **Question:** {question}"
|
| 79 |
+
yield "> Running agent..."
|
| 80 |
+
|
| 81 |
+
# **INTEGRATION**: Call the new `solve` function from `agent.py`
|
| 82 |
+
answer = solve(task_prompt)
|
| 83 |
+
yield f"> **Agent's Answer:** {answer}"
|
| 84 |
+
|
| 85 |
+
# Submit the answer to the GAIA API
|
| 86 |
+
try:
|
| 87 |
+
yield f"> Submitting answer for user '{username}'..."
|
| 88 |
+
submission_payload = {
|
| 89 |
+
"task_id": task_id,
|
| 90 |
+
"submitted_answer": answer,
|
| 91 |
+
"username": username,
|
| 92 |
+
}
|
| 93 |
+
response = requests.post(f"{GAIA_API_URL}/api/submit", json=submission_payload)
|
| 94 |
+
response.raise_for_status()
|
| 95 |
+
yield f"### ✅ **Submission Successful!**"
|
| 96 |
+
yield f"> Server response: `{response.json()}`"
|
| 97 |
|
| 98 |
+
except requests.exceptions.RequestException as e:
|
| 99 |
+
yield f"### ❌ **Submission Failed!**"
|
| 100 |
+
yield f"> Error submitting answer for task {task_id}: {e}"
|
|
|
|
|
|
|
| 101 |
|
| 102 |
+
except Exception as e:
|
| 103 |
+
yield f"\n### ❌ An unexpected error occurred: {e}"
|
| 104 |
+
import traceback
|
| 105 |
+
yield f"```\n{traceback.format_exc()}\n```"
|
| 106 |
|
| 107 |
+
|
| 108 |
+
# --- Gradio UI Definition ---
|
| 109 |
+
with gr.Blocks(theme=gr.themes.Default(primary_hue="blue")) as demo:
|
| 110 |
+
gr.Markdown("# 🏆 GAIA Agent Runner")
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 111 |
gr.Markdown(
|
| 112 |
+
"This application runs an AI agent to solve tasks from the GAIA (General AI Assistants) benchmark. "
|
| 113 |
+
"Log in with your Hugging Face account and provide your API keys to begin."
|
|
|
|
|
|
|
|
|
|
| 114 |
)
|
| 115 |
+
|
| 116 |
with gr.Row():
|
| 117 |
+
login_button = gr.LoginButton(value="Login with Hugging Face 🤗")
|
| 118 |
+
run_button = gr.Button("Run and Submit All Tasks", variant="primary")
|
| 119 |
+
|
| 120 |
+
with gr.Accordion("API Keys (Required)", open=False):
|
| 121 |
+
gr.Markdown("Your keys are used only for this session and are not stored.")
|
| 122 |
+
openai_api_key_box = gr.Textbox(
|
| 123 |
+
label="OpenAI API Key", type="password", interactive=True
|
| 124 |
+
)
|
| 125 |
+
tavily_api_key_box = gr.Textbox(
|
| 126 |
+
label="Tavily API Key", type="password", interactive=True
|
| 127 |
+
)
|
| 128 |
+
|
| 129 |
+
gr.Markdown("---")
|
| 130 |
+
gr.Markdown("### 📝 Live Output")
|
| 131 |
+
output_textbox = gr.Markdown(value="> Waiting to start...")
|
| 132 |
+
|
| 133 |
+
# Connect the "Run" button to the main logic function
|
| 134 |
+
run_button.click(
|
| 135 |
fn=run_and_submit_all,
|
| 136 |
+
inputs=[login_button, openai_api_key_box, tavily_api_key_box],
|
| 137 |
+
outputs=[output_textbox],
|
| 138 |
)
|
| 139 |
|
| 140 |
if __name__ == "__main__":
|