Initial Submission
#113
by
loadedcheese
- opened
- README.md +14 -14
- app.py +259 -196
- 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 |
-
|
8 |
-
#
|
9 |
-
|
10 |
-
|
11 |
-
#
|
12 |
-
|
13 |
-
|
14 |
-
|
15 |
-
|
16 |
-
|
17 |
-
|
18 |
-
|
19 |
-
|
20 |
-
|
21 |
-
|
22 |
-
def
|
23 |
-
|
24 |
-
|
25 |
-
|
26 |
-
|
27 |
-
|
28 |
-
|
29 |
-
|
30 |
-
|
31 |
-
|
32 |
-
print(
|
33 |
-
|
34 |
-
|
35 |
-
|
36 |
-
|
37 |
-
|
38 |
-
|
39 |
-
|
40 |
-
|
41 |
-
|
42 |
-
|
43 |
-
|
44 |
-
|
45 |
-
|
46 |
-
|
47 |
-
|
48 |
-
|
49 |
-
|
50 |
-
|
51 |
-
|
52 |
-
|
53 |
-
|
54 |
-
|
55 |
-
|
56 |
-
|
57 |
-
|
58 |
-
|
59 |
-
|
60 |
-
|
61 |
-
|
62 |
-
|
63 |
-
|
64 |
-
|
65 |
-
|
66 |
-
|
67 |
-
|
68 |
-
|
69 |
-
|
70 |
-
|
71 |
-
|
72 |
-
|
73 |
-
|
74 |
-
|
75 |
-
|
76 |
-
|
77 |
-
|
78 |
-
|
79 |
-
|
80 |
-
|
81 |
-
|
82 |
-
|
83 |
-
|
84 |
-
|
85 |
-
|
86 |
-
|
87 |
-
|
88 |
-
|
89 |
-
|
90 |
-
|
91 |
-
|
92 |
-
|
93 |
-
|
94 |
-
|
95 |
-
|
96 |
-
|
97 |
-
|
98 |
-
|
99 |
-
|
100 |
-
|
101 |
-
|
102 |
-
|
103 |
-
|
104 |
-
|
105 |
-
|
106 |
-
|
107 |
-
|
108 |
-
|
109 |
-
|
110 |
-
|
111 |
-
|
112 |
-
|
113 |
-
|
114 |
-
|
115 |
-
|
116 |
-
|
117 |
-
|
118 |
-
|
119 |
-
|
120 |
-
|
121 |
-
|
122 |
-
|
123 |
-
|
124 |
-
|
125 |
-
|
126 |
-
|
127 |
-
|
128 |
-
|
129 |
-
|
130 |
-
return
|
131 |
-
|
132 |
-
|
133 |
-
|
134 |
-
|
135 |
-
|
136 |
-
|
137 |
-
|
138 |
-
|
139 |
-
|
140 |
-
|
141 |
-
|
142 |
-
|
143 |
-
|
144 |
-
|
145 |
-
|
146 |
-
|
147 |
-
|
148 |
-
|
149 |
-
|
150 |
-
|
151 |
-
|
152 |
-
|
153 |
-
|
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 |
-
|
181 |
-
|
182 |
-
|
183 |
-
|
184 |
-
|
185 |
-
|
186 |
-
|
187 |
-
|
188 |
-
print(
|
189 |
-
|
190 |
-
|
191 |
-
|
192 |
-
|
193 |
-
|
194 |
-
|
195 |
-
|
196 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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 |
-
|
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 |
+
|