Files changed (3) hide show
  1. README.md +14 -14
  2. app.py +259 -196
  3. requirements.txt +13 -2
README.md CHANGED
@@ -1,15 +1,15 @@
1
- ---
2
- title: Template Final Assignment
3
- emoji: ๐Ÿ•ต๐Ÿปโ€โ™‚๏ธ
4
- colorFrom: indigo
5
- colorTo: indigo
6
- sdk: gradio
7
- sdk_version: 5.25.2
8
- app_file: app.py
9
- pinned: false
10
- hf_oauth: true
11
- # optional, default duration is 8 hours/480 minutes. Max duration is 30 days/43200 minutes.
12
- hf_oauth_expiration_minutes: 480
13
- ---
14
-
15
  Check out the configuration reference at https://huggingface.co/docs/hub/spaces-config-reference
 
1
+ ---
2
+ title: Template Final Assignment
3
+ emoji: ๐Ÿ•ต๐Ÿปโ€โ™‚๏ธ
4
+ colorFrom: indigo
5
+ colorTo: indigo
6
+ sdk: gradio
7
+ sdk_version: 5.25.2
8
+ app_file: app.py
9
+ pinned: false
10
+ hf_oauth: true
11
+ # optional, default duration is 8 hours/480 minutes. Max duration is 30 days/43200 minutes.
12
+ hf_oauth_expiration_minutes: 480
13
+ ---
14
+
15
  Check out the configuration reference at https://huggingface.co/docs/hub/spaces-config-reference
app.py CHANGED
@@ -1,196 +1,259 @@
1
- import os
2
- import gradio as gr
3
- import requests
4
- import inspect
5
- import pandas as pd
6
-
7
- # (Keep Constants as is)
8
- # --- Constants ---
9
- DEFAULT_API_URL = "https://agents-course-unit4-scoring.hf.space"
10
-
11
- # --- Basic Agent Definition ---
12
- # ----- THIS IS WERE YOU CAN BUILD WHAT YOU WANT ------
13
- class BasicAgent:
14
- def __init__(self):
15
- print("BasicAgent initialized.")
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
- submitted_answer = agent(question_text)
84
- answers_payload.append({"task_id": task_id, "submitted_answer": submitted_answer})
85
- results_log.append({"Task ID": task_id, "Question": question_text, "Submitted Answer": submitted_answer})
86
- except Exception as e:
87
- print(f"Error running agent on task {task_id}: {e}")
88
- results_log.append({"Task ID": task_id, "Question": question_text, "Submitted Answer": f"AGENT ERROR: {e}"})
89
-
90
- if not answers_payload:
91
- print("Agent did not produce any answers to submit.")
92
- return "Agent did not produce any answers to submit.", pd.DataFrame(results_log)
93
-
94
- # 4. Prepare Submission
95
- submission_data = {"username": username.strip(), "agent_code": agent_code, "answers": answers_payload}
96
- status_update = f"Agent finished. Submitting {len(answers_payload)} answers for user '{username}'..."
97
- print(status_update)
98
-
99
- # 5. Submit
100
- print(f"Submitting {len(answers_payload)} answers to: {submit_url}")
101
- try:
102
- response = requests.post(submit_url, json=submission_data, timeout=60)
103
- response.raise_for_status()
104
- result_data = response.json()
105
- final_status = (
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
- status_message = f"An unexpected error occurred during submission: {e}"
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("# Basic Agent Evaluation Runner")
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
- run_button = gr.Button("Run Evaluation & Submit All Answers")
164
-
165
- status_output = gr.Textbox(label="Run Status / Submission Result", lines=5, interactive=False)
166
- # Removed max_rows=10 from DataFrame constructor
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=[status_output, results_table]
172
- )
173
-
174
- if __name__ == "__main__":
175
- print("\n" + "-"*30 + " App Starting " + "-"*30)
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 inspect
5
+ import pandas as pd
6
+ from dotenv import load_dotenv
7
+
8
+ # Load environment variables
9
+ load_dotenv()
10
+
11
+ # Import your LangGraph agent
12
+ from graph.graph_builder import graph
13
+ from langchain_core.messages import HumanMessage
14
+
15
+ # (Keep Constants as is)
16
+ # --- Constants ---
17
+ DEFAULT_API_URL = "https://agents-course-unit4-scoring.hf.space"
18
+
19
+ # --- Your LangGraph Agent Definition ---
20
+ # ----- THIS IS WHERE YOU BUILD YOUR AGENT ------
21
+ class BasicAgent:
22
+ def __init__(self):
23
+ """Initialize the LangGraph agent"""
24
+ print("LangGraph Agent initialized with multimodal, search, math, and YouTube tools.")
25
+
26
+ # Verify environment variables
27
+ if not os.getenv("OPENROUTER_API_KEY"):
28
+ raise ValueError("OPENROUTER_API_KEY not found in environment variables")
29
+
30
+ # The graph is already compiled and ready to use
31
+ self.graph = graph
32
+ print("โœ… Agent ready with tools: multimodal, search, math, YouTube")
33
+
34
+ def __call__(self, question: str) -> str:
35
+ """
36
+ Process a question using the LangGraph agent and return just the answer
37
+
38
+ Args:
39
+ question: The question to answer
40
+
41
+ Returns:
42
+ str: The final answer (formatted for evaluation)
43
+ """
44
+ print(f"๐Ÿค– Processing question: {question[:50]}...")
45
+
46
+ try:
47
+ # Create initial state with the question
48
+ initial_state = {"messages": [HumanMessage(content=question)]}
49
+
50
+ # Run the LangGraph agent
51
+ result = self.graph.invoke(initial_state)
52
+
53
+ # Extract the final message content
54
+ final_message = result["messages"][-1]
55
+ answer = final_message.content
56
+
57
+ # Clean up the answer for evaluation (remove any extra formatting)
58
+ # The evaluation system expects just the answer, no explanations
59
+ if isinstance(answer, str):
60
+ answer = answer.strip()
61
+
62
+ # Remove common prefixes that might interfere with evaluation
63
+ prefixes_to_remove = [
64
+ "The answer is: ",
65
+ "Answer: ",
66
+ "The result is: ",
67
+ "Result: ",
68
+ "The final answer is: ",
69
+ ]
70
+
71
+ for prefix in prefixes_to_remove:
72
+ if answer.startswith(prefix):
73
+ answer = answer[len(prefix):].strip()
74
+ break
75
+
76
+ print(f"โœ… Agent answer: {answer}")
77
+ return answer
78
+
79
+ except Exception as e:
80
+ error_msg = f"Error processing question: {str(e)}"
81
+ print(f"โŒ {error_msg}")
82
+ return error_msg
83
+
84
+ # Keep the rest of the file unchanged (run_and_submit_all function and Gradio interface)
85
+ def run_and_submit_all(profile: gr.OAuthProfile | None):
86
+ """
87
+ Fetches all questions, runs the BasicAgent on them, submits all answers,
88
+ and displays the results.
89
+ """
90
+ # --- Determine HF Space Runtime URL and Repo URL ---
91
+ space_id = os.getenv("SPACE_ID") # Get the SPACE_ID for sending link to the code
92
+
93
+ if profile:
94
+ username= f"{profile.username}"
95
+ print(f"User logged in: {username}")
96
+ else:
97
+ print("User not logged in.")
98
+ return "Please Login to Hugging Face with the button.", None
99
+
100
+ api_url = DEFAULT_API_URL
101
+ questions_url = f"{api_url}/questions"
102
+ submit_url = f"{api_url}/submit"
103
+
104
+ # 1. Instantiate Agent (using your LangGraph agent)
105
+ try:
106
+ agent = BasicAgent()
107
+ except Exception as e:
108
+ print(f"Error instantiating agent: {e}")
109
+ return f"Error initializing agent: {e}", None
110
+
111
+ # In the case of an app running as a hugging Face space, this link points toward your codebase
112
+ agent_code = f"https://huggingface.co/spaces/{space_id}/tree/main"
113
+ print(agent_code)
114
+
115
+ # 2. Fetch Questions
116
+ print(f"Fetching questions from: {questions_url}")
117
+ try:
118
+ response = requests.get(questions_url, timeout=15)
119
+ response.raise_for_status()
120
+ questions_data = response.json()
121
+ if not questions_data:
122
+ print("Fetched questions list is empty.")
123
+ return "Fetched questions list is empty or invalid format.", None
124
+ print(f"Fetched {len(questions_data)} questions.")
125
+ except requests.exceptions.RequestException as e:
126
+ print(f"Error fetching questions: {e}")
127
+ return f"Error fetching questions: {e}", None
128
+ except Exception as e:
129
+ print(f"An unexpected error occurred fetching questions: {e}")
130
+ return f"An unexpected error occurred fetching questions: {e}", None
131
+
132
+ # 3. Run your Agent
133
+ results_log = []
134
+ answers_payload = []
135
+ print(f"Running agent on {len(questions_data)} questions...")
136
+ for item in questions_data:
137
+ task_id = item.get("task_id")
138
+ question_text = item.get("question")
139
+ if not task_id or question_text is None:
140
+ print(f"Skipping item with missing task_id or question: {item}")
141
+ continue
142
+ try:
143
+ submitted_answer = agent(question_text)
144
+ answers_payload.append({"task_id": task_id, "submitted_answer": submitted_answer})
145
+ results_log.append({"Task ID": task_id, "Question": question_text, "Submitted Answer": submitted_answer})
146
+ except Exception as e:
147
+ print(f"Error running agent on task {task_id}: {e}")
148
+ results_log.append({"Task ID": task_id, "Question": question_text, "Submitted Answer": f"AGENT ERROR: {e}"})
149
+
150
+ if not answers_payload:
151
+ print("Agent did not produce any answers to submit.")
152
+ return "Agent did not produce any answers to submit.", pd.DataFrame(results_log)
153
+
154
+ # 4. Prepare Submission
155
+ submission_data = {"username": username.strip(), "agent_code": agent_code, "answers": answers_payload}
156
+ status_update = f"Agent finished. Submitting {len(answers_payload)} answers for user '{username}'..."
157
+ print(status_update)
158
+
159
+ # 5. Submit
160
+ print(f"Submitting {len(answers_payload)} answers to: {submit_url}")
161
+ try:
162
+ response = requests.post(submit_url, json=submission_data, timeout=60)
163
+ response.raise_for_status()
164
+ result_data = response.json()
165
+ final_status = (
166
+ f"Submission Successful!\n"
167
+ f"User: {result_data.get('username')}\n"
168
+ f"Overall Score: {result_data.get('score', 'N/A')}% "
169
+ f"({result_data.get('correct_count', '?')}/{result_data.get('total_attempted', '?')} correct)\n"
170
+ f"Message: {result_data.get('message', 'No message received.')}"
171
+ )
172
+ print("Submission successful.")
173
+ results_df = pd.DataFrame(results_log)
174
+ return final_status, results_df
175
+ except requests.exceptions.HTTPError as e:
176
+ error_detail = f"Server responded with status {e.response.status_code}."
177
+ try:
178
+ error_json = e.response.json()
179
+ error_detail += f" Detail: {error_json.get('detail', e.response.text)}"
180
+ except requests.exceptions.JSONDecodeError:
181
+ error_detail += f" Response: {e.response.text[:500]}"
182
+ status_message = f"Submission Failed: {error_detail}"
183
+ print(status_message)
184
+ results_df = pd.DataFrame(results_log)
185
+ return status_message, results_df
186
+ except requests.exceptions.Timeout:
187
+ status_message = "Submission Failed: The request timed out."
188
+ print(status_message)
189
+ results_df = pd.DataFrame(results_log)
190
+ return status_message, results_df
191
+ except requests.exceptions.RequestException as e:
192
+ status_message = f"Submission Failed: Network error - {e}"
193
+ print(status_message)
194
+ results_df = pd.DataFrame(results_log)
195
+ return status_message, results_df
196
+ except Exception as e:
197
+ status_message = f"An unexpected error occurred during submission: {e}"
198
+ print(status_message)
199
+ results_df = pd.DataFrame(results_log)
200
+ return status_message, results_df
201
+
202
+ # --- Build Gradio Interface using Blocks ---
203
+ with gr.Blocks() as demo:
204
+ gr.Markdown("# LangGraph Agent Evaluation Runner")
205
+ gr.Markdown(
206
+ """
207
+ **Instructions:**
208
+
209
+ This space uses a LangGraph agent with multimodal, search, math, and YouTube tools powered by OpenRouter.
210
+
211
+ 1. Log in to your Hugging Face account using the button below.
212
+ 2. Click 'Run Evaluation & Submit All Answers' to fetch questions, run your agent, submit answers, and see the score.
213
+
214
+ **Agent Capabilities:**
215
+ - ๐ŸŽจ **Multimodal**: Analyze images, extract text (OCR), process audio transcripts
216
+ - ๐Ÿ” **Search**: Web search using multiple providers (DuckDuckGo, Tavily, SerpAPI)
217
+ - ๐Ÿงฎ **Math**: Basic arithmetic, complex calculations, percentages, factorials
218
+ - ๐Ÿ“บ **YouTube**: Extract captions, get video information
219
+
220
+ ---
221
+ **Note:** Processing all questions may take some time as the agent carefully analyzes each question and uses appropriate tools.
222
+ """
223
+ )
224
+
225
+ gr.LoginButton()
226
+
227
+ run_button = gr.Button("Run Evaluation & Submit All Answers")
228
+
229
+ status_output = gr.Textbox(label="Run Status / Submission Result", lines=5, interactive=False)
230
+ results_table = gr.DataFrame(label="Questions and Agent Answers", wrap=True)
231
+
232
+ run_button.click(
233
+ fn=run_and_submit_all,
234
+ outputs=[status_output, results_table]
235
+ )
236
+
237
+ if __name__ == "__main__":
238
+ print("\n" + "-"*30 + " App Starting " + "-"*30)
239
+ # Check for SPACE_HOST and SPACE_ID at startup for information
240
+ space_host_startup = os.getenv("SPACE_HOST")
241
+ space_id_startup = os.getenv("SPACE_ID")
242
+
243
+ if space_host_startup:
244
+ print(f"โœ… SPACE_HOST found: {space_host_startup}")
245
+ print(f" Runtime URL should be: https://{space_host_startup}.hf.space")
246
+ else:
247
+ print("โ„น๏ธ SPACE_HOST environment variable not found (running locally?).")
248
+
249
+ if space_id_startup:
250
+ print(f"โœ… SPACE_ID found: {space_id_startup}")
251
+ print(f" Repo URL: https://huggingface.co/spaces/{space_id_startup}")
252
+ print(f" Repo Tree URL: https://huggingface.co/spaces/{space_id_startup}/tree/main")
253
+ else:
254
+ print("โ„น๏ธ SPACE_ID environment variable not found (running locally?). Repo URL cannot be determined.")
255
+
256
+ print("-"*(60 + len(" App Starting ")) + "\n")
257
+
258
+ print("Launching Gradio Interface for LangGraph Agent Evaluation...")
259
+ demo.launch(debug=True, share=False)
requirements.txt CHANGED
@@ -1,2 +1,13 @@
1
- gradio
2
- requests
 
 
 
 
 
 
 
 
 
 
 
 
1
+ python-dotenv
2
+ requests
3
+ pytubefix
4
+ pillow
5
+ langgraph
6
+ langchain
7
+ langchain-openai
8
+ langchain-core
9
+ langchain-community
10
+ gradio
11
+ pandas
12
+ gradio[oauth]
13
+