Spaces:
Sleeping
Sleeping
Changed the code
Browse files
app.py
CHANGED
|
@@ -1,222 +1,184 @@
|
|
| 1 |
import os
|
| 2 |
-
import openai
|
| 3 |
import gradio as gr
|
| 4 |
import requests
|
| 5 |
-
import inspect
|
| 6 |
import pandas as pd
|
|
|
|
| 7 |
from smolagents import CodeAgent, DuckDuckGoSearchTool, OpenAIServerModel
|
| 8 |
-
|
| 9 |
-
|
|
|
|
|
|
|
|
|
|
| 10 |
DEFAULT_API_URL = "https://agents-course-unit4-scoring.hf.space"
|
| 11 |
|
| 12 |
|
| 13 |
-
#
|
| 14 |
-
#
|
| 15 |
-
|
| 16 |
-
DEEPSEEK_API_BASE = os.getenv("DEEPSEEK_API_BASE", "https://api.deepseek.com")
|
| 17 |
class BasicAgent:
|
| 18 |
def __init__(self):
|
| 19 |
print("BasicAgent initialized.")
|
| 20 |
-
|
| 21 |
-
#
|
| 22 |
-
|
| 23 |
-
|
| 24 |
-
|
| 25 |
-
|
| 26 |
-
|
| 27 |
-
|
| 28 |
-
|
| 29 |
-
|
| 30 |
model = OpenAIServerModel(
|
| 31 |
-
model_id="
|
| 32 |
-
api_key=
|
| 33 |
)
|
| 34 |
-
|
|
|
|
| 35 |
search_tool = DuckDuckGoSearchTool()
|
| 36 |
-
|
|
|
|
| 37 |
self.agent = CodeAgent(
|
| 38 |
-
model
|
| 39 |
tools=[search_tool]
|
| 40 |
)
|
|
|
|
| 41 |
def __call__(self, question: str) -> str:
|
| 42 |
-
print(f"Agent received question
|
| 43 |
-
|
| 44 |
-
|
| 45 |
-
|
| 46 |
-
|
| 47 |
-
|
| 48 |
-
|
| 49 |
-
|
| 50 |
-
|
| 51 |
-
"""
|
| 52 |
-
# --- Determine HF Space Runtime URL and Repo URL ---
|
| 53 |
-
space_id = os.getenv("SPACE_ID") # Get the SPACE_ID for sending link to the code
|
| 54 |
|
| 55 |
if profile:
|
| 56 |
-
username=
|
| 57 |
print(f"User logged in: {username}")
|
| 58 |
else:
|
| 59 |
-
|
| 60 |
-
return "Please Login to Hugging Face with the button.", None
|
| 61 |
|
| 62 |
-
|
| 63 |
-
|
| 64 |
-
submit_url = f"{api_url}/submit"
|
| 65 |
|
| 66 |
-
#
|
| 67 |
try:
|
| 68 |
agent = BasicAgent()
|
| 69 |
except Exception as e:
|
| 70 |
-
print(f"Error instantiating agent: {e}")
|
| 71 |
return f"Error initializing agent: {e}", None
|
| 72 |
-
|
| 73 |
agent_code = f"https://huggingface.co/spaces/{space_id}/tree/main"
|
| 74 |
-
print(agent_code)
|
| 75 |
|
| 76 |
-
#
|
| 77 |
-
print(f"Fetching questions from: {questions_url}")
|
| 78 |
try:
|
| 79 |
response = requests.get(questions_url, timeout=15)
|
| 80 |
response.raise_for_status()
|
| 81 |
questions_data = response.json()
|
| 82 |
-
if not questions_data:
|
| 83 |
-
print("Fetched questions list is empty.")
|
| 84 |
-
return "Fetched questions list is empty or invalid format.", None
|
| 85 |
-
print(f"Fetched {len(questions_data)} questions.")
|
| 86 |
-
except requests.exceptions.RequestException as e:
|
| 87 |
-
print(f"Error fetching questions: {e}")
|
| 88 |
-
return f"Error fetching questions: {e}", None
|
| 89 |
-
except requests.exceptions.JSONDecodeError as e:
|
| 90 |
-
print(f"Error decoding JSON response from questions endpoint: {e}")
|
| 91 |
-
print(f"Response text: {response.text[:500]}")
|
| 92 |
-
return f"Error decoding server response for questions: {e}", None
|
| 93 |
except Exception as e:
|
| 94 |
-
|
| 95 |
-
return f"An unexpected error occurred fetching questions: {e}", None
|
| 96 |
|
| 97 |
-
# 3. Run your Agent
|
| 98 |
results_log = []
|
| 99 |
answers_payload = []
|
| 100 |
-
|
|
|
|
| 101 |
for item in questions_data:
|
| 102 |
task_id = item.get("task_id")
|
| 103 |
question_text = item.get("question")
|
|
|
|
| 104 |
if not task_id or question_text is None:
|
| 105 |
-
print(f"Skipping item with missing task_id or question: {item}")
|
| 106 |
continue
|
|
|
|
| 107 |
try:
|
| 108 |
-
|
| 109 |
-
answers_payload.append({"task_id": task_id, "submitted_answer": submitted_answer})
|
| 110 |
-
results_log.append({"Task ID": task_id, "Question": question_text, "Submitted Answer": submitted_answer})
|
| 111 |
except Exception as e:
|
| 112 |
-
|
| 113 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 114 |
|
| 115 |
if not answers_payload:
|
| 116 |
-
|
| 117 |
-
return "Agent did not produce any answers to submit.", pd.DataFrame(results_log)
|
| 118 |
|
| 119 |
-
|
| 120 |
-
|
| 121 |
-
|
| 122 |
-
|
|
|
|
| 123 |
|
| 124 |
-
#
|
| 125 |
-
print(f"Submitting {len(answers_payload)} answers to: {submit_url}")
|
| 126 |
try:
|
| 127 |
response = requests.post(submit_url, json=submission_data, timeout=60)
|
| 128 |
response.raise_for_status()
|
| 129 |
-
|
|
|
|
| 130 |
final_status = (
|
| 131 |
f"Submission Successful!\n"
|
| 132 |
-
f"User: {
|
| 133 |
-
f"
|
| 134 |
-
f"({
|
| 135 |
-
f"
|
|
|
|
| 136 |
)
|
| 137 |
-
|
| 138 |
-
|
| 139 |
-
|
| 140 |
-
except requests.exceptions.HTTPError as e:
|
| 141 |
-
error_detail = f"Server responded with status {e.response.status_code}."
|
| 142 |
-
try:
|
| 143 |
-
error_json = e.response.json()
|
| 144 |
-
error_detail += f" Detail: {error_json.get('detail', e.response.text)}"
|
| 145 |
-
except requests.exceptions.JSONDecodeError:
|
| 146 |
-
error_detail += f" Response: {e.response.text[:500]}"
|
| 147 |
-
status_message = f"Submission Failed: {error_detail}"
|
| 148 |
-
print(status_message)
|
| 149 |
-
results_df = pd.DataFrame(results_log)
|
| 150 |
-
return status_message, results_df
|
| 151 |
-
except requests.exceptions.Timeout:
|
| 152 |
-
status_message = "Submission Failed: The request timed out."
|
| 153 |
-
print(status_message)
|
| 154 |
-
results_df = pd.DataFrame(results_log)
|
| 155 |
-
return status_message, results_df
|
| 156 |
-
except requests.exceptions.RequestException as e:
|
| 157 |
-
status_message = f"Submission Failed: Network error - {e}"
|
| 158 |
-
print(status_message)
|
| 159 |
-
results_df = pd.DataFrame(results_log)
|
| 160 |
-
return status_message, results_df
|
| 161 |
except Exception as e:
|
| 162 |
-
|
| 163 |
-
print(status_message)
|
| 164 |
-
results_df = pd.DataFrame(results_log)
|
| 165 |
-
return status_message, results_df
|
| 166 |
|
| 167 |
|
| 168 |
-
#
|
|
|
|
|
|
|
| 169 |
with gr.Blocks() as demo:
|
| 170 |
-
gr.Markdown("# Basic Agent Evaluation Runner")
|
|
|
|
| 171 |
gr.Markdown(
|
| 172 |
"""
|
| 173 |
-
**Instructions
|
| 174 |
-
|
| 175 |
-
|
| 176 |
-
|
| 177 |
-
3. Click 'Run Evaluation & Submit All Answers' to fetch questions, run your agent, submit answers, and see the score.
|
| 178 |
|
| 179 |
---
|
| 180 |
-
**
|
| 181 |
-
|
| 182 |
-
|
| 183 |
-
Please note that this version requires an OpenAI Key to run.
|
| 184 |
"""
|
| 185 |
)
|
| 186 |
|
| 187 |
gr.LoginButton()
|
| 188 |
-
|
| 189 |
run_button = gr.Button("Run Evaluation & Submit All Answers")
|
| 190 |
|
| 191 |
-
status_output = gr.Textbox(
|
| 192 |
-
|
| 193 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 194 |
|
| 195 |
run_button.click(
|
| 196 |
fn=run_and_submit_all,
|
| 197 |
outputs=[status_output, results_table]
|
| 198 |
)
|
| 199 |
|
| 200 |
-
if __name__ == "__main__":
|
| 201 |
-
print("\n" + "-"*30 + " App Starting " + "-"*30)
|
| 202 |
-
# Check for SPACE_HOST and SPACE_ID at startup for information
|
| 203 |
-
space_host_startup = os.getenv("SPACE_HOST")
|
| 204 |
-
space_id_startup = os.getenv("SPACE_ID") # Get SPACE_ID at startup
|
| 205 |
-
|
| 206 |
-
if space_host_startup:
|
| 207 |
-
print(f"✅ SPACE_HOST found: {space_host_startup}")
|
| 208 |
-
print(f" Runtime URL should be: https://{space_host_startup}.hf.space")
|
| 209 |
-
else:
|
| 210 |
-
print("ℹ️ SPACE_HOST environment variable not found (running locally?).")
|
| 211 |
|
| 212 |
-
|
| 213 |
-
|
| 214 |
-
|
| 215 |
-
|
| 216 |
-
|
| 217 |
-
|
| 218 |
-
|
| 219 |
-
print("-"*(60 + len(" App Starting ")) + "\n")
|
| 220 |
-
|
| 221 |
-
print("Launching Gradio Interface for Basic Agent Evaluation...")
|
| 222 |
-
demo.launch(debug=True, share=False)
|
|
|
|
| 1 |
import os
|
|
|
|
| 2 |
import gradio as gr
|
| 3 |
import requests
|
|
|
|
| 4 |
import pandas as pd
|
| 5 |
+
|
| 6 |
from smolagents import CodeAgent, DuckDuckGoSearchTool, OpenAIServerModel
|
| 7 |
+
|
| 8 |
+
|
| 9 |
+
# =========================
|
| 10 |
+
# Constants
|
| 11 |
+
# =========================
|
| 12 |
DEFAULT_API_URL = "https://agents-course-unit4-scoring.hf.space"
|
| 13 |
|
| 14 |
|
| 15 |
+
# =========================
|
| 16 |
+
# Basic Agent Definition
|
| 17 |
+
# =========================
|
|
|
|
| 18 |
class BasicAgent:
|
| 19 |
def __init__(self):
|
| 20 |
print("BasicAgent initialized.")
|
| 21 |
+
|
| 22 |
+
# Get OpenAI API key from environment (HF Secrets)
|
| 23 |
+
OPENAI_API_KEY = os.getenv("OPENAI_API_KEY")
|
| 24 |
+
if not OPENAI_API_KEY:
|
| 25 |
+
raise ValueError(
|
| 26 |
+
"OPENAI_API_KEY environment variable not set. "
|
| 27 |
+
"Add it in Hugging Face → Settings → Secrets."
|
| 28 |
+
)
|
| 29 |
+
|
| 30 |
+
# Initialize OpenAI model
|
| 31 |
model = OpenAIServerModel(
|
| 32 |
+
model_id="gpt-4o-mini", # You can switch to "gpt-4o" if you want
|
| 33 |
+
api_key=OPENAI_API_KEY
|
| 34 |
)
|
| 35 |
+
|
| 36 |
+
# Initialize tools
|
| 37 |
search_tool = DuckDuckGoSearchTool()
|
| 38 |
+
|
| 39 |
+
# Initialize agent
|
| 40 |
self.agent = CodeAgent(
|
| 41 |
+
model=model,
|
| 42 |
tools=[search_tool]
|
| 43 |
)
|
| 44 |
+
|
| 45 |
def __call__(self, question: str) -> str:
|
| 46 |
+
print(f"Agent received question: {question[:50]}...")
|
| 47 |
+
return self.agent.run(question)
|
| 48 |
+
|
| 49 |
+
|
| 50 |
+
# =========================
|
| 51 |
+
# Run + Submit Logic
|
| 52 |
+
# =========================
|
| 53 |
+
def run_and_submit_all(profile: gr.OAuthProfile | None):
|
| 54 |
+
space_id = os.getenv("SPACE_ID")
|
|
|
|
|
|
|
|
|
|
| 55 |
|
| 56 |
if profile:
|
| 57 |
+
username = profile.username
|
| 58 |
print(f"User logged in: {username}")
|
| 59 |
else:
|
| 60 |
+
return "Please login to Hugging Face first.", None
|
|
|
|
| 61 |
|
| 62 |
+
questions_url = f"{DEFAULT_API_URL}/questions"
|
| 63 |
+
submit_url = f"{DEFAULT_API_URL}/submit"
|
|
|
|
| 64 |
|
| 65 |
+
# Instantiate agent
|
| 66 |
try:
|
| 67 |
agent = BasicAgent()
|
| 68 |
except Exception as e:
|
|
|
|
| 69 |
return f"Error initializing agent: {e}", None
|
| 70 |
+
|
| 71 |
agent_code = f"https://huggingface.co/spaces/{space_id}/tree/main"
|
|
|
|
| 72 |
|
| 73 |
+
# Fetch questions
|
|
|
|
| 74 |
try:
|
| 75 |
response = requests.get(questions_url, timeout=15)
|
| 76 |
response.raise_for_status()
|
| 77 |
questions_data = response.json()
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 78 |
except Exception as e:
|
| 79 |
+
return f"Error fetching questions: {e}", None
|
|
|
|
| 80 |
|
|
|
|
| 81 |
results_log = []
|
| 82 |
answers_payload = []
|
| 83 |
+
|
| 84 |
+
# Run agent
|
| 85 |
for item in questions_data:
|
| 86 |
task_id = item.get("task_id")
|
| 87 |
question_text = item.get("question")
|
| 88 |
+
|
| 89 |
if not task_id or question_text is None:
|
|
|
|
| 90 |
continue
|
| 91 |
+
|
| 92 |
try:
|
| 93 |
+
answer = agent(question_text)
|
|
|
|
|
|
|
| 94 |
except Exception as e:
|
| 95 |
+
answer = f"AGENT ERROR: {e}"
|
| 96 |
+
|
| 97 |
+
answers_payload.append(
|
| 98 |
+
{"task_id": task_id, "submitted_answer": answer}
|
| 99 |
+
)
|
| 100 |
+
|
| 101 |
+
results_log.append(
|
| 102 |
+
{
|
| 103 |
+
"Task ID": task_id,
|
| 104 |
+
"Question": question_text,
|
| 105 |
+
"Submitted Answer": answer
|
| 106 |
+
}
|
| 107 |
+
)
|
| 108 |
|
| 109 |
if not answers_payload:
|
| 110 |
+
return "No answers generated.", pd.DataFrame(results_log)
|
|
|
|
| 111 |
|
| 112 |
+
submission_data = {
|
| 113 |
+
"username": username.strip(),
|
| 114 |
+
"agent_code": agent_code,
|
| 115 |
+
"answers": answers_payload
|
| 116 |
+
}
|
| 117 |
|
| 118 |
+
# Submit answers
|
|
|
|
| 119 |
try:
|
| 120 |
response = requests.post(submit_url, json=submission_data, timeout=60)
|
| 121 |
response.raise_for_status()
|
| 122 |
+
result = response.json()
|
| 123 |
+
|
| 124 |
final_status = (
|
| 125 |
f"Submission Successful!\n"
|
| 126 |
+
f"User: {result.get('username')}\n"
|
| 127 |
+
f"Score: {result.get('score', 'N/A')}% "
|
| 128 |
+
f"({result.get('correct_count', '?')}/"
|
| 129 |
+
f"{result.get('total_attempted', '?')})\n"
|
| 130 |
+
f"Message: {result.get('message', '')}"
|
| 131 |
)
|
| 132 |
+
|
| 133 |
+
return final_status, pd.DataFrame(results_log)
|
| 134 |
+
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 135 |
except Exception as e:
|
| 136 |
+
return f"Submission failed: {e}", pd.DataFrame(results_log)
|
|
|
|
|
|
|
|
|
|
| 137 |
|
| 138 |
|
| 139 |
+
# =========================
|
| 140 |
+
# Gradio UI
|
| 141 |
+
# =========================
|
| 142 |
with gr.Blocks() as demo:
|
| 143 |
+
gr.Markdown("# 🤖 Basic Agent Evaluation Runner")
|
| 144 |
+
|
| 145 |
gr.Markdown(
|
| 146 |
"""
|
| 147 |
+
**Instructions**
|
| 148 |
+
1. Login with your Hugging Face account.
|
| 149 |
+
2. Click **Run Evaluation & Submit All Answers**.
|
| 150 |
+
3. Wait while the agent answers and submits.
|
|
|
|
| 151 |
|
| 152 |
---
|
| 153 |
+
**Note:**
|
| 154 |
+
This app uses **OpenAI (gpt-4o-mini)** and requires an `OPENAI_API_KEY`
|
| 155 |
+
set in **Hugging Face → Settings → Secrets**.
|
|
|
|
| 156 |
"""
|
| 157 |
)
|
| 158 |
|
| 159 |
gr.LoginButton()
|
|
|
|
| 160 |
run_button = gr.Button("Run Evaluation & Submit All Answers")
|
| 161 |
|
| 162 |
+
status_output = gr.Textbox(
|
| 163 |
+
label="Run Status / Submission Result",
|
| 164 |
+
lines=6,
|
| 165 |
+
interactive=False
|
| 166 |
+
)
|
| 167 |
+
|
| 168 |
+
results_table = gr.DataFrame(
|
| 169 |
+
label="Questions and Agent Answers",
|
| 170 |
+
wrap=True
|
| 171 |
+
)
|
| 172 |
|
| 173 |
run_button.click(
|
| 174 |
fn=run_and_submit_all,
|
| 175 |
outputs=[status_output, results_table]
|
| 176 |
)
|
| 177 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 178 |
|
| 179 |
+
# =========================
|
| 180 |
+
# App Entry Point
|
| 181 |
+
# =========================
|
| 182 |
+
if __name__ == "__main__":
|
| 183 |
+
print("Launching Gradio app...")
|
| 184 |
+
demo.launch(debug=True, share=False)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|