Spaces:
Runtime error
Runtime error
Create app.py
Browse files
app.py
ADDED
@@ -0,0 +1,206 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
import os
|
2 |
+
import gradio as gr
|
3 |
+
import requests
|
4 |
+
import inspect
|
5 |
+
import pandas as pd
|
6 |
+
|
7 |
+
from llama_index.llms.huggingface_api import HuggingFaceInferenceAPI
|
8 |
+
from llama_index.core.agent.workflow import AgentWorkflow
|
9 |
+
from llama_index.core.tools import FunctionTool
|
10 |
+
|
11 |
+
# --- Constants ---
|
12 |
+
DEFAULT_API_URL = "https://agents-course-unit4-scoring.hf.space"
|
13 |
+
|
14 |
+
# --- Basic Agent Definition ---
|
15 |
+
# ----- THIS IS WERE YOU CAN BUILD WHAT YOU WANT ------
|
16 |
+
class BasicAgent:
|
17 |
+
def __init__(self ):
|
18 |
+
llm = HuggingFaceInferenceAPI(model_name="Qwen/Qwen2.5-Coder-32B-Instruct")
|
19 |
+
self.agent = AgentWorkflow.from_tools_or_functions(
|
20 |
+
[FunctionTool.from_defaults(multiply)],
|
21 |
+
llm=llm
|
22 |
+
)
|
23 |
+
def __call__(self, question: str) -> str:
|
24 |
+
print(f"Agent received question (first 50 chars): {question[:50]}...")
|
25 |
+
response = self.agent.run(question)
|
26 |
+
return str(response)
|
27 |
+
|
28 |
+
def multiply(a: int, b: int) -> int:
|
29 |
+
"""Multiplies two integers and returns the resulting integer"""
|
30 |
+
return a * b
|
31 |
+
|
32 |
+
def run_and_submit_all( profile: gr.OAuthProfile | None):
|
33 |
+
"""
|
34 |
+
Fetches all questions, runs the BasicAgent on them, submits all answers,
|
35 |
+
and displays the results.
|
36 |
+
"""
|
37 |
+
# --- Determine HF Space Runtime URL and Repo URL ---
|
38 |
+
space_id = os.getenv("SPACE_ID") # Get the SPACE_ID for sending link to the code
|
39 |
+
|
40 |
+
if profile:
|
41 |
+
username= f"{profile.username}"
|
42 |
+
print(f"User logged in: {username}")
|
43 |
+
else:
|
44 |
+
print("User not logged in.")
|
45 |
+
return "Please Login to Hugging Face with the button.", None
|
46 |
+
|
47 |
+
api_url = DEFAULT_API_URL
|
48 |
+
questions_url = f"{api_url}/questions"
|
49 |
+
submit_url = f"{api_url}/submit"
|
50 |
+
|
51 |
+
# 1. Instantiate Agent ( modify this part to create your agent)
|
52 |
+
try:
|
53 |
+
agent = BasicAgent()
|
54 |
+
except Exception as e:
|
55 |
+
print("Error instantiating agent: " + str(e))
|
56 |
+
return "Error initializing agent: " + str(e), None
|
57 |
+
# 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)
|
58 |
+
agent_code = "https://huggingface.co/spaces/" + str(space_id ) + "/tree/main"
|
59 |
+
print(agent_code)
|
60 |
+
|
61 |
+
# 2. Fetch Questions
|
62 |
+
print("Fetching questions from: " + questions_url)
|
63 |
+
try:
|
64 |
+
response = requests.get(questions_url, timeout=15)
|
65 |
+
response.raise_for_status()
|
66 |
+
questions_data = response.json()
|
67 |
+
if not questions_data:
|
68 |
+
print("Fetched questions list is empty.")
|
69 |
+
return "Fetched questions list is empty or invalid format.", None
|
70 |
+
print("Fetched " + str(len(questions_data)) + " questions.")
|
71 |
+
except requests.exceptions.RequestException as e:
|
72 |
+
print("Error fetching questions: " + str(e))
|
73 |
+
return "Error fetching questions: " + str(e), None
|
74 |
+
except requests.exceptions.JSONDecodeError as e:
|
75 |
+
print("Error decoding JSON response from questions endpoint: " + str(e))
|
76 |
+
print("Response text: " + response.text[:500])
|
77 |
+
return "Error decoding server response for questions: " + str(e), None
|
78 |
+
except Exception as e:
|
79 |
+
print("An unexpected error occurred fetching questions: " + str(e))
|
80 |
+
return "An unexpected error occurred fetching questions: " + str(e), None
|
81 |
+
|
82 |
+
# 3. Run your Agent
|
83 |
+
results_log = []
|
84 |
+
answers_payload = []
|
85 |
+
print("Running agent on " + str(len(questions_data)) + " questions...")
|
86 |
+
for item in questions_data:
|
87 |
+
task_id = item.get("task_id")
|
88 |
+
question_text = item.get("question")
|
89 |
+
if not task_id or question_text is None:
|
90 |
+
print("Skipping item with missing task_id or question: " + str(item))
|
91 |
+
continue
|
92 |
+
try:
|
93 |
+
submitted_answer = agent(question_text)
|
94 |
+
answers_payload.append({"task_id": task_id, "submitted_answer": submitted_answer})
|
95 |
+
results_log.append({"Task ID": task_id, "Question": question_text, "Submitted Answer": submitted_answer})
|
96 |
+
except Exception as e:
|
97 |
+
print("Error running agent on task " + str(task_id) + ": " + str(e))
|
98 |
+
results_log.append({"Task ID": task_id, "Question": question_text, "Submitted Answer": "AGENT ERROR: " + str(e)})
|
99 |
+
|
100 |
+
if not answers_payload:
|
101 |
+
print("Agent did not produce any answers to submit.")
|
102 |
+
return "Agent did not produce any answers to submit.", pd.DataFrame(results_log)
|
103 |
+
|
104 |
+
# 4. Prepare Submission
|
105 |
+
submission_data = {"username": username.strip(), "agent_code": agent_code, "answers": answers_payload}
|
106 |
+
status_update = "Agent finished. Submitting " + str(len(answers_payload)) + " answers for user \'" + username + "\'..."
|
107 |
+
print(status_update)
|
108 |
+
|
109 |
+
# 5. Submit
|
110 |
+
print("Submitting " + str(len(answers_payload)) + " answers to: " + submit_url)
|
111 |
+
try:
|
112 |
+
response = requests.post(submit_url, json=submission_data, timeout=60)
|
113 |
+
response.raise_for_status()
|
114 |
+
result_data = response.json()
|
115 |
+
final_status = (
|
116 |
+
"Submission Successful!\n" +
|
117 |
+
"User: " + str(result_data.get("username")) + "\n" +
|
118 |
+
"Overall Score: " + str(result_data.get("score", "N/A")) + "% " +
|
119 |
+
"(" + str(result_data.get("correct_count", "?")) + "/" + str(result_data.get("total_attempted", "?")) + " correct)\n" +
|
120 |
+
"Message: " + str(result_data.get("message", "No message received."))
|
121 |
+
)
|
122 |
+
print("Submission successful.")
|
123 |
+
results_df = pd.DataFrame(results_log)
|
124 |
+
return final_status, results_df
|
125 |
+
except requests.exceptions.HTTPError as e:
|
126 |
+
error_detail = "Server responded with status " + str(e.response.status_code) + "."
|
127 |
+
try:
|
128 |
+
error_json = e.response.json()
|
129 |
+
error_detail += " Detail: " + str(error_json.get("detail", e.response.text))
|
130 |
+
except requests.exceptions.JSONDecodeError:
|
131 |
+
error_detail += " Response: " + e.response.text[:500]
|
132 |
+
status_message = "Submission Failed: " + error_detail
|
133 |
+
print(status_message)
|
134 |
+
results_df = pd.DataFrame(results_log)
|
135 |
+
return status_message, results_df
|
136 |
+
except requests.exceptions.Timeout:
|
137 |
+
status_message = "Submission Failed: The request timed out."
|
138 |
+
print(status_message)
|
139 |
+
results_df = pd.DataFrame(results_log)
|
140 |
+
return status_message, results_df
|
141 |
+
except requests.exceptions.RequestException as e:
|
142 |
+
status_message = "Submission Failed: Network error - " + str(e)
|
143 |
+
print(status_message)
|
144 |
+
results_df = pd.DataFrame(results_log)
|
145 |
+
return status_message, results_df
|
146 |
+
except Exception as e:
|
147 |
+
status_message = "An unexpected error occurred during submission: " + str(e)
|
148 |
+
print(status_message)
|
149 |
+
results_df = pd.DataFrame(results_log)
|
150 |
+
return status_message, results_df
|
151 |
+
|
152 |
+
|
153 |
+
# --- Build Gradio Interface using Blocks ---
|
154 |
+
with gr.Blocks() as demo:
|
155 |
+
gr.Markdown("# Basic Agent Evaluation Runner")
|
156 |
+
gr.Markdown(
|
157 |
+
"""
|
158 |
+
**Instructions:**
|
159 |
+
|
160 |
+
1. Please clone this space, then modify the code to define your agent\\'s logic, the tools, the necessary packages, etc ...
|
161 |
+
2. Log in to your Hugging Face account using the button below. This uses your HF username for submission.
|
162 |
+
3. Click \\'Run Evaluation & Submit All Answers\\' to fetch questions, run your agent, submit answers, and see the score.
|
163 |
+
|
164 |
+
---
|
165 |
+
**Disclaimers:**
|
166 |
+
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).
|
167 |
+
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.
|
168 |
+
"""
|
169 |
+
)
|
170 |
+
|
171 |
+
gr.LoginButton()
|
172 |
+
|
173 |
+
run_button = gr.Button("Run Evaluation & Submit All Answers")
|
174 |
+
|
175 |
+
status_output = gr.Textbox(label="Run Status / Submission Result", lines=5, interactive=False)
|
176 |
+
# Removed max_rows=10 from DataFrame constructor
|
177 |
+
results_table = gr.DataFrame(label="Questions and Agent Answers", wrap=True)
|
178 |
+
|
179 |
+
run_button.click(
|
180 |
+
fn=run_and_submit_all,
|
181 |
+
outputs=[status_output, results_table]
|
182 |
+
)
|
183 |
+
|
184 |
+
if __name__ == "__main__":
|
185 |
+
print("\n" + "-"*30 + " App Starting " + "-"*30)
|
186 |
+
# Check for SPACE_HOST and SPACE_ID at startup for information
|
187 |
+
space_host_startup = os.getenv("SPACE_HOST")
|
188 |
+
space_id_startup = os.getenv("SPACE_ID") # Get SPACE_ID at startup
|
189 |
+
|
190 |
+
if space_host_startup:
|
191 |
+
print("✅ SPACE_HOST found: " + space_host_startup)
|
192 |
+
print(" Runtime URL should be: https://" + space_host_startup + ".hf.space" )
|
193 |
+
else:
|
194 |
+
print("ℹ️ SPACE_HOST environment variable not found (running locally?).")
|
195 |
+
|
196 |
+
if space_id_startup: # Print repo URLs if SPACE_ID is found
|
197 |
+
print("✅ SPACE_ID found: " + space_id_startup)
|
198 |
+
print(" Repo URL: https://huggingface.co/spaces/" + space_id_startup )
|
199 |
+
print(" Repo Tree URL: https://huggingface.co/spaces/" + space_id_startup + "/tree/main" )
|
200 |
+
else:
|
201 |
+
print("ℹ️ SPACE_ID environment variable not found (running locally?). Repo URL cannot be determined.")
|
202 |
+
|
203 |
+
print("-"*(60 + len(" App Starting ")) + "\n")
|
204 |
+
|
205 |
+
print("Launching Gradio Interface for Basic Agent Evaluation...")
|
206 |
+
demo.launch(debug=True, share=False)
|