Spaces:
Sleeping
Sleeping
Refine app.py
Browse files
app.py
CHANGED
|
@@ -1,97 +1,84 @@
|
|
| 1 |
import os
|
| 2 |
import gradio as gr
|
| 3 |
import requests
|
| 4 |
-
import inspect
|
| 5 |
import pandas as pd
|
| 6 |
-
from
|
|
|
|
| 7 |
from dotenv import load_dotenv
|
| 8 |
|
| 9 |
-
# Load environment variables
|
| 10 |
load_dotenv()
|
| 11 |
|
| 12 |
-
# (Keep Constants as is)
|
| 13 |
-
# --- Constants ---
|
| 14 |
DEFAULT_API_URL = "https://agents-course-unit4-scoring.hf.space"
|
| 15 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 16 |
def run_and_submit_all(profile: gr.OAuthProfile | None):
|
| 17 |
-
"""
|
| 18 |
-
|
| 19 |
-
|
| 20 |
-
|
| 21 |
-
# --- Determine HF Space Runtime URL and Repo URL ---
|
| 22 |
-
space_id = os.getenv("SPACE_ID") # Get the SPACE_ID for sending link to the code
|
| 23 |
-
|
| 24 |
-
if profile:
|
| 25 |
-
username= f"{profile.username}"
|
| 26 |
-
print(f"User logged in: {username}")
|
| 27 |
-
else:
|
| 28 |
-
print("User not logged in.")
|
| 29 |
return "Please Login to Hugging Face with the button.", None
|
| 30 |
|
|
|
|
|
|
|
|
|
|
| 31 |
api_url = DEFAULT_API_URL
|
| 32 |
questions_url = f"{api_url}/questions"
|
| 33 |
submit_url = f"{api_url}/submit"
|
| 34 |
|
| 35 |
-
# 1. Instantiate Agent ( modify this part to create your agent)
|
| 36 |
try:
|
| 37 |
agent = BasicAgent()
|
| 38 |
except Exception as e:
|
| 39 |
-
print(f"Error instantiating agent: {e}")
|
| 40 |
return f"Error initializing agent: {e}", None
|
| 41 |
-
|
| 42 |
agent_code = f"https://huggingface.co/spaces/{space_id}/tree/main"
|
| 43 |
-
print(agent_code)
|
| 44 |
|
| 45 |
-
# 2. Fetch Questions
|
| 46 |
-
print(f"Fetching questions from: {questions_url}")
|
| 47 |
try:
|
| 48 |
response = requests.get(questions_url, timeout=15)
|
| 49 |
response.raise_for_status()
|
| 50 |
questions_data = response.json()
|
| 51 |
if not questions_data:
|
| 52 |
-
|
| 53 |
-
return "Fetched questions list is empty or invalid format.", None
|
| 54 |
print(f"Fetched {len(questions_data)} questions.")
|
| 55 |
-
except requests.exceptions.RequestException as e:
|
| 56 |
-
print(f"Error fetching questions: {e}")
|
| 57 |
-
return f"Error fetching questions: {e}", None
|
| 58 |
-
except requests.exceptions.JSONDecodeError as e:
|
| 59 |
-
print(f"Error decoding JSON response from questions endpoint: {e}")
|
| 60 |
-
print(f"Response text: {response.text[:500]}")
|
| 61 |
-
return f"Error decoding server response for questions: {e}", None
|
| 62 |
except Exception as e:
|
| 63 |
-
|
| 64 |
-
return f"An unexpected error occurred fetching questions: {e}", None
|
| 65 |
|
| 66 |
-
# 3. Run your Agent
|
| 67 |
results_log = []
|
| 68 |
answers_payload = []
|
| 69 |
print(f"Running agent on {len(questions_data)} questions...")
|
|
|
|
| 70 |
for item in questions_data:
|
| 71 |
task_id = item.get("task_id")
|
| 72 |
question_text = item.get("question")
|
| 73 |
if not task_id or question_text is None:
|
| 74 |
-
print(f"Skipping item with missing task_id or question: {item}")
|
| 75 |
continue
|
| 76 |
try:
|
| 77 |
submitted_answer = agent(question_text)
|
| 78 |
answers_payload.append({"task_id": task_id, "submitted_answer": submitted_answer})
|
| 79 |
results_log.append({"Task ID": task_id, "Question": question_text, "Submitted Answer": submitted_answer})
|
| 80 |
except Exception as e:
|
| 81 |
-
|
| 82 |
-
results_log.append({"Task ID": task_id, "Question": question_text, "Submitted Answer": f"AGENT ERROR: {e}"})
|
| 83 |
|
| 84 |
if not answers_payload:
|
| 85 |
-
print("Agent did not produce any answers to submit.")
|
| 86 |
return "Agent did not produce any answers to submit.", pd.DataFrame(results_log)
|
| 87 |
|
| 88 |
-
|
| 89 |
-
|
| 90 |
-
|
| 91 |
-
|
|
|
|
| 92 |
|
| 93 |
-
# 5. Submit
|
| 94 |
-
print(f"Submitting {len(answers_payload)} answers to: {submit_url}")
|
| 95 |
try:
|
| 96 |
response = requests.post(submit_url, json=submission_data, timeout=60)
|
| 97 |
response.raise_for_status()
|
|
@@ -103,61 +90,24 @@ def run_and_submit_all(profile: gr.OAuthProfile | None):
|
|
| 103 |
f"({result_data.get('correct_count', '?')}/{result_data.get('total_attempted', '?')} correct)\n"
|
| 104 |
f"Message: {result_data.get('message', 'No message received.')}"
|
| 105 |
)
|
| 106 |
-
|
| 107 |
-
results_df = pd.DataFrame(results_log)
|
| 108 |
-
return final_status, results_df
|
| 109 |
-
except requests.exceptions.HTTPError as e:
|
| 110 |
-
error_detail = f"Server responded with status {e.response.status_code}."
|
| 111 |
-
try:
|
| 112 |
-
error_json = e.response.json()
|
| 113 |
-
error_detail += f" Detail: {error_json.get('detail', e.response.text)}"
|
| 114 |
-
except requests.exceptions.JSONDecodeError:
|
| 115 |
-
error_detail += f" Response: {e.response.text[:500]}"
|
| 116 |
-
status_message = f"Submission Failed: {error_detail}"
|
| 117 |
-
print(status_message)
|
| 118 |
-
results_df = pd.DataFrame(results_log)
|
| 119 |
-
return status_message, results_df
|
| 120 |
-
except requests.exceptions.Timeout:
|
| 121 |
-
status_message = "Submission Failed: The request timed out."
|
| 122 |
-
print(status_message)
|
| 123 |
-
results_df = pd.DataFrame(results_log)
|
| 124 |
-
return status_message, results_df
|
| 125 |
-
except requests.exceptions.RequestException as e:
|
| 126 |
-
status_message = f"Submission Failed: Network error - {e}"
|
| 127 |
-
print(status_message)
|
| 128 |
-
results_df = pd.DataFrame(results_log)
|
| 129 |
-
return status_message, results_df
|
| 130 |
except Exception as e:
|
| 131 |
-
|
| 132 |
-
print(status_message)
|
| 133 |
-
results_df = pd.DataFrame(results_log)
|
| 134 |
-
return status_message, results_df
|
| 135 |
-
|
| 136 |
|
| 137 |
-
#
|
| 138 |
with gr.Blocks() as demo:
|
| 139 |
gr.Markdown("# Basic Agent Evaluation Runner")
|
| 140 |
gr.Markdown(
|
| 141 |
"""
|
| 142 |
**Instructions:**
|
| 143 |
-
|
| 144 |
-
|
| 145 |
-
2. Log in to your Hugging Face account using the button below. This uses your HF username for submission.
|
| 146 |
-
3. Click 'Run Evaluation & Submit All Answers' to fetch questions, run your agent, submit answers, and see the score.
|
| 147 |
-
|
| 148 |
-
---
|
| 149 |
-
**Disclaimers:**
|
| 150 |
-
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).
|
| 151 |
-
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.
|
| 152 |
"""
|
| 153 |
)
|
| 154 |
|
| 155 |
gr.LoginButton()
|
| 156 |
-
|
| 157 |
run_button = gr.Button("Run Evaluation & Submit All Answers")
|
| 158 |
-
|
| 159 |
status_output = gr.Textbox(label="Run Status / Submission Result", lines=5, interactive=False)
|
| 160 |
-
# Removed max_rows=10 from DataFrame constructor
|
| 161 |
results_table = gr.DataFrame(label="Questions and Agent Answers", wrap=True)
|
| 162 |
|
| 163 |
run_button.click(
|
|
@@ -165,88 +115,16 @@ with gr.Blocks() as demo:
|
|
| 165 |
outputs=[status_output, results_table]
|
| 166 |
)
|
| 167 |
|
| 168 |
-
# Initialize the agent
|
| 169 |
-
agent = BasicAgent()
|
| 170 |
-
|
| 171 |
-
def process_question(question, file=None):
|
| 172 |
-
"""
|
| 173 |
-
Process a question using the agent and return the answer.
|
| 174 |
-
|
| 175 |
-
Args:
|
| 176 |
-
question (str): The question to be answered
|
| 177 |
-
file (str, optional): Path to a file if the question requires file processing
|
| 178 |
-
|
| 179 |
-
Returns:
|
| 180 |
-
str: The agent's answer to the question
|
| 181 |
-
"""
|
| 182 |
-
try:
|
| 183 |
-
# Basic input validation
|
| 184 |
-
if not question or not question.strip():
|
| 185 |
-
return "Please enter a question."
|
| 186 |
-
|
| 187 |
-
# Process the question using the agent
|
| 188 |
-
answer = agent(question, file)
|
| 189 |
-
|
| 190 |
-
# Format the response
|
| 191 |
-
if isinstance(answer, dict):
|
| 192 |
-
# If the answer is a dictionary (e.g., from file processing)
|
| 193 |
-
return f"Answer: {answer.get('answer', 'No answer found')}"
|
| 194 |
-
else:
|
| 195 |
-
# If the answer is a direct string
|
| 196 |
-
return f"Answer: {answer}"
|
| 197 |
-
|
| 198 |
-
except Exception as e:
|
| 199 |
-
return f"Error processing your question: {str(e)}"
|
| 200 |
-
|
| 201 |
-
# Create the Gradio interface
|
| 202 |
-
demo = gr.Interface(
|
| 203 |
-
fn=process_question,
|
| 204 |
-
inputs=[
|
| 205 |
-
gr.Textbox(
|
| 206 |
-
label="Question",
|
| 207 |
-
placeholder="Enter your question here...",
|
| 208 |
-
lines=3
|
| 209 |
-
),
|
| 210 |
-
gr.File(
|
| 211 |
-
label="Optional File Upload",
|
| 212 |
-
file_types=["txt", "csv", "json"]
|
| 213 |
-
)
|
| 214 |
-
],
|
| 215 |
-
outputs=gr.Textbox(
|
| 216 |
-
label="Answer",
|
| 217 |
-
lines=5
|
| 218 |
-
),
|
| 219 |
-
title="Question Answering Agent",
|
| 220 |
-
description="Ask any question and get a precise answer. You can also upload a file for file-based questions.",
|
| 221 |
-
examples=[
|
| 222 |
-
["What is the capital of France?", None],
|
| 223 |
-
["What is 2 + 2?", None],
|
| 224 |
-
["List the first three planets in our solar system", None]
|
| 225 |
-
],
|
| 226 |
-
theme=gr.themes.Soft()
|
| 227 |
-
)
|
| 228 |
-
|
| 229 |
-
# Launch the interface
|
| 230 |
if __name__ == "__main__":
|
| 231 |
print("\n" + "-"*30 + " App Starting " + "-"*30)
|
| 232 |
-
|
| 233 |
-
space_host_startup = os.getenv("SPACE_HOST")
|
| 234 |
-
space_id_startup = os.getenv("SPACE_ID") # Get SPACE_ID at startup
|
| 235 |
|
| 236 |
-
if
|
| 237 |
-
print(f"✅ SPACE_HOST found: {space_host_startup}")
|
| 238 |
-
print(f" Runtime URL should be: https://{space_host_startup}.hf.space")
|
| 239 |
-
else:
|
| 240 |
-
print("ℹ️ SPACE_HOST environment variable not found (running locally?).")
|
| 241 |
-
|
| 242 |
-
if space_id_startup: # Print repo URLs if SPACE_ID is found
|
| 243 |
print(f"✅ SPACE_ID found: {space_id_startup}")
|
| 244 |
print(f" Repo URL: https://huggingface.co/spaces/{space_id_startup}")
|
| 245 |
-
print(f" Repo Tree URL: https://huggingface.co/spaces/{space_id_startup}/tree/main")
|
| 246 |
else:
|
| 247 |
-
print("ℹ️ SPACE_ID environment variable not found (running locally?).
|
| 248 |
|
| 249 |
print("-"*(60 + len(" App Starting ")) + "\n")
|
| 250 |
-
|
| 251 |
print("Launching Gradio Interface for Basic Agent Evaluation...")
|
| 252 |
demo.launch(debug=True, share=False)
|
|
|
|
| 1 |
import os
|
| 2 |
import gradio as gr
|
| 3 |
import requests
|
|
|
|
| 4 |
import pandas as pd
|
| 5 |
+
from langchain_core.messages import HumanMessage
|
| 6 |
+
from agent import build_graph
|
| 7 |
from dotenv import load_dotenv
|
| 8 |
|
|
|
|
| 9 |
load_dotenv()
|
| 10 |
|
|
|
|
|
|
|
| 11 |
DEFAULT_API_URL = "https://agents-course-unit4-scoring.hf.space"
|
| 12 |
|
| 13 |
+
class BasicAgent:
|
| 14 |
+
"""A langgraph agent."""
|
| 15 |
+
def __init__(self):
|
| 16 |
+
print("BasicAgent initialized.")
|
| 17 |
+
self.graph = build_graph()
|
| 18 |
+
|
| 19 |
+
def __call__(self, question: str) -> str:
|
| 20 |
+
print(f"Agent received question (first 50 chars): {question[:50]}...")
|
| 21 |
+
messages = [HumanMessage(content=question)]
|
| 22 |
+
messages = self.graph.invoke({"messages": messages})
|
| 23 |
+
answer = messages['messages'][-1].content
|
| 24 |
+
return answer[14:]
|
| 25 |
+
|
| 26 |
def run_and_submit_all(profile: gr.OAuthProfile | None):
|
| 27 |
+
"""Fetches questions, runs the agent, submits answers, and displays results."""
|
| 28 |
+
space_id = os.getenv("SPACE_ID")
|
| 29 |
+
|
| 30 |
+
if not profile:
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 31 |
return "Please Login to Hugging Face with the button.", None
|
| 32 |
|
| 33 |
+
username = profile.username
|
| 34 |
+
print(f"User logged in: {username}")
|
| 35 |
+
|
| 36 |
api_url = DEFAULT_API_URL
|
| 37 |
questions_url = f"{api_url}/questions"
|
| 38 |
submit_url = f"{api_url}/submit"
|
| 39 |
|
|
|
|
| 40 |
try:
|
| 41 |
agent = BasicAgent()
|
| 42 |
except Exception as e:
|
|
|
|
| 43 |
return f"Error initializing agent: {e}", None
|
| 44 |
+
|
| 45 |
agent_code = f"https://huggingface.co/spaces/{space_id}/tree/main"
|
|
|
|
| 46 |
|
|
|
|
|
|
|
| 47 |
try:
|
| 48 |
response = requests.get(questions_url, timeout=15)
|
| 49 |
response.raise_for_status()
|
| 50 |
questions_data = response.json()
|
| 51 |
if not questions_data:
|
| 52 |
+
return "Fetched questions list is empty.", None
|
|
|
|
| 53 |
print(f"Fetched {len(questions_data)} questions.")
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 54 |
except Exception as e:
|
| 55 |
+
return f"Error fetching questions: {e}", None
|
|
|
|
| 56 |
|
|
|
|
| 57 |
results_log = []
|
| 58 |
answers_payload = []
|
| 59 |
print(f"Running agent on {len(questions_data)} questions...")
|
| 60 |
+
|
| 61 |
for item in questions_data:
|
| 62 |
task_id = item.get("task_id")
|
| 63 |
question_text = item.get("question")
|
| 64 |
if not task_id or question_text is None:
|
|
|
|
| 65 |
continue
|
| 66 |
try:
|
| 67 |
submitted_answer = agent(question_text)
|
| 68 |
answers_payload.append({"task_id": task_id, "submitted_answer": submitted_answer})
|
| 69 |
results_log.append({"Task ID": task_id, "Question": question_text, "Submitted Answer": submitted_answer})
|
| 70 |
except Exception as e:
|
| 71 |
+
results_log.append({"Task ID": task_id, "Question": question_text, "Submitted Answer": f"AGENT ERROR: {e}"})
|
|
|
|
| 72 |
|
| 73 |
if not answers_payload:
|
|
|
|
| 74 |
return "Agent did not produce any answers to submit.", pd.DataFrame(results_log)
|
| 75 |
|
| 76 |
+
submission_data = {
|
| 77 |
+
"username": username.strip(),
|
| 78 |
+
"agent_code": agent_code,
|
| 79 |
+
"answers": answers_payload
|
| 80 |
+
}
|
| 81 |
|
|
|
|
|
|
|
| 82 |
try:
|
| 83 |
response = requests.post(submit_url, json=submission_data, timeout=60)
|
| 84 |
response.raise_for_status()
|
|
|
|
| 90 |
f"({result_data.get('correct_count', '?')}/{result_data.get('total_attempted', '?')} correct)\n"
|
| 91 |
f"Message: {result_data.get('message', 'No message received.')}"
|
| 92 |
)
|
| 93 |
+
return final_status, pd.DataFrame(results_log)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 94 |
except Exception as e:
|
| 95 |
+
return f"Submission Failed: {str(e)}", pd.DataFrame(results_log)
|
|
|
|
|
|
|
|
|
|
|
|
|
| 96 |
|
| 97 |
+
# Build Gradio Interface
|
| 98 |
with gr.Blocks() as demo:
|
| 99 |
gr.Markdown("# Basic Agent Evaluation Runner")
|
| 100 |
gr.Markdown(
|
| 101 |
"""
|
| 102 |
**Instructions:**
|
| 103 |
+
1. Log in to your Hugging Face account using the button below.
|
| 104 |
+
2. Click 'Run Evaluation & Submit All Answers' to fetch questions, run your agent, submit answers, and see the score.
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 105 |
"""
|
| 106 |
)
|
| 107 |
|
| 108 |
gr.LoginButton()
|
|
|
|
| 109 |
run_button = gr.Button("Run Evaluation & Submit All Answers")
|
|
|
|
| 110 |
status_output = gr.Textbox(label="Run Status / Submission Result", lines=5, interactive=False)
|
|
|
|
| 111 |
results_table = gr.DataFrame(label="Questions and Agent Answers", wrap=True)
|
| 112 |
|
| 113 |
run_button.click(
|
|
|
|
| 115 |
outputs=[status_output, results_table]
|
| 116 |
)
|
| 117 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 118 |
if __name__ == "__main__":
|
| 119 |
print("\n" + "-"*30 + " App Starting " + "-"*30)
|
| 120 |
+
space_id_startup = os.getenv("SPACE_ID")
|
|
|
|
|
|
|
| 121 |
|
| 122 |
+
if space_id_startup:
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 123 |
print(f"✅ SPACE_ID found: {space_id_startup}")
|
| 124 |
print(f" Repo URL: https://huggingface.co/spaces/{space_id_startup}")
|
|
|
|
| 125 |
else:
|
| 126 |
+
print("ℹ️ SPACE_ID environment variable not found (running locally?).")
|
| 127 |
|
| 128 |
print("-"*(60 + len(" App Starting ")) + "\n")
|
|
|
|
| 129 |
print("Launching Gradio Interface for Basic Agent Evaluation...")
|
| 130 |
demo.launch(debug=True, share=False)
|