Spaces:
Running
Running
Update app.py
Browse files
app.py
CHANGED
@@ -3,17 +3,10 @@ import gradio as gr
|
|
3 |
import requests
|
4 |
import inspect
|
5 |
import pandas as pd
|
|
|
6 |
from smolagents import CodeAgent, DuckDuckGoSearchTool, HfApiModel
|
7 |
-
from agent import EnhancedAgent
|
8 |
-
|
9 |
-
|
10 |
-
|
11 |
-
# (Keep Constants as is)
|
12 |
-
# --- Constants ---
|
13 |
-
DEFAULT_API_URL = "https://agents-course-unit4-scoring.hf.space"
|
14 |
|
15 |
# --- Basic Agent Definition ---
|
16 |
-
# ----- THIS IS WERE YOU CAN BUILD WHAT YOU WANT ------
|
17 |
class BasicAgent:
|
18 |
def __init__(self):
|
19 |
print("BasicAgent initialized.")
|
@@ -23,30 +16,26 @@ class BasicAgent:
|
|
23 |
print(f"Agent returning fixed answer: {fixed_answer}")
|
24 |
return fixed_answer
|
25 |
|
26 |
-
|
27 |
-
|
28 |
-
|
29 |
-
agent = CodeAgent(tools=[DuckDuckGoSearchTool()], model=HfApiModel())
|
30 |
|
31 |
def run_smol_agent():
|
32 |
question = "Search for the best music recommendations for a party at the Wayne's mansion."
|
33 |
-
response = agent.run(question)
|
34 |
print(f"Smol Agent Response: {response}")
|
35 |
return response
|
36 |
|
37 |
-
|
38 |
-
|
39 |
-
|
40 |
-
def run_and_submit_all( profile: gr.OAuthProfile | None):
|
41 |
"""
|
42 |
-
Fetches all questions, runs the
|
43 |
and displays the results.
|
44 |
"""
|
45 |
# --- Determine HF Space Runtime URL and Repo URL ---
|
46 |
space_id = os.getenv("SPACE_ID") # Get the SPACE_ID for sending link to the code
|
47 |
|
48 |
if profile:
|
49 |
-
username= f"jujovele"
|
50 |
print(f"User logged in: {username}")
|
51 |
else:
|
52 |
print("User not logged in.")
|
@@ -56,13 +45,13 @@ def run_and_submit_all( profile: gr.OAuthProfile | None):
|
|
56 |
questions_url = f"{api_url}/questions"
|
57 |
submit_url = f"{api_url}/submit"
|
58 |
|
59 |
-
# 1. Instantiate Agent (
|
60 |
try:
|
61 |
-
agent =
|
62 |
except Exception as e:
|
63 |
print(f"Error instantiating agent: {e}")
|
64 |
return f"Error initializing agent: {e}", None
|
65 |
-
|
66 |
agent_code = f"https://huggingface.co/spaces/{space_id}/tree/main"
|
67 |
print(agent_code)
|
68 |
|
@@ -73,16 +62,16 @@ def run_and_submit_all( profile: gr.OAuthProfile | None):
|
|
73 |
response.raise_for_status()
|
74 |
questions_data = response.json()
|
75 |
if not questions_data:
|
76 |
-
|
77 |
-
|
78 |
print(f"Fetched {len(questions_data)} questions.")
|
79 |
except requests.exceptions.RequestException as e:
|
80 |
print(f"Error fetching questions: {e}")
|
81 |
return f"Error fetching questions: {e}", None
|
82 |
except requests.exceptions.JSONDecodeError as e:
|
83 |
-
|
84 |
-
|
85 |
-
|
86 |
except Exception as e:
|
87 |
print(f"An unexpected error occurred fetching questions: {e}")
|
88 |
return f"An unexpected error occurred fetching questions: {e}", None
|
@@ -98,12 +87,12 @@ def run_and_submit_all( profile: gr.OAuthProfile | None):
|
|
98 |
print(f"Skipping item with missing task_id or question: {item}")
|
99 |
continue
|
100 |
try:
|
101 |
-
submitted_answer = agent(question_text)
|
102 |
answers_payload.append({"task_id": task_id, "submitted_answer": submitted_answer})
|
103 |
results_log.append({"Task ID": task_id, "Question": question_text, "Submitted Answer": submitted_answer})
|
104 |
except Exception as e:
|
105 |
-
|
106 |
-
|
107 |
|
108 |
if not answers_payload:
|
109 |
print("Agent did not produce any answers to submit.")
|
@@ -170,7 +159,7 @@ with gr.Blocks() as demo:
|
|
170 |
---
|
171 |
**Disclaimers:**
|
172 |
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).
|
173 |
-
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
|
174 |
"""
|
175 |
)
|
176 |
|
@@ -179,9 +168,7 @@ with gr.Blocks() as demo:
|
|
179 |
run_button = gr.Button("Run Evaluation & Submit All Answers")
|
180 |
run_smol_agent_button = gr.Button("Run SmolAgent Search")
|
181 |
|
182 |
-
|
183 |
status_output = gr.Textbox(label="Run Status / Submission Result", lines=5, interactive=False)
|
184 |
-
# Removed max_rows=10 from DataFrame constructor
|
185 |
results_table = gr.DataFrame(label="Questions and Agent Answers", wrap=True)
|
186 |
|
187 |
run_button.click(
|
@@ -190,25 +177,4 @@ with gr.Blocks() as demo:
|
|
190 |
)
|
191 |
|
192 |
if __name__ == "__main__":
|
193 |
-
|
194 |
-
# Check for SPACE_HOST and SPACE_ID at startup for information
|
195 |
-
space_host_startup = os.getenv("SPACE_HOST")
|
196 |
-
space_id_startup = os.getenv("SPACE_ID") # Get SPACE_ID at startup
|
197 |
-
|
198 |
-
if space_host_startup:
|
199 |
-
print(f"✅ SPACE_HOST found: {space_host_startup}")
|
200 |
-
print(f" Runtime URL should be: https://{space_host_startup}.hf.space")
|
201 |
-
else:
|
202 |
-
print("ℹ️ SPACE_HOST environment variable not found (running locally?).")
|
203 |
-
|
204 |
-
if space_id_startup: # Print repo URLs if SPACE_ID is found
|
205 |
-
print(f"✅ SPACE_ID found: {space_id_startup}")
|
206 |
-
print(f" Repo URL: https://huggingface.co/spaces/{space_id_startup}")
|
207 |
-
print(f" Repo Tree URL: https://huggingface.co/spaces/{space_id_startup}/tree/main")
|
208 |
-
else:
|
209 |
-
print("ℹ️ SPACE_ID environment variable not found (running locally?). Repo URL cannot be determined.")
|
210 |
-
|
211 |
-
print("-"*(60 + len(" App Starting ")) + "\n")
|
212 |
-
|
213 |
-
print("Launching Gradio Interface for Basic Agent Evaluation...")
|
214 |
-
demo.launch(debug=True, share=True)
|
|
|
3 |
import requests
|
4 |
import inspect
|
5 |
import pandas as pd
|
6 |
+
from agent import EnhancedAgent # Importa el EnhancedAgent
|
7 |
from smolagents import CodeAgent, DuckDuckGoSearchTool, HfApiModel
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
8 |
|
9 |
# --- Basic Agent Definition ---
|
|
|
10 |
class BasicAgent:
|
11 |
def __init__(self):
|
12 |
print("BasicAgent initialized.")
|
|
|
16 |
print(f"Agent returning fixed answer: {fixed_answer}")
|
17 |
return fixed_answer
|
18 |
|
19 |
+
# Inicializa el agente mejorado
|
20 |
+
api_key = "tu_api_key" # Asegúrate de tener la API Key correcta
|
21 |
+
agent = EnhancedAgent(api_key=api_key)
|
|
|
22 |
|
23 |
def run_smol_agent():
|
24 |
question = "Search for the best music recommendations for a party at the Wayne's mansion."
|
25 |
+
response = agent.run(question) # Usa el agente mejorado aquí
|
26 |
print(f"Smol Agent Response: {response}")
|
27 |
return response
|
28 |
|
29 |
+
def run_and_submit_all(profile: gr.OAuthProfile | None):
|
|
|
|
|
|
|
30 |
"""
|
31 |
+
Fetches all questions, runs the EnhancedAgent on them, submits all answers,
|
32 |
and displays the results.
|
33 |
"""
|
34 |
# --- Determine HF Space Runtime URL and Repo URL ---
|
35 |
space_id = os.getenv("SPACE_ID") # Get the SPACE_ID for sending link to the code
|
36 |
|
37 |
if profile:
|
38 |
+
username = f"jujovele"
|
39 |
print(f"User logged in: {username}")
|
40 |
else:
|
41 |
print("User not logged in.")
|
|
|
45 |
questions_url = f"{api_url}/questions"
|
46 |
submit_url = f"{api_url}/submit"
|
47 |
|
48 |
+
# 1. Instantiate Agent (modify this part to create your agent)
|
49 |
try:
|
50 |
+
agent = EnhancedAgent(api_key=api_key) # Crea tu agente mejorado
|
51 |
except Exception as e:
|
52 |
print(f"Error instantiating agent: {e}")
|
53 |
return f"Error initializing agent: {e}", None
|
54 |
+
|
55 |
agent_code = f"https://huggingface.co/spaces/{space_id}/tree/main"
|
56 |
print(agent_code)
|
57 |
|
|
|
62 |
response.raise_for_status()
|
63 |
questions_data = response.json()
|
64 |
if not questions_data:
|
65 |
+
print("Fetched questions list is empty.")
|
66 |
+
return "Fetched questions list is empty or invalid format.", None
|
67 |
print(f"Fetched {len(questions_data)} questions.")
|
68 |
except requests.exceptions.RequestException as e:
|
69 |
print(f"Error fetching questions: {e}")
|
70 |
return f"Error fetching questions: {e}", None
|
71 |
except requests.exceptions.JSONDecodeError as e:
|
72 |
+
print(f"Error decoding JSON response from questions endpoint: {e}")
|
73 |
+
print(f"Response text: {response.text[:500]}")
|
74 |
+
return f"Error decoding server response for questions: {e}", None
|
75 |
except Exception as e:
|
76 |
print(f"An unexpected error occurred fetching questions: {e}")
|
77 |
return f"An unexpected error occurred fetching questions: {e}", None
|
|
|
87 |
print(f"Skipping item with missing task_id or question: {item}")
|
88 |
continue
|
89 |
try:
|
90 |
+
submitted_answer = agent.run(question_text) # Usa el método run del agente mejorado
|
91 |
answers_payload.append({"task_id": task_id, "submitted_answer": submitted_answer})
|
92 |
results_log.append({"Task ID": task_id, "Question": question_text, "Submitted Answer": submitted_answer})
|
93 |
except Exception as e:
|
94 |
+
print(f"Error running agent on task {task_id}: {e}")
|
95 |
+
results_log.append({"Task ID": task_id, "Question": question_text, "Submitted Answer": f"AGENT ERROR: {e}"})
|
96 |
|
97 |
if not answers_payload:
|
98 |
print("Agent did not produce any answers to submit.")
|
|
|
159 |
---
|
160 |
**Disclaimers:**
|
161 |
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).
|
162 |
+
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 separate action or even to answer the questions in async.
|
163 |
"""
|
164 |
)
|
165 |
|
|
|
168 |
run_button = gr.Button("Run Evaluation & Submit All Answers")
|
169 |
run_smol_agent_button = gr.Button("Run SmolAgent Search")
|
170 |
|
|
|
171 |
status_output = gr.Textbox(label="Run Status / Submission Result", lines=5, interactive=False)
|
|
|
172 |
results_table = gr.DataFrame(label="Questions and Agent Answers", wrap=True)
|
173 |
|
174 |
run_button.click(
|
|
|
177 |
)
|
178 |
|
179 |
if __name__ == "__main__":
|
180 |
+
demo.launch(debug=True, share=True)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|