Mtchmann commited on
Commit
afca4d8
·
verified ·
1 Parent(s): c471480

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +48 -106
app.py CHANGED
@@ -2,116 +2,48 @@ 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"]
@@ -120,7 +52,7 @@ def run_and_submit_all(uploaded_file_path=None):
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}..."
@@ -128,27 +60,31 @@ def run_and_submit_all(uploaded_file_path=None):
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()
@@ -156,7 +92,7 @@ def run_and_submit_all(uploaded_file_path=None):
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}"
@@ -166,25 +102,31 @@ def run_and_submit_all(uploaded_file_path=None):
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
 
 
2
  import requests
3
  import os
4
  import json
5
+ from huggingface_hub import HfApi
6
+
7
+ # Import the solve function from our agent file
8
+ from agent import solve
 
9
 
10
  # --- Constants ---
11
  GAIA_API_URL = "https://agents-course-unit4-scoring.hf.space"
12
+ # The agent itself will handle API key checks internally, but we can do a preliminary check here.
13
+ GROQ_API_KEY = os.environ.get("GROQ_API_KEY")
14
  TAVILY_API_KEY = os.environ.get("TAVILY_API_KEY")
 
15
 
 
16
 
17
+ # --- Core Logic with Authentication ---
18
+
19
+ def run_and_submit_all(profile: gr.OAuthProfile | None):
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
20
  """
21
+ Fetches all questions from the GAIA API, runs the Groq agent on each,
22
+ and submits the answers under the authenticated user's profile.
23
  """
24
+ # Authentication Guard Clause
25
+ if profile is None:
26
+ raise gr.Error('You must be logged in to run the evaluation. Please log in with your Hugging Face account.')
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
27
 
28
+ username = profile.username
29
+ yield f"Authenticated as Hugging Face user: {username}"
30
 
31
+ if not GROQ_API_KEY or not TAVILY_API_KEY:
32
+ yield "Error: API keys (GROQ_API_KEY, TAVILY_API_KEY) are not set. Please configure them as Space secrets."
 
 
 
 
 
33
  return
34
 
35
+ # Fetch questions from the API
36
  try:
37
  yield "Fetching questions from the GAIA API..."
38
+ response = requests.get(f"{GAIA_API_URL}/questions", timeout=30)
 
 
 
 
39
  response.raise_for_status()
40
  questions = response.json()
41
  yield f"Successfully fetched {len(questions)} questions."
42
  except requests.exceptions.RequestException as e:
 
43
  yield f"Error fetching questions from API: {e}"
44
  return
45
 
46
+ # Process each task using the imported agent
 
 
 
 
 
 
 
 
 
47
  for i, task in enumerate(questions):
48
  task_id = task["task_id"]
49
  question = task["question"]
 
52
  yield f"--- Starting Task {i+1}/{len(questions)} (ID: {task_id}) ---"
53
  yield f"Question: {question}"
54
 
55
+ # Download associated file if it exists
56
  if file_name:
57
  try:
58
  yield f"Downloading file: {file_name}..."
 
60
  file_response.raise_for_status()
61
  with open(file_name, "wb") as f:
62
  f.write(file_response.content)
63
+ yield f"File '{file_name}' downloaded successfully. The agent can now access it using file tools."
64
  except requests.exceptions.RequestException as e:
65
  yield f"Error downloading file {file_name}: {e}"
 
66
  continue
67
 
68
+ # Run the imported Groq agent using the solve function
69
  try:
70
+ yield "Invoking agent..."
71
+ answer = solve(question)
72
  yield f"Agent generated answer: {answer}"
73
  except Exception as e:
74
  yield f"An error occurred while running the agent: {e}"
75
  answer = f"Error processing the question: {e}"
76
 
77
+ # Submit the answer with the username
78
  try:
79
+ yield f"Submitting answer for user '{username}'..."
80
+ submission_payload = {
81
+ "task_id": task_id,
82
+ "answer": answer,
83
+ "username": username
84
+ }
85
  submission_response = requests.post(
86
  f"{GAIA_API_URL}/submission",
87
+ json=submission_payload,
88
  )
89
  submission_response.raise_for_status()
90
  result = submission_response.json()
 
92
  except requests.exceptions.RequestException as e:
93
  yield f"Error submitting answer for task {task_id}: {e}"
94
 
95
+ # Clean up the downloaded file
96
  if file_name and os.path.exists(file_name):
97
  os.remove(file_name)
98
  yield f"Cleaned up file: {file_name}"
 
102
 
103
  # --- Gradio Interface ---
104
 
105
+ with gr.Blocks(theme=gr.themes.Soft()) as demo:
106
  gr.Markdown("# GAIA Benchmark Agent Runner")
107
  gr.Markdown(
108
+ "This application runs a Groq-powered LangChain agent against all questions from the GAIA benchmark API "
109
  "and submits the answers for evaluation. \n\n"
110
+ "**Step 1:** Log in with your Hugging Face account using the button below. \n"
111
+ "**Step 2:** Ensure your `GROQ_API_KEY` and `TAVILY_API_KEY` are set as Space secrets. \n"
112
+ "**Step 3:** Click 'Run and Submit All Tasks' to begin."
113
  )
114
+
115
+ with gr.Row():
116
+ login_button = gr.LoginButton(value="Login with Hugging Face")
117
+ start_button = gr.Button("Run and Submit All Tasks", variant="primary")
118
 
 
119
  output_textbox = gr.Textbox(
120
  label="Progress and Logs",
121
  lines=20,
122
  autoscroll=True,
123
+ interactive=False,
124
+ placeholder="Evaluation progress will be shown here..."
125
  )
126
+
127
  start_button.click(
128
  fn=run_and_submit_all,
129
+ inputs=[login_button], # Pass the OAuthProfile from the login button
130
  outputs=[output_textbox]
131
  )
132