Mtchmann commited on
Commit
dcc0f3f
·
verified ·
1 Parent(s): 66dfd1b

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +161 -164
app.py CHANGED
@@ -1,194 +1,191 @@
1
- import os
2
  import gradio as gr
3
  import requests
4
- from gradio.themes.base import Base
5
-
6
- # Import the agent logic from agent.py
7
- # This assumes agent.py, which contains the `solve` function, is in the same directory.
8
- from agent import solve
9
-
10
- # -----------------------------------------------------------------------------
11
- # Configuration
12
- # -----------------------------------------------------------------------------
13
-
14
- # The base URL for the GAIA benchmark API
15
  GAIA_API_URL = "https://agents-course-unit4-scoring.hf.space"
 
 
16
 
17
- # IMPORTANT: Replace this with the URL of your Hugging Face Space or public GitHub repository.
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
- # Read the agent.py file content to display it in the UI for transparency
26
- try:
27
- # Corrected the encoding from "utf-utf-8" to "utf-8"
28
- with open("agent.py", "r", encoding="utf-8") as f:
29
- AGENT_CODE = f.read()
30
- except FileNotFoundError:
31
- AGENT_CODE = "Could not load agent.py. Please ensure the file is in the same directory."
32
-
33
- # A simple custom theme for a clean, professional look
34
- class Seafoam(Base):
35
- pass
36
-
37
- seafoam = Seafoam()
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
- **How it works:**
45
- 1. **Login:** You must log in with your Hugging Face account using the button below. This is required for submission to the official leaderboard.
46
- 2. **Run Evaluation:** Click the "Run Evaluation & Submit All Answers" button.
47
- 3. **Process:** The application will fetch all test-level questions from the GAIA API, run the agent for each question to find an answer, and then submit all answers to the leaderboard.
48
- 4. **Results:** The final score will be displayed in the output box. The entire process may take several minutes to complete.
 
 
 
 
 
 
 
49
 
50
- Below is the core agent logic (`agent.py`) used for this evaluation.
51
- """
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
52
 
53
- # -----------------------------------------------------------------------------
54
- # Core Application Logic
55
- # -----------------------------------------------------------------------------
56
 
57
- def run_and_submit_all(profile: gr.OAuthProfile | None):
58
  """
59
- Orchestrates the entire evaluation process:
60
- 1. Fetches questions from the GAIA API.
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
- # Step 1: Verify user is logged in using Hugging Face OAuth.
67
- # The `profile` object is automatically passed by Gradio due to the function's type hint.
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
- username = profile.username
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(f"{GAIA_API_URL}/questions")
 
 
 
 
79
  response.raise_for_status()
80
- questions = response.json()["questions"]
81
- yield f"✅ Successfully fetched {len(questions)} questions."
82
  except requests.exceptions.RequestException as e:
83
- yield f"❌ Error fetching questions: {e}. Please check your connection or the API status."
84
- return
85
- except (KeyError, ValueError):
86
- yield "❌ Error: The API response for questions is not in the expected JSON format."
87
  return
88
 
89
- # Step 3: Run the agent on each question and collect answers
90
- answers = []
91
- total_questions = len(questions)
92
- for i, task in enumerate(questions):
93
- task_id = task["task_id"]
94
- # Correctly access the question text using the 'question' key.
95
- question_text = task["question"]
96
 
97
- yield f"--- \n⚙️ **Processing Question {i + 1}/{total_questions} (Task ID: {task_id})** \n> {question_text}"
98
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
99
  try:
100
- # Invoke the agent logic imported from agent.py
101
- submitted_answer = solve(question_text)
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"❌ An error occurred while running the agent on task {task_id}: {e}"
110
- # Submit a placeholder answer to not break the submission format, using the correct keys.
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
- # Gradio Interface Definition
158
- # -----------------------------------------------------------------------------
159
- with gr.Blocks(theme=seafoam, title="GAIA Benchmark Agent Evaluation") as demo:
160
- gr.Markdown(UI_DESCRIPTION)
161
-
162
- with gr.Row():
163
- gr.LoginButton()
164
-
165
- with gr.Accordion("View Agent Logic (agent.py)", open=False):
166
- gr.Code(
167
- language="python",
168
- value=AGENT_CODE,
169
- interactive=False,
170
- label="agent.py"
171
- )
 
 
 
 
 
 
 
 
 
 
 
 
 
 
172
 
173
- with gr.Column():
174
- run_button = gr.Button(
175
- "Run Evaluation & Submit All Answers",
176
- variant="primary"
177
- )
178
- output_textbox = gr.Markdown(
179
- label="Evaluation Progress & Final Score",
180
- value="Click the run button to start the evaluation process.",
181
- rtl=False
182
- )
183
 
184
- # Connect the button click to the main function.
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
- outputs=[output_textbox],
191
- api_name="run_evaluation"
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__":